id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
20,400 | chrisb2/pi_ina219 | ina219.py | INA219.wake | def wake(self):
""" Wake the INA219 from power down mode """
configuration = self._read_configuration()
self._configuration_register(configuration | 0x0007)
# 40us delay to recover from powerdown (p14 of spec)
time.sleep(0.00004) | python | def wake(self):
configuration = self._read_configuration()
self._configuration_register(configuration | 0x0007)
# 40us delay to recover from powerdown (p14 of spec)
time.sleep(0.00004) | [
"def",
"wake",
"(",
"self",
")",
":",
"configuration",
"=",
"self",
".",
"_read_configuration",
"(",
")",
"self",
".",
"_configuration_register",
"(",
"configuration",
"|",
"0x0007",
")",
"# 40us delay to recover from powerdown (p14 of spec)",
"time",
".",
"sleep",
... | Wake the INA219 from power down mode | [
"Wake",
"the",
"INA219",
"from",
"power",
"down",
"mode"
] | 2caeb8a387286ac3504905a0d2d478370a691339 | https://github.com/chrisb2/pi_ina219/blob/2caeb8a387286ac3504905a0d2d478370a691339/ina219.py#L202-L207 |
20,401 | blacktop/virustotal-api | virus_total_apis/api.py | _return_response_and_status_code | def _return_response_and_status_code(response, json_results=True):
""" Output the requests response content or content as json and status code
:rtype : dict
:param response: requests response object
:param json_results: Should return JSON or raw content
:return: dict containing the response content and/or the status code with error string.
"""
if response.status_code == requests.codes.ok:
return dict(results=response.json() if json_results else response.content, response_code=response.status_code)
elif response.status_code == 400:
return dict(
error='package sent is either malformed or not within the past 24 hours.',
response_code=response.status_code)
elif response.status_code == 204:
return dict(
error='You exceeded the public API request rate limit (4 requests of any nature per minute)',
response_code=response.status_code)
elif response.status_code == 403:
return dict(
error='You tried to perform calls to functions for which you require a Private API key.',
response_code=response.status_code)
elif response.status_code == 404:
return dict(error='File not found.', response_code=response.status_code)
else:
return dict(response_code=response.status_code) | python | def _return_response_and_status_code(response, json_results=True):
if response.status_code == requests.codes.ok:
return dict(results=response.json() if json_results else response.content, response_code=response.status_code)
elif response.status_code == 400:
return dict(
error='package sent is either malformed or not within the past 24 hours.',
response_code=response.status_code)
elif response.status_code == 204:
return dict(
error='You exceeded the public API request rate limit (4 requests of any nature per minute)',
response_code=response.status_code)
elif response.status_code == 403:
return dict(
error='You tried to perform calls to functions for which you require a Private API key.',
response_code=response.status_code)
elif response.status_code == 404:
return dict(error='File not found.', response_code=response.status_code)
else:
return dict(response_code=response.status_code) | [
"def",
"_return_response_and_status_code",
"(",
"response",
",",
"json_results",
"=",
"True",
")",
":",
"if",
"response",
".",
"status_code",
"==",
"requests",
".",
"codes",
".",
"ok",
":",
"return",
"dict",
"(",
"results",
"=",
"response",
".",
"json",
"(",... | Output the requests response content or content as json and status code
:rtype : dict
:param response: requests response object
:param json_results: Should return JSON or raw content
:return: dict containing the response content and/or the status code with error string. | [
"Output",
"the",
"requests",
"response",
"content",
"or",
"content",
"as",
"json",
"and",
"status",
"code"
] | 4e01e1c6d87255ec8370ac2a4ee16edce00e1e86 | https://github.com/blacktop/virustotal-api/blob/4e01e1c6d87255ec8370ac2a4ee16edce00e1e86/virus_total_apis/api.py#L954-L979 |
20,402 | blacktop/virustotal-api | virus_total_apis/api.py | PublicApi.put_comments | def put_comments(self, resource, comment, timeout=None):
""" Post a comment on a file or URL.
The initial idea of VirusTotal Community was that users should be able to make comments on files and URLs,
the comments may be malware analyses, false positive flags, disinfection instructions, etc.
Imagine you have some automatic setup that can produce interesting results related to a given sample or URL
that you submit to VirusTotal for antivirus characterization, you might want to give visibility to your setup
by automatically reviewing samples and URLs with the output of your automation.
:param resource: either a md5/sha1/sha256 hash of the file you want to review or the URL itself that you want
to comment on.
:param comment: the actual review, you can tag it using the "#" twitter-like syntax (e.g. #disinfection #zbot)
and reference users using the "@" syntax (e.g. @VirusTotalTeam).
:param timeout: The amount of time in seconds the request should wait before timing out.
:return: If the comment was successfully posted the response code will be 1, 0 otherwise.
"""
params = {'apikey': self.api_key, 'resource': resource, 'comment': comment}
try:
response = requests.post(self.base + 'comments/put', params=params, proxies=self.proxies, timeout=timeout)
except requests.RequestException as e:
return dict(error=str(e))
return _return_response_and_status_code(response) | python | def put_comments(self, resource, comment, timeout=None):
params = {'apikey': self.api_key, 'resource': resource, 'comment': comment}
try:
response = requests.post(self.base + 'comments/put', params=params, proxies=self.proxies, timeout=timeout)
except requests.RequestException as e:
return dict(error=str(e))
return _return_response_and_status_code(response) | [
"def",
"put_comments",
"(",
"self",
",",
"resource",
",",
"comment",
",",
"timeout",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'apikey'",
":",
"self",
".",
"api_key",
",",
"'resource'",
":",
"resource",
",",
"'comment'",
":",
"comment",
"}",
"try",
"... | Post a comment on a file or URL.
The initial idea of VirusTotal Community was that users should be able to make comments on files and URLs,
the comments may be malware analyses, false positive flags, disinfection instructions, etc.
Imagine you have some automatic setup that can produce interesting results related to a given sample or URL
that you submit to VirusTotal for antivirus characterization, you might want to give visibility to your setup
by automatically reviewing samples and URLs with the output of your automation.
:param resource: either a md5/sha1/sha256 hash of the file you want to review or the URL itself that you want
to comment on.
:param comment: the actual review, you can tag it using the "#" twitter-like syntax (e.g. #disinfection #zbot)
and reference users using the "@" syntax (e.g. @VirusTotalTeam).
:param timeout: The amount of time in seconds the request should wait before timing out.
:return: If the comment was successfully posted the response code will be 1, 0 otherwise. | [
"Post",
"a",
"comment",
"on",
"a",
"file",
"or",
"URL",
"."
] | 4e01e1c6d87255ec8370ac2a4ee16edce00e1e86 | https://github.com/blacktop/virustotal-api/blob/4e01e1c6d87255ec8370ac2a4ee16edce00e1e86/virus_total_apis/api.py#L188-L213 |
20,403 | blacktop/virustotal-api | virus_total_apis/api.py | PublicApi.get_ip_report | def get_ip_report(self, this_ip, timeout=None):
""" Get IP address reports.
:param this_ip: a valid IPv4 address in dotted quad notation, for the time being only IPv4 addresses are
supported.
:param timeout: The amount of time in seconds the request should wait before timing out.
:return: JSON response
"""
params = {'apikey': self.api_key, 'ip': this_ip}
try:
response = requests.get(self.base + 'ip-address/report',
params=params,
proxies=self.proxies,
timeout=timeout)
except requests.RequestException as e:
return dict(error=str(e))
return _return_response_and_status_code(response) | python | def get_ip_report(self, this_ip, timeout=None):
params = {'apikey': self.api_key, 'ip': this_ip}
try:
response = requests.get(self.base + 'ip-address/report',
params=params,
proxies=self.proxies,
timeout=timeout)
except requests.RequestException as e:
return dict(error=str(e))
return _return_response_and_status_code(response) | [
"def",
"get_ip_report",
"(",
"self",
",",
"this_ip",
",",
"timeout",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'apikey'",
":",
"self",
".",
"api_key",
",",
"'ip'",
":",
"this_ip",
"}",
"try",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"self... | Get IP address reports.
:param this_ip: a valid IPv4 address in dotted quad notation, for the time being only IPv4 addresses are
supported.
:param timeout: The amount of time in seconds the request should wait before timing out.
:return: JSON response | [
"Get",
"IP",
"address",
"reports",
"."
] | 4e01e1c6d87255ec8370ac2a4ee16edce00e1e86 | https://github.com/blacktop/virustotal-api/blob/4e01e1c6d87255ec8370ac2a4ee16edce00e1e86/virus_total_apis/api.py#L215-L234 |
20,404 | blacktop/virustotal-api | virus_total_apis/api.py | PublicApi.get_domain_report | def get_domain_report(self, this_domain, timeout=None):
""" Get information about a given domain.
:param this_domain: a domain name.
:param timeout: The amount of time in seconds the request should wait before timing out.
:return: JSON response
"""
params = {'apikey': self.api_key, 'domain': this_domain}
try:
response = requests.get(self.base + 'domain/report', params=params, proxies=self.proxies, timeout=timeout)
except requests.RequestException as e:
return dict(error=str(e))
return _return_response_and_status_code(response) | python | def get_domain_report(self, this_domain, timeout=None):
params = {'apikey': self.api_key, 'domain': this_domain}
try:
response = requests.get(self.base + 'domain/report', params=params, proxies=self.proxies, timeout=timeout)
except requests.RequestException as e:
return dict(error=str(e))
return _return_response_and_status_code(response) | [
"def",
"get_domain_report",
"(",
"self",
",",
"this_domain",
",",
"timeout",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'apikey'",
":",
"self",
".",
"api_key",
",",
"'domain'",
":",
"this_domain",
"}",
"try",
":",
"response",
"=",
"requests",
".",
"get"... | Get information about a given domain.
:param this_domain: a domain name.
:param timeout: The amount of time in seconds the request should wait before timing out.
:return: JSON response | [
"Get",
"information",
"about",
"a",
"given",
"domain",
"."
] | 4e01e1c6d87255ec8370ac2a4ee16edce00e1e86 | https://github.com/blacktop/virustotal-api/blob/4e01e1c6d87255ec8370ac2a4ee16edce00e1e86/virus_total_apis/api.py#L236-L251 |
20,405 | blacktop/virustotal-api | virus_total_apis/api.py | PrivateApi.get_upload_url | def get_upload_url(self, timeout=None):
""" Get a special URL for submitted files bigger than 32MB.
In order to submit files bigger than 32MB you need to obtain a special upload URL to which you
can POST files up to 200MB in size. This API generates such a URL.
:param timeout: The amount of time in seconds the request should wait before timing out.
:return: JSON special upload URL to which you can POST files up to 200MB in size.
"""
params = {'apikey': self.api_key}
try:
response = requests.get(self.base + 'file/scan/upload_url',
params=params,
proxies=self.proxies,
timeout=timeout)
if response.status_code == requests.codes.ok:
return response.json().get('upload_url')
else:
return dict(response_code=response.status_code)
except requests.RequestException as e:
return dict(error=str(e)) | python | def get_upload_url(self, timeout=None):
params = {'apikey': self.api_key}
try:
response = requests.get(self.base + 'file/scan/upload_url',
params=params,
proxies=self.proxies,
timeout=timeout)
if response.status_code == requests.codes.ok:
return response.json().get('upload_url')
else:
return dict(response_code=response.status_code)
except requests.RequestException as e:
return dict(error=str(e)) | [
"def",
"get_upload_url",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'apikey'",
":",
"self",
".",
"api_key",
"}",
"try",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"base",
"+",
"'file/scan/upload_url'",
... | Get a special URL for submitted files bigger than 32MB.
In order to submit files bigger than 32MB you need to obtain a special upload URL to which you
can POST files up to 200MB in size. This API generates such a URL.
:param timeout: The amount of time in seconds the request should wait before timing out.
:return: JSON special upload URL to which you can POST files up to 200MB in size. | [
"Get",
"a",
"special",
"URL",
"for",
"submitted",
"files",
"bigger",
"than",
"32MB",
"."
] | 4e01e1c6d87255ec8370ac2a4ee16edce00e1e86 | https://github.com/blacktop/virustotal-api/blob/4e01e1c6d87255ec8370ac2a4ee16edce00e1e86/virus_total_apis/api.py#L301-L323 |
20,406 | blacktop/virustotal-api | virus_total_apis/api.py | PrivateApi.file_search | def file_search(self, query, offset=None, timeout=None):
""" Search for samples.
In addition to retrieving all information on a particular file, VirusTotal allows you to perform what we
call "advanced reverse searches". Reverse searches take you from a file property to a list of files that
match that property. For example, this functionality enables you to retrieve all those files marked by at
least one antivirus vendor as Zbot, or all those files that have a size under 90KB and are detected by at
least 10 antivirus solutions, or all those PDF files that have an invalid XREF section, etc.
This API is equivalent to VirusTotal Intelligence advanced searches. A very wide variety of search modifiers
are available, including: file size, file type, first submission date to VirusTotal, last submission date to
VirusTotal, number of positives, dynamic behavioural properties, binary content, submission file name, and a
very long etcetera. The full list of search modifiers allowed for file search queries is documented at:
https://www.virustotal.com/intelligence/help/file-search/#search-modifiers
NOTE:
Daily limited! No matter what API step you have licensed, this API call is limited to 50K requests per day.
If you need any more, chances are you are approaching your engineering problem erroneously and you can
probably solve it using the file distribution call. Do not hesitate to contact us with your particular
use case.
EXAMPLE:
search_options = 'type:peexe size:90kb+ positives:5+ behaviour:"taskkill"'
:param query: A search modifier compliant file search query.
:param offset: (optional) The offset value returned by a previously issued identical query, allows you to
paginate over the results. If not specified the first 300 matching files sorted according to last submission
date to VirusTotal in a descending fashion will be returned.
:param timeout: The amount of time in seconds the request should wait before timing out.
:return: JSON response - By default the list returned contains at most 300 hashes, ordered according to
last submission date to VirusTotal in a descending fashion.
"""
params = dict(apikey=self.api_key, query=query, offset=offset)
try:
response = requests.get(self.base + 'file/search', params=params, proxies=self.proxies, timeout=timeout)
except requests.RequestException as e:
return dict(error=str(e))
return _return_response_and_status_code(response) | python | def file_search(self, query, offset=None, timeout=None):
params = dict(apikey=self.api_key, query=query, offset=offset)
try:
response = requests.get(self.base + 'file/search', params=params, proxies=self.proxies, timeout=timeout)
except requests.RequestException as e:
return dict(error=str(e))
return _return_response_and_status_code(response) | [
"def",
"file_search",
"(",
"self",
",",
"query",
",",
"offset",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
"params",
"=",
"dict",
"(",
"apikey",
"=",
"self",
".",
"api_key",
",",
"query",
"=",
"query",
",",
"offset",
"=",
"offset",
")",
"t... | Search for samples.
In addition to retrieving all information on a particular file, VirusTotal allows you to perform what we
call "advanced reverse searches". Reverse searches take you from a file property to a list of files that
match that property. For example, this functionality enables you to retrieve all those files marked by at
least one antivirus vendor as Zbot, or all those files that have a size under 90KB and are detected by at
least 10 antivirus solutions, or all those PDF files that have an invalid XREF section, etc.
This API is equivalent to VirusTotal Intelligence advanced searches. A very wide variety of search modifiers
are available, including: file size, file type, first submission date to VirusTotal, last submission date to
VirusTotal, number of positives, dynamic behavioural properties, binary content, submission file name, and a
very long etcetera. The full list of search modifiers allowed for file search queries is documented at:
https://www.virustotal.com/intelligence/help/file-search/#search-modifiers
NOTE:
Daily limited! No matter what API step you have licensed, this API call is limited to 50K requests per day.
If you need any more, chances are you are approaching your engineering problem erroneously and you can
probably solve it using the file distribution call. Do not hesitate to contact us with your particular
use case.
EXAMPLE:
search_options = 'type:peexe size:90kb+ positives:5+ behaviour:"taskkill"'
:param query: A search modifier compliant file search query.
:param offset: (optional) The offset value returned by a previously issued identical query, allows you to
paginate over the results. If not specified the first 300 matching files sorted according to last submission
date to VirusTotal in a descending fashion will be returned.
:param timeout: The amount of time in seconds the request should wait before timing out.
:return: JSON response - By default the list returned contains at most 300 hashes, ordered according to
last submission date to VirusTotal in a descending fashion. | [
"Search",
"for",
"samples",
"."
] | 4e01e1c6d87255ec8370ac2a4ee16edce00e1e86 | https://github.com/blacktop/virustotal-api/blob/4e01e1c6d87255ec8370ac2a4ee16edce00e1e86/virus_total_apis/api.py#L469-L509 |
20,407 | blacktop/virustotal-api | virus_total_apis/api.py | PrivateApi.get_file_clusters | def get_file_clusters(self, this_date, timeout=None):
""" File similarity clusters for a given time frame.
VirusTotal has built its own in-house file similarity clustering functionality. At present, this clustering
works only on PE, PDF, DOC and RTF files and is based on a very simple structural feature hash. This hash
can very often be confused by certain compression and packing strategies, in other words, this clustering
logic is no holly grail, yet it has proven itself very useful in the past.
This API offers a programmatic access to the clustering section of VirusTotal Intelligence:
https://www.virustotal.com/intelligence/clustering/
NOTE:
Please note that you must be logged in with a valid VirusTotal Community user account with access to
VirusTotal Intelligence in order to be able to view the clustering listing.
:param this_date: A specific day for which we want to access the clustering details, example: 2013-09-10.
:param timeout: The amount of time in seconds the request should wait before timing out.
:return: JSON object contains several properties
num_candidates - Total number of files submitted during the given time frame for which a feature hash could
be calculated.
num_clusters - Total number of clusters generated for the given time period under consideration, a cluster
can be as small as an individual file, meaning that no other feature-wise similar file was
found.
size_top200 - The sum of the number of files in the 200 largest clusters identified.
clusters - List of JSON objects that contain details about the 200 largest clusters identified. These
objects contain 4 properties: id, label, size and avg_positives.. The id field can be used
to then query the search API call for files contained in the given cluster. The label
property is a verbose human-intelligible name for the cluster. The size field is the number
of files that make up the cluster. Finally, avg_positives represents the average number of
antivirus detections that the files in the cluster exhibit.
"""
params = {'apikey': self.api_key, 'date': this_date}
try:
response = requests.get(self.base + 'file/clusters', params=params, proxies=self.proxies, timeout=timeout)
except requests.RequestException as e:
return dict(error=str(e))
return _return_response_and_status_code(response) | python | def get_file_clusters(self, this_date, timeout=None):
params = {'apikey': self.api_key, 'date': this_date}
try:
response = requests.get(self.base + 'file/clusters', params=params, proxies=self.proxies, timeout=timeout)
except requests.RequestException as e:
return dict(error=str(e))
return _return_response_and_status_code(response) | [
"def",
"get_file_clusters",
"(",
"self",
",",
"this_date",
",",
"timeout",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'apikey'",
":",
"self",
".",
"api_key",
",",
"'date'",
":",
"this_date",
"}",
"try",
":",
"response",
"=",
"requests",
".",
"get",
"(... | File similarity clusters for a given time frame.
VirusTotal has built its own in-house file similarity clustering functionality. At present, this clustering
works only on PE, PDF, DOC and RTF files and is based on a very simple structural feature hash. This hash
can very often be confused by certain compression and packing strategies, in other words, this clustering
logic is no holly grail, yet it has proven itself very useful in the past.
This API offers a programmatic access to the clustering section of VirusTotal Intelligence:
https://www.virustotal.com/intelligence/clustering/
NOTE:
Please note that you must be logged in with a valid VirusTotal Community user account with access to
VirusTotal Intelligence in order to be able to view the clustering listing.
:param this_date: A specific day for which we want to access the clustering details, example: 2013-09-10.
:param timeout: The amount of time in seconds the request should wait before timing out.
:return: JSON object contains several properties
num_candidates - Total number of files submitted during the given time frame for which a feature hash could
be calculated.
num_clusters - Total number of clusters generated for the given time period under consideration, a cluster
can be as small as an individual file, meaning that no other feature-wise similar file was
found.
size_top200 - The sum of the number of files in the 200 largest clusters identified.
clusters - List of JSON objects that contain details about the 200 largest clusters identified. These
objects contain 4 properties: id, label, size and avg_positives.. The id field can be used
to then query the search API call for files contained in the given cluster. The label
property is a verbose human-intelligible name for the cluster. The size field is the number
of files that make up the cluster. Finally, avg_positives represents the average number of
antivirus detections that the files in the cluster exhibit. | [
"File",
"similarity",
"clusters",
"for",
"a",
"given",
"time",
"frame",
"."
] | 4e01e1c6d87255ec8370ac2a4ee16edce00e1e86 | https://github.com/blacktop/virustotal-api/blob/4e01e1c6d87255ec8370ac2a4ee16edce00e1e86/virus_total_apis/api.py#L511-L550 |
20,408 | blacktop/virustotal-api | virus_total_apis/api.py | PrivateApi.get_url_distribution | def get_url_distribution(self, after=None, reports='true', limit=1000, timeout=None):
""" Get a live feed with the lastest URLs submitted to VirusTotal.
Allows you to retrieve a live feed of URLs submitted to VirusTotal, along with their scan reports. This
call enables you to stay synced with VirusTotal URL submissions and replicate our dataset.
:param after: (optional) Retrieve URLs received after the given timestamp, in timestamp ascending order.
:param reports: (optional) When set to "true" each item retrieved will include the results for each particular
URL scan (in exactly the same format as the URL scan retrieving API). If the parameter is not specified, each
item returned will only contain the scanned URL and its detection ratio.
:param limit: (optional) Retrieve limit file items at most (default: 1000).
:param timeout: The amount of time in seconds the request should wait before timing out.
:return: JSON response
"""
params = {'apikey': self.api_key, 'after': after, 'reports': reports, 'limit': limit}
try:
response = requests.get(self.base + 'url/distribution',
params=params,
proxies=self.proxies,
timeout=timeout)
except requests.RequestException as e:
return dict(error=str(e))
return _return_response_and_status_code(response) | python | def get_url_distribution(self, after=None, reports='true', limit=1000, timeout=None):
params = {'apikey': self.api_key, 'after': after, 'reports': reports, 'limit': limit}
try:
response = requests.get(self.base + 'url/distribution',
params=params,
proxies=self.proxies,
timeout=timeout)
except requests.RequestException as e:
return dict(error=str(e))
return _return_response_and_status_code(response) | [
"def",
"get_url_distribution",
"(",
"self",
",",
"after",
"=",
"None",
",",
"reports",
"=",
"'true'",
",",
"limit",
"=",
"1000",
",",
"timeout",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'apikey'",
":",
"self",
".",
"api_key",
",",
"'after'",
":",
... | Get a live feed with the lastest URLs submitted to VirusTotal.
Allows you to retrieve a live feed of URLs submitted to VirusTotal, along with their scan reports. This
call enables you to stay synced with VirusTotal URL submissions and replicate our dataset.
:param after: (optional) Retrieve URLs received after the given timestamp, in timestamp ascending order.
:param reports: (optional) When set to "true" each item retrieved will include the results for each particular
URL scan (in exactly the same format as the URL scan retrieving API). If the parameter is not specified, each
item returned will only contain the scanned URL and its detection ratio.
:param limit: (optional) Retrieve limit file items at most (default: 1000).
:param timeout: The amount of time in seconds the request should wait before timing out.
:return: JSON response | [
"Get",
"a",
"live",
"feed",
"with",
"the",
"lastest",
"URLs",
"submitted",
"to",
"VirusTotal",
"."
] | 4e01e1c6d87255ec8370ac2a4ee16edce00e1e86 | https://github.com/blacktop/virustotal-api/blob/4e01e1c6d87255ec8370ac2a4ee16edce00e1e86/virus_total_apis/api.py#L663-L689 |
20,409 | blacktop/virustotal-api | virus_total_apis/api.py | PrivateApi.get_url_feed | def get_url_feed(self, package=None, timeout=None):
""" Get a live file feed with the latest files submitted to VirusTotal.
Allows you to retrieve a live feed of reports on absolutely all URLs scanned by VirusTotal. This API requires
you to stay relatively synced with the live submissions as only a backlog of 24 hours is provided at any given
point in time.
This API returns a bzip2 compressed tarball. For per-minute packages the compressed package contains a unique
file, the file contains a json per line, this json is a full report on a given URL processed by VirusTotal
during the given time window. The URL report follows the exact same format as the response of the URL report
API if the allinfo=1 parameter is provided. For hourly packages, the tarball contains 60 files, one per each
minute of the window.
:param package: Indicates a time window to pull reports on all items received during such window.
Only per-minute and hourly windows are allowed, the format is %Y%m%dT%H%M (e.g. 20160304T0900)
or %Y%m%dT%H (e.g. 20160304T09). Time is expressed in UTC.
:param timeout: The amount of time in seconds the request should wait before timing out.
:return: BZIP2 response: please see https://www.virustotal.com/en/documentation/private-api/#file-feed
"""
if package is None:
now = datetime.utcnow()
five_minutes_ago = now - timedelta(
minutes=now.minute % 5 + 5, seconds=now.second, microseconds=now.microsecond)
package = five_minutes_ago.strftime('%Y%m%dT%H%M')
params = {'apikey': self.api_key, 'package': package}
try:
response = requests.get(self.base + 'url/feed', params=params, proxies=self.proxies, timeout=timeout)
except requests.RequestException as e:
return dict(error=str(e))
return _return_response_and_status_code(response, json_results=False) | python | def get_url_feed(self, package=None, timeout=None):
if package is None:
now = datetime.utcnow()
five_minutes_ago = now - timedelta(
minutes=now.minute % 5 + 5, seconds=now.second, microseconds=now.microsecond)
package = five_minutes_ago.strftime('%Y%m%dT%H%M')
params = {'apikey': self.api_key, 'package': package}
try:
response = requests.get(self.base + 'url/feed', params=params, proxies=self.proxies, timeout=timeout)
except requests.RequestException as e:
return dict(error=str(e))
return _return_response_and_status_code(response, json_results=False) | [
"def",
"get_url_feed",
"(",
"self",
",",
"package",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"package",
"is",
"None",
":",
"now",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"five_minutes_ago",
"=",
"now",
"-",
"timedelta",
"(",
"minutes... | Get a live file feed with the latest files submitted to VirusTotal.
Allows you to retrieve a live feed of reports on absolutely all URLs scanned by VirusTotal. This API requires
you to stay relatively synced with the live submissions as only a backlog of 24 hours is provided at any given
point in time.
This API returns a bzip2 compressed tarball. For per-minute packages the compressed package contains a unique
file, the file contains a json per line, this json is a full report on a given URL processed by VirusTotal
during the given time window. The URL report follows the exact same format as the response of the URL report
API if the allinfo=1 parameter is provided. For hourly packages, the tarball contains 60 files, one per each
minute of the window.
:param package: Indicates a time window to pull reports on all items received during such window.
Only per-minute and hourly windows are allowed, the format is %Y%m%dT%H%M (e.g. 20160304T0900)
or %Y%m%dT%H (e.g. 20160304T09). Time is expressed in UTC.
:param timeout: The amount of time in seconds the request should wait before timing out.
:return: BZIP2 response: please see https://www.virustotal.com/en/documentation/private-api/#file-feed | [
"Get",
"a",
"live",
"file",
"feed",
"with",
"the",
"latest",
"files",
"submitted",
"to",
"VirusTotal",
"."
] | 4e01e1c6d87255ec8370ac2a4ee16edce00e1e86 | https://github.com/blacktop/virustotal-api/blob/4e01e1c6d87255ec8370ac2a4ee16edce00e1e86/virus_total_apis/api.py#L691-L724 |
20,410 | blacktop/virustotal-api | virus_total_apis/api.py | IntelApi.get_intel_notifications_feed | def get_intel_notifications_feed(self, page=None, timeout=None):
""" Get notification feed in JSON for further processing.
:param page: the next_page property of the results of a previously issued query to this API. This parameter
should not be provided if it is the very first query to the API, i.e. if we are retrieving the
first page of results.
:param timeout: The amount of time in seconds the request should wait before timing out.
:returns: The next page identifier, The results (JSON is possible with .json())
"""
params = {'apikey': self.api_key, 'next': page}
try:
response = requests.get(self.base + 'hunting/notifications-feed/',
params=params,
proxies=self.proxies,
timeout=timeout)
# VT returns an empty result, len(content)==0, and status OK if there are no pending notifications.
# To keep the API consistent we generate an empty object instead.
# This might not be necessary with a later release of the VTI API. (bug has been submitted)
if len(response.content) == 0:
response.__dict__['_content'] = \
b'{"notifications":[],"verbose_msg":"No pending notification","result":0,"next":null}'
except requests.RequestException as e:
return dict(error=str(e))
return _return_response_and_status_code(response) | python | def get_intel_notifications_feed(self, page=None, timeout=None):
params = {'apikey': self.api_key, 'next': page}
try:
response = requests.get(self.base + 'hunting/notifications-feed/',
params=params,
proxies=self.proxies,
timeout=timeout)
# VT returns an empty result, len(content)==0, and status OK if there are no pending notifications.
# To keep the API consistent we generate an empty object instead.
# This might not be necessary with a later release of the VTI API. (bug has been submitted)
if len(response.content) == 0:
response.__dict__['_content'] = \
b'{"notifications":[],"verbose_msg":"No pending notification","result":0,"next":null}'
except requests.RequestException as e:
return dict(error=str(e))
return _return_response_and_status_code(response) | [
"def",
"get_intel_notifications_feed",
"(",
"self",
",",
"page",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'apikey'",
":",
"self",
".",
"api_key",
",",
"'next'",
":",
"page",
"}",
"try",
":",
"response",
"=",
"requests",
... | Get notification feed in JSON for further processing.
:param page: the next_page property of the results of a previously issued query to this API. This parameter
should not be provided if it is the very first query to the API, i.e. if we are retrieving the
first page of results.
:param timeout: The amount of time in seconds the request should wait before timing out.
:returns: The next page identifier, The results (JSON is possible with .json()) | [
"Get",
"notification",
"feed",
"in",
"JSON",
"for",
"further",
"processing",
"."
] | 4e01e1c6d87255ec8370ac2a4ee16edce00e1e86 | https://github.com/blacktop/virustotal-api/blob/4e01e1c6d87255ec8370ac2a4ee16edce00e1e86/virus_total_apis/api.py#L887-L911 |
20,411 | blacktop/virustotal-api | virus_total_apis/api.py | IntelApi.delete_intel_notifications | def delete_intel_notifications(self, ids, timeout=None):
""" Programmatically delete notifications via the Intel API.
:param ids: A list of IDs to delete from the notification feed.
:returns: The post response.
"""
if not isinstance(ids, list):
raise TypeError("ids must be a list")
# VirusTotal needs ids as a stringified array
data = json.dumps(ids)
try:
response = requests.post(
self.base + 'hunting/delete-notifications/programmatic/?key=' + self.api_key,
data=data,
proxies=self.proxies,
timeout=timeout)
except requests.RequestException as e:
return dict(error=str(e))
return _return_response_and_status_code(response) | python | def delete_intel_notifications(self, ids, timeout=None):
if not isinstance(ids, list):
raise TypeError("ids must be a list")
# VirusTotal needs ids as a stringified array
data = json.dumps(ids)
try:
response = requests.post(
self.base + 'hunting/delete-notifications/programmatic/?key=' + self.api_key,
data=data,
proxies=self.proxies,
timeout=timeout)
except requests.RequestException as e:
return dict(error=str(e))
return _return_response_and_status_code(response) | [
"def",
"delete_intel_notifications",
"(",
"self",
",",
"ids",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"ids",
",",
"list",
")",
":",
"raise",
"TypeError",
"(",
"\"ids must be a list\"",
")",
"# VirusTotal needs ids as a stringified ar... | Programmatically delete notifications via the Intel API.
:param ids: A list of IDs to delete from the notification feed.
:returns: The post response. | [
"Programmatically",
"delete",
"notifications",
"via",
"the",
"Intel",
"API",
"."
] | 4e01e1c6d87255ec8370ac2a4ee16edce00e1e86 | https://github.com/blacktop/virustotal-api/blob/4e01e1c6d87255ec8370ac2a4ee16edce00e1e86/virus_total_apis/api.py#L913-L934 |
20,412 | localstack/localstack-python-client | localstack_client/session.py | Session.get_credentials | def get_credentials(self):
"""
Returns botocore.credential.Credential object.
"""
return Credentials(access_key=self.aws_access_key_id,
secret_key=self.aws_secret_access_key,
token=self.aws_session_token) | python | def get_credentials(self):
return Credentials(access_key=self.aws_access_key_id,
secret_key=self.aws_secret_access_key,
token=self.aws_session_token) | [
"def",
"get_credentials",
"(",
"self",
")",
":",
"return",
"Credentials",
"(",
"access_key",
"=",
"self",
".",
"aws_access_key_id",
",",
"secret_key",
"=",
"self",
".",
"aws_secret_access_key",
",",
"token",
"=",
"self",
".",
"aws_session_token",
")"
] | Returns botocore.credential.Credential object. | [
"Returns",
"botocore",
".",
"credential",
".",
"Credential",
"object",
"."
] | 62ab3f3d5ce94105f8374963397dfbf05d4f0642 | https://github.com/localstack/localstack-python-client/blob/62ab3f3d5ce94105f8374963397dfbf05d4f0642/localstack_client/session.py#L25-L31 |
20,413 | fabric-bolt/fabric-bolt | fabric_bolt/hosts/views.py | HostCreate.form_valid | def form_valid(self, form):
"""First call the parent's form valid then let the user know it worked."""
form_valid_from_parent = super(HostCreate, self).form_valid(form)
messages.success(self.request, 'Host {} Successfully Created'.format(self.object))
return form_valid_from_parent | python | def form_valid(self, form):
form_valid_from_parent = super(HostCreate, self).form_valid(form)
messages.success(self.request, 'Host {} Successfully Created'.format(self.object))
return form_valid_from_parent | [
"def",
"form_valid",
"(",
"self",
",",
"form",
")",
":",
"form_valid_from_parent",
"=",
"super",
"(",
"HostCreate",
",",
"self",
")",
".",
"form_valid",
"(",
"form",
")",
"messages",
".",
"success",
"(",
"self",
".",
"request",
",",
"'Host {} Successfully Cr... | First call the parent's form valid then let the user know it worked. | [
"First",
"call",
"the",
"parent",
"s",
"form",
"valid",
"then",
"let",
"the",
"user",
"know",
"it",
"worked",
"."
] | 0f434783026f1b9ce16a416fa496d76921fe49ca | https://github.com/fabric-bolt/fabric-bolt/blob/0f434783026f1b9ce16a416fa496d76921fe49ca/fabric_bolt/hosts/views.py#L30-L36 |
20,414 | fabric-bolt/fabric-bolt | fabric_bolt/hosts/views.py | SSHKeys.post | def post(self, *args, **kwargs):
"""Create the SSH file & then return the normal get method..."""
existing_ssh = models.SSHConfig.objects.all()
if existing_ssh.exists():
return self.get_view()
remote_user = self.request.POST.get('remote_user', 'root')
create_ssh_config(remote_user=remote_user)
return self.get_view() | python | def post(self, *args, **kwargs):
existing_ssh = models.SSHConfig.objects.all()
if existing_ssh.exists():
return self.get_view()
remote_user = self.request.POST.get('remote_user', 'root')
create_ssh_config(remote_user=remote_user)
return self.get_view() | [
"def",
"post",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"existing_ssh",
"=",
"models",
".",
"SSHConfig",
".",
"objects",
".",
"all",
"(",
")",
"if",
"existing_ssh",
".",
"exists",
"(",
")",
":",
"return",
"self",
".",
"get_... | Create the SSH file & then return the normal get method... | [
"Create",
"the",
"SSH",
"file",
"&",
"then",
"return",
"the",
"normal",
"get",
"method",
"..."
] | 0f434783026f1b9ce16a416fa496d76921fe49ca | https://github.com/fabric-bolt/fabric-bolt/blob/0f434783026f1b9ce16a416fa496d76921fe49ca/fabric_bolt/hosts/views.py#L79-L91 |
20,415 | fabric-bolt/fabric-bolt | fabric_bolt/fabfile.py | update_sandbox_site | def update_sandbox_site(comment_text):
"""put's a text file on the server"""
file_to_deliver = NamedTemporaryFile(delete=False)
file_text = "Deployed at: {} <br /> Comment: {}".format(datetime.datetime.now().strftime('%c'), cgi.escape(comment_text))
file_to_deliver.write(file_text)
file_to_deliver.close()
put(file_to_deliver.name, '/var/www/html/index.html', use_sudo=True) | python | def update_sandbox_site(comment_text):
file_to_deliver = NamedTemporaryFile(delete=False)
file_text = "Deployed at: {} <br /> Comment: {}".format(datetime.datetime.now().strftime('%c'), cgi.escape(comment_text))
file_to_deliver.write(file_text)
file_to_deliver.close()
put(file_to_deliver.name, '/var/www/html/index.html', use_sudo=True) | [
"def",
"update_sandbox_site",
"(",
"comment_text",
")",
":",
"file_to_deliver",
"=",
"NamedTemporaryFile",
"(",
"delete",
"=",
"False",
")",
"file_text",
"=",
"\"Deployed at: {} <br /> Comment: {}\"",
".",
"format",
"(",
"datetime",
".",
"datetime",
".",
"now",
"(",... | put's a text file on the server | [
"put",
"s",
"a",
"text",
"file",
"on",
"the",
"server"
] | 0f434783026f1b9ce16a416fa496d76921fe49ca | https://github.com/fabric-bolt/fabric-bolt/blob/0f434783026f1b9ce16a416fa496d76921fe49ca/fabric_bolt/fabfile.py#L133-L143 |
20,416 | fabric-bolt/fabric-bolt | fabric_bolt/projects/models.py | Project.web_hooks | def web_hooks(self, include_global=True):
"""Get all web hooks for this project. Includes global hooks."""
from fabric_bolt.web_hooks.models import Hook
ors = [Q(project=self)]
if include_global:
ors.append(Q(project=None))
hooks = Hook.objects.filter(reduce(operator.or_, ors))
return hooks | python | def web_hooks(self, include_global=True):
from fabric_bolt.web_hooks.models import Hook
ors = [Q(project=self)]
if include_global:
ors.append(Q(project=None))
hooks = Hook.objects.filter(reduce(operator.or_, ors))
return hooks | [
"def",
"web_hooks",
"(",
"self",
",",
"include_global",
"=",
"True",
")",
":",
"from",
"fabric_bolt",
".",
"web_hooks",
".",
"models",
"import",
"Hook",
"ors",
"=",
"[",
"Q",
"(",
"project",
"=",
"self",
")",
"]",
"if",
"include_global",
":",
"ors",
".... | Get all web hooks for this project. Includes global hooks. | [
"Get",
"all",
"web",
"hooks",
"for",
"this",
"project",
".",
"Includes",
"global",
"hooks",
"."
] | 0f434783026f1b9ce16a416fa496d76921fe49ca | https://github.com/fabric-bolt/fabric-bolt/blob/0f434783026f1b9ce16a416fa496d76921fe49ca/fabric_bolt/projects/models.py#L54-L64 |
20,417 | fabric-bolt/fabric-bolt | fabric_bolt/projects/models.py | Project.get_deployment_count | def get_deployment_count(self):
"""Utility function to get the number of deployments a given project has"""
ret = self.stage_set.annotate(num_deployments=Count('deployment')).aggregate(total_deployments=Sum('num_deployments'))
return ret['total_deployments'] | python | def get_deployment_count(self):
ret = self.stage_set.annotate(num_deployments=Count('deployment')).aggregate(total_deployments=Sum('num_deployments'))
return ret['total_deployments'] | [
"def",
"get_deployment_count",
"(",
"self",
")",
":",
"ret",
"=",
"self",
".",
"stage_set",
".",
"annotate",
"(",
"num_deployments",
"=",
"Count",
"(",
"'deployment'",
")",
")",
".",
"aggregate",
"(",
"total_deployments",
"=",
"Sum",
"(",
"'num_deployments'",
... | Utility function to get the number of deployments a given project has | [
"Utility",
"function",
"to",
"get",
"the",
"number",
"of",
"deployments",
"a",
"given",
"project",
"has"
] | 0f434783026f1b9ce16a416fa496d76921fe49ca | https://github.com/fabric-bolt/fabric-bolt/blob/0f434783026f1b9ce16a416fa496d76921fe49ca/fabric_bolt/projects/models.py#L66-L70 |
20,418 | fabric-bolt/fabric-bolt | fabric_bolt/projects/models.py | Stage.get_configurations | def get_configurations(self):
"""
Generates a dictionary that's made up of the configurations on the project.
Any configurations on a project that are duplicated on a stage, the stage configuration will take precedence.
"""
project_configurations_dictionary = {}
project_configurations = self.project.project_configurations()
# Create project specific configurations dictionary
for config in project_configurations:
project_configurations_dictionary[config.key] = config
stage_configurations_dictionary = {}
stage_configurations = self.stage_configurations()
# Create stage specific configurations dictionary
for s in stage_configurations:
stage_configurations_dictionary[s.key] = s
# override project specific configuration with the ones in the stage if they are there
project_configurations_dictionary.update(stage_configurations_dictionary)
# Return the updated configurations
return project_configurations_dictionary | python | def get_configurations(self):
project_configurations_dictionary = {}
project_configurations = self.project.project_configurations()
# Create project specific configurations dictionary
for config in project_configurations:
project_configurations_dictionary[config.key] = config
stage_configurations_dictionary = {}
stage_configurations = self.stage_configurations()
# Create stage specific configurations dictionary
for s in stage_configurations:
stage_configurations_dictionary[s.key] = s
# override project specific configuration with the ones in the stage if they are there
project_configurations_dictionary.update(stage_configurations_dictionary)
# Return the updated configurations
return project_configurations_dictionary | [
"def",
"get_configurations",
"(",
"self",
")",
":",
"project_configurations_dictionary",
"=",
"{",
"}",
"project_configurations",
"=",
"self",
".",
"project",
".",
"project_configurations",
"(",
")",
"# Create project specific configurations dictionary",
"for",
"config",
... | Generates a dictionary that's made up of the configurations on the project.
Any configurations on a project that are duplicated on a stage, the stage configuration will take precedence. | [
"Generates",
"a",
"dictionary",
"that",
"s",
"made",
"up",
"of",
"the",
"configurations",
"on",
"the",
"project",
".",
"Any",
"configurations",
"on",
"a",
"project",
"that",
"are",
"duplicated",
"on",
"a",
"stage",
"the",
"stage",
"configuration",
"will",
"t... | 0f434783026f1b9ce16a416fa496d76921fe49ca | https://github.com/fabric-bolt/fabric-bolt/blob/0f434783026f1b9ce16a416fa496d76921fe49ca/fabric_bolt/projects/models.py#L133-L157 |
20,419 | fabric-bolt/fabric-bolt | fabric_bolt/projects/models.py | Configuration.get_absolute_url | def get_absolute_url(self):
"""Determine where I am coming from and where I am going"""
# Determine if this configuration is on a stage
if self.stage:
# Stage specific configurations go back to the stage view
url = reverse('projects_stage_view', args=(self.project.pk, self.stage.pk))
else:
# Project specific configurations go back to the project page
url = self.project.get_absolute_url()
return url | python | def get_absolute_url(self):
# Determine if this configuration is on a stage
if self.stage:
# Stage specific configurations go back to the stage view
url = reverse('projects_stage_view', args=(self.project.pk, self.stage.pk))
else:
# Project specific configurations go back to the project page
url = self.project.get_absolute_url()
return url | [
"def",
"get_absolute_url",
"(",
"self",
")",
":",
"# Determine if this configuration is on a stage",
"if",
"self",
".",
"stage",
":",
"# Stage specific configurations go back to the stage view",
"url",
"=",
"reverse",
"(",
"'projects_stage_view'",
",",
"args",
"=",
"(",
"... | Determine where I am coming from and where I am going | [
"Determine",
"where",
"I",
"am",
"coming",
"from",
"and",
"where",
"I",
"am",
"going"
] | 0f434783026f1b9ce16a416fa496d76921fe49ca | https://github.com/fabric-bolt/fabric-bolt/blob/0f434783026f1b9ce16a416fa496d76921fe49ca/fabric_bolt/projects/models.py#L215-L226 |
20,420 | fabric-bolt/fabric-bolt | fabric_bolt/accounts/models.py | DeployUser.gravatar | def gravatar(self, size=20):
"""
Construct a gravatar image address for the user
"""
default = "mm"
gravatar_url = "//www.gravatar.com/avatar/" + hashlib.md5(self.email.lower()).hexdigest() + "?"
gravatar_url += urllib.urlencode({'d': default, 's': str(size)})
return gravatar_url | python | def gravatar(self, size=20):
default = "mm"
gravatar_url = "//www.gravatar.com/avatar/" + hashlib.md5(self.email.lower()).hexdigest() + "?"
gravatar_url += urllib.urlencode({'d': default, 's': str(size)})
return gravatar_url | [
"def",
"gravatar",
"(",
"self",
",",
"size",
"=",
"20",
")",
":",
"default",
"=",
"\"mm\"",
"gravatar_url",
"=",
"\"//www.gravatar.com/avatar/\"",
"+",
"hashlib",
".",
"md5",
"(",
"self",
".",
"email",
".",
"lower",
"(",
")",
")",
".",
"hexdigest",
"(",
... | Construct a gravatar image address for the user | [
"Construct",
"a",
"gravatar",
"image",
"address",
"for",
"the",
"user"
] | 0f434783026f1b9ce16a416fa496d76921fe49ca | https://github.com/fabric-bolt/fabric-bolt/blob/0f434783026f1b9ce16a416fa496d76921fe49ca/fabric_bolt/accounts/models.py#L65-L74 |
20,421 | fabric-bolt/fabric-bolt | fabric_bolt/web_hooks/managers.py | HookManager.hooks | def hooks(self, project):
""" Look up the urls we need to post to"""
return self.get_queryset().filter(
Q(project=None) |
Q(project=project)
).distinct('url') | python | def hooks(self, project):
return self.get_queryset().filter(
Q(project=None) |
Q(project=project)
).distinct('url') | [
"def",
"hooks",
"(",
"self",
",",
"project",
")",
":",
"return",
"self",
".",
"get_queryset",
"(",
")",
".",
"filter",
"(",
"Q",
"(",
"project",
"=",
"None",
")",
"|",
"Q",
"(",
"project",
"=",
"project",
")",
")",
".",
"distinct",
"(",
"'url'",
... | Look up the urls we need to post to | [
"Look",
"up",
"the",
"urls",
"we",
"need",
"to",
"post",
"to"
] | 0f434783026f1b9ce16a416fa496d76921fe49ca | https://github.com/fabric-bolt/fabric-bolt/blob/0f434783026f1b9ce16a416fa496d76921fe49ca/fabric_bolt/web_hooks/managers.py#L7-L13 |
20,422 | fabric-bolt/fabric-bolt | fabric_bolt/web_hooks/receivers.py | web_hook_receiver | def web_hook_receiver(sender, **kwargs):
"""Generic receiver for the web hook firing piece."""
deployment = Deployment.objects.get(pk=kwargs.get('deployment_id'))
hooks = deployment.web_hooks
if not hooks:
return
for hook in hooks:
data = payload_generator(deployment)
deliver_hook(deployment, hook.url, data) | python | def web_hook_receiver(sender, **kwargs):
deployment = Deployment.objects.get(pk=kwargs.get('deployment_id'))
hooks = deployment.web_hooks
if not hooks:
return
for hook in hooks:
data = payload_generator(deployment)
deliver_hook(deployment, hook.url, data) | [
"def",
"web_hook_receiver",
"(",
"sender",
",",
"*",
"*",
"kwargs",
")",
":",
"deployment",
"=",
"Deployment",
".",
"objects",
".",
"get",
"(",
"pk",
"=",
"kwargs",
".",
"get",
"(",
"'deployment_id'",
")",
")",
"hooks",
"=",
"deployment",
".",
"web_hooks... | Generic receiver for the web hook firing piece. | [
"Generic",
"receiver",
"for",
"the",
"web",
"hook",
"firing",
"piece",
"."
] | 0f434783026f1b9ce16a416fa496d76921fe49ca | https://github.com/fabric-bolt/fabric-bolt/blob/0f434783026f1b9ce16a416fa496d76921fe49ca/fabric_bolt/web_hooks/receivers.py#L9-L23 |
20,423 | fabric-bolt/fabric-bolt | fabric_bolt/core/mixins/tables.py | PaginateTable.paginate | def paginate(self, klass=Paginator, per_page=None, page=1, *args, **kwargs):
"""
Paginates the table using a paginator and creates a ``page`` property
containing information for the current page.
:type klass: Paginator class
:param klass: a paginator class to paginate the results
:type per_page: `int`
:param per_page: how many records are displayed on each page
:type page: `int`
:param page: which page should be displayed.
Extra arguments are passed to the paginator.
Pagination exceptions (`~django.core.paginator.EmptyPage` and
`~django.core.paginator.PageNotAnInteger`) may be raised from this
method and should be handled by the caller.
"""
self.per_page_options = [25, 50, 100, 200] # This should probably be a passed in option
self.per_page = per_page = per_page or self._meta.per_page
self.paginator = klass(self.rows, per_page, *args, **kwargs)
self.page = self.paginator.page(page)
# Calc variables for use in displaying first, adjacent, and last page links
adjacent_pages = 1 # This should probably be a passed in option
# Starting page (first page between the ellipsis)
start_page = max(self.page.number - adjacent_pages, 1)
if start_page <= 3:
start_page = 1
# Ending page (last page between the ellipsis)
end_page = self.page.number + adjacent_pages + 1
if end_page >= self.paginator.num_pages - 1:
end_page = self.paginator.num_pages + 1
# Paging vars used in template
self.page_numbers = [n for n in range(start_page, end_page) if 0 < n <= self.paginator.num_pages]
self.show_first = 1 not in self.page_numbers
self.show_last = self.paginator.num_pages not in self.page_numbers | python | def paginate(self, klass=Paginator, per_page=None, page=1, *args, **kwargs):
self.per_page_options = [25, 50, 100, 200] # This should probably be a passed in option
self.per_page = per_page = per_page or self._meta.per_page
self.paginator = klass(self.rows, per_page, *args, **kwargs)
self.page = self.paginator.page(page)
# Calc variables for use in displaying first, adjacent, and last page links
adjacent_pages = 1 # This should probably be a passed in option
# Starting page (first page between the ellipsis)
start_page = max(self.page.number - adjacent_pages, 1)
if start_page <= 3:
start_page = 1
# Ending page (last page between the ellipsis)
end_page = self.page.number + adjacent_pages + 1
if end_page >= self.paginator.num_pages - 1:
end_page = self.paginator.num_pages + 1
# Paging vars used in template
self.page_numbers = [n for n in range(start_page, end_page) if 0 < n <= self.paginator.num_pages]
self.show_first = 1 not in self.page_numbers
self.show_last = self.paginator.num_pages not in self.page_numbers | [
"def",
"paginate",
"(",
"self",
",",
"klass",
"=",
"Paginator",
",",
"per_page",
"=",
"None",
",",
"page",
"=",
"1",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"per_page_options",
"=",
"[",
"25",
",",
"50",
",",
"100",
",",... | Paginates the table using a paginator and creates a ``page`` property
containing information for the current page.
:type klass: Paginator class
:param klass: a paginator class to paginate the results
:type per_page: `int`
:param per_page: how many records are displayed on each page
:type page: `int`
:param page: which page should be displayed.
Extra arguments are passed to the paginator.
Pagination exceptions (`~django.core.paginator.EmptyPage` and
`~django.core.paginator.PageNotAnInteger`) may be raised from this
method and should be handled by the caller. | [
"Paginates",
"the",
"table",
"using",
"a",
"paginator",
"and",
"creates",
"a",
"page",
"property",
"containing",
"information",
"for",
"the",
"current",
"page",
"."
] | 0f434783026f1b9ce16a416fa496d76921fe49ca | https://github.com/fabric-bolt/fabric-bolt/blob/0f434783026f1b9ce16a416fa496d76921fe49ca/fabric_bolt/core/mixins/tables.py#L79-L121 |
20,424 | fabric-bolt/fabric-bolt | fabric_bolt/task_runners/base.py | BaseTaskRunnerBackend.get_fabric_tasks | def get_fabric_tasks(self, project):
"""
Generate a list of fabric tasks that are available
"""
cache_key = 'project_{}_fabfile_tasks'.format(project.pk)
cached_result = cache.get(cache_key)
if cached_result:
return cached_result
try:
fabfile_path, activate_loc = self.get_fabfile_path(project)
if activate_loc:
output = self.check_output(
'source {};fab --list --list-format=short --fabfile={}'.format(activate_loc, fabfile_path),
shell=True
)
else:
output = self.check_output(
'fab --list --list-format=short --fabfile={}'.format(fabfile_path),
shell=True
)
lines = output.splitlines()
tasks = []
for line in lines:
name = line.strip()
if activate_loc:
o = self.check_output(
'source {};fab --display={} --fabfile={}'.format(activate_loc, name, fabfile_path),
shell=True
)
else:
o = self.check_output(
['fab', '--display={}'.format(name), '--fabfile={}'.format(fabfile_path)]
)
tasks.append(self.parse_task_details(name, o))
cache.set(cache_key, tasks, settings.FABRIC_TASK_CACHE_TIMEOUT)
except Exception as e:
tasks = []
return tasks | python | def get_fabric_tasks(self, project):
cache_key = 'project_{}_fabfile_tasks'.format(project.pk)
cached_result = cache.get(cache_key)
if cached_result:
return cached_result
try:
fabfile_path, activate_loc = self.get_fabfile_path(project)
if activate_loc:
output = self.check_output(
'source {};fab --list --list-format=short --fabfile={}'.format(activate_loc, fabfile_path),
shell=True
)
else:
output = self.check_output(
'fab --list --list-format=short --fabfile={}'.format(fabfile_path),
shell=True
)
lines = output.splitlines()
tasks = []
for line in lines:
name = line.strip()
if activate_loc:
o = self.check_output(
'source {};fab --display={} --fabfile={}'.format(activate_loc, name, fabfile_path),
shell=True
)
else:
o = self.check_output(
['fab', '--display={}'.format(name), '--fabfile={}'.format(fabfile_path)]
)
tasks.append(self.parse_task_details(name, o))
cache.set(cache_key, tasks, settings.FABRIC_TASK_CACHE_TIMEOUT)
except Exception as e:
tasks = []
return tasks | [
"def",
"get_fabric_tasks",
"(",
"self",
",",
"project",
")",
":",
"cache_key",
"=",
"'project_{}_fabfile_tasks'",
".",
"format",
"(",
"project",
".",
"pk",
")",
"cached_result",
"=",
"cache",
".",
"get",
"(",
"cache_key",
")",
"if",
"cached_result",
":",
"re... | Generate a list of fabric tasks that are available | [
"Generate",
"a",
"list",
"of",
"fabric",
"tasks",
"that",
"are",
"available"
] | 0f434783026f1b9ce16a416fa496d76921fe49ca | https://github.com/fabric-bolt/fabric-bolt/blob/0f434783026f1b9ce16a416fa496d76921fe49ca/fabric_bolt/task_runners/base.py#L143-L188 |
20,425 | fabric-bolt/fabric-bolt | fabric_bolt/projects/views.py | ProjectCopy.get_initial | def get_initial(self):
"""
Returns the initial data to use for forms on this view.
"""
initial = super(ProjectCopy, self).get_initial()
if self.copy_object:
initial.update({'name': '%s copy' % self.copy_object.name,
'description': self.copy_object.description,
'use_repo_fabfile': self.copy_object.use_repo_fabfile,
'fabfile_requirements': self.copy_object.fabfile_requirements,
'repo_url': self.copy_object.repo_url})
return initial | python | def get_initial(self):
initial = super(ProjectCopy, self).get_initial()
if self.copy_object:
initial.update({'name': '%s copy' % self.copy_object.name,
'description': self.copy_object.description,
'use_repo_fabfile': self.copy_object.use_repo_fabfile,
'fabfile_requirements': self.copy_object.fabfile_requirements,
'repo_url': self.copy_object.repo_url})
return initial | [
"def",
"get_initial",
"(",
"self",
")",
":",
"initial",
"=",
"super",
"(",
"ProjectCopy",
",",
"self",
")",
".",
"get_initial",
"(",
")",
"if",
"self",
".",
"copy_object",
":",
"initial",
".",
"update",
"(",
"{",
"'name'",
":",
"'%s copy'",
"%",
"self"... | Returns the initial data to use for forms on this view. | [
"Returns",
"the",
"initial",
"data",
"to",
"use",
"for",
"forms",
"on",
"this",
"view",
"."
] | 0f434783026f1b9ce16a416fa496d76921fe49ca | https://github.com/fabric-bolt/fabric-bolt/blob/0f434783026f1b9ce16a416fa496d76921fe49ca/fabric_bolt/projects/views.py#L101-L112 |
20,426 | fabric-bolt/fabric-bolt | fabric_bolt/projects/views.py | ProjectConfigurationDelete.get_success_url | def get_success_url(self):
"""Get the url depending on what type of configuration I deleted."""
if self.stage_id:
url = reverse('projects_stage_view', args=(self.project_id, self.stage_id))
else:
url = reverse('projects_project_view', args=(self.project_id,))
return url | python | def get_success_url(self):
if self.stage_id:
url = reverse('projects_stage_view', args=(self.project_id, self.stage_id))
else:
url = reverse('projects_project_view', args=(self.project_id,))
return url | [
"def",
"get_success_url",
"(",
"self",
")",
":",
"if",
"self",
".",
"stage_id",
":",
"url",
"=",
"reverse",
"(",
"'projects_stage_view'",
",",
"args",
"=",
"(",
"self",
".",
"project_id",
",",
"self",
".",
"stage_id",
")",
")",
"else",
":",
"url",
"=",... | Get the url depending on what type of configuration I deleted. | [
"Get",
"the",
"url",
"depending",
"on",
"what",
"type",
"of",
"configuration",
"I",
"deleted",
"."
] | 0f434783026f1b9ce16a416fa496d76921fe49ca | https://github.com/fabric-bolt/fabric-bolt/blob/0f434783026f1b9ce16a416fa496d76921fe49ca/fabric_bolt/projects/views.py#L300-L308 |
20,427 | fabric-bolt/fabric-bolt | fabric_bolt/hosts/utils.py | create_ssh_config | def create_ssh_config(remote_user='root', name='Auto Generated SSH Key',
file_name='fabricbolt_private.key', email='deployments@fabricbolt.io', public_key_text=None,
private_key_text=None):
"""Create SSH Key"""
if not private_key_text and not public_key_text:
key = RSA.generate(2048)
pubkey = key.publickey()
private_key_text = key.exportKey('PEM')
public_key_text = pubkey.exportKey('OpenSSH')
ssh_config = models.SSHConfig()
ssh_config.name = name
ssh_config.private_key_file.save(file_name, ContentFile(private_key_text))
ssh_config.public_key = '{} {}'.format(public_key_text, email)
ssh_config.remote_user = remote_user
ssh_config.save()
return ssh_config | python | def create_ssh_config(remote_user='root', name='Auto Generated SSH Key',
file_name='fabricbolt_private.key', email='deployments@fabricbolt.io', public_key_text=None,
private_key_text=None):
if not private_key_text and not public_key_text:
key = RSA.generate(2048)
pubkey = key.publickey()
private_key_text = key.exportKey('PEM')
public_key_text = pubkey.exportKey('OpenSSH')
ssh_config = models.SSHConfig()
ssh_config.name = name
ssh_config.private_key_file.save(file_name, ContentFile(private_key_text))
ssh_config.public_key = '{} {}'.format(public_key_text, email)
ssh_config.remote_user = remote_user
ssh_config.save()
return ssh_config | [
"def",
"create_ssh_config",
"(",
"remote_user",
"=",
"'root'",
",",
"name",
"=",
"'Auto Generated SSH Key'",
",",
"file_name",
"=",
"'fabricbolt_private.key'",
",",
"email",
"=",
"'deployments@fabricbolt.io'",
",",
"public_key_text",
"=",
"None",
",",
"private_key_text"... | Create SSH Key | [
"Create",
"SSH",
"Key"
] | 0f434783026f1b9ce16a416fa496d76921fe49ca | https://github.com/fabric-bolt/fabric-bolt/blob/0f434783026f1b9ce16a416fa496d76921fe49ca/fabric_bolt/hosts/utils.py#L7-L26 |
20,428 | softvar/json2html | json2html/jsonconv.py | Json2Html.convert | def convert(self, json="", table_attributes='border="1"', clubbing=True, encode=False, escape=True):
"""
Convert JSON to HTML Table format
"""
# table attributes such as class, id, data-attr-*, etc.
# eg: table_attributes = 'class = "table table-bordered sortable"'
self.table_init_markup = "<table %s>" % table_attributes
self.clubbing = clubbing
self.escape = escape
json_input = None
if not json:
json_input = {}
elif type(json) in text_types:
try:
json_input = json_parser.loads(json, object_pairs_hook=OrderedDict)
except ValueError as e:
#so the string passed here is actually not a json string
# - let's analyze whether we want to pass on the error or use the string as-is as a text node
if u"Expecting property name" in text(e):
#if this specific json loads error is raised, then the user probably actually wanted to pass json, but made a mistake
raise e
json_input = json
else:
json_input = json
converted = self.convert_json_node(json_input)
if encode:
return converted.encode('ascii', 'xmlcharrefreplace')
return converted | python | def convert(self, json="", table_attributes='border="1"', clubbing=True, encode=False, escape=True):
# table attributes such as class, id, data-attr-*, etc.
# eg: table_attributes = 'class = "table table-bordered sortable"'
self.table_init_markup = "<table %s>" % table_attributes
self.clubbing = clubbing
self.escape = escape
json_input = None
if not json:
json_input = {}
elif type(json) in text_types:
try:
json_input = json_parser.loads(json, object_pairs_hook=OrderedDict)
except ValueError as e:
#so the string passed here is actually not a json string
# - let's analyze whether we want to pass on the error or use the string as-is as a text node
if u"Expecting property name" in text(e):
#if this specific json loads error is raised, then the user probably actually wanted to pass json, but made a mistake
raise e
json_input = json
else:
json_input = json
converted = self.convert_json_node(json_input)
if encode:
return converted.encode('ascii', 'xmlcharrefreplace')
return converted | [
"def",
"convert",
"(",
"self",
",",
"json",
"=",
"\"\"",
",",
"table_attributes",
"=",
"'border=\"1\"'",
",",
"clubbing",
"=",
"True",
",",
"encode",
"=",
"False",
",",
"escape",
"=",
"True",
")",
":",
"# table attributes such as class, id, data-attr-*, etc.",
"... | Convert JSON to HTML Table format | [
"Convert",
"JSON",
"to",
"HTML",
"Table",
"format"
] | 7070939172f1afd5c11c664e6cfece280cfde7e6 | https://github.com/softvar/json2html/blob/7070939172f1afd5c11c664e6cfece280cfde7e6/json2html/jsonconv.py#L37-L64 |
20,429 | softvar/json2html | json2html/jsonconv.py | Json2Html.column_headers_from_list_of_dicts | def column_headers_from_list_of_dicts(self, json_input):
"""
This method is required to implement clubbing.
It tries to come up with column headers for your input
"""
if not json_input \
or not hasattr(json_input, '__getitem__') \
or not hasattr(json_input[0], 'keys'):
return None
column_headers = json_input[0].keys()
for entry in json_input:
if not hasattr(entry, 'keys') \
or not hasattr(entry, '__iter__') \
or len(entry.keys()) != len(column_headers):
return None
for header in column_headers:
if header not in entry:
return None
return column_headers | python | def column_headers_from_list_of_dicts(self, json_input):
if not json_input \
or not hasattr(json_input, '__getitem__') \
or not hasattr(json_input[0], 'keys'):
return None
column_headers = json_input[0].keys()
for entry in json_input:
if not hasattr(entry, 'keys') \
or not hasattr(entry, '__iter__') \
or len(entry.keys()) != len(column_headers):
return None
for header in column_headers:
if header not in entry:
return None
return column_headers | [
"def",
"column_headers_from_list_of_dicts",
"(",
"self",
",",
"json_input",
")",
":",
"if",
"not",
"json_input",
"or",
"not",
"hasattr",
"(",
"json_input",
",",
"'__getitem__'",
")",
"or",
"not",
"hasattr",
"(",
"json_input",
"[",
"0",
"]",
",",
"'keys'",
")... | This method is required to implement clubbing.
It tries to come up with column headers for your input | [
"This",
"method",
"is",
"required",
"to",
"implement",
"clubbing",
".",
"It",
"tries",
"to",
"come",
"up",
"with",
"column",
"headers",
"for",
"your",
"input"
] | 7070939172f1afd5c11c664e6cfece280cfde7e6 | https://github.com/softvar/json2html/blob/7070939172f1afd5c11c664e6cfece280cfde7e6/json2html/jsonconv.py#L66-L84 |
20,430 | softvar/json2html | json2html/jsonconv.py | Json2Html.convert_list | def convert_list(self, list_input):
"""
Iterate over the JSON list and process it
to generate either an HTML table or a HTML list, depending on what's inside.
If suppose some key has array of objects and all the keys are same,
instead of creating a new row for each such entry,
club such values, thus it makes more sense and more readable table.
@example:
jsonObject = {
"sampleData": [
{"a":1, "b":2, "c":3},
{"a":5, "b":6, "c":7}
]
}
OUTPUT:
_____________________________
| | | | |
| | a | c | b |
| sampleData |---|---|---|
| | 1 | 3 | 2 |
| | 5 | 7 | 6 |
-----------------------------
@contributed by: @muellermichel
"""
if not list_input:
return ""
converted_output = ""
column_headers = None
if self.clubbing:
column_headers = self.column_headers_from_list_of_dicts(list_input)
if column_headers is not None:
converted_output += self.table_init_markup
converted_output += '<thead>'
converted_output += '<tr><th>' + '</th><th>'.join(column_headers) + '</th></tr>'
converted_output += '</thead>'
converted_output += '<tbody>'
for list_entry in list_input:
converted_output += '<tr><td>'
converted_output += '</td><td>'.join([self.convert_json_node(list_entry[column_header]) for column_header in
column_headers])
converted_output += '</td></tr>'
converted_output += '</tbody>'
converted_output += '</table>'
return converted_output
#so you don't want or need clubbing eh? This makes @muellermichel very sad... ;(
#alright, let's fall back to a basic list here...
converted_output = '<ul><li>'
converted_output += '</li><li>'.join([self.convert_json_node(child) for child in list_input])
converted_output += '</li></ul>'
return converted_output | python | def convert_list(self, list_input):
if not list_input:
return ""
converted_output = ""
column_headers = None
if self.clubbing:
column_headers = self.column_headers_from_list_of_dicts(list_input)
if column_headers is not None:
converted_output += self.table_init_markup
converted_output += '<thead>'
converted_output += '<tr><th>' + '</th><th>'.join(column_headers) + '</th></tr>'
converted_output += '</thead>'
converted_output += '<tbody>'
for list_entry in list_input:
converted_output += '<tr><td>'
converted_output += '</td><td>'.join([self.convert_json_node(list_entry[column_header]) for column_header in
column_headers])
converted_output += '</td></tr>'
converted_output += '</tbody>'
converted_output += '</table>'
return converted_output
#so you don't want or need clubbing eh? This makes @muellermichel very sad... ;(
#alright, let's fall back to a basic list here...
converted_output = '<ul><li>'
converted_output += '</li><li>'.join([self.convert_json_node(child) for child in list_input])
converted_output += '</li></ul>'
return converted_output | [
"def",
"convert_list",
"(",
"self",
",",
"list_input",
")",
":",
"if",
"not",
"list_input",
":",
"return",
"\"\"",
"converted_output",
"=",
"\"\"",
"column_headers",
"=",
"None",
"if",
"self",
".",
"clubbing",
":",
"column_headers",
"=",
"self",
".",
"column... | Iterate over the JSON list and process it
to generate either an HTML table or a HTML list, depending on what's inside.
If suppose some key has array of objects and all the keys are same,
instead of creating a new row for each such entry,
club such values, thus it makes more sense and more readable table.
@example:
jsonObject = {
"sampleData": [
{"a":1, "b":2, "c":3},
{"a":5, "b":6, "c":7}
]
}
OUTPUT:
_____________________________
| | | | |
| | a | c | b |
| sampleData |---|---|---|
| | 1 | 3 | 2 |
| | 5 | 7 | 6 |
-----------------------------
@contributed by: @muellermichel | [
"Iterate",
"over",
"the",
"JSON",
"list",
"and",
"process",
"it",
"to",
"generate",
"either",
"an",
"HTML",
"table",
"or",
"a",
"HTML",
"list",
"depending",
"on",
"what",
"s",
"inside",
".",
"If",
"suppose",
"some",
"key",
"has",
"array",
"of",
"objects"... | 7070939172f1afd5c11c664e6cfece280cfde7e6 | https://github.com/softvar/json2html/blob/7070939172f1afd5c11c664e6cfece280cfde7e6/json2html/jsonconv.py#L105-L157 |
20,431 | softvar/json2html | json2html/jsonconv.py | Json2Html.convert_object | def convert_object(self, json_input):
"""
Iterate over the JSON object and process it
to generate the super awesome HTML Table format
"""
if not json_input:
return "" #avoid empty tables
converted_output = self.table_init_markup + "<tr>"
converted_output += "</tr><tr>".join([
"<th>%s</th><td>%s</td>" %(
self.convert_json_node(k),
self.convert_json_node(v)
)
for k, v in json_input.items()
])
converted_output += '</tr></table>'
return converted_output | python | def convert_object(self, json_input):
if not json_input:
return "" #avoid empty tables
converted_output = self.table_init_markup + "<tr>"
converted_output += "</tr><tr>".join([
"<th>%s</th><td>%s</td>" %(
self.convert_json_node(k),
self.convert_json_node(v)
)
for k, v in json_input.items()
])
converted_output += '</tr></table>'
return converted_output | [
"def",
"convert_object",
"(",
"self",
",",
"json_input",
")",
":",
"if",
"not",
"json_input",
":",
"return",
"\"\"",
"#avoid empty tables",
"converted_output",
"=",
"self",
".",
"table_init_markup",
"+",
"\"<tr>\"",
"converted_output",
"+=",
"\"</tr><tr>\"",
".",
... | Iterate over the JSON object and process it
to generate the super awesome HTML Table format | [
"Iterate",
"over",
"the",
"JSON",
"object",
"and",
"process",
"it",
"to",
"generate",
"the",
"super",
"awesome",
"HTML",
"Table",
"format"
] | 7070939172f1afd5c11c664e6cfece280cfde7e6 | https://github.com/softvar/json2html/blob/7070939172f1afd5c11c664e6cfece280cfde7e6/json2html/jsonconv.py#L159-L175 |
20,432 | philippelt/netatmo-api-python | lnetatmo.py | HomeData.personsAtHome | def personsAtHome(self, home=None):
"""
Return the list of known persons who are currently at home
"""
if not home: home = self.default_home
home_data = self.homeByName(home)
atHome = []
for p in home_data['persons']:
#Only check known persons
if 'pseudo' in p:
if not p["out_of_sight"]:
atHome.append(p['pseudo'])
return atHome | python | def personsAtHome(self, home=None):
if not home: home = self.default_home
home_data = self.homeByName(home)
atHome = []
for p in home_data['persons']:
#Only check known persons
if 'pseudo' in p:
if not p["out_of_sight"]:
atHome.append(p['pseudo'])
return atHome | [
"def",
"personsAtHome",
"(",
"self",
",",
"home",
"=",
"None",
")",
":",
"if",
"not",
"home",
":",
"home",
"=",
"self",
".",
"default_home",
"home_data",
"=",
"self",
".",
"homeByName",
"(",
"home",
")",
"atHome",
"=",
"[",
"]",
"for",
"p",
"in",
"... | Return the list of known persons who are currently at home | [
"Return",
"the",
"list",
"of",
"known",
"persons",
"who",
"are",
"currently",
"at",
"home"
] | d749fca3637c07c2943aba7992f683fff1812f77 | https://github.com/philippelt/netatmo-api-python/blob/d749fca3637c07c2943aba7992f683fff1812f77/lnetatmo.py#L566-L578 |
20,433 | philippelt/netatmo-api-python | lnetatmo.py | HomeData.getProfileImage | def getProfileImage(self, name):
"""
Retrieve the face of a given person
"""
for p in self.persons:
if 'pseudo' in self.persons[p]:
if name == self.persons[p]['pseudo']:
image_id = self.persons[p]['face']['id']
key = self.persons[p]['face']['key']
return self.getCameraPicture(image_id, key)
return None, None | python | def getProfileImage(self, name):
for p in self.persons:
if 'pseudo' in self.persons[p]:
if name == self.persons[p]['pseudo']:
image_id = self.persons[p]['face']['id']
key = self.persons[p]['face']['key']
return self.getCameraPicture(image_id, key)
return None, None | [
"def",
"getProfileImage",
"(",
"self",
",",
"name",
")",
":",
"for",
"p",
"in",
"self",
".",
"persons",
":",
"if",
"'pseudo'",
"in",
"self",
".",
"persons",
"[",
"p",
"]",
":",
"if",
"name",
"==",
"self",
".",
"persons",
"[",
"p",
"]",
"[",
"'pse... | Retrieve the face of a given person | [
"Retrieve",
"the",
"face",
"of",
"a",
"given",
"person"
] | d749fca3637c07c2943aba7992f683fff1812f77 | https://github.com/philippelt/netatmo-api-python/blob/d749fca3637c07c2943aba7992f683fff1812f77/lnetatmo.py#L593-L603 |
20,434 | philippelt/netatmo-api-python | lnetatmo.py | HomeData.updateEvent | def updateEvent(self, event=None, home=None):
"""
Update the list of event with the latest ones
"""
if not home: home=self.default_home
if not event:
#If not event is provided we need to retrieve the oldest of the last event seen by each camera
listEvent = dict()
for cam_id in self.lastEvent:
listEvent[self.lastEvent[cam_id]['time']] = self.lastEvent[cam_id]
event = listEvent[sorted(listEvent)[0]]
home_data = self.homeByName(home)
postParams = {
"access_token" : self.getAuthToken,
"home_id" : home_data['id'],
"event_id" : event['id']
}
resp = postRequest(_GETEVENTSUNTIL_REQ, postParams)
eventList = resp['body']['events_list']
for e in eventList:
self.events[ e['camera_id'] ][ e['time'] ] = e
for camera in self.events:
self.lastEvent[camera]=self.events[camera][sorted(self.events[camera])[-1]] | python | def updateEvent(self, event=None, home=None):
if not home: home=self.default_home
if not event:
#If not event is provided we need to retrieve the oldest of the last event seen by each camera
listEvent = dict()
for cam_id in self.lastEvent:
listEvent[self.lastEvent[cam_id]['time']] = self.lastEvent[cam_id]
event = listEvent[sorted(listEvent)[0]]
home_data = self.homeByName(home)
postParams = {
"access_token" : self.getAuthToken,
"home_id" : home_data['id'],
"event_id" : event['id']
}
resp = postRequest(_GETEVENTSUNTIL_REQ, postParams)
eventList = resp['body']['events_list']
for e in eventList:
self.events[ e['camera_id'] ][ e['time'] ] = e
for camera in self.events:
self.lastEvent[camera]=self.events[camera][sorted(self.events[camera])[-1]] | [
"def",
"updateEvent",
"(",
"self",
",",
"event",
"=",
"None",
",",
"home",
"=",
"None",
")",
":",
"if",
"not",
"home",
":",
"home",
"=",
"self",
".",
"default_home",
"if",
"not",
"event",
":",
"#If not event is provided we need to retrieve the oldest of the last... | Update the list of event with the latest ones | [
"Update",
"the",
"list",
"of",
"event",
"with",
"the",
"latest",
"ones"
] | d749fca3637c07c2943aba7992f683fff1812f77 | https://github.com/philippelt/netatmo-api-python/blob/d749fca3637c07c2943aba7992f683fff1812f77/lnetatmo.py#L605-L628 |
20,435 | philippelt/netatmo-api-python | lnetatmo.py | HomeData.personSeenByCamera | def personSeenByCamera(self, name, home=None, camera=None):
"""
Return True if a specific person has been seen by a camera
"""
try:
cam_id = self.cameraByName(camera=camera, home=home)['id']
except TypeError:
logger.warning("personSeenByCamera: Camera name or home is unknown")
return False
#Check in the last event is someone known has been seen
if self.lastEvent[cam_id]['type'] == 'person':
person_id = self.lastEvent[cam_id]['person_id']
if 'pseudo' in self.persons[person_id]:
if self.persons[person_id]['pseudo'] == name:
return True
return False | python | def personSeenByCamera(self, name, home=None, camera=None):
try:
cam_id = self.cameraByName(camera=camera, home=home)['id']
except TypeError:
logger.warning("personSeenByCamera: Camera name or home is unknown")
return False
#Check in the last event is someone known has been seen
if self.lastEvent[cam_id]['type'] == 'person':
person_id = self.lastEvent[cam_id]['person_id']
if 'pseudo' in self.persons[person_id]:
if self.persons[person_id]['pseudo'] == name:
return True
return False | [
"def",
"personSeenByCamera",
"(",
"self",
",",
"name",
",",
"home",
"=",
"None",
",",
"camera",
"=",
"None",
")",
":",
"try",
":",
"cam_id",
"=",
"self",
".",
"cameraByName",
"(",
"camera",
"=",
"camera",
",",
"home",
"=",
"home",
")",
"[",
"'id'",
... | Return True if a specific person has been seen by a camera | [
"Return",
"True",
"if",
"a",
"specific",
"person",
"has",
"been",
"seen",
"by",
"a",
"camera"
] | d749fca3637c07c2943aba7992f683fff1812f77 | https://github.com/philippelt/netatmo-api-python/blob/d749fca3637c07c2943aba7992f683fff1812f77/lnetatmo.py#L630-L645 |
20,436 | philippelt/netatmo-api-python | lnetatmo.py | HomeData.someoneKnownSeen | def someoneKnownSeen(self, home=None, camera=None):
"""
Return True if someone known has been seen
"""
try:
cam_id = self.cameraByName(camera=camera, home=home)['id']
except TypeError:
logger.warning("personSeenByCamera: Camera name or home is unknown")
return False
#Check in the last event is someone known has been seen
if self.lastEvent[cam_id]['type'] == 'person':
if self.lastEvent[cam_id]['person_id'] in self._knownPersons():
return True
return False | python | def someoneKnownSeen(self, home=None, camera=None):
try:
cam_id = self.cameraByName(camera=camera, home=home)['id']
except TypeError:
logger.warning("personSeenByCamera: Camera name or home is unknown")
return False
#Check in the last event is someone known has been seen
if self.lastEvent[cam_id]['type'] == 'person':
if self.lastEvent[cam_id]['person_id'] in self._knownPersons():
return True
return False | [
"def",
"someoneKnownSeen",
"(",
"self",
",",
"home",
"=",
"None",
",",
"camera",
"=",
"None",
")",
":",
"try",
":",
"cam_id",
"=",
"self",
".",
"cameraByName",
"(",
"camera",
"=",
"camera",
",",
"home",
"=",
"home",
")",
"[",
"'id'",
"]",
"except",
... | Return True if someone known has been seen | [
"Return",
"True",
"if",
"someone",
"known",
"has",
"been",
"seen"
] | d749fca3637c07c2943aba7992f683fff1812f77 | https://github.com/philippelt/netatmo-api-python/blob/d749fca3637c07c2943aba7992f683fff1812f77/lnetatmo.py#L654-L667 |
20,437 | philippelt/netatmo-api-python | lnetatmo.py | HomeData.motionDetected | def motionDetected(self, home=None, camera=None):
"""
Return True if movement has been detected
"""
try:
cam_id = self.cameraByName(camera=camera, home=home)['id']
except TypeError:
logger.warning("personSeenByCamera: Camera name or home is unknown")
return False
if self.lastEvent[cam_id]['type'] == 'movement':
return True
return False | python | def motionDetected(self, home=None, camera=None):
try:
cam_id = self.cameraByName(camera=camera, home=home)['id']
except TypeError:
logger.warning("personSeenByCamera: Camera name or home is unknown")
return False
if self.lastEvent[cam_id]['type'] == 'movement':
return True
return False | [
"def",
"motionDetected",
"(",
"self",
",",
"home",
"=",
"None",
",",
"camera",
"=",
"None",
")",
":",
"try",
":",
"cam_id",
"=",
"self",
".",
"cameraByName",
"(",
"camera",
"=",
"camera",
",",
"home",
"=",
"home",
")",
"[",
"'id'",
"]",
"except",
"... | Return True if movement has been detected | [
"Return",
"True",
"if",
"movement",
"has",
"been",
"detected"
] | d749fca3637c07c2943aba7992f683fff1812f77 | https://github.com/philippelt/netatmo-api-python/blob/d749fca3637c07c2943aba7992f683fff1812f77/lnetatmo.py#L684-L695 |
20,438 | fprimex/zdesk | zdesk/zdesk.py | batch | def batch(sequence, callback, size=100, **kwargs):
"""Helper to setup batch requests.
There are endpoints which support updating multiple resources at once,
but they are often limited to 100 updates per request.
This function helps with splitting bigger requests into sequence of
smaller ones.
Example:
def add_organization_tag(organizations, tag):
request = {'organizations': [
{
'id': org['id'],
'tags': org['tags'] + [tag],
} for org in organizations
]}
job = z.organizations_update_many(request)['job_status']
return job['id']
# z = Zendesk(...)
orgs = z.organizations_list(get_all_pages=True)['organizations']
job_ids = [job for job in
batch(orgs, add_organization_tag, tag='new_tag')]
Parameters:
sequence - any sequence you want to split
callback - function to call with slices of sequence,
its return value is yielded on each slice
size - size of chunks, combined with length of sequence determines
how many times callback is called (defaults to 100)
**kwargs - any additional keyword arguments are passed to callback
"""
batch_len, rem = divmod(len(sequence), size)
if rem > 0:
batch_len += 1
for i in range(batch_len):
offset = i * size
yield callback(sequence[offset:offset + size], **kwargs) | python | def batch(sequence, callback, size=100, **kwargs):
batch_len, rem = divmod(len(sequence), size)
if rem > 0:
batch_len += 1
for i in range(batch_len):
offset = i * size
yield callback(sequence[offset:offset + size], **kwargs) | [
"def",
"batch",
"(",
"sequence",
",",
"callback",
",",
"size",
"=",
"100",
",",
"*",
"*",
"kwargs",
")",
":",
"batch_len",
",",
"rem",
"=",
"divmod",
"(",
"len",
"(",
"sequence",
")",
",",
"size",
")",
"if",
"rem",
">",
"0",
":",
"batch_len",
"+=... | Helper to setup batch requests.
There are endpoints which support updating multiple resources at once,
but they are often limited to 100 updates per request.
This function helps with splitting bigger requests into sequence of
smaller ones.
Example:
def add_organization_tag(organizations, tag):
request = {'organizations': [
{
'id': org['id'],
'tags': org['tags'] + [tag],
} for org in organizations
]}
job = z.organizations_update_many(request)['job_status']
return job['id']
# z = Zendesk(...)
orgs = z.organizations_list(get_all_pages=True)['organizations']
job_ids = [job for job in
batch(orgs, add_organization_tag, tag='new_tag')]
Parameters:
sequence - any sequence you want to split
callback - function to call with slices of sequence,
its return value is yielded on each slice
size - size of chunks, combined with length of sequence determines
how many times callback is called (defaults to 100)
**kwargs - any additional keyword arguments are passed to callback | [
"Helper",
"to",
"setup",
"batch",
"requests",
"."
] | 851611c13b4d530e9df31390b3ec709baf0a0188 | https://github.com/fprimex/zdesk/blob/851611c13b4d530e9df31390b3ec709baf0a0188/zdesk/zdesk.py#L20-L57 |
20,439 | fprimex/zdesk | zdesk/zdesk.py | Zendesk._handle_retry | def _handle_retry(self, resp):
"""Handle any exceptions during API request or
parsing its response status code.
Parameters:
resp: requests.Response instance obtained during concerning request
or None, when request failed
Returns: True if should retry our request or raises original Exception
"""
exc_t, exc_v, exc_tb = sys.exc_info()
if exc_t is None:
raise TypeError('Must be called in except block.')
retry_on_exc = tuple(
(x for x in self._retry_on if inspect.isclass(x)))
retry_on_codes = tuple(
(x for x in self._retry_on if isinstance(x, int)))
if issubclass(exc_t, ZendeskError):
code = exc_v.error_code
if exc_t not in retry_on_exc and code not in retry_on_codes:
six.reraise(exc_t, exc_v, exc_tb)
else:
if not issubclass(exc_t, retry_on_exc):
six.reraise(exc_t, exc_v, exc_tb)
if resp is not None:
try:
retry_after = float(resp.headers.get('Retry-After', 0))
time.sleep(retry_after)
except (TypeError, ValueError):
pass
return True | python | def _handle_retry(self, resp):
exc_t, exc_v, exc_tb = sys.exc_info()
if exc_t is None:
raise TypeError('Must be called in except block.')
retry_on_exc = tuple(
(x for x in self._retry_on if inspect.isclass(x)))
retry_on_codes = tuple(
(x for x in self._retry_on if isinstance(x, int)))
if issubclass(exc_t, ZendeskError):
code = exc_v.error_code
if exc_t not in retry_on_exc and code not in retry_on_codes:
six.reraise(exc_t, exc_v, exc_tb)
else:
if not issubclass(exc_t, retry_on_exc):
six.reraise(exc_t, exc_v, exc_tb)
if resp is not None:
try:
retry_after = float(resp.headers.get('Retry-After', 0))
time.sleep(retry_after)
except (TypeError, ValueError):
pass
return True | [
"def",
"_handle_retry",
"(",
"self",
",",
"resp",
")",
":",
"exc_t",
",",
"exc_v",
",",
"exc_tb",
"=",
"sys",
".",
"exc_info",
"(",
")",
"if",
"exc_t",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"'Must be called in except block.'",
")",
"retry_on_exc",
... | Handle any exceptions during API request or
parsing its response status code.
Parameters:
resp: requests.Response instance obtained during concerning request
or None, when request failed
Returns: True if should retry our request or raises original Exception | [
"Handle",
"any",
"exceptions",
"during",
"API",
"request",
"or",
"parsing",
"its",
"response",
"status",
"code",
"."
] | 851611c13b4d530e9df31390b3ec709baf0a0188 | https://github.com/fprimex/zdesk/blob/851611c13b4d530e9df31390b3ec709baf0a0188/zdesk/zdesk.py#L600-L635 |
20,440 | v1k45/django-notify-x | notify/views.py | notification_redirect | def notification_redirect(request, ctx):
"""
Helper to handle HTTP response after an action is performed on notification
:param request: HTTP request context of the notification
:param ctx: context to be returned when a AJAX call is made.
:returns: Either JSON for AJAX or redirects to the calculated next page.
"""
if request.is_ajax():
return JsonResponse(ctx)
else:
next_page = request.POST.get('next', reverse('notifications:all'))
if not ctx['success']:
return HttpResponseBadRequest(ctx['msg'])
if is_safe_url(next_page):
return HttpResponseRedirect(next_page)
else:
return HttpResponseRedirect(reverse('notifications:all')) | python | def notification_redirect(request, ctx):
if request.is_ajax():
return JsonResponse(ctx)
else:
next_page = request.POST.get('next', reverse('notifications:all'))
if not ctx['success']:
return HttpResponseBadRequest(ctx['msg'])
if is_safe_url(next_page):
return HttpResponseRedirect(next_page)
else:
return HttpResponseRedirect(reverse('notifications:all')) | [
"def",
"notification_redirect",
"(",
"request",
",",
"ctx",
")",
":",
"if",
"request",
".",
"is_ajax",
"(",
")",
":",
"return",
"JsonResponse",
"(",
"ctx",
")",
"else",
":",
"next_page",
"=",
"request",
".",
"POST",
".",
"get",
"(",
"'next'",
",",
"rev... | Helper to handle HTTP response after an action is performed on notification
:param request: HTTP request context of the notification
:param ctx: context to be returned when a AJAX call is made.
:returns: Either JSON for AJAX or redirects to the calculated next page. | [
"Helper",
"to",
"handle",
"HTTP",
"response",
"after",
"an",
"action",
"is",
"performed",
"on",
"notification"
] | b4aa03039759126889666a59117e83dcd4cdb374 | https://github.com/v1k45/django-notify-x/blob/b4aa03039759126889666a59117e83dcd4cdb374/notify/views.py#L20-L39 |
20,441 | v1k45/django-notify-x | notify/views.py | mark | def mark(request):
"""
Handles marking of individual notifications as read or unread.
Takes ``notification id`` and mark ``action`` as POST data.
:param request: HTTP request context.
:returns: Response to mark action of supplied notification ID.
"""
notification_id = request.POST.get('id', None)
action = request.POST.get('action', None)
success = True
if notification_id:
try:
notification = Notification.objects.get(pk=notification_id,
recipient=request.user)
if action == 'read':
notification.mark_as_read()
msg = _("Marked as read")
elif action == 'unread':
notification.mark_as_unread()
msg = _("Marked as unread")
else:
success = False
msg = _("Invalid mark action.")
except Notification.DoesNotExist:
success = False
msg = _("Notification does not exists.")
else:
success = False
msg = _("Invalid Notification ID")
ctx = {'msg': msg, 'success': success, 'action': action}
return notification_redirect(request, ctx) | python | def mark(request):
notification_id = request.POST.get('id', None)
action = request.POST.get('action', None)
success = True
if notification_id:
try:
notification = Notification.objects.get(pk=notification_id,
recipient=request.user)
if action == 'read':
notification.mark_as_read()
msg = _("Marked as read")
elif action == 'unread':
notification.mark_as_unread()
msg = _("Marked as unread")
else:
success = False
msg = _("Invalid mark action.")
except Notification.DoesNotExist:
success = False
msg = _("Notification does not exists.")
else:
success = False
msg = _("Invalid Notification ID")
ctx = {'msg': msg, 'success': success, 'action': action}
return notification_redirect(request, ctx) | [
"def",
"mark",
"(",
"request",
")",
":",
"notification_id",
"=",
"request",
".",
"POST",
".",
"get",
"(",
"'id'",
",",
"None",
")",
"action",
"=",
"request",
".",
"POST",
".",
"get",
"(",
"'action'",
",",
"None",
")",
"success",
"=",
"True",
"if",
... | Handles marking of individual notifications as read or unread.
Takes ``notification id`` and mark ``action`` as POST data.
:param request: HTTP request context.
:returns: Response to mark action of supplied notification ID. | [
"Handles",
"marking",
"of",
"individual",
"notifications",
"as",
"read",
"or",
"unread",
".",
"Takes",
"notification",
"id",
"and",
"mark",
"action",
"as",
"POST",
"data",
"."
] | b4aa03039759126889666a59117e83dcd4cdb374 | https://github.com/v1k45/django-notify-x/blob/b4aa03039759126889666a59117e83dcd4cdb374/notify/views.py#L61-L96 |
20,442 | v1k45/django-notify-x | notify/views.py | mark_all | def mark_all(request):
"""
Marks notifications as either read or unread depending of POST parameters.
Takes ``action`` as POST data, it can either be ``read`` or ``unread``.
:param request: HTTP Request context.
:return: Response to mark_all action.
"""
action = request.POST.get('action', None)
success = True
if action == 'read':
request.user.notifications.read_all()
msg = _("Marked all notifications as read")
elif action == 'unread':
request.user.notifications.unread_all()
msg = _("Marked all notifications as unread")
else:
msg = _("Invalid mark action")
success = False
ctx = {'msg': msg, 'success': success, 'action': action}
return notification_redirect(request, ctx) | python | def mark_all(request):
action = request.POST.get('action', None)
success = True
if action == 'read':
request.user.notifications.read_all()
msg = _("Marked all notifications as read")
elif action == 'unread':
request.user.notifications.unread_all()
msg = _("Marked all notifications as unread")
else:
msg = _("Invalid mark action")
success = False
ctx = {'msg': msg, 'success': success, 'action': action}
return notification_redirect(request, ctx) | [
"def",
"mark_all",
"(",
"request",
")",
":",
"action",
"=",
"request",
".",
"POST",
".",
"get",
"(",
"'action'",
",",
"None",
")",
"success",
"=",
"True",
"if",
"action",
"==",
"'read'",
":",
"request",
".",
"user",
".",
"notifications",
".",
"read_all... | Marks notifications as either read or unread depending of POST parameters.
Takes ``action`` as POST data, it can either be ``read`` or ``unread``.
:param request: HTTP Request context.
:return: Response to mark_all action. | [
"Marks",
"notifications",
"as",
"either",
"read",
"or",
"unread",
"depending",
"of",
"POST",
"parameters",
".",
"Takes",
"action",
"as",
"POST",
"data",
"it",
"can",
"either",
"be",
"read",
"or",
"unread",
"."
] | b4aa03039759126889666a59117e83dcd4cdb374 | https://github.com/v1k45/django-notify-x/blob/b4aa03039759126889666a59117e83dcd4cdb374/notify/views.py#L101-L125 |
20,443 | v1k45/django-notify-x | notify/views.py | delete | def delete(request):
"""
Deletes notification of supplied notification ID.
Depending on project settings, if ``NOTIFICATIONS_SOFT_DELETE``
is set to ``False``, the notifications will be deleted from DB.
If not, a soft delete will be performed.
By default, notifications are deleted softly.
:param request: HTTP request context.
:return: Response to delete action on supplied notification ID.
"""
notification_id = request.POST.get('id', None)
success = True
if notification_id:
try:
notification = Notification.objects.get(pk=notification_id,
recipient=request.user)
soft_delete = getattr(settings, 'NOTIFY_SOFT_DELETE', True)
if soft_delete:
notification.deleted = True
notification.save()
else:
notification.delete()
msg = _("Deleted notification successfully")
except Notification.DoesNotExist:
success = False
msg = _("Notification does not exists.")
else:
success = False
msg = _("Invalid Notification ID")
ctx = {'msg': msg, 'success': success, }
return notification_redirect(request, ctx) | python | def delete(request):
notification_id = request.POST.get('id', None)
success = True
if notification_id:
try:
notification = Notification.objects.get(pk=notification_id,
recipient=request.user)
soft_delete = getattr(settings, 'NOTIFY_SOFT_DELETE', True)
if soft_delete:
notification.deleted = True
notification.save()
else:
notification.delete()
msg = _("Deleted notification successfully")
except Notification.DoesNotExist:
success = False
msg = _("Notification does not exists.")
else:
success = False
msg = _("Invalid Notification ID")
ctx = {'msg': msg, 'success': success, }
return notification_redirect(request, ctx) | [
"def",
"delete",
"(",
"request",
")",
":",
"notification_id",
"=",
"request",
".",
"POST",
".",
"get",
"(",
"'id'",
",",
"None",
")",
"success",
"=",
"True",
"if",
"notification_id",
":",
"try",
":",
"notification",
"=",
"Notification",
".",
"objects",
"... | Deletes notification of supplied notification ID.
Depending on project settings, if ``NOTIFICATIONS_SOFT_DELETE``
is set to ``False``, the notifications will be deleted from DB.
If not, a soft delete will be performed.
By default, notifications are deleted softly.
:param request: HTTP request context.
:return: Response to delete action on supplied notification ID. | [
"Deletes",
"notification",
"of",
"supplied",
"notification",
"ID",
"."
] | b4aa03039759126889666a59117e83dcd4cdb374 | https://github.com/v1k45/django-notify-x/blob/b4aa03039759126889666a59117e83dcd4cdb374/notify/views.py#L130-L167 |
20,444 | v1k45/django-notify-x | notify/views.py | notification_update | def notification_update(request):
"""
Handles live updating of notifications, follows ajax-polling approach.
Read more: http://stackoverflow.com/a/12855533/4726598
Required URL parameters: ``flag``.
Explanation:
- The ``flag`` parameter carries the last notification ID \
received by the user's browser.
- This ``flag`` is most likely to be generated by using \
a simple JS/JQuery DOM. Just grab the first element of \
the notification list.
- The element will have a ``data-id`` attribute set to the \
corresponding notification.
- We'll use it's value as the flag parameter.
- The view treats the ``last notification flag`` as a model \
```filter()`` and fetches all notifications greater than \
the flag for the user.
- Then the a JSON data is prepared with all necessary \
details such as, ``verb``, ``actor``, ``target`` and their \
URL etc. The foreignkey are serialized as their \
default ``__str__`` value.
- Everything will be HTML escaped by django's ``escape()``.
- Since these notification sent will only serve temporarily \
on the notification box and will be generated fresh \
using a whole template, to avoid client-side notification \
generation using the JSON data, the JSON data will also \
contain a rendered HTML string so that you can easily \
do a JQuery ``$yourNotificationBox.prepend()`` on the \
rendered html string of the notification.
- The template used is expected to be different than the \
template used in full page notification as the css \
and some other elements are highly likely to be \
different than the full page notification list. \
- The template used will be the ``notification type`` of the \
notification suffixed ``_box.html``. So, if your \
notification type is ``comment_reply``, the template \
will be ``comment_reply_box.html``.
- This template will be stored in ``notifications/includes/`` \
of your template directory.
- That makes: ``notifications/includes/comment_reply_box.html``
- The rest is self-explanatory.
:param request: HTTP request context.
:return: Notification updates (if any) in JSON format.
"""
flag = request.GET.get('flag', None)
target = request.GET.get('target', 'box')
last_notification = int(flag) if flag.isdigit() else None
if last_notification:
new_notifications = request.user.notifications.filter(
id__gt=last_notification).active().prefetch()
msg = _("Notifications successfully retrieved.") \
if new_notifications else _("No new notifications.")
notification_list = []
for nf in new_notifications:
notification = nf.as_json()
notification_list.append(notification)
notification['html'] = render_notification(
nf, render_target=target, **notification)
ctx = {
"retrieved": len(new_notifications),
"unread_count": request.user.notifications.unread().count(),
"notifications": notification_list,
"success": True,
"msg": msg,
}
return JsonResponse(ctx)
else:
msg = _("Notification flag not sent.")
ctx = {"success": False, "msg": msg}
return JsonResponse(ctx) | python | def notification_update(request):
flag = request.GET.get('flag', None)
target = request.GET.get('target', 'box')
last_notification = int(flag) if flag.isdigit() else None
if last_notification:
new_notifications = request.user.notifications.filter(
id__gt=last_notification).active().prefetch()
msg = _("Notifications successfully retrieved.") \
if new_notifications else _("No new notifications.")
notification_list = []
for nf in new_notifications:
notification = nf.as_json()
notification_list.append(notification)
notification['html'] = render_notification(
nf, render_target=target, **notification)
ctx = {
"retrieved": len(new_notifications),
"unread_count": request.user.notifications.unread().count(),
"notifications": notification_list,
"success": True,
"msg": msg,
}
return JsonResponse(ctx)
else:
msg = _("Notification flag not sent.")
ctx = {"success": False, "msg": msg}
return JsonResponse(ctx) | [
"def",
"notification_update",
"(",
"request",
")",
":",
"flag",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"'flag'",
",",
"None",
")",
"target",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"'target'",
",",
"'box'",
")",
"last_notification",
"=",
"in... | Handles live updating of notifications, follows ajax-polling approach.
Read more: http://stackoverflow.com/a/12855533/4726598
Required URL parameters: ``flag``.
Explanation:
- The ``flag`` parameter carries the last notification ID \
received by the user's browser.
- This ``flag`` is most likely to be generated by using \
a simple JS/JQuery DOM. Just grab the first element of \
the notification list.
- The element will have a ``data-id`` attribute set to the \
corresponding notification.
- We'll use it's value as the flag parameter.
- The view treats the ``last notification flag`` as a model \
```filter()`` and fetches all notifications greater than \
the flag for the user.
- Then the a JSON data is prepared with all necessary \
details such as, ``verb``, ``actor``, ``target`` and their \
URL etc. The foreignkey are serialized as their \
default ``__str__`` value.
- Everything will be HTML escaped by django's ``escape()``.
- Since these notification sent will only serve temporarily \
on the notification box and will be generated fresh \
using a whole template, to avoid client-side notification \
generation using the JSON data, the JSON data will also \
contain a rendered HTML string so that you can easily \
do a JQuery ``$yourNotificationBox.prepend()`` on the \
rendered html string of the notification.
- The template used is expected to be different than the \
template used in full page notification as the css \
and some other elements are highly likely to be \
different than the full page notification list. \
- The template used will be the ``notification type`` of the \
notification suffixed ``_box.html``. So, if your \
notification type is ``comment_reply``, the template \
will be ``comment_reply_box.html``.
- This template will be stored in ``notifications/includes/`` \
of your template directory.
- That makes: ``notifications/includes/comment_reply_box.html``
- The rest is self-explanatory.
:param request: HTTP request context.
:return: Notification updates (if any) in JSON format. | [
"Handles",
"live",
"updating",
"of",
"notifications",
"follows",
"ajax",
"-",
"polling",
"approach",
"."
] | b4aa03039759126889666a59117e83dcd4cdb374 | https://github.com/v1k45/django-notify-x/blob/b4aa03039759126889666a59117e83dcd4cdb374/notify/views.py#L171-L264 |
20,445 | v1k45/django-notify-x | notify/views.py | read_and_redirect | def read_and_redirect(request, notification_id):
"""
Marks the supplied notification as read and then redirects
to the supplied URL from the ``next`` URL parameter.
**IMPORTANT**: This is CSRF - unsafe method.
Only use it if its okay for you to mark notifications \
as read without a robust check.
:param request: HTTP request context.
:param notification_id: ID of the notification to be marked a read.
:returns: Redirect response to a valid target url.
"""
notification_page = reverse('notifications:all')
next_page = request.GET.get('next', notification_page)
if is_safe_url(next_page):
target = next_page
else:
target = notification_page
try:
user_nf = request.user.notifications.get(pk=notification_id)
if not user_nf.read:
user_nf.mark_as_read()
except Notification.DoesNotExist:
pass
return HttpResponseRedirect(target) | python | def read_and_redirect(request, notification_id):
notification_page = reverse('notifications:all')
next_page = request.GET.get('next', notification_page)
if is_safe_url(next_page):
target = next_page
else:
target = notification_page
try:
user_nf = request.user.notifications.get(pk=notification_id)
if not user_nf.read:
user_nf.mark_as_read()
except Notification.DoesNotExist:
pass
return HttpResponseRedirect(target) | [
"def",
"read_and_redirect",
"(",
"request",
",",
"notification_id",
")",
":",
"notification_page",
"=",
"reverse",
"(",
"'notifications:all'",
")",
"next_page",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"'next'",
",",
"notification_page",
")",
"if",
"is_safe_... | Marks the supplied notification as read and then redirects
to the supplied URL from the ``next`` URL parameter.
**IMPORTANT**: This is CSRF - unsafe method.
Only use it if its okay for you to mark notifications \
as read without a robust check.
:param request: HTTP request context.
:param notification_id: ID of the notification to be marked a read.
:returns: Redirect response to a valid target url. | [
"Marks",
"the",
"supplied",
"notification",
"as",
"read",
"and",
"then",
"redirects",
"to",
"the",
"supplied",
"URL",
"from",
"the",
"next",
"URL",
"parameter",
"."
] | b4aa03039759126889666a59117e83dcd4cdb374 | https://github.com/v1k45/django-notify-x/blob/b4aa03039759126889666a59117e83dcd4cdb374/notify/views.py#L268-L296 |
20,446 | mezz64/pyHik | pyhik/hikvision.py | HikCamera.get_motion_detection | def get_motion_detection(self):
"""Fetch current motion state from camera"""
url = ('%s/ISAPI/System/Video/inputs/'
'channels/1/motionDetection') % self.root_url
try:
response = self.hik_request.get(url, timeout=CONNECT_TIMEOUT)
except (requests.exceptions.RequestException,
requests.exceptions.ConnectionError) as err:
_LOGGING.error('Unable to fetch MotionDetection, error: %s', err)
self.motion_detection = None
return self.motion_detection
if response.status_code == requests.codes.unauthorized:
_LOGGING.error('Authentication failed')
self.motion_detection = None
return self.motion_detection
if response.status_code != requests.codes.ok:
# If we didn't receive 200, abort
_LOGGING.debug('Unable to fetch motion detection.')
self.motion_detection = None
return self.motion_detection
try:
tree = ET.fromstring(response.text)
ET.register_namespace("", self.namespace)
enabled = tree.find(self.element_query('enabled'))
if enabled is not None:
self._motion_detection_xml = tree
self.motion_detection = {'true': True, 'false': False}[enabled.text]
return self.motion_detection
except AttributeError as err:
_LOGGING.error('Entire response: %s', response.text)
_LOGGING.error('There was a problem: %s', err)
self.motion_detection = None
return self.motion_detection | python | def get_motion_detection(self):
url = ('%s/ISAPI/System/Video/inputs/'
'channels/1/motionDetection') % self.root_url
try:
response = self.hik_request.get(url, timeout=CONNECT_TIMEOUT)
except (requests.exceptions.RequestException,
requests.exceptions.ConnectionError) as err:
_LOGGING.error('Unable to fetch MotionDetection, error: %s', err)
self.motion_detection = None
return self.motion_detection
if response.status_code == requests.codes.unauthorized:
_LOGGING.error('Authentication failed')
self.motion_detection = None
return self.motion_detection
if response.status_code != requests.codes.ok:
# If we didn't receive 200, abort
_LOGGING.debug('Unable to fetch motion detection.')
self.motion_detection = None
return self.motion_detection
try:
tree = ET.fromstring(response.text)
ET.register_namespace("", self.namespace)
enabled = tree.find(self.element_query('enabled'))
if enabled is not None:
self._motion_detection_xml = tree
self.motion_detection = {'true': True, 'false': False}[enabled.text]
return self.motion_detection
except AttributeError as err:
_LOGGING.error('Entire response: %s', response.text)
_LOGGING.error('There was a problem: %s', err)
self.motion_detection = None
return self.motion_detection | [
"def",
"get_motion_detection",
"(",
"self",
")",
":",
"url",
"=",
"(",
"'%s/ISAPI/System/Video/inputs/'",
"'channels/1/motionDetection'",
")",
"%",
"self",
".",
"root_url",
"try",
":",
"response",
"=",
"self",
".",
"hik_request",
".",
"get",
"(",
"url",
",",
"... | Fetch current motion state from camera | [
"Fetch",
"current",
"motion",
"state",
"from",
"camera"
] | 1e7afca926e2b045257a43cbf8b1236a435493c2 | https://github.com/mezz64/pyHik/blob/1e7afca926e2b045257a43cbf8b1236a435493c2/pyhik/hikvision.py#L141-L179 |
20,447 | mezz64/pyHik | pyhik/hikvision.py | HikCamera._set_motion_detection | def _set_motion_detection(self, enable):
"""Set desired motion detection state on camera"""
url = ('%s/ISAPI/System/Video/inputs/'
'channels/1/motionDetection') % self.root_url
enabled = self._motion_detection_xml.find(self.element_query('enabled'))
if enabled is None:
_LOGGING.error("Couldn't find 'enabled' in the xml")
_LOGGING.error('XML: %s', ET.tostring(self._motion_detection_xml))
return
enabled.text = 'true' if enable else 'false'
xml = ET.tostring(self._motion_detection_xml)
try:
response = self.hik_request.put(url, data=xml, timeout=CONNECT_TIMEOUT)
except (requests.exceptions.RequestException,
requests.exceptions.ConnectionError) as err:
_LOGGING.error('Unable to set MotionDetection, error: %s', err)
return
if response.status_code == requests.codes.unauthorized:
_LOGGING.error('Authentication failed')
return
if response.status_code != requests.codes.ok:
# If we didn't receive 200, abort
_LOGGING.error('Unable to set motion detection: %s', response.text)
self.motion_detection = enable | python | def _set_motion_detection(self, enable):
url = ('%s/ISAPI/System/Video/inputs/'
'channels/1/motionDetection') % self.root_url
enabled = self._motion_detection_xml.find(self.element_query('enabled'))
if enabled is None:
_LOGGING.error("Couldn't find 'enabled' in the xml")
_LOGGING.error('XML: %s', ET.tostring(self._motion_detection_xml))
return
enabled.text = 'true' if enable else 'false'
xml = ET.tostring(self._motion_detection_xml)
try:
response = self.hik_request.put(url, data=xml, timeout=CONNECT_TIMEOUT)
except (requests.exceptions.RequestException,
requests.exceptions.ConnectionError) as err:
_LOGGING.error('Unable to set MotionDetection, error: %s', err)
return
if response.status_code == requests.codes.unauthorized:
_LOGGING.error('Authentication failed')
return
if response.status_code != requests.codes.ok:
# If we didn't receive 200, abort
_LOGGING.error('Unable to set motion detection: %s', response.text)
self.motion_detection = enable | [
"def",
"_set_motion_detection",
"(",
"self",
",",
"enable",
")",
":",
"url",
"=",
"(",
"'%s/ISAPI/System/Video/inputs/'",
"'channels/1/motionDetection'",
")",
"%",
"self",
".",
"root_url",
"enabled",
"=",
"self",
".",
"_motion_detection_xml",
".",
"find",
"(",
"se... | Set desired motion detection state on camera | [
"Set",
"desired",
"motion",
"detection",
"state",
"on",
"camera"
] | 1e7afca926e2b045257a43cbf8b1236a435493c2 | https://github.com/mezz64/pyHik/blob/1e7afca926e2b045257a43cbf8b1236a435493c2/pyhik/hikvision.py#L189-L218 |
20,448 | mezz64/pyHik | pyhik/hikvision.py | HikCamera.add_update_callback | def add_update_callback(self, callback, sensor):
"""Register as callback for when a matching device sensor changes."""
self._updateCallbacks.append([callback, sensor])
_LOGGING.debug('Added update callback to %s on %s', callback, sensor) | python | def add_update_callback(self, callback, sensor):
self._updateCallbacks.append([callback, sensor])
_LOGGING.debug('Added update callback to %s on %s', callback, sensor) | [
"def",
"add_update_callback",
"(",
"self",
",",
"callback",
",",
"sensor",
")",
":",
"self",
".",
"_updateCallbacks",
".",
"append",
"(",
"[",
"callback",
",",
"sensor",
"]",
")",
"_LOGGING",
".",
"debug",
"(",
"'Added update callback to %s on %s'",
",",
"call... | Register as callback for when a matching device sensor changes. | [
"Register",
"as",
"callback",
"for",
"when",
"a",
"matching",
"device",
"sensor",
"changes",
"."
] | 1e7afca926e2b045257a43cbf8b1236a435493c2 | https://github.com/mezz64/pyHik/blob/1e7afca926e2b045257a43cbf8b1236a435493c2/pyhik/hikvision.py#L220-L223 |
20,449 | mezz64/pyHik | pyhik/hikvision.py | HikCamera.initialize | def initialize(self):
"""Initialize deviceInfo and available events."""
device_info = self.get_device_info()
if device_info is None:
self.name = None
self.cam_id = None
self.event_states = None
return
for key in device_info:
if key == 'deviceName':
self.name = device_info[key]
elif key == 'deviceID':
if len(device_info[key]) > 10:
self.cam_id = device_info[key]
else:
self.cam_id = uuid.uuid4()
events_available = self.get_event_triggers()
if events_available:
for event, channel_list in events_available.items():
for channel in channel_list:
try:
self.event_states.setdefault(
SENSOR_MAP[event.lower()], []).append(
[False, channel, 0, datetime.datetime.now()])
except KeyError:
# Sensor type doesn't have a known friendly name
# We can't reliably handle it at this time...
_LOGGING.warning(
'Sensor type "%s" is unsupported.', event)
_LOGGING.debug('Initialized Dictionary: %s', self.event_states)
else:
_LOGGING.debug('No Events available in dictionary.')
self.get_motion_detection() | python | def initialize(self):
device_info = self.get_device_info()
if device_info is None:
self.name = None
self.cam_id = None
self.event_states = None
return
for key in device_info:
if key == 'deviceName':
self.name = device_info[key]
elif key == 'deviceID':
if len(device_info[key]) > 10:
self.cam_id = device_info[key]
else:
self.cam_id = uuid.uuid4()
events_available = self.get_event_triggers()
if events_available:
for event, channel_list in events_available.items():
for channel in channel_list:
try:
self.event_states.setdefault(
SENSOR_MAP[event.lower()], []).append(
[False, channel, 0, datetime.datetime.now()])
except KeyError:
# Sensor type doesn't have a known friendly name
# We can't reliably handle it at this time...
_LOGGING.warning(
'Sensor type "%s" is unsupported.', event)
_LOGGING.debug('Initialized Dictionary: %s', self.event_states)
else:
_LOGGING.debug('No Events available in dictionary.')
self.get_motion_detection() | [
"def",
"initialize",
"(",
"self",
")",
":",
"device_info",
"=",
"self",
".",
"get_device_info",
"(",
")",
"if",
"device_info",
"is",
"None",
":",
"self",
".",
"name",
"=",
"None",
"self",
".",
"cam_id",
"=",
"None",
"self",
".",
"event_states",
"=",
"N... | Initialize deviceInfo and available events. | [
"Initialize",
"deviceInfo",
"and",
"available",
"events",
"."
] | 1e7afca926e2b045257a43cbf8b1236a435493c2 | https://github.com/mezz64/pyHik/blob/1e7afca926e2b045257a43cbf8b1236a435493c2/pyhik/hikvision.py#L237-L274 |
20,450 | mezz64/pyHik | pyhik/hikvision.py | HikCamera.get_event_triggers | def get_event_triggers(self):
"""
Returns dict of supported events.
Key = Event Type
List = Channels that have that event activated
"""
events = {}
nvrflag = False
event_xml = []
url = '%s/ISAPI/Event/triggers' % self.root_url
try:
response = self.hik_request.get(url, timeout=CONNECT_TIMEOUT)
if response.status_code == requests.codes.not_found:
# Try alternate URL for triggers
_LOGGING.debug('Using alternate triggers URL.')
url = '%s/Event/triggers' % self.root_url
response = self.hik_request.get(url)
except (requests.exceptions.RequestException,
requests.exceptions.ConnectionError) as err:
_LOGGING.error('Unable to fetch events, error: %s', err)
return None
if response.status_code != 200:
# If we didn't recieve 200, abort
return None
# pylint: disable=too-many-nested-blocks
try:
content = ET.fromstring(response.text)
if content[0].find(self.element_query('EventTrigger')):
event_xml = content[0].findall(
self.element_query('EventTrigger'))
elif content.find(self.element_query('EventTrigger')):
# This is either an NVR or a rebadged camera
event_xml = content.findall(
self.element_query('EventTrigger'))
for eventtrigger in event_xml:
ettype = eventtrigger.find(self.element_query('eventType'))
# Catch empty xml defintions
if ettype is None:
break
etnotify = eventtrigger.find(
self.element_query('EventTriggerNotificationList'))
etchannel = None
etchannel_num = 0
for node_name in CHANNEL_NAMES:
etchannel = eventtrigger.find(
self.element_query(node_name))
if etchannel is not None:
try:
# Need to make sure this is actually a number
etchannel_num = int(etchannel.text)
if etchannel_num > 1:
# Must be an nvr
nvrflag = True
break
except ValueError:
# Field must not be an integer
pass
if etnotify:
for notifytrigger in etnotify:
ntype = notifytrigger.find(
self.element_query('notificationMethod'))
if ntype.text == 'center' or ntype.text == 'HTTP':
"""
If we got this far we found an event that we want
to track.
"""
events.setdefault(ettype.text, []) \
.append(etchannel_num)
except (AttributeError, ET.ParseError) as err:
_LOGGING.error(
'There was a problem finding an element: %s', err)
return None
if nvrflag:
self.device_type = NVR_DEVICE
else:
self.device_type = CAM_DEVICE
_LOGGING.debug('Processed %s as %s Device.',
self.cam_id, self.device_type)
_LOGGING.debug('Found events: %s', events)
self.hik_request.close()
return events | python | def get_event_triggers(self):
events = {}
nvrflag = False
event_xml = []
url = '%s/ISAPI/Event/triggers' % self.root_url
try:
response = self.hik_request.get(url, timeout=CONNECT_TIMEOUT)
if response.status_code == requests.codes.not_found:
# Try alternate URL for triggers
_LOGGING.debug('Using alternate triggers URL.')
url = '%s/Event/triggers' % self.root_url
response = self.hik_request.get(url)
except (requests.exceptions.RequestException,
requests.exceptions.ConnectionError) as err:
_LOGGING.error('Unable to fetch events, error: %s', err)
return None
if response.status_code != 200:
# If we didn't recieve 200, abort
return None
# pylint: disable=too-many-nested-blocks
try:
content = ET.fromstring(response.text)
if content[0].find(self.element_query('EventTrigger')):
event_xml = content[0].findall(
self.element_query('EventTrigger'))
elif content.find(self.element_query('EventTrigger')):
# This is either an NVR or a rebadged camera
event_xml = content.findall(
self.element_query('EventTrigger'))
for eventtrigger in event_xml:
ettype = eventtrigger.find(self.element_query('eventType'))
# Catch empty xml defintions
if ettype is None:
break
etnotify = eventtrigger.find(
self.element_query('EventTriggerNotificationList'))
etchannel = None
etchannel_num = 0
for node_name in CHANNEL_NAMES:
etchannel = eventtrigger.find(
self.element_query(node_name))
if etchannel is not None:
try:
# Need to make sure this is actually a number
etchannel_num = int(etchannel.text)
if etchannel_num > 1:
# Must be an nvr
nvrflag = True
break
except ValueError:
# Field must not be an integer
pass
if etnotify:
for notifytrigger in etnotify:
ntype = notifytrigger.find(
self.element_query('notificationMethod'))
if ntype.text == 'center' or ntype.text == 'HTTP':
"""
If we got this far we found an event that we want
to track.
"""
events.setdefault(ettype.text, []) \
.append(etchannel_num)
except (AttributeError, ET.ParseError) as err:
_LOGGING.error(
'There was a problem finding an element: %s', err)
return None
if nvrflag:
self.device_type = NVR_DEVICE
else:
self.device_type = CAM_DEVICE
_LOGGING.debug('Processed %s as %s Device.',
self.cam_id, self.device_type)
_LOGGING.debug('Found events: %s', events)
self.hik_request.close()
return events | [
"def",
"get_event_triggers",
"(",
"self",
")",
":",
"events",
"=",
"{",
"}",
"nvrflag",
"=",
"False",
"event_xml",
"=",
"[",
"]",
"url",
"=",
"'%s/ISAPI/Event/triggers'",
"%",
"self",
".",
"root_url",
"try",
":",
"response",
"=",
"self",
".",
"hik_request"... | Returns dict of supported events.
Key = Event Type
List = Channels that have that event activated | [
"Returns",
"dict",
"of",
"supported",
"events",
".",
"Key",
"=",
"Event",
"Type",
"List",
"=",
"Channels",
"that",
"have",
"that",
"event",
"activated"
] | 1e7afca926e2b045257a43cbf8b1236a435493c2 | https://github.com/mezz64/pyHik/blob/1e7afca926e2b045257a43cbf8b1236a435493c2/pyhik/hikvision.py#L276-L369 |
20,451 | mezz64/pyHik | pyhik/hikvision.py | HikCamera.get_device_info | def get_device_info(self):
"""Parse deviceInfo into dictionary."""
device_info = {}
url = '%s/ISAPI/System/deviceInfo' % self.root_url
using_digest = False
try:
response = self.hik_request.get(url, timeout=CONNECT_TIMEOUT)
if response.status_code == requests.codes.unauthorized:
_LOGGING.debug('Basic authentication failed. Using digest.')
self.hik_request.auth = HTTPDigestAuth(self.usr, self.pwd)
using_digest = True
response = self.hik_request.get(url)
if response.status_code == requests.codes.not_found:
# Try alternate URL for deviceInfo
_LOGGING.debug('Using alternate deviceInfo URL.')
url = '%s/System/deviceInfo' % self.root_url
response = self.hik_request.get(url)
# Seems to be difference between camera and nvr, they can't seem to
# agree if they should 404 or 401 first
if not using_digest and response.status_code == requests.codes.unauthorized:
_LOGGING.debug('Basic authentication failed. Using digest.')
self.hik_request.auth = HTTPDigestAuth(self.usr, self.pwd)
using_digest = True
response = self.hik_request.get(url)
except (requests.exceptions.RequestException,
requests.exceptions.ConnectionError) as err:
_LOGGING.error('Unable to fetch deviceInfo, error: %s', err)
return None
if response.status_code == requests.codes.unauthorized:
_LOGGING.error('Authentication failed')
return None
if response.status_code != requests.codes.ok:
# If we didn't receive 200, abort
_LOGGING.debug('Unable to fetch device info.')
return None
try:
tree = ET.fromstring(response.text)
# Try to fetch namespace from XML
nmsp = tree.tag.split('}')[0].strip('{')
self.namespace = nmsp if nmsp.startswith('http') else XML_NAMESPACE
_LOGGING.debug('Using Namespace: %s', self.namespace)
for item in tree:
tag = item.tag.split('}')[1]
device_info[tag] = item.text
return device_info
except AttributeError as err:
_LOGGING.error('Entire response: %s', response.text)
_LOGGING.error('There was a problem: %s', err)
return None | python | def get_device_info(self):
device_info = {}
url = '%s/ISAPI/System/deviceInfo' % self.root_url
using_digest = False
try:
response = self.hik_request.get(url, timeout=CONNECT_TIMEOUT)
if response.status_code == requests.codes.unauthorized:
_LOGGING.debug('Basic authentication failed. Using digest.')
self.hik_request.auth = HTTPDigestAuth(self.usr, self.pwd)
using_digest = True
response = self.hik_request.get(url)
if response.status_code == requests.codes.not_found:
# Try alternate URL for deviceInfo
_LOGGING.debug('Using alternate deviceInfo URL.')
url = '%s/System/deviceInfo' % self.root_url
response = self.hik_request.get(url)
# Seems to be difference between camera and nvr, they can't seem to
# agree if they should 404 or 401 first
if not using_digest and response.status_code == requests.codes.unauthorized:
_LOGGING.debug('Basic authentication failed. Using digest.')
self.hik_request.auth = HTTPDigestAuth(self.usr, self.pwd)
using_digest = True
response = self.hik_request.get(url)
except (requests.exceptions.RequestException,
requests.exceptions.ConnectionError) as err:
_LOGGING.error('Unable to fetch deviceInfo, error: %s', err)
return None
if response.status_code == requests.codes.unauthorized:
_LOGGING.error('Authentication failed')
return None
if response.status_code != requests.codes.ok:
# If we didn't receive 200, abort
_LOGGING.debug('Unable to fetch device info.')
return None
try:
tree = ET.fromstring(response.text)
# Try to fetch namespace from XML
nmsp = tree.tag.split('}')[0].strip('{')
self.namespace = nmsp if nmsp.startswith('http') else XML_NAMESPACE
_LOGGING.debug('Using Namespace: %s', self.namespace)
for item in tree:
tag = item.tag.split('}')[1]
device_info[tag] = item.text
return device_info
except AttributeError as err:
_LOGGING.error('Entire response: %s', response.text)
_LOGGING.error('There was a problem: %s', err)
return None | [
"def",
"get_device_info",
"(",
"self",
")",
":",
"device_info",
"=",
"{",
"}",
"url",
"=",
"'%s/ISAPI/System/deviceInfo'",
"%",
"self",
".",
"root_url",
"using_digest",
"=",
"False",
"try",
":",
"response",
"=",
"self",
".",
"hik_request",
".",
"get",
"(",
... | Parse deviceInfo into dictionary. | [
"Parse",
"deviceInfo",
"into",
"dictionary",
"."
] | 1e7afca926e2b045257a43cbf8b1236a435493c2 | https://github.com/mezz64/pyHik/blob/1e7afca926e2b045257a43cbf8b1236a435493c2/pyhik/hikvision.py#L371-L428 |
20,452 | mezz64/pyHik | pyhik/hikvision.py | HikCamera.watchdog_handler | def watchdog_handler(self):
"""Take care of threads if wachdog expires."""
_LOGGING.debug('%s Watchdog expired. Resetting connection.', self.name)
self.watchdog.stop()
self.reset_thrd.set() | python | def watchdog_handler(self):
_LOGGING.debug('%s Watchdog expired. Resetting connection.', self.name)
self.watchdog.stop()
self.reset_thrd.set() | [
"def",
"watchdog_handler",
"(",
"self",
")",
":",
"_LOGGING",
".",
"debug",
"(",
"'%s Watchdog expired. Resetting connection.'",
",",
"self",
".",
"name",
")",
"self",
".",
"watchdog",
".",
"stop",
"(",
")",
"self",
".",
"reset_thrd",
".",
"set",
"(",
")"
] | Take care of threads if wachdog expires. | [
"Take",
"care",
"of",
"threads",
"if",
"wachdog",
"expires",
"."
] | 1e7afca926e2b045257a43cbf8b1236a435493c2 | https://github.com/mezz64/pyHik/blob/1e7afca926e2b045257a43cbf8b1236a435493c2/pyhik/hikvision.py#L430-L434 |
20,453 | mezz64/pyHik | pyhik/hikvision.py | HikCamera.disconnect | def disconnect(self):
"""Disconnect from event stream."""
_LOGGING.debug('Disconnecting from stream: %s', self.name)
self.kill_thrd.set()
self.thrd.join()
_LOGGING.debug('Event stream thread for %s is stopped', self.name)
self.kill_thrd.clear() | python | def disconnect(self):
_LOGGING.debug('Disconnecting from stream: %s', self.name)
self.kill_thrd.set()
self.thrd.join()
_LOGGING.debug('Event stream thread for %s is stopped', self.name)
self.kill_thrd.clear() | [
"def",
"disconnect",
"(",
"self",
")",
":",
"_LOGGING",
".",
"debug",
"(",
"'Disconnecting from stream: %s'",
",",
"self",
".",
"name",
")",
"self",
".",
"kill_thrd",
".",
"set",
"(",
")",
"self",
".",
"thrd",
".",
"join",
"(",
")",
"_LOGGING",
".",
"d... | Disconnect from event stream. | [
"Disconnect",
"from",
"event",
"stream",
"."
] | 1e7afca926e2b045257a43cbf8b1236a435493c2 | https://github.com/mezz64/pyHik/blob/1e7afca926e2b045257a43cbf8b1236a435493c2/pyhik/hikvision.py#L436-L442 |
20,454 | mezz64/pyHik | pyhik/hikvision.py | HikCamera.alert_stream | def alert_stream(self, reset_event, kill_event):
"""Open event stream."""
_LOGGING.debug('Stream Thread Started: %s, %s', self.name, self.cam_id)
start_event = False
parse_string = ""
fail_count = 0
url = '%s/ISAPI/Event/notification/alertStream' % self.root_url
# pylint: disable=too-many-nested-blocks
while True:
try:
stream = self.hik_request.get(url, stream=True,
timeout=(CONNECT_TIMEOUT,
READ_TIMEOUT))
if stream.status_code == requests.codes.not_found:
# Try alternate URL for stream
url = '%s/Event/notification/alertStream' % self.root_url
stream = self.hik_request.get(url, stream=True)
if stream.status_code != requests.codes.ok:
raise ValueError('Connection unsucessful.')
else:
_LOGGING.debug('%s Connection Successful.', self.name)
fail_count = 0
self.watchdog.start()
for line in stream.iter_lines():
# _LOGGING.debug('Processing line from %s', self.name)
# filter out keep-alive new lines
if line:
str_line = line.decode("utf-8", "ignore")
# New events start with --boundry
if str_line.find('<EventNotificationAlert') != -1:
# Start of event message
start_event = True
parse_string += str_line
elif str_line.find('</EventNotificationAlert>') != -1:
# Message end found found
parse_string += str_line
start_event = False
if parse_string:
tree = ET.fromstring(parse_string)
self.process_stream(tree)
self.update_stale()
parse_string = ""
else:
if start_event:
parse_string += str_line
if kill_event.is_set():
# We were asked to stop the thread so lets do so.
break
elif reset_event.is_set():
# We need to reset the connection.
raise ValueError('Watchdog failed.')
if kill_event.is_set():
# We were asked to stop the thread so lets do so.
_LOGGING.debug('Stopping event stream thread for %s',
self.name)
self.watchdog.stop()
self.hik_request.close()
return
elif reset_event.is_set():
# We need to reset the connection.
raise ValueError('Watchdog failed.')
except (ValueError,
requests.exceptions.ConnectionError,
requests.exceptions.ChunkedEncodingError) as err:
fail_count += 1
reset_event.clear()
_LOGGING.warning('%s Connection Failed (count=%d). Waiting %ss. Err: %s',
self.name, fail_count, (fail_count * 5) + 5, err)
parse_string = ""
self.watchdog.stop()
self.hik_request.close()
time.sleep(5)
self.update_stale()
time.sleep(fail_count * 5)
continue | python | def alert_stream(self, reset_event, kill_event):
_LOGGING.debug('Stream Thread Started: %s, %s', self.name, self.cam_id)
start_event = False
parse_string = ""
fail_count = 0
url = '%s/ISAPI/Event/notification/alertStream' % self.root_url
# pylint: disable=too-many-nested-blocks
while True:
try:
stream = self.hik_request.get(url, stream=True,
timeout=(CONNECT_TIMEOUT,
READ_TIMEOUT))
if stream.status_code == requests.codes.not_found:
# Try alternate URL for stream
url = '%s/Event/notification/alertStream' % self.root_url
stream = self.hik_request.get(url, stream=True)
if stream.status_code != requests.codes.ok:
raise ValueError('Connection unsucessful.')
else:
_LOGGING.debug('%s Connection Successful.', self.name)
fail_count = 0
self.watchdog.start()
for line in stream.iter_lines():
# _LOGGING.debug('Processing line from %s', self.name)
# filter out keep-alive new lines
if line:
str_line = line.decode("utf-8", "ignore")
# New events start with --boundry
if str_line.find('<EventNotificationAlert') != -1:
# Start of event message
start_event = True
parse_string += str_line
elif str_line.find('</EventNotificationAlert>') != -1:
# Message end found found
parse_string += str_line
start_event = False
if parse_string:
tree = ET.fromstring(parse_string)
self.process_stream(tree)
self.update_stale()
parse_string = ""
else:
if start_event:
parse_string += str_line
if kill_event.is_set():
# We were asked to stop the thread so lets do so.
break
elif reset_event.is_set():
# We need to reset the connection.
raise ValueError('Watchdog failed.')
if kill_event.is_set():
# We were asked to stop the thread so lets do so.
_LOGGING.debug('Stopping event stream thread for %s',
self.name)
self.watchdog.stop()
self.hik_request.close()
return
elif reset_event.is_set():
# We need to reset the connection.
raise ValueError('Watchdog failed.')
except (ValueError,
requests.exceptions.ConnectionError,
requests.exceptions.ChunkedEncodingError) as err:
fail_count += 1
reset_event.clear()
_LOGGING.warning('%s Connection Failed (count=%d). Waiting %ss. Err: %s',
self.name, fail_count, (fail_count * 5) + 5, err)
parse_string = ""
self.watchdog.stop()
self.hik_request.close()
time.sleep(5)
self.update_stale()
time.sleep(fail_count * 5)
continue | [
"def",
"alert_stream",
"(",
"self",
",",
"reset_event",
",",
"kill_event",
")",
":",
"_LOGGING",
".",
"debug",
"(",
"'Stream Thread Started: %s, %s'",
",",
"self",
".",
"name",
",",
"self",
".",
"cam_id",
")",
"start_event",
"=",
"False",
"parse_string",
"=",
... | Open event stream. | [
"Open",
"event",
"stream",
"."
] | 1e7afca926e2b045257a43cbf8b1236a435493c2 | https://github.com/mezz64/pyHik/blob/1e7afca926e2b045257a43cbf8b1236a435493c2/pyhik/hikvision.py#L449-L531 |
20,455 | mezz64/pyHik | pyhik/hikvision.py | HikCamera.process_stream | def process_stream(self, tree):
"""Process incoming event stream packets."""
try:
etype = SENSOR_MAP[tree.find(
self.element_query('eventType')).text.lower()]
estate = tree.find(
self.element_query('eventState')).text
echid = tree.find(
self.element_query('channelID'))
if echid is None:
# Some devices use a different key
echid = tree.find(
self.element_query('dynChannelID'))
echid = int(echid.text)
ecount = tree.find(
self.element_query('activePostCount')).text
except (AttributeError, KeyError, IndexError) as err:
_LOGGING.error('Problem finding attribute: %s', err)
return
# Take care of keep-alive
if len(etype) > 0 and etype == 'Video Loss':
self.watchdog.pet()
# Track state if it's in the event list.
if len(etype) > 0:
state = self.fetch_attributes(etype, echid)
if state:
# Determine if state has changed
# If so, publish, otherwise do nothing
estate = (estate == 'active')
old_state = state[0]
attr = [estate, echid, int(ecount),
datetime.datetime.now()]
self.update_attributes(etype, echid, attr)
if estate != old_state:
self.publish_changes(etype, echid)
self.watchdog.pet() | python | def process_stream(self, tree):
try:
etype = SENSOR_MAP[tree.find(
self.element_query('eventType')).text.lower()]
estate = tree.find(
self.element_query('eventState')).text
echid = tree.find(
self.element_query('channelID'))
if echid is None:
# Some devices use a different key
echid = tree.find(
self.element_query('dynChannelID'))
echid = int(echid.text)
ecount = tree.find(
self.element_query('activePostCount')).text
except (AttributeError, KeyError, IndexError) as err:
_LOGGING.error('Problem finding attribute: %s', err)
return
# Take care of keep-alive
if len(etype) > 0 and etype == 'Video Loss':
self.watchdog.pet()
# Track state if it's in the event list.
if len(etype) > 0:
state = self.fetch_attributes(etype, echid)
if state:
# Determine if state has changed
# If so, publish, otherwise do nothing
estate = (estate == 'active')
old_state = state[0]
attr = [estate, echid, int(ecount),
datetime.datetime.now()]
self.update_attributes(etype, echid, attr)
if estate != old_state:
self.publish_changes(etype, echid)
self.watchdog.pet() | [
"def",
"process_stream",
"(",
"self",
",",
"tree",
")",
":",
"try",
":",
"etype",
"=",
"SENSOR_MAP",
"[",
"tree",
".",
"find",
"(",
"self",
".",
"element_query",
"(",
"'eventType'",
")",
")",
".",
"text",
".",
"lower",
"(",
")",
"]",
"estate",
"=",
... | Process incoming event stream packets. | [
"Process",
"incoming",
"event",
"stream",
"packets",
"."
] | 1e7afca926e2b045257a43cbf8b1236a435493c2 | https://github.com/mezz64/pyHik/blob/1e7afca926e2b045257a43cbf8b1236a435493c2/pyhik/hikvision.py#L533-L571 |
20,456 | mezz64/pyHik | pyhik/hikvision.py | HikCamera.update_stale | def update_stale(self):
"""Update stale active statuses"""
# Some events don't post an inactive XML, only active.
# If we don't get an active update for 5 seconds we can
# assume the event is no longer active and update accordingly.
for etype, echannels in self.event_states.items():
for eprop in echannels:
if eprop[3] is not None:
sec_elap = ((datetime.datetime.now()-eprop[3])
.total_seconds())
# print('Seconds since last update: {}'.format(sec_elap))
if sec_elap > 5 and eprop[0] is True:
_LOGGING.debug('Updating stale event %s on CH(%s)',
etype, eprop[1])
attr = [False, eprop[1], eprop[2],
datetime.datetime.now()]
self.update_attributes(etype, eprop[1], attr)
self.publish_changes(etype, eprop[1]) | python | def update_stale(self):
# Some events don't post an inactive XML, only active.
# If we don't get an active update for 5 seconds we can
# assume the event is no longer active and update accordingly.
for etype, echannels in self.event_states.items():
for eprop in echannels:
if eprop[3] is not None:
sec_elap = ((datetime.datetime.now()-eprop[3])
.total_seconds())
# print('Seconds since last update: {}'.format(sec_elap))
if sec_elap > 5 and eprop[0] is True:
_LOGGING.debug('Updating stale event %s on CH(%s)',
etype, eprop[1])
attr = [False, eprop[1], eprop[2],
datetime.datetime.now()]
self.update_attributes(etype, eprop[1], attr)
self.publish_changes(etype, eprop[1]) | [
"def",
"update_stale",
"(",
"self",
")",
":",
"# Some events don't post an inactive XML, only active.",
"# If we don't get an active update for 5 seconds we can",
"# assume the event is no longer active and update accordingly.",
"for",
"etype",
",",
"echannels",
"in",
"self",
".",
"e... | Update stale active statuses | [
"Update",
"stale",
"active",
"statuses"
] | 1e7afca926e2b045257a43cbf8b1236a435493c2 | https://github.com/mezz64/pyHik/blob/1e7afca926e2b045257a43cbf8b1236a435493c2/pyhik/hikvision.py#L573-L590 |
20,457 | mezz64/pyHik | pyhik/hikvision.py | HikCamera.publish_changes | def publish_changes(self, etype, echid):
"""Post updates for specified event type."""
_LOGGING.debug('%s Update: %s, %s',
self.name, etype, self.fetch_attributes(etype, echid))
signal = 'ValueChanged.{}'.format(self.cam_id)
sender = '{}.{}'.format(etype, echid)
if dispatcher:
dispatcher.send(signal=signal, sender=sender)
self._do_update_callback('{}.{}.{}'.format(self.cam_id, etype, echid)) | python | def publish_changes(self, etype, echid):
_LOGGING.debug('%s Update: %s, %s',
self.name, etype, self.fetch_attributes(etype, echid))
signal = 'ValueChanged.{}'.format(self.cam_id)
sender = '{}.{}'.format(etype, echid)
if dispatcher:
dispatcher.send(signal=signal, sender=sender)
self._do_update_callback('{}.{}.{}'.format(self.cam_id, etype, echid)) | [
"def",
"publish_changes",
"(",
"self",
",",
"etype",
",",
"echid",
")",
":",
"_LOGGING",
".",
"debug",
"(",
"'%s Update: %s, %s'",
",",
"self",
".",
"name",
",",
"etype",
",",
"self",
".",
"fetch_attributes",
"(",
"etype",
",",
"echid",
")",
")",
"signal... | Post updates for specified event type. | [
"Post",
"updates",
"for",
"specified",
"event",
"type",
"."
] | 1e7afca926e2b045257a43cbf8b1236a435493c2 | https://github.com/mezz64/pyHik/blob/1e7afca926e2b045257a43cbf8b1236a435493c2/pyhik/hikvision.py#L592-L601 |
20,458 | mezz64/pyHik | pyhik/watchdog.py | Watchdog.start | def start(self):
""" Starts the watchdog timer. """
self._timer = Timer(self.time, self.handler)
self._timer.daemon = True
self._timer.start()
return | python | def start(self):
self._timer = Timer(self.time, self.handler)
self._timer.daemon = True
self._timer.start()
return | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"_timer",
"=",
"Timer",
"(",
"self",
".",
"time",
",",
"self",
".",
"handler",
")",
"self",
".",
"_timer",
".",
"daemon",
"=",
"True",
"self",
".",
"_timer",
".",
"start",
"(",
")",
"return"
] | Starts the watchdog timer. | [
"Starts",
"the",
"watchdog",
"timer",
"."
] | 1e7afca926e2b045257a43cbf8b1236a435493c2 | https://github.com/mezz64/pyHik/blob/1e7afca926e2b045257a43cbf8b1236a435493c2/pyhik/watchdog.py#L21-L26 |
20,459 | mezz64/pyHik | examples/basic_usage.py | HikCamObject.flip_motion | def flip_motion(self, value):
"""Toggle motion detection"""
if value:
self.cam.enable_motion_detection()
else:
self.cam.disable_motion_detection() | python | def flip_motion(self, value):
if value:
self.cam.enable_motion_detection()
else:
self.cam.disable_motion_detection() | [
"def",
"flip_motion",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
":",
"self",
".",
"cam",
".",
"enable_motion_detection",
"(",
")",
"else",
":",
"self",
".",
"cam",
".",
"disable_motion_detection",
"(",
")"
] | Toggle motion detection | [
"Toggle",
"motion",
"detection"
] | 1e7afca926e2b045257a43cbf8b1236a435493c2 | https://github.com/mezz64/pyHik/blob/1e7afca926e2b045257a43cbf8b1236a435493c2/examples/basic_usage.py#L47-L52 |
20,460 | mezz64/pyHik | examples/basic_usage.py | HikSensor.update_callback | def update_callback(self, msg):
""" get updates. """
print('Callback: {}'.format(msg))
print('{}:{} @ {}'.format(self.name, self._sensor_state(), self._sensor_last_update())) | python | def update_callback(self, msg):
print('Callback: {}'.format(msg))
print('{}:{} @ {}'.format(self.name, self._sensor_state(), self._sensor_last_update())) | [
"def",
"update_callback",
"(",
"self",
",",
"msg",
")",
":",
"print",
"(",
"'Callback: {}'",
".",
"format",
"(",
"msg",
")",
")",
"print",
"(",
"'{}:{} @ {}'",
".",
"format",
"(",
"self",
".",
"name",
",",
"self",
".",
"_sensor_state",
"(",
")",
",",
... | get updates. | [
"get",
"updates",
"."
] | 1e7afca926e2b045257a43cbf8b1236a435493c2 | https://github.com/mezz64/pyHik/blob/1e7afca926e2b045257a43cbf8b1236a435493c2/examples/basic_usage.py#L91-L94 |
20,461 | mbr/flask-nav | flask_nav/elements.py | NavigationItem.render | def render(self, renderer=None, **kwargs):
"""Render the navigational item using a renderer.
:param renderer: An object implementing the :class:`~.Renderer`
interface.
:return: A markupsafe string with the rendered result.
"""
return Markup(get_renderer(current_app, renderer)(**kwargs).visit(
self)) | python | def render(self, renderer=None, **kwargs):
return Markup(get_renderer(current_app, renderer)(**kwargs).visit(
self)) | [
"def",
"render",
"(",
"self",
",",
"renderer",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"Markup",
"(",
"get_renderer",
"(",
"current_app",
",",
"renderer",
")",
"(",
"*",
"*",
"kwargs",
")",
".",
"visit",
"(",
"self",
")",
")"
] | Render the navigational item using a renderer.
:param renderer: An object implementing the :class:`~.Renderer`
interface.
:return: A markupsafe string with the rendered result. | [
"Render",
"the",
"navigational",
"item",
"using",
"a",
"renderer",
"."
] | 06f3b5b2addad29c2fc531a7e8e74958e9e4b793 | https://github.com/mbr/flask-nav/blob/06f3b5b2addad29c2fc531a7e8e74958e9e4b793/flask_nav/elements.py#L16-L24 |
20,462 | mbr/flask-nav | flask_nav/renderers.py | Renderer.visit_object | def visit_object(self, node):
"""Fallback rendering for objects.
If the current application is in debug-mode
(``flask.current_app.debug`` is ``True``), an ``<!-- HTML comment
-->`` will be rendered, indicating which class is missing a visitation
function.
Outside of debug-mode, returns an empty string.
"""
if current_app.debug:
return tags.comment('no implementation in {} to render {}'.format(
self.__class__.__name__,
node.__class__.__name__, ))
return '' | python | def visit_object(self, node):
if current_app.debug:
return tags.comment('no implementation in {} to render {}'.format(
self.__class__.__name__,
node.__class__.__name__, ))
return '' | [
"def",
"visit_object",
"(",
"self",
",",
"node",
")",
":",
"if",
"current_app",
".",
"debug",
":",
"return",
"tags",
".",
"comment",
"(",
"'no implementation in {} to render {}'",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"node",
".... | Fallback rendering for objects.
If the current application is in debug-mode
(``flask.current_app.debug`` is ``True``), an ``<!-- HTML comment
-->`` will be rendered, indicating which class is missing a visitation
function.
Outside of debug-mode, returns an empty string. | [
"Fallback",
"rendering",
"for",
"objects",
"."
] | 06f3b5b2addad29c2fc531a7e8e74958e9e4b793 | https://github.com/mbr/flask-nav/blob/06f3b5b2addad29c2fc531a7e8e74958e9e4b793/flask_nav/renderers.py#L13-L27 |
20,463 | mbr/flask-nav | flask_nav/__init__.py | register_renderer | def register_renderer(app, id, renderer, force=True):
"""Registers a renderer on the application.
:param app: The :class:`~flask.Flask` application to register the renderer
on
:param id: Internal id-string for the renderer
:param renderer: Renderer to register
:param force: Whether or not to overwrite the renderer if a different one
is already registered for ``id``
"""
renderers = app.extensions.setdefault('nav_renderers', {})
if force:
renderers[id] = renderer
else:
renderers.setdefault(id, renderer) | python | def register_renderer(app, id, renderer, force=True):
renderers = app.extensions.setdefault('nav_renderers', {})
if force:
renderers[id] = renderer
else:
renderers.setdefault(id, renderer) | [
"def",
"register_renderer",
"(",
"app",
",",
"id",
",",
"renderer",
",",
"force",
"=",
"True",
")",
":",
"renderers",
"=",
"app",
".",
"extensions",
".",
"setdefault",
"(",
"'nav_renderers'",
",",
"{",
"}",
")",
"if",
"force",
":",
"renderers",
"[",
"i... | Registers a renderer on the application.
:param app: The :class:`~flask.Flask` application to register the renderer
on
:param id: Internal id-string for the renderer
:param renderer: Renderer to register
:param force: Whether or not to overwrite the renderer if a different one
is already registered for ``id`` | [
"Registers",
"a",
"renderer",
"on",
"the",
"application",
"."
] | 06f3b5b2addad29c2fc531a7e8e74958e9e4b793 | https://github.com/mbr/flask-nav/blob/06f3b5b2addad29c2fc531a7e8e74958e9e4b793/flask_nav/__init__.py#L6-L21 |
20,464 | mbr/flask-nav | flask_nav/__init__.py | get_renderer | def get_renderer(app, id):
"""Retrieve a renderer.
:param app: :class:`~flask.Flask` application to look ``id`` up on
:param id: Internal renderer id-string to look up
"""
renderer = app.extensions.get('nav_renderers', {})[id]
if isinstance(renderer, tuple):
mod_name, cls_name = renderer
mod = import_module(mod_name)
cls = mod
for name in cls_name.split('.'):
cls = getattr(cls, name)
return cls
return renderer | python | def get_renderer(app, id):
renderer = app.extensions.get('nav_renderers', {})[id]
if isinstance(renderer, tuple):
mod_name, cls_name = renderer
mod = import_module(mod_name)
cls = mod
for name in cls_name.split('.'):
cls = getattr(cls, name)
return cls
return renderer | [
"def",
"get_renderer",
"(",
"app",
",",
"id",
")",
":",
"renderer",
"=",
"app",
".",
"extensions",
".",
"get",
"(",
"'nav_renderers'",
",",
"{",
"}",
")",
"[",
"id",
"]",
"if",
"isinstance",
"(",
"renderer",
",",
"tuple",
")",
":",
"mod_name",
",",
... | Retrieve a renderer.
:param app: :class:`~flask.Flask` application to look ``id`` up on
:param id: Internal renderer id-string to look up | [
"Retrieve",
"a",
"renderer",
"."
] | 06f3b5b2addad29c2fc531a7e8e74958e9e4b793 | https://github.com/mbr/flask-nav/blob/06f3b5b2addad29c2fc531a7e8e74958e9e4b793/flask_nav/__init__.py#L24-L42 |
20,465 | mbr/flask-nav | flask_nav/__init__.py | Nav.init_app | def init_app(self, app):
"""Initialize an application.
:param app: A :class:`~flask.Flask` app.
"""
if not hasattr(app, 'extensions'):
app.extensions = {}
app.extensions['nav'] = self
app.add_template_global(self.elems, 'nav')
# register some renderers
for args in self._renderers:
register_renderer(app, *args) | python | def init_app(self, app):
if not hasattr(app, 'extensions'):
app.extensions = {}
app.extensions['nav'] = self
app.add_template_global(self.elems, 'nav')
# register some renderers
for args in self._renderers:
register_renderer(app, *args) | [
"def",
"init_app",
"(",
"self",
",",
"app",
")",
":",
"if",
"not",
"hasattr",
"(",
"app",
",",
"'extensions'",
")",
":",
"app",
".",
"extensions",
"=",
"{",
"}",
"app",
".",
"extensions",
"[",
"'nav'",
"]",
"=",
"self",
"app",
".",
"add_template_glob... | Initialize an application.
:param app: A :class:`~flask.Flask` app. | [
"Initialize",
"an",
"application",
"."
] | 06f3b5b2addad29c2fc531a7e8e74958e9e4b793 | https://github.com/mbr/flask-nav/blob/06f3b5b2addad29c2fc531a7e8e74958e9e4b793/flask_nav/__init__.py#L99-L112 |
20,466 | mbr/flask-nav | flask_nav/__init__.py | Nav.navigation | def navigation(self, id=None):
"""Function decorator for navbar registration.
Convenience function, calls :meth:`.register_element` with ``id`` and
the decorated function as ``elem``.
:param id: ID to pass on. If ``None``, uses the decorated functions
name.
"""
def wrapper(f):
self.register_element(id or f.__name__, f)
return f
return wrapper | python | def navigation(self, id=None):
def wrapper(f):
self.register_element(id or f.__name__, f)
return f
return wrapper | [
"def",
"navigation",
"(",
"self",
",",
"id",
"=",
"None",
")",
":",
"def",
"wrapper",
"(",
"f",
")",
":",
"self",
".",
"register_element",
"(",
"id",
"or",
"f",
".",
"__name__",
",",
"f",
")",
"return",
"f",
"return",
"wrapper"
] | Function decorator for navbar registration.
Convenience function, calls :meth:`.register_element` with ``id`` and
the decorated function as ``elem``.
:param id: ID to pass on. If ``None``, uses the decorated functions
name. | [
"Function",
"decorator",
"for",
"navbar",
"registration",
"."
] | 06f3b5b2addad29c2fc531a7e8e74958e9e4b793 | https://github.com/mbr/flask-nav/blob/06f3b5b2addad29c2fc531a7e8e74958e9e4b793/flask_nav/__init__.py#L114-L128 |
20,467 | mbr/flask-nav | flask_nav/__init__.py | Nav.renderer | def renderer(self, id=None, force=True):
"""Class decorator for Renderers.
The decorated class will be added to the list of renderers kept by this
instance that will be registered on the app upon app initialization.
:param id: Id for the renderer, defaults to the class name in snake
case.
:param force: Whether or not to overwrite existing renderers.
"""
def _(cls):
name = cls.__name__
sn = name[0] + re.sub(r'([A-Z])', r'_\1', name[1:])
self._renderers.append((id or sn.lower(), cls, force))
return cls
return _ | python | def renderer(self, id=None, force=True):
def _(cls):
name = cls.__name__
sn = name[0] + re.sub(r'([A-Z])', r'_\1', name[1:])
self._renderers.append((id or sn.lower(), cls, force))
return cls
return _ | [
"def",
"renderer",
"(",
"self",
",",
"id",
"=",
"None",
",",
"force",
"=",
"True",
")",
":",
"def",
"_",
"(",
"cls",
")",
":",
"name",
"=",
"cls",
".",
"__name__",
"sn",
"=",
"name",
"[",
"0",
"]",
"+",
"re",
".",
"sub",
"(",
"r'([A-Z])'",
",... | Class decorator for Renderers.
The decorated class will be added to the list of renderers kept by this
instance that will be registered on the app upon app initialization.
:param id: Id for the renderer, defaults to the class name in snake
case.
:param force: Whether or not to overwrite existing renderers. | [
"Class",
"decorator",
"for",
"Renderers",
"."
] | 06f3b5b2addad29c2fc531a7e8e74958e9e4b793 | https://github.com/mbr/flask-nav/blob/06f3b5b2addad29c2fc531a7e8e74958e9e4b793/flask_nav/__init__.py#L148-L166 |
20,468 | tonyseek/openvpn-status | openvpn_status/utils.py | parse_time | def parse_time(time):
"""Parses date and time from input string in OpenVPN logging format."""
if isinstance(time, datetime.datetime):
return time
return datetime.datetime.strptime(time, DATETIME_FORMAT_OPENVPN) | python | def parse_time(time):
if isinstance(time, datetime.datetime):
return time
return datetime.datetime.strptime(time, DATETIME_FORMAT_OPENVPN) | [
"def",
"parse_time",
"(",
"time",
")",
":",
"if",
"isinstance",
"(",
"time",
",",
"datetime",
".",
"datetime",
")",
":",
"return",
"time",
"return",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"time",
",",
"DATETIME_FORMAT_OPENVPN",
")"
] | Parses date and time from input string in OpenVPN logging format. | [
"Parses",
"date",
"and",
"time",
"from",
"input",
"string",
"in",
"OpenVPN",
"logging",
"format",
"."
] | b8f5ec5f79933605af2301c42e4e7ec230334237 | https://github.com/tonyseek/openvpn-status/blob/b8f5ec5f79933605af2301c42e4e7ec230334237/openvpn_status/utils.py#L19-L23 |
20,469 | jieter/python-lora | lora/payload.py | LoRaPayload.decrypt | def decrypt(self, key, dev_addr):
"""
Decrypt the actual payload in this LoraPayload.
key: 16-byte hex-encoded AES key. (i.e. AABBCCDDEEFFAABBCCDDEEFFAABBCCDD)
dev_addr: 4-byte hex-encoded DevAddr (i.e. AABBCCDD)
"""
sequence_counter = int(self.FCntUp)
return loramac_decrypt(self.payload_hex, sequence_counter, key, dev_addr) | python | def decrypt(self, key, dev_addr):
sequence_counter = int(self.FCntUp)
return loramac_decrypt(self.payload_hex, sequence_counter, key, dev_addr) | [
"def",
"decrypt",
"(",
"self",
",",
"key",
",",
"dev_addr",
")",
":",
"sequence_counter",
"=",
"int",
"(",
"self",
".",
"FCntUp",
")",
"return",
"loramac_decrypt",
"(",
"self",
".",
"payload_hex",
",",
"sequence_counter",
",",
"key",
",",
"dev_addr",
")"
] | Decrypt the actual payload in this LoraPayload.
key: 16-byte hex-encoded AES key. (i.e. AABBCCDDEEFFAABBCCDDEEFFAABBCCDD)
dev_addr: 4-byte hex-encoded DevAddr (i.e. AABBCCDD) | [
"Decrypt",
"the",
"actual",
"payload",
"in",
"this",
"LoraPayload",
"."
] | 0edb8dbad771da1e2b455571c7a9b064ba67fbcd | https://github.com/jieter/python-lora/blob/0edb8dbad771da1e2b455571c7a9b064ba67fbcd/lora/payload.py#L38-L47 |
20,470 | tonyseek/openvpn-status | openvpn_status/parser.py | LogParser.parse | def parse(self):
"""Parses the status log.
:raises ParsingError: if syntax error found in the log.
:return: The :class:`.models.Status` with filled data.
"""
status = Status()
self.expect_line(Status.client_list.label)
status.updated_at = self.expect_tuple(Status.updated_at.label)
status.client_list.update({
text_type(c.real_address): c
for c in self._parse_fields(Client, Status.routing_table.label)})
status.routing_table.update({
text_type(r.virtual_address): r
for r in self._parse_fields(Routing, Status.global_stats.label)})
status.global_stats = GlobalStats()
status.global_stats.max_bcast_mcast_queue_len = self.expect_tuple(
GlobalStats.max_bcast_mcast_queue_len.label)
self.expect_line(self.terminator)
return status | python | def parse(self):
status = Status()
self.expect_line(Status.client_list.label)
status.updated_at = self.expect_tuple(Status.updated_at.label)
status.client_list.update({
text_type(c.real_address): c
for c in self._parse_fields(Client, Status.routing_table.label)})
status.routing_table.update({
text_type(r.virtual_address): r
for r in self._parse_fields(Routing, Status.global_stats.label)})
status.global_stats = GlobalStats()
status.global_stats.max_bcast_mcast_queue_len = self.expect_tuple(
GlobalStats.max_bcast_mcast_queue_len.label)
self.expect_line(self.terminator)
return status | [
"def",
"parse",
"(",
"self",
")",
":",
"status",
"=",
"Status",
"(",
")",
"self",
".",
"expect_line",
"(",
"Status",
".",
"client_list",
".",
"label",
")",
"status",
".",
"updated_at",
"=",
"self",
".",
"expect_tuple",
"(",
"Status",
".",
"updated_at",
... | Parses the status log.
:raises ParsingError: if syntax error found in the log.
:return: The :class:`.models.Status` with filled data. | [
"Parses",
"the",
"status",
"log",
"."
] | b8f5ec5f79933605af2301c42e4e7ec230334237 | https://github.com/tonyseek/openvpn-status/blob/b8f5ec5f79933605af2301c42e4e7ec230334237/openvpn_status/parser.py#L77-L98 |
20,471 | tonyseek/openvpn-status | openvpn_status/shortcuts.py | parse_status | def parse_status(status_log, encoding='utf-8'):
"""Parses the status log of OpenVPN.
:param status_log: The content of status log.
:type status_log: :class:`str`
:param encoding: Optional. The encoding of status log.
:type encoding: :class:`str`
:return: The instance of :class:`.models.Status`
"""
if isinstance(status_log, bytes):
status_log = status_log.decode(encoding)
parser = LogParser.fromstring(status_log)
return parser.parse() | python | def parse_status(status_log, encoding='utf-8'):
if isinstance(status_log, bytes):
status_log = status_log.decode(encoding)
parser = LogParser.fromstring(status_log)
return parser.parse() | [
"def",
"parse_status",
"(",
"status_log",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"if",
"isinstance",
"(",
"status_log",
",",
"bytes",
")",
":",
"status_log",
"=",
"status_log",
".",
"decode",
"(",
"encoding",
")",
"parser",
"=",
"LogParser",
".",
"from... | Parses the status log of OpenVPN.
:param status_log: The content of status log.
:type status_log: :class:`str`
:param encoding: Optional. The encoding of status log.
:type encoding: :class:`str`
:return: The instance of :class:`.models.Status` | [
"Parses",
"the",
"status",
"log",
"of",
"OpenVPN",
"."
] | b8f5ec5f79933605af2301c42e4e7ec230334237 | https://github.com/tonyseek/openvpn-status/blob/b8f5ec5f79933605af2301c42e4e7ec230334237/openvpn_status/shortcuts.py#L6-L18 |
20,472 | vfilimonov/pydatastream | pydatastream/pydatastream.py | Datastream.version | def version(self):
"""Return version of the TR DWE."""
res = self.client.service.Version()
return '.'.join([ustr(x) for x in res[0]]) | python | def version(self):
res = self.client.service.Version()
return '.'.join([ustr(x) for x in res[0]]) | [
"def",
"version",
"(",
"self",
")",
":",
"res",
"=",
"self",
".",
"client",
".",
"service",
".",
"Version",
"(",
")",
"return",
"'.'",
".",
"join",
"(",
"[",
"ustr",
"(",
"x",
")",
"for",
"x",
"in",
"res",
"[",
"0",
"]",
"]",
")"
] | Return version of the TR DWE. | [
"Return",
"version",
"of",
"the",
"TR",
"DWE",
"."
] | 15d2adac1c83501715db1542373fa8428542816e | https://github.com/vfilimonov/pydatastream/blob/15d2adac1c83501715db1542373fa8428542816e/pydatastream/pydatastream.py#L119-L122 |
20,473 | vfilimonov/pydatastream | pydatastream/pydatastream.py | Datastream.system_info | def system_info(self):
"""Return system information."""
res = self.client.service.SystemInfo()
res = {ustr(x[0]): x[1] for x in res[0]}
to_str = lambda arr: '.'.join([ustr(x) for x in arr[0]])
res['OSVersion'] = to_str(res['OSVersion'])
res['RuntimeVersion'] = to_str(res['RuntimeVersion'])
res['Version'] = to_str(res['Version'])
res['Name'] = ustr(res['Name'])
res['Server'] = ustr(res['Server'])
res['LocalNameCheck'] = ustr(res['LocalNameCheck'])
res['UserHostAddress'] = ustr(res['UserHostAddress'])
return res | python | def system_info(self):
res = self.client.service.SystemInfo()
res = {ustr(x[0]): x[1] for x in res[0]}
to_str = lambda arr: '.'.join([ustr(x) for x in arr[0]])
res['OSVersion'] = to_str(res['OSVersion'])
res['RuntimeVersion'] = to_str(res['RuntimeVersion'])
res['Version'] = to_str(res['Version'])
res['Name'] = ustr(res['Name'])
res['Server'] = ustr(res['Server'])
res['LocalNameCheck'] = ustr(res['LocalNameCheck'])
res['UserHostAddress'] = ustr(res['UserHostAddress'])
return res | [
"def",
"system_info",
"(",
"self",
")",
":",
"res",
"=",
"self",
".",
"client",
".",
"service",
".",
"SystemInfo",
"(",
")",
"res",
"=",
"{",
"ustr",
"(",
"x",
"[",
"0",
"]",
")",
":",
"x",
"[",
"1",
"]",
"for",
"x",
"in",
"res",
"[",
"0",
... | Return system information. | [
"Return",
"system",
"information",
"."
] | 15d2adac1c83501715db1542373fa8428542816e | https://github.com/vfilimonov/pydatastream/blob/15d2adac1c83501715db1542373fa8428542816e/pydatastream/pydatastream.py#L124-L139 |
20,474 | vfilimonov/pydatastream | pydatastream/pydatastream.py | Datastream.sources | def sources(self):
"""Return available sources of data."""
res = self.client.service.Sources(self.userdata, 0)
return [ustr(x[0]) for x in res[0]] | python | def sources(self):
res = self.client.service.Sources(self.userdata, 0)
return [ustr(x[0]) for x in res[0]] | [
"def",
"sources",
"(",
"self",
")",
":",
"res",
"=",
"self",
".",
"client",
".",
"service",
".",
"Sources",
"(",
"self",
".",
"userdata",
",",
"0",
")",
"return",
"[",
"ustr",
"(",
"x",
"[",
"0",
"]",
")",
"for",
"x",
"in",
"res",
"[",
"0",
"... | Return available sources of data. | [
"Return",
"available",
"sources",
"of",
"data",
"."
] | 15d2adac1c83501715db1542373fa8428542816e | https://github.com/vfilimonov/pydatastream/blob/15d2adac1c83501715db1542373fa8428542816e/pydatastream/pydatastream.py#L141-L144 |
20,475 | vfilimonov/pydatastream | pydatastream/pydatastream.py | Datastream.status | def status(self, record=None):
"""Extract status from the retrieved data and save it as a property of an object.
If record with data is not specified then the status of previous operation is
returned.
status - dictionary with data source, string with request and status type,
code and message.
status['StatusType']: 'Connected' - the data is fine
'Stale' - the source is unavailable. It may be
worthwhile to try again later
'Failure' - data could not be obtained (e.g. the
instrument is incorrect)
'Pending' - for internal use only
status['StatusCode']: 0 - 'No Error'
1 - 'Disconnected'
2 - 'Source Fault'
3 - 'Network Fault'
4 - 'Access Denied' (user does not have permissions)
5 - 'No Such Item' (no instrument with given name)
11 - 'Blocking Timeout'
12 - 'Internal'
"""
if record is not None:
self.last_status = {'Source': ustr(record['Source']),
'StatusType': ustr(record['StatusType']),
'StatusCode': record['StatusCode'],
'StatusMessage': ustr(record['StatusMessage']),
'Request': ustr(record['Instrument'])}
return self.last_status | python | def status(self, record=None):
if record is not None:
self.last_status = {'Source': ustr(record['Source']),
'StatusType': ustr(record['StatusType']),
'StatusCode': record['StatusCode'],
'StatusMessage': ustr(record['StatusMessage']),
'Request': ustr(record['Instrument'])}
return self.last_status | [
"def",
"status",
"(",
"self",
",",
"record",
"=",
"None",
")",
":",
"if",
"record",
"is",
"not",
"None",
":",
"self",
".",
"last_status",
"=",
"{",
"'Source'",
":",
"ustr",
"(",
"record",
"[",
"'Source'",
"]",
")",
",",
"'StatusType'",
":",
"ustr",
... | Extract status from the retrieved data and save it as a property of an object.
If record with data is not specified then the status of previous operation is
returned.
status - dictionary with data source, string with request and status type,
code and message.
status['StatusType']: 'Connected' - the data is fine
'Stale' - the source is unavailable. It may be
worthwhile to try again later
'Failure' - data could not be obtained (e.g. the
instrument is incorrect)
'Pending' - for internal use only
status['StatusCode']: 0 - 'No Error'
1 - 'Disconnected'
2 - 'Source Fault'
3 - 'Network Fault'
4 - 'Access Denied' (user does not have permissions)
5 - 'No Such Item' (no instrument with given name)
11 - 'Blocking Timeout'
12 - 'Internal' | [
"Extract",
"status",
"from",
"the",
"retrieved",
"data",
"and",
"save",
"it",
"as",
"a",
"property",
"of",
"an",
"object",
".",
"If",
"record",
"with",
"data",
"is",
"not",
"specified",
"then",
"the",
"status",
"of",
"previous",
"operation",
"is",
"returne... | 15d2adac1c83501715db1542373fa8428542816e | https://github.com/vfilimonov/pydatastream/blob/15d2adac1c83501715db1542373fa8428542816e/pydatastream/pydatastream.py#L230-L259 |
20,476 | vfilimonov/pydatastream | pydatastream/pydatastream.py | Datastream.construct_request | def construct_request(ticker, fields=None, date=None,
date_from=None, date_to=None, freq=None):
"""Construct a request string for querying TR DWE.
tickers - ticker or symbol
fields - list of fields.
date - date for a single-date query
date_from, date_to - date range (used only if "date" is not specified)
freq - frequency of data: daily('D'), weekly('W') or monthly('M')
Use here 'REP' for static requests
Some of available fields:
P - adjusted closing price
PO - opening price
PH - high price
PL - low price
VO - volume, which is expressed in 1000's of shares.
UP - unadjusted price
OI - open interest
MV - market value
EPS - earnings per share
DI - dividend index
MTVB - market to book value
PTVB - price to book value
...
The full list of data fields is available at http://dtg.tfn.com/.
"""
if isinstance(ticker, basestring):
request = ticker
elif hasattr(ticker, '__len__'):
request = ','.join(ticker)
else:
raise ValueError('ticker should be either string or list/array of strings')
if fields is not None:
if isinstance(fields, basestring):
request += '~=' + fields
elif isinstance(fields, list) and len(fields) > 0:
request += '~=' + ','.join(fields)
if date is not None:
request += '~@' + pd.to_datetime(date).strftime('%Y-%m-%d')
else:
if date_from is not None:
request += '~' + pd.to_datetime(date_from).strftime('%Y-%m-%d')
if date_to is not None:
request += '~:' + pd.to_datetime(date_to).strftime('%Y-%m-%d')
if freq is not None:
request += '~' + freq
return request | python | def construct_request(ticker, fields=None, date=None,
date_from=None, date_to=None, freq=None):
if isinstance(ticker, basestring):
request = ticker
elif hasattr(ticker, '__len__'):
request = ','.join(ticker)
else:
raise ValueError('ticker should be either string or list/array of strings')
if fields is not None:
if isinstance(fields, basestring):
request += '~=' + fields
elif isinstance(fields, list) and len(fields) > 0:
request += '~=' + ','.join(fields)
if date is not None:
request += '~@' + pd.to_datetime(date).strftime('%Y-%m-%d')
else:
if date_from is not None:
request += '~' + pd.to_datetime(date_from).strftime('%Y-%m-%d')
if date_to is not None:
request += '~:' + pd.to_datetime(date_to).strftime('%Y-%m-%d')
if freq is not None:
request += '~' + freq
return request | [
"def",
"construct_request",
"(",
"ticker",
",",
"fields",
"=",
"None",
",",
"date",
"=",
"None",
",",
"date_from",
"=",
"None",
",",
"date_to",
"=",
"None",
",",
"freq",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"ticker",
",",
"basestring",
")",
... | Construct a request string for querying TR DWE.
tickers - ticker or symbol
fields - list of fields.
date - date for a single-date query
date_from, date_to - date range (used only if "date" is not specified)
freq - frequency of data: daily('D'), weekly('W') or monthly('M')
Use here 'REP' for static requests
Some of available fields:
P - adjusted closing price
PO - opening price
PH - high price
PL - low price
VO - volume, which is expressed in 1000's of shares.
UP - unadjusted price
OI - open interest
MV - market value
EPS - earnings per share
DI - dividend index
MTVB - market to book value
PTVB - price to book value
...
The full list of data fields is available at http://dtg.tfn.com/. | [
"Construct",
"a",
"request",
"string",
"for",
"querying",
"TR",
"DWE",
"."
] | 15d2adac1c83501715db1542373fa8428542816e | https://github.com/vfilimonov/pydatastream/blob/15d2adac1c83501715db1542373fa8428542816e/pydatastream/pydatastream.py#L413-L462 |
20,477 | vfilimonov/pydatastream | pydatastream/pydatastream.py | Datastream.fetch | def fetch(self, tickers, fields=None, date=None, date_from=None, date_to=None,
freq='D', only_data=True, static=False):
"""Fetch data from TR DWE.
tickers - ticker or list of tickers
fields - list of fields.
date - date for a single-date query
date_from, date_to - date range (used only if "date" is not specified)
freq - frequency of data: daily('D'), weekly('W') or monthly('M')
only_data - if True then metadata will not be returned
static - if True "static" request is created (i.e. not a series).
In this case 'date_from', 'date_to' and 'freq' are ignored
In case list of tickers is requested, a MultiIndex-dataframe is returned.
Some of available fields:
P - adjusted closing price
PO - opening price
PH - high price
PL - low price
VO - volume, which is expressed in 1000's of shares.
UP - unadjusted price
OI - open interest
MV - market value
EPS - earnings per share
DI - dividend index
MTVB - market to book value
PTVB - price to book value
...
The full list of data fields is available at http://dtg.tfn.com/.
"""
if static:
query = self.construct_request(tickers, fields, date, freq='REP')
else:
query = self.construct_request(tickers, fields, date, date_from, date_to, freq)
raw = self.request(query)
if static:
data, metadata = self.parse_record_static(raw)
elif isinstance(tickers, basestring) or len(tickers) == 1:
data, metadata = self.parse_record(raw)
elif hasattr(tickers, '__len__'):
metadata = pd.DataFrame()
data = {}
for indx in range(len(tickers)):
dat, meta = self.parse_record(raw, indx)
data[tickers[indx]] = dat
metadata = metadata.append(meta, ignore_index=False)
data = pd.concat(data)
else:
raise DatastreamException(('First argument should be either ticker or '
'list of tickers'))
if only_data:
return data
else:
return data, metadata | python | def fetch(self, tickers, fields=None, date=None, date_from=None, date_to=None,
freq='D', only_data=True, static=False):
if static:
query = self.construct_request(tickers, fields, date, freq='REP')
else:
query = self.construct_request(tickers, fields, date, date_from, date_to, freq)
raw = self.request(query)
if static:
data, metadata = self.parse_record_static(raw)
elif isinstance(tickers, basestring) or len(tickers) == 1:
data, metadata = self.parse_record(raw)
elif hasattr(tickers, '__len__'):
metadata = pd.DataFrame()
data = {}
for indx in range(len(tickers)):
dat, meta = self.parse_record(raw, indx)
data[tickers[indx]] = dat
metadata = metadata.append(meta, ignore_index=False)
data = pd.concat(data)
else:
raise DatastreamException(('First argument should be either ticker or '
'list of tickers'))
if only_data:
return data
else:
return data, metadata | [
"def",
"fetch",
"(",
"self",
",",
"tickers",
",",
"fields",
"=",
"None",
",",
"date",
"=",
"None",
",",
"date_from",
"=",
"None",
",",
"date_to",
"=",
"None",
",",
"freq",
"=",
"'D'",
",",
"only_data",
"=",
"True",
",",
"static",
"=",
"False",
")",... | Fetch data from TR DWE.
tickers - ticker or list of tickers
fields - list of fields.
date - date for a single-date query
date_from, date_to - date range (used only if "date" is not specified)
freq - frequency of data: daily('D'), weekly('W') or monthly('M')
only_data - if True then metadata will not be returned
static - if True "static" request is created (i.e. not a series).
In this case 'date_from', 'date_to' and 'freq' are ignored
In case list of tickers is requested, a MultiIndex-dataframe is returned.
Some of available fields:
P - adjusted closing price
PO - opening price
PH - high price
PL - low price
VO - volume, which is expressed in 1000's of shares.
UP - unadjusted price
OI - open interest
MV - market value
EPS - earnings per share
DI - dividend index
MTVB - market to book value
PTVB - price to book value
...
The full list of data fields is available at http://dtg.tfn.com/. | [
"Fetch",
"data",
"from",
"TR",
"DWE",
"."
] | 15d2adac1c83501715db1542373fa8428542816e | https://github.com/vfilimonov/pydatastream/blob/15d2adac1c83501715db1542373fa8428542816e/pydatastream/pydatastream.py#L465-L525 |
20,478 | vfilimonov/pydatastream | pydatastream/pydatastream.py | Datastream.get_OHLCV | def get_OHLCV(self, ticker, date=None, date_from=None, date_to=None):
"""Get Open, High, Low, Close prices and daily Volume for a given ticker.
ticker - ticker or symbol
date - date for a single-date query
date_from, date_to - date range (used only if "date" is not specified)
Returns pandas.Dataframe with data. If error occurs, then it is printed as
a warning.
"""
data, meta = self.fetch(ticker + "~OHLCV", None, date,
date_from, date_to, 'D', only_data=False)
return data | python | def get_OHLCV(self, ticker, date=None, date_from=None, date_to=None):
data, meta = self.fetch(ticker + "~OHLCV", None, date,
date_from, date_to, 'D', only_data=False)
return data | [
"def",
"get_OHLCV",
"(",
"self",
",",
"ticker",
",",
"date",
"=",
"None",
",",
"date_from",
"=",
"None",
",",
"date_to",
"=",
"None",
")",
":",
"data",
",",
"meta",
"=",
"self",
".",
"fetch",
"(",
"ticker",
"+",
"\"~OHLCV\"",
",",
"None",
",",
"dat... | Get Open, High, Low, Close prices and daily Volume for a given ticker.
ticker - ticker or symbol
date - date for a single-date query
date_from, date_to - date range (used only if "date" is not specified)
Returns pandas.Dataframe with data. If error occurs, then it is printed as
a warning. | [
"Get",
"Open",
"High",
"Low",
"Close",
"prices",
"and",
"daily",
"Volume",
"for",
"a",
"given",
"ticker",
"."
] | 15d2adac1c83501715db1542373fa8428542816e | https://github.com/vfilimonov/pydatastream/blob/15d2adac1c83501715db1542373fa8428542816e/pydatastream/pydatastream.py#L528-L540 |
20,479 | vfilimonov/pydatastream | pydatastream/pydatastream.py | Datastream.get_constituents | def get_constituents(self, index_ticker, date=None, only_list=False):
""" Get a list of all constituents of a given index.
index_ticker - Datastream ticker for index
date - date for which list should be retrieved (if None then
list of present constituents is retrieved)
only_list - request only list of symbols. By default the method
retrieves many extra fields with information (various
mnemonics and codes). This might pose some problems
for large indices like Russel-3000. If only_list=True,
then only the list of symbols and names are retrieved.
"""
if date is not None:
str_date = pd.to_datetime(date).strftime('%m%y')
else:
str_date = ''
# Note: ~XREF is equal to the following large request
# ~REP~=DSCD,EXMNEM,GEOG,GEOGC,IBTKR,INDC,INDG,INDM,INDX,INDXEG,INDXFS,INDXL,
# INDXS,ISIN,ISINID,LOC,MNEM,NAME,SECD,TYPE
fields = '~REP~=NAME' if only_list else '~XREF'
query = 'L' + index_ticker + str_date + fields
raw = self.request(query)
res, metadata = self.parse_record_static(raw)
return res | python | def get_constituents(self, index_ticker, date=None, only_list=False):
if date is not None:
str_date = pd.to_datetime(date).strftime('%m%y')
else:
str_date = ''
# Note: ~XREF is equal to the following large request
# ~REP~=DSCD,EXMNEM,GEOG,GEOGC,IBTKR,INDC,INDG,INDM,INDX,INDXEG,INDXFS,INDXL,
# INDXS,ISIN,ISINID,LOC,MNEM,NAME,SECD,TYPE
fields = '~REP~=NAME' if only_list else '~XREF'
query = 'L' + index_ticker + str_date + fields
raw = self.request(query)
res, metadata = self.parse_record_static(raw)
return res | [
"def",
"get_constituents",
"(",
"self",
",",
"index_ticker",
",",
"date",
"=",
"None",
",",
"only_list",
"=",
"False",
")",
":",
"if",
"date",
"is",
"not",
"None",
":",
"str_date",
"=",
"pd",
".",
"to_datetime",
"(",
"date",
")",
".",
"strftime",
"(",
... | Get a list of all constituents of a given index.
index_ticker - Datastream ticker for index
date - date for which list should be retrieved (if None then
list of present constituents is retrieved)
only_list - request only list of symbols. By default the method
retrieves many extra fields with information (various
mnemonics and codes). This might pose some problems
for large indices like Russel-3000. If only_list=True,
then only the list of symbols and names are retrieved. | [
"Get",
"a",
"list",
"of",
"all",
"constituents",
"of",
"a",
"given",
"index",
"."
] | 15d2adac1c83501715db1542373fa8428542816e | https://github.com/vfilimonov/pydatastream/blob/15d2adac1c83501715db1542373fa8428542816e/pydatastream/pydatastream.py#L571-L595 |
20,480 | crs4/hl7apy | hl7apy/__init__.py | check_encoding_chars | def check_encoding_chars(encoding_chars):
"""
Validate the given encoding chars
:type encoding_chars: ``dict``
:param encoding_chars: the encoding chars (see :func:`hl7apy.set_default_encoding_chars`)
:raises: :exc:`hl7apy.exceptions.InvalidEncodingChars` if the given encoding chars are not valid
"""
if not isinstance(encoding_chars, collections.MutableMapping):
raise InvalidEncodingChars
required = {'FIELD', 'COMPONENT', 'SUBCOMPONENT', 'REPETITION', 'ESCAPE'}
missing = required - set(encoding_chars.keys())
if missing:
raise InvalidEncodingChars('Missing required encoding chars')
values = [v for k, v in encoding_chars.items() if k in required]
if len(values) > len(set(values)):
raise InvalidEncodingChars('Found duplicate encoding chars') | python | def check_encoding_chars(encoding_chars):
if not isinstance(encoding_chars, collections.MutableMapping):
raise InvalidEncodingChars
required = {'FIELD', 'COMPONENT', 'SUBCOMPONENT', 'REPETITION', 'ESCAPE'}
missing = required - set(encoding_chars.keys())
if missing:
raise InvalidEncodingChars('Missing required encoding chars')
values = [v for k, v in encoding_chars.items() if k in required]
if len(values) > len(set(values)):
raise InvalidEncodingChars('Found duplicate encoding chars') | [
"def",
"check_encoding_chars",
"(",
"encoding_chars",
")",
":",
"if",
"not",
"isinstance",
"(",
"encoding_chars",
",",
"collections",
".",
"MutableMapping",
")",
":",
"raise",
"InvalidEncodingChars",
"required",
"=",
"{",
"'FIELD'",
",",
"'COMPONENT'",
",",
"'SUBC... | Validate the given encoding chars
:type encoding_chars: ``dict``
:param encoding_chars: the encoding chars (see :func:`hl7apy.set_default_encoding_chars`)
:raises: :exc:`hl7apy.exceptions.InvalidEncodingChars` if the given encoding chars are not valid | [
"Validate",
"the",
"given",
"encoding",
"chars"
] | 91be488e9274f6ec975519a1d9c17045bc91bf74 | https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/__init__.py#L46-L63 |
20,481 | crs4/hl7apy | hl7apy/__init__.py | check_validation_level | def check_validation_level(validation_level):
"""
Validate the given validation level
:type validation_level: ``int``
:param validation_level: validation level (see :class:`hl7apy.consts.VALIDATION_LEVEL`)
:raises: :exc:`hl7apy.exceptions.UnknownValidationLevel` if the given validation level is unsupported
"""
if validation_level not in (VALIDATION_LEVEL.QUIET, VALIDATION_LEVEL.STRICT, VALIDATION_LEVEL.TOLERANT):
raise UnknownValidationLevel | python | def check_validation_level(validation_level):
if validation_level not in (VALIDATION_LEVEL.QUIET, VALIDATION_LEVEL.STRICT, VALIDATION_LEVEL.TOLERANT):
raise UnknownValidationLevel | [
"def",
"check_validation_level",
"(",
"validation_level",
")",
":",
"if",
"validation_level",
"not",
"in",
"(",
"VALIDATION_LEVEL",
".",
"QUIET",
",",
"VALIDATION_LEVEL",
".",
"STRICT",
",",
"VALIDATION_LEVEL",
".",
"TOLERANT",
")",
":",
"raise",
"UnknownValidationL... | Validate the given validation level
:type validation_level: ``int``
:param validation_level: validation level (see :class:`hl7apy.consts.VALIDATION_LEVEL`)
:raises: :exc:`hl7apy.exceptions.UnknownValidationLevel` if the given validation level is unsupported | [
"Validate",
"the",
"given",
"validation",
"level"
] | 91be488e9274f6ec975519a1d9c17045bc91bf74 | https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/__init__.py#L66-L75 |
20,482 | crs4/hl7apy | hl7apy/__init__.py | load_library | def load_library(version):
"""
Load the correct module according to the version
:type version: ``str``
:param version: the version of the library to be loaded (e.g. '2.6')
:rtype: module object
"""
check_version(version)
module_name = SUPPORTED_LIBRARIES[version]
lib = sys.modules.get(module_name)
if lib is None:
lib = importlib.import_module(module_name)
return lib | python | def load_library(version):
check_version(version)
module_name = SUPPORTED_LIBRARIES[version]
lib = sys.modules.get(module_name)
if lib is None:
lib = importlib.import_module(module_name)
return lib | [
"def",
"load_library",
"(",
"version",
")",
":",
"check_version",
"(",
"version",
")",
"module_name",
"=",
"SUPPORTED_LIBRARIES",
"[",
"version",
"]",
"lib",
"=",
"sys",
".",
"modules",
".",
"get",
"(",
"module_name",
")",
"if",
"lib",
"is",
"None",
":",
... | Load the correct module according to the version
:type version: ``str``
:param version: the version of the library to be loaded (e.g. '2.6')
:rtype: module object | [
"Load",
"the",
"correct",
"module",
"according",
"to",
"the",
"version"
] | 91be488e9274f6ec975519a1d9c17045bc91bf74 | https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/__init__.py#L223-L236 |
20,483 | crs4/hl7apy | hl7apy/__init__.py | load_reference | def load_reference(name, element_type, version):
"""
Look for an element of the given type, name and version and return its reference structure
:type element_type: ``str``
:param element_type: the element type to look for (e.g. 'Segment')
:type name: ``str``
:param name: the element name to look for (e.g. 'MSH')
:type version: ``str``
:param version: the version of the library where to search the element (e.g. '2.6')
:rtype: ``dict``
:return: a dictionary describing the element structure
:raise: ``KeyError`` if the element has not been found
The returned dictionary will contain the following keys:
+--------------+--------------------------------------------+
|Key |Value |
+==============+============================================+
|cls |an :class:`hl7apy.core.Element` subclass |
+--------------+--------------------------------------------+
|name |the Element name (e.g. PID) |
+--------------+--------------------------------------------+
|ref |a tuple of one of the following format: |
| | |
| |('leaf', <datatype>, <longName>, <table>) |
| |('sequence', (<child>, (<min>, <max>), ...))|
+--------------+--------------------------------------------+
>>> load_reference('UNKNOWN', 'Segment', '2.5') # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
ChildNotFound: No child named UNKNOWN
>>> r = load_reference('ADT_A01', 'Message', '2.5')
>>> print(r[0])
sequence
>>> r = load_reference('MSH_3', 'Field', '2.5')
>>> print(r[0])
sequence
"""
lib = load_library(version)
ref = lib.get(name, element_type)
return ref | python | def load_reference(name, element_type, version):
lib = load_library(version)
ref = lib.get(name, element_type)
return ref | [
"def",
"load_reference",
"(",
"name",
",",
"element_type",
",",
"version",
")",
":",
"lib",
"=",
"load_library",
"(",
"version",
")",
"ref",
"=",
"lib",
".",
"get",
"(",
"name",
",",
"element_type",
")",
"return",
"ref"
] | Look for an element of the given type, name and version and return its reference structure
:type element_type: ``str``
:param element_type: the element type to look for (e.g. 'Segment')
:type name: ``str``
:param name: the element name to look for (e.g. 'MSH')
:type version: ``str``
:param version: the version of the library where to search the element (e.g. '2.6')
:rtype: ``dict``
:return: a dictionary describing the element structure
:raise: ``KeyError`` if the element has not been found
The returned dictionary will contain the following keys:
+--------------+--------------------------------------------+
|Key |Value |
+==============+============================================+
|cls |an :class:`hl7apy.core.Element` subclass |
+--------------+--------------------------------------------+
|name |the Element name (e.g. PID) |
+--------------+--------------------------------------------+
|ref |a tuple of one of the following format: |
| | |
| |('leaf', <datatype>, <longName>, <table>) |
| |('sequence', (<child>, (<min>, <max>), ...))|
+--------------+--------------------------------------------+
>>> load_reference('UNKNOWN', 'Segment', '2.5') # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
ChildNotFound: No child named UNKNOWN
>>> r = load_reference('ADT_A01', 'Message', '2.5')
>>> print(r[0])
sequence
>>> r = load_reference('MSH_3', 'Field', '2.5')
>>> print(r[0])
sequence | [
"Look",
"for",
"an",
"element",
"of",
"the",
"given",
"type",
"name",
"and",
"version",
"and",
"return",
"its",
"reference",
"structure"
] | 91be488e9274f6ec975519a1d9c17045bc91bf74 | https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/__init__.py#L239-L281 |
20,484 | crs4/hl7apy | hl7apy/__init__.py | find_reference | def find_reference(name, element_types, version):
"""
Look for an element of the given name and version into the given types and return its reference structure
:type name: ``str``
:param name: the element name to look for (e.g. 'MSH')
:type types: ``list`` or ``tuple``
:param types: the element classes where to look for the element (e.g. (Group, Segment))
:type version: ``str``
:param version: the version of the library where to search the element (e.g. '2.6')
:rtype: ``dict``
:return: a dictionary describing the element structure
:raise: :class:`hl7apy.exceptions.ChildNotFound` if the element has not been found
>>> from hl7apy.core import Message, Segment
>>> find_reference('UNKNOWN', (Segment, ), '2.5') # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
ChildNotFound: No child named UNKNOWN
>>> find_reference('ADT_A01', (Segment,), '2.5') # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
ChildNotFound: No child named ADT_A01
>>> r = find_reference('ADT_A01', (Message,), '2.5')
>>> print('%s %s' % (r['name'], r['cls']))
ADT_A01 <class 'hl7apy.core.Message'>
"""
lib = load_library(version)
ref = lib.find(name, element_types)
return ref | python | def find_reference(name, element_types, version):
lib = load_library(version)
ref = lib.find(name, element_types)
return ref | [
"def",
"find_reference",
"(",
"name",
",",
"element_types",
",",
"version",
")",
":",
"lib",
"=",
"load_library",
"(",
"version",
")",
"ref",
"=",
"lib",
".",
"find",
"(",
"name",
",",
"element_types",
")",
"return",
"ref"
] | Look for an element of the given name and version into the given types and return its reference structure
:type name: ``str``
:param name: the element name to look for (e.g. 'MSH')
:type types: ``list`` or ``tuple``
:param types: the element classes where to look for the element (e.g. (Group, Segment))
:type version: ``str``
:param version: the version of the library where to search the element (e.g. '2.6')
:rtype: ``dict``
:return: a dictionary describing the element structure
:raise: :class:`hl7apy.exceptions.ChildNotFound` if the element has not been found
>>> from hl7apy.core import Message, Segment
>>> find_reference('UNKNOWN', (Segment, ), '2.5') # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
ChildNotFound: No child named UNKNOWN
>>> find_reference('ADT_A01', (Segment,), '2.5') # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
ChildNotFound: No child named ADT_A01
>>> r = find_reference('ADT_A01', (Message,), '2.5')
>>> print('%s %s' % (r['name'], r['cls']))
ADT_A01 <class 'hl7apy.core.Message'> | [
"Look",
"for",
"an",
"element",
"of",
"the",
"given",
"name",
"and",
"version",
"into",
"the",
"given",
"types",
"and",
"return",
"its",
"reference",
"structure"
] | 91be488e9274f6ec975519a1d9c17045bc91bf74 | https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/__init__.py#L284-L313 |
20,485 | crs4/hl7apy | hl7apy/utils.py | get_date_info | def get_date_info(value):
"""
Returns the datetime object and the format of the date in input
:type value: `str`
"""
fmt = _get_date_format(value)
dt_value = _datetime_obj_factory(value, fmt)
return dt_value, fmt | python | def get_date_info(value):
fmt = _get_date_format(value)
dt_value = _datetime_obj_factory(value, fmt)
return dt_value, fmt | [
"def",
"get_date_info",
"(",
"value",
")",
":",
"fmt",
"=",
"_get_date_format",
"(",
"value",
")",
"dt_value",
"=",
"_datetime_obj_factory",
"(",
"value",
",",
"fmt",
")",
"return",
"dt_value",
",",
"fmt"
] | Returns the datetime object and the format of the date in input
:type value: `str` | [
"Returns",
"the",
"datetime",
"object",
"and",
"the",
"format",
"of",
"the",
"date",
"in",
"input"
] | 91be488e9274f6ec975519a1d9c17045bc91bf74 | https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/utils.py#L70-L78 |
20,486 | crs4/hl7apy | hl7apy/utils.py | get_timestamp_info | def get_timestamp_info(value):
"""
Returns the datetime object, the format, the offset and the microsecond of the timestamp in input
:type value: `str`
"""
value, offset = _split_offset(value)
fmt, microsec = _get_timestamp_format(value)
dt_value = _datetime_obj_factory(value, fmt)
return dt_value, fmt, offset, microsec | python | def get_timestamp_info(value):
value, offset = _split_offset(value)
fmt, microsec = _get_timestamp_format(value)
dt_value = _datetime_obj_factory(value, fmt)
return dt_value, fmt, offset, microsec | [
"def",
"get_timestamp_info",
"(",
"value",
")",
":",
"value",
",",
"offset",
"=",
"_split_offset",
"(",
"value",
")",
"fmt",
",",
"microsec",
"=",
"_get_timestamp_format",
"(",
"value",
")",
"dt_value",
"=",
"_datetime_obj_factory",
"(",
"value",
",",
"fmt",
... | Returns the datetime object, the format, the offset and the microsecond of the timestamp in input
:type value: `str` | [
"Returns",
"the",
"datetime",
"object",
"the",
"format",
"the",
"offset",
"and",
"the",
"microsecond",
"of",
"the",
"timestamp",
"in",
"input"
] | 91be488e9274f6ec975519a1d9c17045bc91bf74 | https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/utils.py#L81-L90 |
20,487 | crs4/hl7apy | hl7apy/utils.py | get_datetime_info | def get_datetime_info(value):
"""
Returns the datetime object, the format, the offset and the microsecond of the datetime in input
:type value: `str`
"""
date_value, offset = _split_offset(value)
date_format = _get_date_format(date_value[:8])
try:
timestamp_form, microsec = _get_timestamp_format(date_value[8:])
except ValueError:
if not date_value[8:]: # if it's empty
timestamp_form, microsec = '', 4
else:
raise ValueError('{0} is not an HL7 valid date value'.format(value))
fmt = '{0}{1}'.format(date_format, timestamp_form)
dt_value = _datetime_obj_factory(date_value, fmt)
return dt_value, fmt, offset, microsec | python | def get_datetime_info(value):
date_value, offset = _split_offset(value)
date_format = _get_date_format(date_value[:8])
try:
timestamp_form, microsec = _get_timestamp_format(date_value[8:])
except ValueError:
if not date_value[8:]: # if it's empty
timestamp_form, microsec = '', 4
else:
raise ValueError('{0} is not an HL7 valid date value'.format(value))
fmt = '{0}{1}'.format(date_format, timestamp_form)
dt_value = _datetime_obj_factory(date_value, fmt)
return dt_value, fmt, offset, microsec | [
"def",
"get_datetime_info",
"(",
"value",
")",
":",
"date_value",
",",
"offset",
"=",
"_split_offset",
"(",
"value",
")",
"date_format",
"=",
"_get_date_format",
"(",
"date_value",
"[",
":",
"8",
"]",
")",
"try",
":",
"timestamp_form",
",",
"microsec",
"=",
... | Returns the datetime object, the format, the offset and the microsecond of the datetime in input
:type value: `str` | [
"Returns",
"the",
"datetime",
"object",
"the",
"format",
"the",
"offset",
"and",
"the",
"microsecond",
"of",
"the",
"datetime",
"in",
"input"
] | 91be488e9274f6ec975519a1d9c17045bc91bf74 | https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/utils.py#L93-L112 |
20,488 | crs4/hl7apy | hl7apy/core.py | is_base_datatype | def is_base_datatype(datatype, version=None):
"""
Check if the given datatype is a base datatype of the specified version
:type datatype: ``str``
:param datatype: the datatype (e.g. ST)
:type version: ``str``
:param version: the HL7 version (e.g. 2.5)
:return: ``True`` if it is a base datatype, ``False`` otherwise
>>> is_base_datatype('ST')
True
>>> is_base_datatype('CE')
False
"""
if version is None:
version = get_default_version()
lib = load_library(version)
return lib.is_base_datatype(datatype) | python | def is_base_datatype(datatype, version=None):
if version is None:
version = get_default_version()
lib = load_library(version)
return lib.is_base_datatype(datatype) | [
"def",
"is_base_datatype",
"(",
"datatype",
",",
"version",
"=",
"None",
")",
":",
"if",
"version",
"is",
"None",
":",
"version",
"=",
"get_default_version",
"(",
")",
"lib",
"=",
"load_library",
"(",
"version",
")",
"return",
"lib",
".",
"is_base_datatype",... | Check if the given datatype is a base datatype of the specified version
:type datatype: ``str``
:param datatype: the datatype (e.g. ST)
:type version: ``str``
:param version: the HL7 version (e.g. 2.5)
:return: ``True`` if it is a base datatype, ``False`` otherwise
>>> is_base_datatype('ST')
True
>>> is_base_datatype('CE')
False | [
"Check",
"if",
"the",
"given",
"datatype",
"is",
"a",
"base",
"datatype",
"of",
"the",
"specified",
"version"
] | 91be488e9274f6ec975519a1d9c17045bc91bf74 | https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/core.py#L59-L79 |
20,489 | crs4/hl7apy | hl7apy/core.py | ElementList.get_ordered_children | def get_ordered_children(self):
"""
Return the list of children ordered according to the element structure
:return: a list of :class:`Element <hl7apy.core.Element>`
"""
ordered_keys = self.element.ordered_children if self.element.ordered_children is not None else []
children = [self.indexes.get(k, None) for k in ordered_keys]
return children | python | def get_ordered_children(self):
ordered_keys = self.element.ordered_children if self.element.ordered_children is not None else []
children = [self.indexes.get(k, None) for k in ordered_keys]
return children | [
"def",
"get_ordered_children",
"(",
"self",
")",
":",
"ordered_keys",
"=",
"self",
".",
"element",
".",
"ordered_children",
"if",
"self",
".",
"element",
".",
"ordered_children",
"is",
"not",
"None",
"else",
"[",
"]",
"children",
"=",
"[",
"self",
".",
"in... | Return the list of children ordered according to the element structure
:return: a list of :class:`Element <hl7apy.core.Element>` | [
"Return",
"the",
"list",
"of",
"children",
"ordered",
"according",
"to",
"the",
"element",
"structure"
] | 91be488e9274f6ec975519a1d9c17045bc91bf74 | https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/core.py#L210-L218 |
20,490 | crs4/hl7apy | hl7apy/core.py | ElementList.insert | def insert(self, index, child, by_name_index=-1):
"""
Add the child at the given index
:type index: ``int``
:param index: child position
:type child: :class:`Element <hl7apy.core.Element>`
:param child: an instance of an :class:`Element <hl7apy.core.Element>` subclass
"""
if self._can_add_child(child):
try:
if by_name_index == -1:
self.indexes[child.name].append(child)
else:
self.indexes[child.name].insert(by_name_index, child)
except KeyError:
self.indexes[child.name] = [child]
self.list.insert(index, child) | python | def insert(self, index, child, by_name_index=-1):
if self._can_add_child(child):
try:
if by_name_index == -1:
self.indexes[child.name].append(child)
else:
self.indexes[child.name].insert(by_name_index, child)
except KeyError:
self.indexes[child.name] = [child]
self.list.insert(index, child) | [
"def",
"insert",
"(",
"self",
",",
"index",
",",
"child",
",",
"by_name_index",
"=",
"-",
"1",
")",
":",
"if",
"self",
".",
"_can_add_child",
"(",
"child",
")",
":",
"try",
":",
"if",
"by_name_index",
"==",
"-",
"1",
":",
"self",
".",
"indexes",
"[... | Add the child at the given index
:type index: ``int``
:param index: child position
:type child: :class:`Element <hl7apy.core.Element>`
:param child: an instance of an :class:`Element <hl7apy.core.Element>` subclass | [
"Add",
"the",
"child",
"at",
"the",
"given",
"index"
] | 91be488e9274f6ec975519a1d9c17045bc91bf74 | https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/core.py#L228-L246 |
20,491 | crs4/hl7apy | hl7apy/core.py | ElementList.append | def append(self, child):
"""
Append the given child
:class:`Element <hl7apy.core.Element>`
:param child: an instance of an :class:`Element <hl7apy.core.Element>` subclass
"""
if self._can_add_child(child):
if self.element == child.parent:
self._remove_from_traversal_index(child)
self.list.append(child)
try:
self.indexes[child.name].append(child)
except KeyError:
self.indexes[child.name] = [child]
elif self.element == child.traversal_parent:
try:
self.traversal_indexes[child.name].append(child)
except KeyError:
self.traversal_indexes[child.name] = [child] | python | def append(self, child):
if self._can_add_child(child):
if self.element == child.parent:
self._remove_from_traversal_index(child)
self.list.append(child)
try:
self.indexes[child.name].append(child)
except KeyError:
self.indexes[child.name] = [child]
elif self.element == child.traversal_parent:
try:
self.traversal_indexes[child.name].append(child)
except KeyError:
self.traversal_indexes[child.name] = [child] | [
"def",
"append",
"(",
"self",
",",
"child",
")",
":",
"if",
"self",
".",
"_can_add_child",
"(",
"child",
")",
":",
"if",
"self",
".",
"element",
"==",
"child",
".",
"parent",
":",
"self",
".",
"_remove_from_traversal_index",
"(",
"child",
")",
"self",
... | Append the given child
:class:`Element <hl7apy.core.Element>`
:param child: an instance of an :class:`Element <hl7apy.core.Element>` subclass | [
"Append",
"the",
"given",
"child"
] | 91be488e9274f6ec975519a1d9c17045bc91bf74 | https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/core.py#L248-L267 |
20,492 | crs4/hl7apy | hl7apy/core.py | ElementList.set | def set(self, name, value, index=-1):
"""
Assign the ``value`` to the child having the given ``name`` at the ``index`` position
:type name: ``str``
:param name: the child name (e.g. PID)
:type value: an instance of :class:`Element <hl7apy.core.Element>`, a `str` or an instance of
:class:`ElementProxy <hl7apy.core.ElementProxy>`
:param value: the child value
:type index: ``int``
:param index: the child position (e.g. 1)
"""
# just copy the first element of the ElementProxy (e.g. message.pid = message2.pid)
if isinstance(value, ElementProxy):
value = value[0].to_er7()
name = name.upper()
reference = None if name is None else self.element.find_child_reference(name)
child_ref, child_name = (None, None) if reference is None else (reference['ref'], reference['name'])
if isinstance(value, basestring): # if the value is a basestring, parse it
child = self.element.parse_child(value, child_name=child_name, reference=child_ref)
elif isinstance(value, Element): # it is already an instance of Element
child = value
elif isinstance(value, BaseDataType):
child = self.create_element(name, False, reference)
child.value = value
else:
raise ChildNotValid(value, child_name)
if child.name != child_name: # e.g. message.pid = Segment('SPM') is forbidden
raise ChildNotValid(value, child_name)
child_to_remove = self.child_at_index(child_name, index)
if child_to_remove is None:
self.append(child)
else:
self.replace_child(child_to_remove, child)
# a set has been called, change the temporary parent to be the actual one
self.element.set_parent_to_traversal() | python | def set(self, name, value, index=-1):
# just copy the first element of the ElementProxy (e.g. message.pid = message2.pid)
if isinstance(value, ElementProxy):
value = value[0].to_er7()
name = name.upper()
reference = None if name is None else self.element.find_child_reference(name)
child_ref, child_name = (None, None) if reference is None else (reference['ref'], reference['name'])
if isinstance(value, basestring): # if the value is a basestring, parse it
child = self.element.parse_child(value, child_name=child_name, reference=child_ref)
elif isinstance(value, Element): # it is already an instance of Element
child = value
elif isinstance(value, BaseDataType):
child = self.create_element(name, False, reference)
child.value = value
else:
raise ChildNotValid(value, child_name)
if child.name != child_name: # e.g. message.pid = Segment('SPM') is forbidden
raise ChildNotValid(value, child_name)
child_to_remove = self.child_at_index(child_name, index)
if child_to_remove is None:
self.append(child)
else:
self.replace_child(child_to_remove, child)
# a set has been called, change the temporary parent to be the actual one
self.element.set_parent_to_traversal() | [
"def",
"set",
"(",
"self",
",",
"name",
",",
"value",
",",
"index",
"=",
"-",
"1",
")",
":",
"# just copy the first element of the ElementProxy (e.g. message.pid = message2.pid)",
"if",
"isinstance",
"(",
"value",
",",
"ElementProxy",
")",
":",
"value",
"=",
"valu... | Assign the ``value`` to the child having the given ``name`` at the ``index`` position
:type name: ``str``
:param name: the child name (e.g. PID)
:type value: an instance of :class:`Element <hl7apy.core.Element>`, a `str` or an instance of
:class:`ElementProxy <hl7apy.core.ElementProxy>`
:param value: the child value
:type index: ``int``
:param index: the child position (e.g. 1) | [
"Assign",
"the",
"value",
"to",
"the",
"child",
"having",
"the",
"given",
"name",
"at",
"the",
"index",
"position"
] | 91be488e9274f6ec975519a1d9c17045bc91bf74 | https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/core.py#L285-L329 |
20,493 | crs4/hl7apy | hl7apy/core.py | ElementList.remove | def remove(self, child):
"""
Remove the given child from both child list and child indexes
:type child: :class:`Element <hl7apy.core.Element>`
:param child: an instance of :class:`Element <hl7apy.core.Element>` subclass
"""
try:
if self.element == child.traversal_parent:
self._remove_from_traversal_index(child)
else:
self._remove_from_index(child)
self.list.remove(child)
except:
raise | python | def remove(self, child):
try:
if self.element == child.traversal_parent:
self._remove_from_traversal_index(child)
else:
self._remove_from_index(child)
self.list.remove(child)
except:
raise | [
"def",
"remove",
"(",
"self",
",",
"child",
")",
":",
"try",
":",
"if",
"self",
".",
"element",
"==",
"child",
".",
"traversal_parent",
":",
"self",
".",
"_remove_from_traversal_index",
"(",
"child",
")",
"else",
":",
"self",
".",
"_remove_from_index",
"("... | Remove the given child from both child list and child indexes
:type child: :class:`Element <hl7apy.core.Element>`
:param child: an instance of :class:`Element <hl7apy.core.Element>` subclass | [
"Remove",
"the",
"given",
"child",
"from",
"both",
"child",
"list",
"and",
"child",
"indexes"
] | 91be488e9274f6ec975519a1d9c17045bc91bf74 | https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/core.py#L331-L345 |
20,494 | crs4/hl7apy | hl7apy/core.py | ElementList.remove_by_name | def remove_by_name(self, name, index=0):
"""
Remove the child having the given name at the given position
:type name: ``str``
:param name: child name (e.g. PID)
:type index: ``int``
:param index: child index
:return: an instance of :class:`Element <hl7apy.core.Element>` subclass
"""
child = self.child_at_index(name, index)
self.remove(child)
return child | python | def remove_by_name(self, name, index=0):
child = self.child_at_index(name, index)
self.remove(child)
return child | [
"def",
"remove_by_name",
"(",
"self",
",",
"name",
",",
"index",
"=",
"0",
")",
":",
"child",
"=",
"self",
".",
"child_at_index",
"(",
"name",
",",
"index",
")",
"self",
".",
"remove",
"(",
"child",
")",
"return",
"child"
] | Remove the child having the given name at the given position
:type name: ``str``
:param name: child name (e.g. PID)
:type index: ``int``
:param index: child index
:return: an instance of :class:`Element <hl7apy.core.Element>` subclass | [
"Remove",
"the",
"child",
"having",
"the",
"given",
"name",
"at",
"the",
"given",
"position"
] | 91be488e9274f6ec975519a1d9c17045bc91bf74 | https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/core.py#L347-L361 |
20,495 | crs4/hl7apy | hl7apy/core.py | ElementList.child_at_index | def child_at_index(self, name, index):
"""
Return the child named `name` at the given index
:type name: ``str``
:param name: child name (e.g. PID)
:type index: ``int``
:param index: child index
:return: an instance of :class:`Element <hl7apy.core.Element>` subclass
"""
def _finder(n, i):
try:
return self.indexes[n][i]
except (KeyError, IndexError):
try:
return self.traversal_indexes[n][i]
except (KeyError, IndexError):
return None
child = _finder(name, index)
child_name = None if name is None else self._find_name(name)
if child_name != name:
child = _finder(child_name, index)
return child | python | def child_at_index(self, name, index):
def _finder(n, i):
try:
return self.indexes[n][i]
except (KeyError, IndexError):
try:
return self.traversal_indexes[n][i]
except (KeyError, IndexError):
return None
child = _finder(name, index)
child_name = None if name is None else self._find_name(name)
if child_name != name:
child = _finder(child_name, index)
return child | [
"def",
"child_at_index",
"(",
"self",
",",
"name",
",",
"index",
")",
":",
"def",
"_finder",
"(",
"n",
",",
"i",
")",
":",
"try",
":",
"return",
"self",
".",
"indexes",
"[",
"n",
"]",
"[",
"i",
"]",
"except",
"(",
"KeyError",
",",
"IndexError",
"... | Return the child named `name` at the given index
:type name: ``str``
:param name: child name (e.g. PID)
:type index: ``int``
:param index: child index
:return: an instance of :class:`Element <hl7apy.core.Element>` subclass | [
"Return",
"the",
"child",
"named",
"name",
"at",
"the",
"given",
"index"
] | 91be488e9274f6ec975519a1d9c17045bc91bf74 | https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/core.py#L363-L389 |
20,496 | crs4/hl7apy | hl7apy/core.py | ElementList.create_element | def create_element(self, name, traversal_parent=False, reference=None):
"""
Create an element having the given name
:type name: ``str``
:param name: the name of the element to be created (e.g. PID)
:type traversal_parent: ``bool``
:param traversal_parent: if ``True``, the parent will be set as temporary for traversal purposes
:param reference: the new element structure (see :func:`load_reference <hl7apy.load_reference>`)
:return: an instance of an :class:`hl7apy.core.Element` subclass
:raises: :exc:`ChildNotFound <hl7apy.exceptions.ChildNotFound>` if the element does not exist
"""
if reference is None:
reference = self.element.find_child_reference(name)
if reference is not None:
cls = reference['cls']
element_name = reference['name']
kwargs = {'reference': reference['ref'],
'validation_level': self.element.validation_level,
'version': self.element.version}
if not traversal_parent:
kwargs['parent'] = self.element
else:
kwargs['traversal_parent'] = self.element
return cls(element_name, **kwargs)
else:
raise ChildNotFound(name) | python | def create_element(self, name, traversal_parent=False, reference=None):
if reference is None:
reference = self.element.find_child_reference(name)
if reference is not None:
cls = reference['cls']
element_name = reference['name']
kwargs = {'reference': reference['ref'],
'validation_level': self.element.validation_level,
'version': self.element.version}
if not traversal_parent:
kwargs['parent'] = self.element
else:
kwargs['traversal_parent'] = self.element
return cls(element_name, **kwargs)
else:
raise ChildNotFound(name) | [
"def",
"create_element",
"(",
"self",
",",
"name",
",",
"traversal_parent",
"=",
"False",
",",
"reference",
"=",
"None",
")",
":",
"if",
"reference",
"is",
"None",
":",
"reference",
"=",
"self",
".",
"element",
".",
"find_child_reference",
"(",
"name",
")"... | Create an element having the given name
:type name: ``str``
:param name: the name of the element to be created (e.g. PID)
:type traversal_parent: ``bool``
:param traversal_parent: if ``True``, the parent will be set as temporary for traversal purposes
:param reference: the new element structure (see :func:`load_reference <hl7apy.load_reference>`)
:return: an instance of an :class:`hl7apy.core.Element` subclass
:raises: :exc:`ChildNotFound <hl7apy.exceptions.ChildNotFound>` if the element does not exist | [
"Create",
"an",
"element",
"having",
"the",
"given",
"name"
] | 91be488e9274f6ec975519a1d9c17045bc91bf74 | https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/core.py#L403-L433 |
20,497 | crs4/hl7apy | hl7apy/core.py | ElementList._find_name | def _find_name(self, name):
"""
Find the reference of a child having the given name
:type name: ``str``
:param name: the child name (e.g. PID)
:return: the element structure (see :func:`load_reference <hl7apy.load_reference>`) or ``None`` if the
element has not been found
"""
name = name.upper()
element = self.element.find_child_reference(name)
return element['name'] if element is not None else None | python | def _find_name(self, name):
name = name.upper()
element = self.element.find_child_reference(name)
return element['name'] if element is not None else None | [
"def",
"_find_name",
"(",
"self",
",",
"name",
")",
":",
"name",
"=",
"name",
".",
"upper",
"(",
")",
"element",
"=",
"self",
".",
"element",
".",
"find_child_reference",
"(",
"name",
")",
"return",
"element",
"[",
"'name'",
"]",
"if",
"element",
"is",... | Find the reference of a child having the given name
:type name: ``str``
:param name: the child name (e.g. PID)
:return: the element structure (see :func:`load_reference <hl7apy.load_reference>`) or ``None`` if the
element has not been found | [
"Find",
"the",
"reference",
"of",
"a",
"child",
"having",
"the",
"given",
"name"
] | 91be488e9274f6ec975519a1d9c17045bc91bf74 | https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/core.py#L435-L447 |
20,498 | crs4/hl7apy | hl7apy/core.py | ElementFinder.get_structure | def get_structure(element, reference=None):
"""
Get the element structure
:type element: :class:`Element <hl7apy.core.Element>`
:param element: element having the given reference structure
:param reference: the element structure from :func:`load_reference <hl7apy.load_reference>` or from a
message profile
:return: a dictionary containing the structure data
"""
if reference is None:
try:
reference = load_reference(element.name, element.classname, element.version)
except (ChildNotFound, KeyError):
raise InvalidName(element.classname, element.name)
if not isinstance(reference, collections.Sequence):
raise Exception
return ElementFinder._parse_structure(element, reference) | python | def get_structure(element, reference=None):
if reference is None:
try:
reference = load_reference(element.name, element.classname, element.version)
except (ChildNotFound, KeyError):
raise InvalidName(element.classname, element.name)
if not isinstance(reference, collections.Sequence):
raise Exception
return ElementFinder._parse_structure(element, reference) | [
"def",
"get_structure",
"(",
"element",
",",
"reference",
"=",
"None",
")",
":",
"if",
"reference",
"is",
"None",
":",
"try",
":",
"reference",
"=",
"load_reference",
"(",
"element",
".",
"name",
",",
"element",
".",
"classname",
",",
"element",
".",
"ve... | Get the element structure
:type element: :class:`Element <hl7apy.core.Element>`
:param element: element having the given reference structure
:param reference: the element structure from :func:`load_reference <hl7apy.load_reference>` or from a
message profile
:return: a dictionary containing the structure data | [
"Get",
"the",
"element",
"structure"
] | 91be488e9274f6ec975519a1d9c17045bc91bf74 | https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/core.py#L532-L551 |
20,499 | crs4/hl7apy | hl7apy/core.py | ElementFinder._parse_structure | def _parse_structure(element, reference):
"""
Parse the given reference
:type element: :class:`Element <hl7apy.core.Element>`
:param element: element having the given reference structure
:param reference: the element structure from :func:`load_reference <hl7apy.load_reference>` or from a
message profile
:return: a dictionary containing the structure data
"""
data = {
'reference': reference
}
content_type = reference[0] # content type can be sequence, choice or leaf
if content_type in ('sequence', 'choice'):
children = reference[1]
ordered_children = []
structure = {}
structure_by_longname = {}
repetitions = {}
counters = collections.defaultdict(int)
for c in children:
child_name, child_ref, cardinality, cls = c
k = child_name if child_name not in structure \
else '{0}_{1}'.format(child_name, counters[child_name])
structure[k] = {"ref": child_ref, "name": k, "cls": element.child_classes[cls]}
try:
structure_by_longname[child_ref[3]] = structure[k]
except IndexError:
pass
counters[child_name] += 1
repetitions[k] = cardinality
ordered_children.append(k)
data['repetitions'] = repetitions
data['ordered_children'] = ordered_children
data['structure_by_name'] = structure
data['structure_by_longname'] = structure_by_longname
if len(reference) > 5:
datatype, long_name, table, max_length = reference[2:]
data['datatype'] = datatype
data['table'] = table
data['long_name'] = long_name
return data | python | def _parse_structure(element, reference):
data = {
'reference': reference
}
content_type = reference[0] # content type can be sequence, choice or leaf
if content_type in ('sequence', 'choice'):
children = reference[1]
ordered_children = []
structure = {}
structure_by_longname = {}
repetitions = {}
counters = collections.defaultdict(int)
for c in children:
child_name, child_ref, cardinality, cls = c
k = child_name if child_name not in structure \
else '{0}_{1}'.format(child_name, counters[child_name])
structure[k] = {"ref": child_ref, "name": k, "cls": element.child_classes[cls]}
try:
structure_by_longname[child_ref[3]] = structure[k]
except IndexError:
pass
counters[child_name] += 1
repetitions[k] = cardinality
ordered_children.append(k)
data['repetitions'] = repetitions
data['ordered_children'] = ordered_children
data['structure_by_name'] = structure
data['structure_by_longname'] = structure_by_longname
if len(reference) > 5:
datatype, long_name, table, max_length = reference[2:]
data['datatype'] = datatype
data['table'] = table
data['long_name'] = long_name
return data | [
"def",
"_parse_structure",
"(",
"element",
",",
"reference",
")",
":",
"data",
"=",
"{",
"'reference'",
":",
"reference",
"}",
"content_type",
"=",
"reference",
"[",
"0",
"]",
"# content type can be sequence, choice or leaf",
"if",
"content_type",
"in",
"(",
"'seq... | Parse the given reference
:type element: :class:`Element <hl7apy.core.Element>`
:param element: element having the given reference structure
:param reference: the element structure from :func:`load_reference <hl7apy.load_reference>` or from a
message profile
:return: a dictionary containing the structure data | [
"Parse",
"the",
"given",
"reference"
] | 91be488e9274f6ec975519a1d9c17045bc91bf74 | https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/core.py#L554-L600 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.