I am trying to dynamically create stubby.yml configuration file. I have a template yaml file as follows:
resolution_type: GETDNS_RESOLUTION_STUB
dns_transport_list:
- GETDNS_TRANSPORT_TLS
tls_authentication: GETDNS_AUTHENTICATION_REQUIRED
tls_query_padding_blocksize: 128
edns_client_subnet_private : 1
round_robin_upstreams: 1
idle_timeout: 10000
listen_addresses:
- 10.7.0.1
appdata_dir: "/var/cache/stubby"
I am trying to append this native yaml configuration
upstream_recursive_servers:
- address_data: 185.228.168.168
tls_auth_name: "family-filter-dns.cleanbrowsing.org"
- address_data: 185.228.169.168
tls_auth_name: "family-filter-dns.cleanbrowsing.org"
The stubby configuration will not work without the tls_auth_name values being wrapped in quotations, and also appdata_dir. Quotations are being stripped and i cannot figure out how to dump the yaml without the " being stripped. Even chatgpt is struggling with this one!
def get_dns_config(dns_option) -> dict:
# return stubby.yml configuration
with open('dns.yml', 'r') as f:
data = yaml.safe_load(f)
with open('dns_template.yml', 'r') as f:
template = yaml.safe_load(f)
template['upstream_recursive_servers'] = data[dns_option]['servers']
logging.debug(json.dumps(template, indent=4))
logging.debug(yaml.safe_dump(template, default_flow_style=False,indent=2))
return yaml.safe_dump(template, default_flow_style=False,indent=2)
This is the dict after adding the upstream_recursive_servers value:
{
"resolution_type": "GETDNS_RESOLUTION_STUB",
"dns_transport_list": [
"GETDNS_TRANSPORT_TLS"
],
"tls_authentication": "GETDNS_AUTHENTICATION_REQUIRED",
"tls_query_padding_blocksize": 128,
"edns_client_subnet_private": 1,
"round_robin_upstreams": 1,
"idle_timeout": 10000,
"listen_addresses": [
"10.7.0.1"
],
"appdata_dir": "/var/cache/stubby",
"upstream_recursive_servers": [
{
"address_data": "185.228.168.168",
"tls_auth_name": "family-filter-dns.cleanbrowsing.org"
},
{
"address_data": "185.228.169.168",
"tls_auth_name": "family-filter-dns.cleanbrowsing.org"
}
]
}
This is the result from yaml.safe_load()
appdata_dir: /var/cache/stubby
dns_transport_list:
- GETDNS_TRANSPORT_TLS
edns_client_subnet_private: 1
idle_timeout: 10000
listen_addresses:
- 10.7.0.1
resolution_type: GETDNS_RESOLUTION_STUB
round_robin_upstreams: 1
tls_authentication: GETDNS_AUTHENTICATION_REQUIRED
tls_query_padding_blocksize: 128
upstream_recursive_servers:
- address_data: 185.228.168.168
tls_auth_name: family-filter-dns.cleanbrowsing.org
- address_data: 185.228.169.168
tls_auth_name: family-filter-dns.cleanbrowsing.org
Apologies for the long post - didn't want to miss anything out.
In the YAML file the record
"family-filter-dns.cleanbrowsing.org"
denotes the string family-filter-dns.cleanbrowsing.org without quotes: the quotes at the beginning and at the end are part of the representation, but aren't a part of the data.
For make the record to denote the string "family-filter-dns.cleanbrowsing.org" (with quotes) you could write whole that string inside single quotes:
'"family-filter-dns.cleanbrowsing.org"'
That way is described in YAML specification in the Example 2.17.
Alternatively, you may write whole that string inside double quotes, but escape the inner double quotes:
"\"family-filter-dns.cleanbrowsing.org\""
Related
How do i change the default download directory in the current running driver session? as i need to change the download directory many times to store particular file at particular location using 'for' loop.
below are the code which the tried to change the default directory of already running chrome driver session:
os.getcwd()
os.chdir("C:\\Site_tracker\\Output")
direc = ['S1_2g3g4g', 'S2_2g3g4g','S3_2g3g4g']
for i in direc:
if not os.path.exists(i):
os.makedirs(i)
download_path=os.path.abspath(i)
print(download_path)
chr_Options.add_experimental_option('prefs', {
"download.default_directory": "download_path", #Change default directory for downloads
"download.prompt_for_download": False, #To auto download the file
"download.directory_upgrade": True,
"plugins.always_open_pdf_externally": True})
driver1=webdriver.Chrome(chrome_options=chr_Options)
Download directory is usually set when you create a browser instance by option setting
"download.default_directory"
like described here: How to use chrome webdriver in selenium to download files in python?
or as you have in snippet.
If you want to store files to different directories during one session, you have some choices, but the one, which I choose, because in same task I also need to change filenames, was store file to local /tmp directory, rename and move it to final place.
import os
import shutil
CWD = os.getcwd()
TMP_DIR = CWD + "/tmpf" # directly downloaded files
if not os.path.isdir(TMP_DIR):
os.mkdir(TMP_DIR)
DWN_DIR = CWD + '/downloaded_files' # renamed files from TMP_DIR
if not os.path.isdir(DWN_DIR):
os.mkdir(DWN_DIR)
in prefs:
"download.default_directory" : TMP_DIR,
then
file_to_download.click()
old_name = os.listdir("./tmpf")[0]
old_file_name = TMP_DIR + "/" + old_name
new_file_name = DWN_DIR + '/' + "SPECIFIC_Prefix_" + old_name.lower().replace(" ","_")
shutil.move(old_file_name, new_file_name)
print("File downloaded and moved to: ", new_file_name)
How to generate a new access token with the use of refresh token in python.if I'm using google fit API.?
I need to update that i have found my answer
from urllib2 import Request, urlopen, URLError
import json
import mimetools
BOUNDARY = mimetools.choose_boundary()
CRLF = '\r\n'
def EncodeMultiPart(fields, files, file_type='application/xml'):
"""Encodes list of parameters and files for HTTP multipart format.
Args:
fields: list of tuples containing name and value of parameters.
files: list of tuples containing param name, filename, and file contents.
file_type: string if file type different than application/xml.
Returns:
A string to be sent as data for the HTTP post request.
"""
lines = []
for (key, value) in fields:
lines.append('--' + BOUNDARY)
lines.append('Content-Disposition: form-data; name="%s"' % key)
lines.append('') # blank line
lines.append(value)
for (key, filename, value) in files:
lines.append('--' + BOUNDARY)
lines.append(
'Content-Disposition: form-data; name="%s"; filename="%s"'
% (key, filename))
lines.append('Content-Type: %s' % file_type)
lines.append('') # blank line
lines.append(value)
lines.append('--' + BOUNDARY + '--')
lines.append('') # blank line
return CRLF.join(lines)
def refresh_token():
url = "https://oauth2.googleapis.com/token"
headers = [
("grant_type", "refresh_token"),
("client_id", "xxxxxx"),
("client_secret", "xxxxxx"),
("refresh_token", "xxxxx"),
]
files = []
edata = EncodeMultiPart(headers, files, file_type='text/plain')
#print(EncodeMultiPart(headers, files, file_type='text/plain'))
headers = {}
request = Request(url, headers=headers)
request.add_data(edata)
request.add_header('Content-Length', str(len(edata)))
request.add_header('Content-Type', 'multipart/form-data;boundary=%s' % BOUNDARY)
response = urlopen(request).read()
print(response)
refresh_token()
#response = json.decode(response)
#print(refresh_token())
How to write not condition in alert manager route matches?
I want to execute this condition only when severity is not critical..
routes
- match_re:
severity: ^(?!critical)
receiver: teams-channel-webhook-high-priority
I tried the above regex condition .But it didnt work.
I also tried with
not_match_re:
severity: critical
Even that didnt work.
Answer:
You can make a nested tree of routes, which in effect gives you an "if ... then ... else ..." capability.
routes:
- ... something to do always
continue: true
- match:
severity: critical
routes:
- ... things to do when critical
- ...
- ... things to do when not critical
- ...
Leaving out the "match" condition entirely makes a rule match always.
Note that "continue: true" carries on to the next rule after a match, but only at the same level. It will only fall out to the parent ruleset if no matches occur.
Or of course, you can explicitly match all non-critical severities e.g. match_re: severity: 'debug|informational|warning'
match and match_re have been deprecated in route in favor of using matcher
matchers takes a list of conditions (and) and supports regex match =~ and NOT match !~ operators.
route:
# root route
routes:
- receiver: recvA
matchers:
- severity!~"^critical$"
- receiver: recvB
# route:receiverB with no matchers will always match if the previous routes don't
i am using the bellow code to download a file from my ftp server.The file is downloaded on Mobile devices.
i am try to use a progress bar to show up the amount of data downloaded
The problem is always i get "cached".
this is my code
constant FTPHOST = "myIp"
constant FTPUSER = "user"
constant FTPPASS = "password"
global sDownloadStart
on mouseUp
put "test.zip" into tFileName
put "ftp://" & FTPUSER & ":" & FTPPASS & "#" & FTPHOST & "/" & tFileName into pUrl
-- start the download process, telling Rev to call the "downloadComplete" handler when finished
Load URL pUrl with message "urlProgress"
set the startvalue of sb "progressbar" to 0
end mouseUp
on urlProgress pURL, pStatus, pBytesDone, pBytesTotal
put pStatus into fld "pf1"
switch item 1 of pStatus
case "loading"
set the thumbPosition of sb "Progressbar" to round((pBytesDone / pBytesTotal) * 100)
put the round of (item 1 of pBytesDone / 1024)&& "KB Downloaded" into field "status"
break
case "cached"
-- if pStatus is "cached" then
-- work out a file name for saving this file to the desktop
set the itemDel to slash
put "binfile:" & specialfolderpath("documents") & "/test.zip" into myPath
//put "data.file" into tFileName
put url pUrl into url myPath
answer "Download completed" with ok
-- to save memory, now unload the URL from memory
-- this also means that if you want to run the test again, it does not just use a cached version
unload pURL
--end if
break
case "error"
if pStatus = "error" or pStatus = "timeout" then
answer error "The file could not be downloaded." with "ok"
end if
break
end switch
end urlProgress
Your urlProgresshandler is called after the loading of the URL finishes. To get a different status, you have to call another message or call the message in a different way, e.g.
on mouseUp
//delete URL "binfile:" & specialfolderpath("documents") & "/data.file"
put "data.file" into tFileName
put "ftp://" & FTPUSER & ":" & FTPPASS & "#" & FTPHOST & "/" & tFileName into pUrl
-- start the download process, telling Rev to call the "downloadComplete" handler when finished
// the callback message has only 2 parameters: url and urlStatus
Load URL pUrl with message "downloadComplete"
send "urlProgress pUrl" to me in 200 millisecs
end mouseUp
on urlProgress pUrl //,pStatus, pMessage,pbytesR,pbytesT
put urlStatus(pUrl) into pStatus
if item 1 of pUrl is "loading" then
put item 2 of pStatus into pBytesR
put item 3 of pStatus into pbytesT
put item 1 of pStatus into pStatus
send "urlProgress pUrl" to me in 200 millisecs
end if
end urlProgress
on downloadComplete theUrl,theUrlStatus
if theUrlStatus is "cached" then
-- work out a file name for saving this file to the desktop
set the itemDel to slash
put "binfile:" & specialfolderpath("documents") & "/data.file" into myPath
put "data.file" into tFileName
put url theUrl into url myPath
answer "Download completed" with ok
-- to save memory, now unload the URL from memory
-- this also means that if you want to run the test again, it does not just use a cached version
unload pURL
end if
-- check if there was a problem with the download
if pStatus = "error" or pStatus = "timeout" then
put libUrlErrodData(theUrl) into myErr
answer error "The file could not be downloaded."&& myErr with "ok"
end if
end downloadComplete
Let me know if this works (it should). If not, I'll have another look.
I have a table in my app.
Using Capybara and Cucumber, how do I assert that values 4.5 and 1.1 happen only in the Mike's row?
Is such assertion possible in Capybara?
Thanks!
You can use within to scope where you are searching for a specific value:
For example, to assert that value 4.5 happens in the second column of Mike's row, try the following:
within("table tr:nth-child(2)") do
find("td:nth-child(2)").text.should == 4.5
end
You can wrap these in helper methods for ease of use if you would like:
def within_row(num, &block)
within("table tr:nth-child(#{num})", &block)
end
def column_text(num)
find("td:nth-child(#{num})").text
end
Now you could make the same assertion about Mike's row by doing the following:
within_row(2) do
column_text(2).should == 4.1
end
Hopefully you will find one of these techniques useful for what you are trying to do.
Yes, it's possible and easy:
def td_text(n)
find(:xpath, "./td[#{n}]").text
end
h = {2 => 4.5, 3 => 1.1}
all('table tr').each do |row|
within row do
if td_text(1) == 'Mike'
h.each { |i, value| td_text(i).should == value.to_s }
else
h.each { |i, value| td_text(i).should_not == value.to_s }
end
end
end
Here's full script that you can use for testing
Update: I thought about it more. The code above will be very slow as every invocation of find and text in td_text will make new query to browser.
The only way to mitigate it that I see is to use JS and Nokogiri:
source = page.evaluate_script("document.getElementsByTagName('table')[0].innerHTML")
doc = Nokogiri::HTML(source)
def td_text(row, n)
row.xpath("./td[#{n}]").text
end
h = {2 => 4.5, 3 => 1.1}
doc.css('tr').each do |row|
if td_text(row, 1) == 'Mike'
h.each { |i, value| td_text(row, i).should == value.to_s }
else
h.each { |i, value| td_text(row, i).should_not == value.to_s }
end
end
The first variant of code runs about 200 milliseconds at my machine though the second one - 8 milliseconds. Good optimization!