repository_name
stringlengths 7
55
| func_path_in_repository
stringlengths 4
223
| func_name
stringlengths 1
134
| whole_func_string
stringlengths 75
104k
| language
stringclasses 1
value | func_code_string
stringlengths 75
104k
| func_code_tokens
sequencelengths 19
28.4k
| func_documentation_string
stringlengths 1
46.9k
| func_documentation_tokens
sequencelengths 1
1.97k
| split_name
stringclasses 1
value | func_code_url
stringlengths 87
315
|
---|---|---|---|---|---|---|---|---|---|---|
cons3rt/pycons3rt | pycons3rt/awsapi/s3util.py | S3Util.__download_from_s3 | def __download_from_s3(self, key, dest_dir):
"""Private method for downloading from S3
This private helper method takes a key and the full path to
the destination directory, assumes that the args have been
validated by the public caller methods, and attempts to
download the specified key to the dest_dir.
:param key: (str) S3 key for the file to be downloaded
:param dest_dir: (str) Full path destination directory
:return: (str) Downloaded file destination if the file was
downloaded successfully, None otherwise.
"""
log = logging.getLogger(self.cls_logger + '.__download_from_s3')
filename = key.split('/')[-1]
if filename is None:
log.error('Could not determine the filename from key: %s', key)
return None
destination = dest_dir + '/' + filename
log.info('Attempting to download %s from bucket %s to destination %s',
key, self.bucket_name, destination)
max_tries = 10
count = 1
while count <= max_tries:
log.info('Attempting to download file %s, try %s of %s', key,
count, max_tries)
try:
self.s3client.download_file(
Bucket=self.bucket_name, Key=key, Filename=destination)
except ClientError:
if count >= max_tries:
_, ex, trace = sys.exc_info()
msg = 'Unable to download key {k} from S3 bucket {b}:\n{e}'.format(
k=key, b=self.bucket_name, e=str(ex))
log.error(msg)
raise S3UtilError, msg, trace
else:
log.warn('Download failed, re-trying...')
count += 1
time.sleep(5)
continue
else:
log.info('Successfully downloaded %s from S3 bucket %s to: %s',
key,
self.bucket_name,
destination)
return destination | python | def __download_from_s3(self, key, dest_dir):
"""Private method for downloading from S3
This private helper method takes a key and the full path to
the destination directory, assumes that the args have been
validated by the public caller methods, and attempts to
download the specified key to the dest_dir.
:param key: (str) S3 key for the file to be downloaded
:param dest_dir: (str) Full path destination directory
:return: (str) Downloaded file destination if the file was
downloaded successfully, None otherwise.
"""
log = logging.getLogger(self.cls_logger + '.__download_from_s3')
filename = key.split('/')[-1]
if filename is None:
log.error('Could not determine the filename from key: %s', key)
return None
destination = dest_dir + '/' + filename
log.info('Attempting to download %s from bucket %s to destination %s',
key, self.bucket_name, destination)
max_tries = 10
count = 1
while count <= max_tries:
log.info('Attempting to download file %s, try %s of %s', key,
count, max_tries)
try:
self.s3client.download_file(
Bucket=self.bucket_name, Key=key, Filename=destination)
except ClientError:
if count >= max_tries:
_, ex, trace = sys.exc_info()
msg = 'Unable to download key {k} from S3 bucket {b}:\n{e}'.format(
k=key, b=self.bucket_name, e=str(ex))
log.error(msg)
raise S3UtilError, msg, trace
else:
log.warn('Download failed, re-trying...')
count += 1
time.sleep(5)
continue
else:
log.info('Successfully downloaded %s from S3 bucket %s to: %s',
key,
self.bucket_name,
destination)
return destination | [
"def",
"__download_from_s3",
"(",
"self",
",",
"key",
",",
"dest_dir",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"self",
".",
"cls_logger",
"+",
"'.__download_from_s3'",
")",
"filename",
"=",
"key",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
"if",
"filename",
"is",
"None",
":",
"log",
".",
"error",
"(",
"'Could not determine the filename from key: %s'",
",",
"key",
")",
"return",
"None",
"destination",
"=",
"dest_dir",
"+",
"'/'",
"+",
"filename",
"log",
".",
"info",
"(",
"'Attempting to download %s from bucket %s to destination %s'",
",",
"key",
",",
"self",
".",
"bucket_name",
",",
"destination",
")",
"max_tries",
"=",
"10",
"count",
"=",
"1",
"while",
"count",
"<=",
"max_tries",
":",
"log",
".",
"info",
"(",
"'Attempting to download file %s, try %s of %s'",
",",
"key",
",",
"count",
",",
"max_tries",
")",
"try",
":",
"self",
".",
"s3client",
".",
"download_file",
"(",
"Bucket",
"=",
"self",
".",
"bucket_name",
",",
"Key",
"=",
"key",
",",
"Filename",
"=",
"destination",
")",
"except",
"ClientError",
":",
"if",
"count",
">=",
"max_tries",
":",
"_",
",",
"ex",
",",
"trace",
"=",
"sys",
".",
"exc_info",
"(",
")",
"msg",
"=",
"'Unable to download key {k} from S3 bucket {b}:\\n{e}'",
".",
"format",
"(",
"k",
"=",
"key",
",",
"b",
"=",
"self",
".",
"bucket_name",
",",
"e",
"=",
"str",
"(",
"ex",
")",
")",
"log",
".",
"error",
"(",
"msg",
")",
"raise",
"S3UtilError",
",",
"msg",
",",
"trace",
"else",
":",
"log",
".",
"warn",
"(",
"'Download failed, re-trying...'",
")",
"count",
"+=",
"1",
"time",
".",
"sleep",
"(",
"5",
")",
"continue",
"else",
":",
"log",
".",
"info",
"(",
"'Successfully downloaded %s from S3 bucket %s to: %s'",
",",
"key",
",",
"self",
".",
"bucket_name",
",",
"destination",
")",
"return",
"destination"
] | Private method for downloading from S3
This private helper method takes a key and the full path to
the destination directory, assumes that the args have been
validated by the public caller methods, and attempts to
download the specified key to the dest_dir.
:param key: (str) S3 key for the file to be downloaded
:param dest_dir: (str) Full path destination directory
:return: (str) Downloaded file destination if the file was
downloaded successfully, None otherwise. | [
"Private",
"method",
"for",
"downloading",
"from",
"S3"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/awsapi/s3util.py#L133-L179 |
cons3rt/pycons3rt | pycons3rt/awsapi/s3util.py | S3Util.download_file_by_key | def download_file_by_key(self, key, dest_dir):
"""Downloads a file by key from the specified S3 bucket
This method takes the full 'key' as the arg, and attempts to
download the file to the specified dest_dir as the destination
directory. This method sets the downloaded filename to be the
same as it is on S3.
:param key: (str) S3 key for the file to be downloaded.
:param dest_dir: (str) Full path destination directory
:return: (str) Downloaded file destination if the file was
downloaded successfully, None otherwise.
"""
log = logging.getLogger(self.cls_logger + '.download_file_by_key')
if not isinstance(key, basestring):
log.error('key argument is not a string')
return None
if not isinstance(dest_dir, basestring):
log.error('dest_dir argument is not a string')
return None
if not os.path.isdir(dest_dir):
log.error('Directory not found on file system: %s', dest_dir)
return None
try:
dest_path = self.__download_from_s3(key, dest_dir)
except S3UtilError:
raise
return dest_path | python | def download_file_by_key(self, key, dest_dir):
"""Downloads a file by key from the specified S3 bucket
This method takes the full 'key' as the arg, and attempts to
download the file to the specified dest_dir as the destination
directory. This method sets the downloaded filename to be the
same as it is on S3.
:param key: (str) S3 key for the file to be downloaded.
:param dest_dir: (str) Full path destination directory
:return: (str) Downloaded file destination if the file was
downloaded successfully, None otherwise.
"""
log = logging.getLogger(self.cls_logger + '.download_file_by_key')
if not isinstance(key, basestring):
log.error('key argument is not a string')
return None
if not isinstance(dest_dir, basestring):
log.error('dest_dir argument is not a string')
return None
if not os.path.isdir(dest_dir):
log.error('Directory not found on file system: %s', dest_dir)
return None
try:
dest_path = self.__download_from_s3(key, dest_dir)
except S3UtilError:
raise
return dest_path | [
"def",
"download_file_by_key",
"(",
"self",
",",
"key",
",",
"dest_dir",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"self",
".",
"cls_logger",
"+",
"'.download_file_by_key'",
")",
"if",
"not",
"isinstance",
"(",
"key",
",",
"basestring",
")",
":",
"log",
".",
"error",
"(",
"'key argument is not a string'",
")",
"return",
"None",
"if",
"not",
"isinstance",
"(",
"dest_dir",
",",
"basestring",
")",
":",
"log",
".",
"error",
"(",
"'dest_dir argument is not a string'",
")",
"return",
"None",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"dest_dir",
")",
":",
"log",
".",
"error",
"(",
"'Directory not found on file system: %s'",
",",
"dest_dir",
")",
"return",
"None",
"try",
":",
"dest_path",
"=",
"self",
".",
"__download_from_s3",
"(",
"key",
",",
"dest_dir",
")",
"except",
"S3UtilError",
":",
"raise",
"return",
"dest_path"
] | Downloads a file by key from the specified S3 bucket
This method takes the full 'key' as the arg, and attempts to
download the file to the specified dest_dir as the destination
directory. This method sets the downloaded filename to be the
same as it is on S3.
:param key: (str) S3 key for the file to be downloaded.
:param dest_dir: (str) Full path destination directory
:return: (str) Downloaded file destination if the file was
downloaded successfully, None otherwise. | [
"Downloads",
"a",
"file",
"by",
"key",
"from",
"the",
"specified",
"S3",
"bucket"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/awsapi/s3util.py#L181-L208 |
cons3rt/pycons3rt | pycons3rt/awsapi/s3util.py | S3Util.download_file | def download_file(self, regex, dest_dir):
"""Downloads a file by regex from the specified S3 bucket
This method takes a regular expression as the arg, and attempts
to download the file to the specified dest_dir as the
destination directory. This method sets the downloaded filename
to be the same as it is on S3.
:param regex: (str) Regular expression matching the S3 key for
the file to be downloaded.
:param dest_dir: (str) Full path destination directory
:return: (str) Downloaded file destination if the file was
downloaded successfully, None otherwise.
"""
log = logging.getLogger(self.cls_logger + '.download_file')
if not isinstance(regex, basestring):
log.error('regex argument is not a string')
return None
if not isinstance(dest_dir, basestring):
log.error('dest_dir argument is not a string')
return None
if not os.path.isdir(dest_dir):
log.error('Directory not found on file system: %s', dest_dir)
return None
key = self.find_key(regex)
if key is None:
log.warn('Could not find a matching S3 key for: %s', regex)
return None
return self.__download_from_s3(key, dest_dir) | python | def download_file(self, regex, dest_dir):
"""Downloads a file by regex from the specified S3 bucket
This method takes a regular expression as the arg, and attempts
to download the file to the specified dest_dir as the
destination directory. This method sets the downloaded filename
to be the same as it is on S3.
:param regex: (str) Regular expression matching the S3 key for
the file to be downloaded.
:param dest_dir: (str) Full path destination directory
:return: (str) Downloaded file destination if the file was
downloaded successfully, None otherwise.
"""
log = logging.getLogger(self.cls_logger + '.download_file')
if not isinstance(regex, basestring):
log.error('regex argument is not a string')
return None
if not isinstance(dest_dir, basestring):
log.error('dest_dir argument is not a string')
return None
if not os.path.isdir(dest_dir):
log.error('Directory not found on file system: %s', dest_dir)
return None
key = self.find_key(regex)
if key is None:
log.warn('Could not find a matching S3 key for: %s', regex)
return None
return self.__download_from_s3(key, dest_dir) | [
"def",
"download_file",
"(",
"self",
",",
"regex",
",",
"dest_dir",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"self",
".",
"cls_logger",
"+",
"'.download_file'",
")",
"if",
"not",
"isinstance",
"(",
"regex",
",",
"basestring",
")",
":",
"log",
".",
"error",
"(",
"'regex argument is not a string'",
")",
"return",
"None",
"if",
"not",
"isinstance",
"(",
"dest_dir",
",",
"basestring",
")",
":",
"log",
".",
"error",
"(",
"'dest_dir argument is not a string'",
")",
"return",
"None",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"dest_dir",
")",
":",
"log",
".",
"error",
"(",
"'Directory not found on file system: %s'",
",",
"dest_dir",
")",
"return",
"None",
"key",
"=",
"self",
".",
"find_key",
"(",
"regex",
")",
"if",
"key",
"is",
"None",
":",
"log",
".",
"warn",
"(",
"'Could not find a matching S3 key for: %s'",
",",
"regex",
")",
"return",
"None",
"return",
"self",
".",
"__download_from_s3",
"(",
"key",
",",
"dest_dir",
")"
] | Downloads a file by regex from the specified S3 bucket
This method takes a regular expression as the arg, and attempts
to download the file to the specified dest_dir as the
destination directory. This method sets the downloaded filename
to be the same as it is on S3.
:param regex: (str) Regular expression matching the S3 key for
the file to be downloaded.
:param dest_dir: (str) Full path destination directory
:return: (str) Downloaded file destination if the file was
downloaded successfully, None otherwise. | [
"Downloads",
"a",
"file",
"by",
"regex",
"from",
"the",
"specified",
"S3",
"bucket"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/awsapi/s3util.py#L210-L238 |
cons3rt/pycons3rt | pycons3rt/awsapi/s3util.py | S3Util.find_key | def find_key(self, regex):
"""Attempts to find a single S3 key based on the passed regex
Given a regular expression, this method searches the S3 bucket
for a matching key, and returns it if exactly 1 key matches.
Otherwise, None is returned.
:param regex: (str) Regular expression for an S3 key
:return: (str) Full length S3 key matching the regex, None
otherwise
"""
log = logging.getLogger(self.cls_logger + '.find_key')
if not isinstance(regex, basestring):
log.error('regex argument is not a string')
return None
log.info('Looking up a single S3 key based on regex: %s', regex)
matched_keys = []
for item in self.bucket.objects.all():
log.debug('Checking if regex matches key: %s', item.key)
match = re.search(regex, item.key)
if match:
matched_keys.append(item.key)
if len(matched_keys) == 1:
log.info('Found matching key: %s', matched_keys[0])
return matched_keys[0]
elif len(matched_keys) > 1:
log.info('Passed regex matched more than 1 key: %s', regex)
return None
else:
log.info('Passed regex did not match any key: %s', regex)
return None | python | def find_key(self, regex):
"""Attempts to find a single S3 key based on the passed regex
Given a regular expression, this method searches the S3 bucket
for a matching key, and returns it if exactly 1 key matches.
Otherwise, None is returned.
:param regex: (str) Regular expression for an S3 key
:return: (str) Full length S3 key matching the regex, None
otherwise
"""
log = logging.getLogger(self.cls_logger + '.find_key')
if not isinstance(regex, basestring):
log.error('regex argument is not a string')
return None
log.info('Looking up a single S3 key based on regex: %s', regex)
matched_keys = []
for item in self.bucket.objects.all():
log.debug('Checking if regex matches key: %s', item.key)
match = re.search(regex, item.key)
if match:
matched_keys.append(item.key)
if len(matched_keys) == 1:
log.info('Found matching key: %s', matched_keys[0])
return matched_keys[0]
elif len(matched_keys) > 1:
log.info('Passed regex matched more than 1 key: %s', regex)
return None
else:
log.info('Passed regex did not match any key: %s', regex)
return None | [
"def",
"find_key",
"(",
"self",
",",
"regex",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"self",
".",
"cls_logger",
"+",
"'.find_key'",
")",
"if",
"not",
"isinstance",
"(",
"regex",
",",
"basestring",
")",
":",
"log",
".",
"error",
"(",
"'regex argument is not a string'",
")",
"return",
"None",
"log",
".",
"info",
"(",
"'Looking up a single S3 key based on regex: %s'",
",",
"regex",
")",
"matched_keys",
"=",
"[",
"]",
"for",
"item",
"in",
"self",
".",
"bucket",
".",
"objects",
".",
"all",
"(",
")",
":",
"log",
".",
"debug",
"(",
"'Checking if regex matches key: %s'",
",",
"item",
".",
"key",
")",
"match",
"=",
"re",
".",
"search",
"(",
"regex",
",",
"item",
".",
"key",
")",
"if",
"match",
":",
"matched_keys",
".",
"append",
"(",
"item",
".",
"key",
")",
"if",
"len",
"(",
"matched_keys",
")",
"==",
"1",
":",
"log",
".",
"info",
"(",
"'Found matching key: %s'",
",",
"matched_keys",
"[",
"0",
"]",
")",
"return",
"matched_keys",
"[",
"0",
"]",
"elif",
"len",
"(",
"matched_keys",
")",
">",
"1",
":",
"log",
".",
"info",
"(",
"'Passed regex matched more than 1 key: %s'",
",",
"regex",
")",
"return",
"None",
"else",
":",
"log",
".",
"info",
"(",
"'Passed regex did not match any key: %s'",
",",
"regex",
")",
"return",
"None"
] | Attempts to find a single S3 key based on the passed regex
Given a regular expression, this method searches the S3 bucket
for a matching key, and returns it if exactly 1 key matches.
Otherwise, None is returned.
:param regex: (str) Regular expression for an S3 key
:return: (str) Full length S3 key matching the regex, None
otherwise | [
"Attempts",
"to",
"find",
"a",
"single",
"S3",
"key",
"based",
"on",
"the",
"passed",
"regex"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/awsapi/s3util.py#L240-L270 |
cons3rt/pycons3rt | pycons3rt/awsapi/s3util.py | S3Util.find_keys | def find_keys(self, regex, bucket_name=None):
"""Finds a list of S3 keys matching the passed regex
Given a regular expression, this method searches the S3 bucket
for matching keys, and returns an array of strings for matched
keys, an empty array if non are found.
:param regex: (str) Regular expression to use is the key search
:param bucket_name: (str) Name of bucket to search (optional)
:return: Array of strings containing matched S3 keys
"""
log = logging.getLogger(self.cls_logger + '.find_keys')
matched_keys = []
if not isinstance(regex, basestring):
log.error('regex argument is not a string, found: {t}'.format(t=regex.__class__.__name__))
return None
# Determine which bucket to use
if bucket_name is None:
s3bucket = self.bucket
else:
log.debug('Using the provided S3 bucket: {n}'.format(n=bucket_name))
s3bucket = self.s3resource.Bucket(bucket_name)
log.info('Looking up S3 keys based on regex: {r}'.format(r=regex))
for item in s3bucket.objects.all():
log.debug('Checking if regex matches key: {k}'.format(k=item.key))
match = re.search(regex, item.key)
if match:
matched_keys.append(item.key)
log.info('Found matching keys: {k}'.format(k=matched_keys))
return matched_keys | python | def find_keys(self, regex, bucket_name=None):
"""Finds a list of S3 keys matching the passed regex
Given a regular expression, this method searches the S3 bucket
for matching keys, and returns an array of strings for matched
keys, an empty array if non are found.
:param regex: (str) Regular expression to use is the key search
:param bucket_name: (str) Name of bucket to search (optional)
:return: Array of strings containing matched S3 keys
"""
log = logging.getLogger(self.cls_logger + '.find_keys')
matched_keys = []
if not isinstance(regex, basestring):
log.error('regex argument is not a string, found: {t}'.format(t=regex.__class__.__name__))
return None
# Determine which bucket to use
if bucket_name is None:
s3bucket = self.bucket
else:
log.debug('Using the provided S3 bucket: {n}'.format(n=bucket_name))
s3bucket = self.s3resource.Bucket(bucket_name)
log.info('Looking up S3 keys based on regex: {r}'.format(r=regex))
for item in s3bucket.objects.all():
log.debug('Checking if regex matches key: {k}'.format(k=item.key))
match = re.search(regex, item.key)
if match:
matched_keys.append(item.key)
log.info('Found matching keys: {k}'.format(k=matched_keys))
return matched_keys | [
"def",
"find_keys",
"(",
"self",
",",
"regex",
",",
"bucket_name",
"=",
"None",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"self",
".",
"cls_logger",
"+",
"'.find_keys'",
")",
"matched_keys",
"=",
"[",
"]",
"if",
"not",
"isinstance",
"(",
"regex",
",",
"basestring",
")",
":",
"log",
".",
"error",
"(",
"'regex argument is not a string, found: {t}'",
".",
"format",
"(",
"t",
"=",
"regex",
".",
"__class__",
".",
"__name__",
")",
")",
"return",
"None",
"# Determine which bucket to use",
"if",
"bucket_name",
"is",
"None",
":",
"s3bucket",
"=",
"self",
".",
"bucket",
"else",
":",
"log",
".",
"debug",
"(",
"'Using the provided S3 bucket: {n}'",
".",
"format",
"(",
"n",
"=",
"bucket_name",
")",
")",
"s3bucket",
"=",
"self",
".",
"s3resource",
".",
"Bucket",
"(",
"bucket_name",
")",
"log",
".",
"info",
"(",
"'Looking up S3 keys based on regex: {r}'",
".",
"format",
"(",
"r",
"=",
"regex",
")",
")",
"for",
"item",
"in",
"s3bucket",
".",
"objects",
".",
"all",
"(",
")",
":",
"log",
".",
"debug",
"(",
"'Checking if regex matches key: {k}'",
".",
"format",
"(",
"k",
"=",
"item",
".",
"key",
")",
")",
"match",
"=",
"re",
".",
"search",
"(",
"regex",
",",
"item",
".",
"key",
")",
"if",
"match",
":",
"matched_keys",
".",
"append",
"(",
"item",
".",
"key",
")",
"log",
".",
"info",
"(",
"'Found matching keys: {k}'",
".",
"format",
"(",
"k",
"=",
"matched_keys",
")",
")",
"return",
"matched_keys"
] | Finds a list of S3 keys matching the passed regex
Given a regular expression, this method searches the S3 bucket
for matching keys, and returns an array of strings for matched
keys, an empty array if non are found.
:param regex: (str) Regular expression to use is the key search
:param bucket_name: (str) Name of bucket to search (optional)
:return: Array of strings containing matched S3 keys | [
"Finds",
"a",
"list",
"of",
"S3",
"keys",
"matching",
"the",
"passed",
"regex"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/awsapi/s3util.py#L272-L303 |
cons3rt/pycons3rt | pycons3rt/awsapi/s3util.py | S3Util.upload_file | def upload_file(self, filepath, key):
"""Uploads a file using the passed S3 key
This method uploads a file specified by the filepath to S3
using the provided S3 key.
:param filepath: (str) Full path to the file to be uploaded
:param key: (str) S3 key to be set for the upload
:return: True if upload is successful, False otherwise.
"""
log = logging.getLogger(self.cls_logger + '.upload_file')
log.info('Attempting to upload file %s to S3 bucket %s as key %s...',
filepath, self.bucket_name, key)
if not isinstance(filepath, basestring):
log.error('filepath argument is not a string')
return False
if not isinstance(key, basestring):
log.error('key argument is not a string')
return False
if not os.path.isfile(filepath):
log.error('File not found on file system: %s', filepath)
return False
try:
self.s3client.upload_file(
Filename=filepath, Bucket=self.bucket_name, Key=key)
except ClientError as e:
log.error('Unable to upload file %s to bucket %s as key %s:\n%s',
filepath, self.bucket_name, key, e)
return False
else:
log.info('Successfully uploaded file to S3 bucket %s as key %s',
self.bucket_name, key)
return True | python | def upload_file(self, filepath, key):
"""Uploads a file using the passed S3 key
This method uploads a file specified by the filepath to S3
using the provided S3 key.
:param filepath: (str) Full path to the file to be uploaded
:param key: (str) S3 key to be set for the upload
:return: True if upload is successful, False otherwise.
"""
log = logging.getLogger(self.cls_logger + '.upload_file')
log.info('Attempting to upload file %s to S3 bucket %s as key %s...',
filepath, self.bucket_name, key)
if not isinstance(filepath, basestring):
log.error('filepath argument is not a string')
return False
if not isinstance(key, basestring):
log.error('key argument is not a string')
return False
if not os.path.isfile(filepath):
log.error('File not found on file system: %s', filepath)
return False
try:
self.s3client.upload_file(
Filename=filepath, Bucket=self.bucket_name, Key=key)
except ClientError as e:
log.error('Unable to upload file %s to bucket %s as key %s:\n%s',
filepath, self.bucket_name, key, e)
return False
else:
log.info('Successfully uploaded file to S3 bucket %s as key %s',
self.bucket_name, key)
return True | [
"def",
"upload_file",
"(",
"self",
",",
"filepath",
",",
"key",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"self",
".",
"cls_logger",
"+",
"'.upload_file'",
")",
"log",
".",
"info",
"(",
"'Attempting to upload file %s to S3 bucket %s as key %s...'",
",",
"filepath",
",",
"self",
".",
"bucket_name",
",",
"key",
")",
"if",
"not",
"isinstance",
"(",
"filepath",
",",
"basestring",
")",
":",
"log",
".",
"error",
"(",
"'filepath argument is not a string'",
")",
"return",
"False",
"if",
"not",
"isinstance",
"(",
"key",
",",
"basestring",
")",
":",
"log",
".",
"error",
"(",
"'key argument is not a string'",
")",
"return",
"False",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"filepath",
")",
":",
"log",
".",
"error",
"(",
"'File not found on file system: %s'",
",",
"filepath",
")",
"return",
"False",
"try",
":",
"self",
".",
"s3client",
".",
"upload_file",
"(",
"Filename",
"=",
"filepath",
",",
"Bucket",
"=",
"self",
".",
"bucket_name",
",",
"Key",
"=",
"key",
")",
"except",
"ClientError",
"as",
"e",
":",
"log",
".",
"error",
"(",
"'Unable to upload file %s to bucket %s as key %s:\\n%s'",
",",
"filepath",
",",
"self",
".",
"bucket_name",
",",
"key",
",",
"e",
")",
"return",
"False",
"else",
":",
"log",
".",
"info",
"(",
"'Successfully uploaded file to S3 bucket %s as key %s'",
",",
"self",
".",
"bucket_name",
",",
"key",
")",
"return",
"True"
] | Uploads a file using the passed S3 key
This method uploads a file specified by the filepath to S3
using the provided S3 key.
:param filepath: (str) Full path to the file to be uploaded
:param key: (str) S3 key to be set for the upload
:return: True if upload is successful, False otherwise. | [
"Uploads",
"a",
"file",
"using",
"the",
"passed",
"S3",
"key"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/awsapi/s3util.py#L305-L341 |
cons3rt/pycons3rt | pycons3rt/awsapi/s3util.py | S3Util.delete_key | def delete_key(self, key_to_delete):
"""Deletes the specified key
:param key_to_delete:
:return:
"""
log = logging.getLogger(self.cls_logger + '.delete_key')
log.info('Attempting to delete key: {k}'.format(k=key_to_delete))
try:
self.s3client.delete_object(Bucket=self.bucket_name, Key=key_to_delete)
except ClientError:
_, ex, trace = sys.exc_info()
log.error('ClientError: Unable to delete key: {k}\n{e}'.format(k=key_to_delete, e=str(ex)))
return False
else:
log.info('Successfully deleted key: {k}'.format(k=key_to_delete))
return True | python | def delete_key(self, key_to_delete):
"""Deletes the specified key
:param key_to_delete:
:return:
"""
log = logging.getLogger(self.cls_logger + '.delete_key')
log.info('Attempting to delete key: {k}'.format(k=key_to_delete))
try:
self.s3client.delete_object(Bucket=self.bucket_name, Key=key_to_delete)
except ClientError:
_, ex, trace = sys.exc_info()
log.error('ClientError: Unable to delete key: {k}\n{e}'.format(k=key_to_delete, e=str(ex)))
return False
else:
log.info('Successfully deleted key: {k}'.format(k=key_to_delete))
return True | [
"def",
"delete_key",
"(",
"self",
",",
"key_to_delete",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"self",
".",
"cls_logger",
"+",
"'.delete_key'",
")",
"log",
".",
"info",
"(",
"'Attempting to delete key: {k}'",
".",
"format",
"(",
"k",
"=",
"key_to_delete",
")",
")",
"try",
":",
"self",
".",
"s3client",
".",
"delete_object",
"(",
"Bucket",
"=",
"self",
".",
"bucket_name",
",",
"Key",
"=",
"key_to_delete",
")",
"except",
"ClientError",
":",
"_",
",",
"ex",
",",
"trace",
"=",
"sys",
".",
"exc_info",
"(",
")",
"log",
".",
"error",
"(",
"'ClientError: Unable to delete key: {k}\\n{e}'",
".",
"format",
"(",
"k",
"=",
"key_to_delete",
",",
"e",
"=",
"str",
"(",
"ex",
")",
")",
")",
"return",
"False",
"else",
":",
"log",
".",
"info",
"(",
"'Successfully deleted key: {k}'",
".",
"format",
"(",
"k",
"=",
"key_to_delete",
")",
")",
"return",
"True"
] | Deletes the specified key
:param key_to_delete:
:return: | [
"Deletes",
"the",
"specified",
"key"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/awsapi/s3util.py#L343-L360 |
novopl/peltak | src/peltak/extra/gitflow/logic/common.py | assert_branch_type | def assert_branch_type(branch_type):
# type: (str) -> None
""" Print error and exit if the current branch is not of a given type.
Args:
branch_type (str):
The branch type. This assumes the branch is in the '<type>/<title>`
format.
"""
branch = git.current_branch(refresh=True)
if branch.type != branch_type:
if context.get('pretend', False):
log.info("Would assert that you're on a <33>{}/*<32> branch",
branch_type)
else:
log.err("Not on a <33>{}<31> branch!", branch_type)
fmt = ("The branch must follow <33>{required_type}/<name><31>"
"format and your branch is called <33>{name}<31>.")
log.err(fmt, required_type=branch_type, name=branch.name)
sys.exit(1) | python | def assert_branch_type(branch_type):
# type: (str) -> None
""" Print error and exit if the current branch is not of a given type.
Args:
branch_type (str):
The branch type. This assumes the branch is in the '<type>/<title>`
format.
"""
branch = git.current_branch(refresh=True)
if branch.type != branch_type:
if context.get('pretend', False):
log.info("Would assert that you're on a <33>{}/*<32> branch",
branch_type)
else:
log.err("Not on a <33>{}<31> branch!", branch_type)
fmt = ("The branch must follow <33>{required_type}/<name><31>"
"format and your branch is called <33>{name}<31>.")
log.err(fmt, required_type=branch_type, name=branch.name)
sys.exit(1) | [
"def",
"assert_branch_type",
"(",
"branch_type",
")",
":",
"# type: (str) -> None",
"branch",
"=",
"git",
".",
"current_branch",
"(",
"refresh",
"=",
"True",
")",
"if",
"branch",
".",
"type",
"!=",
"branch_type",
":",
"if",
"context",
".",
"get",
"(",
"'pretend'",
",",
"False",
")",
":",
"log",
".",
"info",
"(",
"\"Would assert that you're on a <33>{}/*<32> branch\"",
",",
"branch_type",
")",
"else",
":",
"log",
".",
"err",
"(",
"\"Not on a <33>{}<31> branch!\"",
",",
"branch_type",
")",
"fmt",
"=",
"(",
"\"The branch must follow <33>{required_type}/<name><31>\"",
"\"format and your branch is called <33>{name}<31>.\"",
")",
"log",
".",
"err",
"(",
"fmt",
",",
"required_type",
"=",
"branch_type",
",",
"name",
"=",
"branch",
".",
"name",
")",
"sys",
".",
"exit",
"(",
"1",
")"
] | Print error and exit if the current branch is not of a given type.
Args:
branch_type (str):
The branch type. This assumes the branch is in the '<type>/<title>`
format. | [
"Print",
"error",
"and",
"exit",
"if",
"the",
"current",
"branch",
"is",
"not",
"of",
"a",
"given",
"type",
"."
] | train | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/gitflow/logic/common.py#L38-L58 |
novopl/peltak | src/peltak/extra/gitflow/logic/common.py | assert_on_branch | def assert_on_branch(branch_name):
# type: (str) -> None
""" Print error and exit if *branch_name* is not the current branch.
Args:
branch_name (str):
The supposed name of the current branch.
"""
branch = git.current_branch(refresh=True)
if branch.name != branch_name:
if context.get('pretend', False):
log.info("Would assert that you're on a <33>{}<32> branch",
branch_name)
else:
log.err("You're not on a <33>{}<31> branch!", branch_name)
sys.exit(1) | python | def assert_on_branch(branch_name):
# type: (str) -> None
""" Print error and exit if *branch_name* is not the current branch.
Args:
branch_name (str):
The supposed name of the current branch.
"""
branch = git.current_branch(refresh=True)
if branch.name != branch_name:
if context.get('pretend', False):
log.info("Would assert that you're on a <33>{}<32> branch",
branch_name)
else:
log.err("You're not on a <33>{}<31> branch!", branch_name)
sys.exit(1) | [
"def",
"assert_on_branch",
"(",
"branch_name",
")",
":",
"# type: (str) -> None",
"branch",
"=",
"git",
".",
"current_branch",
"(",
"refresh",
"=",
"True",
")",
"if",
"branch",
".",
"name",
"!=",
"branch_name",
":",
"if",
"context",
".",
"get",
"(",
"'pretend'",
",",
"False",
")",
":",
"log",
".",
"info",
"(",
"\"Would assert that you're on a <33>{}<32> branch\"",
",",
"branch_name",
")",
"else",
":",
"log",
".",
"err",
"(",
"\"You're not on a <33>{}<31> branch!\"",
",",
"branch_name",
")",
"sys",
".",
"exit",
"(",
"1",
")"
] | Print error and exit if *branch_name* is not the current branch.
Args:
branch_name (str):
The supposed name of the current branch. | [
"Print",
"error",
"and",
"exit",
"if",
"*",
"branch_name",
"*",
"is",
"not",
"the",
"current",
"branch",
"."
] | train | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/gitflow/logic/common.py#L61-L77 |
novopl/peltak | src/peltak/extra/gitflow/logic/common.py | git_branch_delete | def git_branch_delete(branch_name):
# type: (str) -> None
""" Delete the given branch.
Args:
branch_name (str):
Name of the branch to delete.
"""
if branch_name not in git.protected_branches():
log.info("Deleting branch <33>{}", branch_name)
shell.run('git branch -d {}'.format(branch_name)) | python | def git_branch_delete(branch_name):
# type: (str) -> None
""" Delete the given branch.
Args:
branch_name (str):
Name of the branch to delete.
"""
if branch_name not in git.protected_branches():
log.info("Deleting branch <33>{}", branch_name)
shell.run('git branch -d {}'.format(branch_name)) | [
"def",
"git_branch_delete",
"(",
"branch_name",
")",
":",
"# type: (str) -> None",
"if",
"branch_name",
"not",
"in",
"git",
".",
"protected_branches",
"(",
")",
":",
"log",
".",
"info",
"(",
"\"Deleting branch <33>{}\"",
",",
"branch_name",
")",
"shell",
".",
"run",
"(",
"'git branch -d {}'",
".",
"format",
"(",
"branch_name",
")",
")"
] | Delete the given branch.
Args:
branch_name (str):
Name of the branch to delete. | [
"Delete",
"the",
"given",
"branch",
"."
] | train | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/gitflow/logic/common.py#L80-L90 |
novopl/peltak | src/peltak/extra/gitflow/logic/common.py | git_branch_rename | def git_branch_rename(new_name):
# type: (str) -> None
""" Rename the current branch
Args:
new_name (str):
New name for the current branch.
"""
curr_name = git.current_branch(refresh=True).name
if curr_name not in git.protected_branches():
log.info("Renaming branch from <33>{}<32> to <33>{}".format(
curr_name, new_name
))
shell.run('git branch -m {}'.format(new_name)) | python | def git_branch_rename(new_name):
# type: (str) -> None
""" Rename the current branch
Args:
new_name (str):
New name for the current branch.
"""
curr_name = git.current_branch(refresh=True).name
if curr_name not in git.protected_branches():
log.info("Renaming branch from <33>{}<32> to <33>{}".format(
curr_name, new_name
))
shell.run('git branch -m {}'.format(new_name)) | [
"def",
"git_branch_rename",
"(",
"new_name",
")",
":",
"# type: (str) -> None",
"curr_name",
"=",
"git",
".",
"current_branch",
"(",
"refresh",
"=",
"True",
")",
".",
"name",
"if",
"curr_name",
"not",
"in",
"git",
".",
"protected_branches",
"(",
")",
":",
"log",
".",
"info",
"(",
"\"Renaming branch from <33>{}<32> to <33>{}\"",
".",
"format",
"(",
"curr_name",
",",
"new_name",
")",
")",
"shell",
".",
"run",
"(",
"'git branch -m {}'",
".",
"format",
"(",
"new_name",
")",
")"
] | Rename the current branch
Args:
new_name (str):
New name for the current branch. | [
"Rename",
"the",
"current",
"branch"
] | train | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/gitflow/logic/common.py#L93-L107 |
novopl/peltak | src/peltak/extra/gitflow/logic/common.py | git_checkout | def git_checkout(branch_name, create=False):
# type: (str, bool) -> None
""" Checkout or create a given branch
Args:
branch_name (str):
The name of the branch to checkout or create.
create (bool):
If set to **True** it will create the branch instead of checking it
out.
"""
log.info("Checking out <33>{}".format(branch_name))
shell.run('git checkout {} {}'.format('-b' if create else '', branch_name)) | python | def git_checkout(branch_name, create=False):
# type: (str, bool) -> None
""" Checkout or create a given branch
Args:
branch_name (str):
The name of the branch to checkout or create.
create (bool):
If set to **True** it will create the branch instead of checking it
out.
"""
log.info("Checking out <33>{}".format(branch_name))
shell.run('git checkout {} {}'.format('-b' if create else '', branch_name)) | [
"def",
"git_checkout",
"(",
"branch_name",
",",
"create",
"=",
"False",
")",
":",
"# type: (str, bool) -> None",
"log",
".",
"info",
"(",
"\"Checking out <33>{}\"",
".",
"format",
"(",
"branch_name",
")",
")",
"shell",
".",
"run",
"(",
"'git checkout {} {}'",
".",
"format",
"(",
"'-b'",
"if",
"create",
"else",
"''",
",",
"branch_name",
")",
")"
] | Checkout or create a given branch
Args:
branch_name (str):
The name of the branch to checkout or create.
create (bool):
If set to **True** it will create the branch instead of checking it
out. | [
"Checkout",
"or",
"create",
"a",
"given",
"branch"
] | train | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/gitflow/logic/common.py#L110-L122 |
novopl/peltak | src/peltak/extra/gitflow/logic/common.py | git_merge | def git_merge(base, head, no_ff=False):
# type: (str, str, bool) -> None
""" Merge *head* into *base*.
Args:
base (str):
The base branch. *head* will be merged into this branch.
head (str):
The branch that will be merged into *base*.
no_ff (bool):
If set to **True** it will force git to create merge commit. If set
to **False** (default) it will do a fast-forward merge if possible.
"""
pretend = context.get('pretend', False)
branch = git.current_branch(refresh=True)
if branch.name != base and not pretend:
git_checkout(base)
args = []
if no_ff:
args.append('--no-ff')
log.info("Merging <33>{}<32> into <33>{}<32>", head, base)
shell.run('git merge {args} {branch}'.format(
args=' '.join(args),
branch=head,
))
if branch.name != base and not pretend:
git_checkout(branch.name) | python | def git_merge(base, head, no_ff=False):
# type: (str, str, bool) -> None
""" Merge *head* into *base*.
Args:
base (str):
The base branch. *head* will be merged into this branch.
head (str):
The branch that will be merged into *base*.
no_ff (bool):
If set to **True** it will force git to create merge commit. If set
to **False** (default) it will do a fast-forward merge if possible.
"""
pretend = context.get('pretend', False)
branch = git.current_branch(refresh=True)
if branch.name != base and not pretend:
git_checkout(base)
args = []
if no_ff:
args.append('--no-ff')
log.info("Merging <33>{}<32> into <33>{}<32>", head, base)
shell.run('git merge {args} {branch}'.format(
args=' '.join(args),
branch=head,
))
if branch.name != base and not pretend:
git_checkout(branch.name) | [
"def",
"git_merge",
"(",
"base",
",",
"head",
",",
"no_ff",
"=",
"False",
")",
":",
"# type: (str, str, bool) -> None",
"pretend",
"=",
"context",
".",
"get",
"(",
"'pretend'",
",",
"False",
")",
"branch",
"=",
"git",
".",
"current_branch",
"(",
"refresh",
"=",
"True",
")",
"if",
"branch",
".",
"name",
"!=",
"base",
"and",
"not",
"pretend",
":",
"git_checkout",
"(",
"base",
")",
"args",
"=",
"[",
"]",
"if",
"no_ff",
":",
"args",
".",
"append",
"(",
"'--no-ff'",
")",
"log",
".",
"info",
"(",
"\"Merging <33>{}<32> into <33>{}<32>\"",
",",
"head",
",",
"base",
")",
"shell",
".",
"run",
"(",
"'git merge {args} {branch}'",
".",
"format",
"(",
"args",
"=",
"' '",
".",
"join",
"(",
"args",
")",
",",
"branch",
"=",
"head",
",",
")",
")",
"if",
"branch",
".",
"name",
"!=",
"base",
"and",
"not",
"pretend",
":",
"git_checkout",
"(",
"branch",
".",
"name",
")"
] | Merge *head* into *base*.
Args:
base (str):
The base branch. *head* will be merged into this branch.
head (str):
The branch that will be merged into *base*.
no_ff (bool):
If set to **True** it will force git to create merge commit. If set
to **False** (default) it will do a fast-forward merge if possible. | [
"Merge",
"*",
"head",
"*",
"into",
"*",
"base",
"*",
"."
] | train | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/gitflow/logic/common.py#L137-L168 |
novopl/peltak | src/peltak/extra/gitflow/logic/common.py | get_base_branch | def get_base_branch():
# type: () -> str
""" Return the base branch for the current branch.
This function will first try to guess the base branch and if it can't it
will let the user choose the branch from the list of all local branches.
Returns:
str: The name of the branch the current branch is based on.
"""
base_branch = git.guess_base_branch()
if base_branch is None:
log.info("Can't guess the base branch, you have to pick one yourself:")
base_branch = choose_branch()
return base_branch | python | def get_base_branch():
# type: () -> str
""" Return the base branch for the current branch.
This function will first try to guess the base branch and if it can't it
will let the user choose the branch from the list of all local branches.
Returns:
str: The name of the branch the current branch is based on.
"""
base_branch = git.guess_base_branch()
if base_branch is None:
log.info("Can't guess the base branch, you have to pick one yourself:")
base_branch = choose_branch()
return base_branch | [
"def",
"get_base_branch",
"(",
")",
":",
"# type: () -> str",
"base_branch",
"=",
"git",
".",
"guess_base_branch",
"(",
")",
"if",
"base_branch",
"is",
"None",
":",
"log",
".",
"info",
"(",
"\"Can't guess the base branch, you have to pick one yourself:\"",
")",
"base_branch",
"=",
"choose_branch",
"(",
")",
"return",
"base_branch"
] | Return the base branch for the current branch.
This function will first try to guess the base branch and if it can't it
will let the user choose the branch from the list of all local branches.
Returns:
str: The name of the branch the current branch is based on. | [
"Return",
"the",
"base",
"branch",
"for",
"the",
"current",
"branch",
"."
] | train | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/gitflow/logic/common.py#L178-L194 |
novopl/peltak | src/peltak/extra/gitflow/logic/common.py | choose_branch | def choose_branch(exclude=None):
# type: (List[str]) -> str
""" Show the user a menu to pick a branch from the existing ones.
Args:
exclude (list[str]):
List of branch names to exclude from the menu. By default it will
exclude master and develop branches. To show all branches pass an
empty array here.
Returns:
str: The name of the branch chosen by the user. If the user inputs an
invalid choice, he will be asked again (and again) until he picks a
a valid branch.
"""
if exclude is None:
master = conf.get('git.master_branch', 'master')
develop = conf.get('git.devel_branch', 'develop')
exclude = {master, develop}
branches = list(set(git.branches()) - exclude)
# Print the menu
for i, branch_name in enumerate(branches):
shell.cprint('<90>[{}] <33>{}'.format(i + 1, branch_name))
# Get a valid choice from the user
choice = 0
while choice < 1 or choice > len(branches):
prompt = "Pick a base branch from the above [1-{}]".format(
len(branches)
)
choice = click.prompt(prompt, value_proc=int)
if not (1 <= choice <= len(branches)):
fmt = "Invalid choice {}, you must pick a number between {} and {}"
log.err(fmt.format(choice, 1, len(branches)))
return branches[choice - 1] | python | def choose_branch(exclude=None):
# type: (List[str]) -> str
""" Show the user a menu to pick a branch from the existing ones.
Args:
exclude (list[str]):
List of branch names to exclude from the menu. By default it will
exclude master and develop branches. To show all branches pass an
empty array here.
Returns:
str: The name of the branch chosen by the user. If the user inputs an
invalid choice, he will be asked again (and again) until he picks a
a valid branch.
"""
if exclude is None:
master = conf.get('git.master_branch', 'master')
develop = conf.get('git.devel_branch', 'develop')
exclude = {master, develop}
branches = list(set(git.branches()) - exclude)
# Print the menu
for i, branch_name in enumerate(branches):
shell.cprint('<90>[{}] <33>{}'.format(i + 1, branch_name))
# Get a valid choice from the user
choice = 0
while choice < 1 or choice > len(branches):
prompt = "Pick a base branch from the above [1-{}]".format(
len(branches)
)
choice = click.prompt(prompt, value_proc=int)
if not (1 <= choice <= len(branches)):
fmt = "Invalid choice {}, you must pick a number between {} and {}"
log.err(fmt.format(choice, 1, len(branches)))
return branches[choice - 1] | [
"def",
"choose_branch",
"(",
"exclude",
"=",
"None",
")",
":",
"# type: (List[str]) -> str",
"if",
"exclude",
"is",
"None",
":",
"master",
"=",
"conf",
".",
"get",
"(",
"'git.master_branch'",
",",
"'master'",
")",
"develop",
"=",
"conf",
".",
"get",
"(",
"'git.devel_branch'",
",",
"'develop'",
")",
"exclude",
"=",
"{",
"master",
",",
"develop",
"}",
"branches",
"=",
"list",
"(",
"set",
"(",
"git",
".",
"branches",
"(",
")",
")",
"-",
"exclude",
")",
"# Print the menu",
"for",
"i",
",",
"branch_name",
"in",
"enumerate",
"(",
"branches",
")",
":",
"shell",
".",
"cprint",
"(",
"'<90>[{}] <33>{}'",
".",
"format",
"(",
"i",
"+",
"1",
",",
"branch_name",
")",
")",
"# Get a valid choice from the user",
"choice",
"=",
"0",
"while",
"choice",
"<",
"1",
"or",
"choice",
">",
"len",
"(",
"branches",
")",
":",
"prompt",
"=",
"\"Pick a base branch from the above [1-{}]\"",
".",
"format",
"(",
"len",
"(",
"branches",
")",
")",
"choice",
"=",
"click",
".",
"prompt",
"(",
"prompt",
",",
"value_proc",
"=",
"int",
")",
"if",
"not",
"(",
"1",
"<=",
"choice",
"<=",
"len",
"(",
"branches",
")",
")",
":",
"fmt",
"=",
"\"Invalid choice {}, you must pick a number between {} and {}\"",
"log",
".",
"err",
"(",
"fmt",
".",
"format",
"(",
"choice",
",",
"1",
",",
"len",
"(",
"branches",
")",
")",
")",
"return",
"branches",
"[",
"choice",
"-",
"1",
"]"
] | Show the user a menu to pick a branch from the existing ones.
Args:
exclude (list[str]):
List of branch names to exclude from the menu. By default it will
exclude master and develop branches. To show all branches pass an
empty array here.
Returns:
str: The name of the branch chosen by the user. If the user inputs an
invalid choice, he will be asked again (and again) until he picks a
a valid branch. | [
"Show",
"the",
"user",
"a",
"menu",
"to",
"pick",
"a",
"branch",
"from",
"the",
"existing",
"ones",
"."
] | train | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/gitflow/logic/common.py#L197-L234 |
Varkal/chuda | chuda/decorators.py | autorun | def autorun():
'''
Call the run method of the decorated class if the current file is the main file
'''
def wrapper(cls):
import inspect
if inspect.getmodule(cls).__name__ == "__main__":
cls().run()
return cls
return wrapper | python | def autorun():
'''
Call the run method of the decorated class if the current file is the main file
'''
def wrapper(cls):
import inspect
if inspect.getmodule(cls).__name__ == "__main__":
cls().run()
return cls
return wrapper | [
"def",
"autorun",
"(",
")",
":",
"def",
"wrapper",
"(",
"cls",
")",
":",
"import",
"inspect",
"if",
"inspect",
".",
"getmodule",
"(",
"cls",
")",
".",
"__name__",
"==",
"\"__main__\"",
":",
"cls",
"(",
")",
".",
"run",
"(",
")",
"return",
"cls",
"return",
"wrapper"
] | Call the run method of the decorated class if the current file is the main file | [
"Call",
"the",
"run",
"method",
"of",
"the",
"decorated",
"class",
"if",
"the",
"current",
"file",
"is",
"the",
"main",
"file"
] | train | https://github.com/Varkal/chuda/blob/0d93b716dede35231c21be97bcc19a656655983f/chuda/decorators.py#L1-L12 |
jaredLunde/vital-tools | vital/tools/lists.py | unique_list | def unique_list(seq):
""" Removes duplicate elements from given @seq
@seq: a #list or sequence-like object
-> #list
"""
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))] | python | def unique_list(seq):
""" Removes duplicate elements from given @seq
@seq: a #list or sequence-like object
-> #list
"""
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))] | [
"def",
"unique_list",
"(",
"seq",
")",
":",
"seen",
"=",
"set",
"(",
")",
"seen_add",
"=",
"seen",
".",
"add",
"return",
"[",
"x",
"for",
"x",
"in",
"seq",
"if",
"not",
"(",
"x",
"in",
"seen",
"or",
"seen_add",
"(",
"x",
")",
")",
"]"
] | Removes duplicate elements from given @seq
@seq: a #list or sequence-like object
-> #list | [
"Removes",
"duplicate",
"elements",
"from",
"given",
"@seq"
] | train | https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/tools/lists.py#L17-L26 |
jaredLunde/vital-tools | vital/tools/lists.py | flatten | def flatten(*seqs):
""" Flattens a sequence e.g. |[(1, 2), (3, (4, 5))] -> [1, 2, 3, 4, 5]|
@seq: #tuple, #list or :class:UserList
-> yields an iterator
..
l = [(1, 2), (3, 4)]
for x in flatten(l):
print(x)
..
"""
for seq in seqs:
for item in seq:
if isinstance(item, (tuple, list, UserList)):
for subitem in flatten(item):
yield subitem
else:
yield item | python | def flatten(*seqs):
""" Flattens a sequence e.g. |[(1, 2), (3, (4, 5))] -> [1, 2, 3, 4, 5]|
@seq: #tuple, #list or :class:UserList
-> yields an iterator
..
l = [(1, 2), (3, 4)]
for x in flatten(l):
print(x)
..
"""
for seq in seqs:
for item in seq:
if isinstance(item, (tuple, list, UserList)):
for subitem in flatten(item):
yield subitem
else:
yield item | [
"def",
"flatten",
"(",
"*",
"seqs",
")",
":",
"for",
"seq",
"in",
"seqs",
":",
"for",
"item",
"in",
"seq",
":",
"if",
"isinstance",
"(",
"item",
",",
"(",
"tuple",
",",
"list",
",",
"UserList",
")",
")",
":",
"for",
"subitem",
"in",
"flatten",
"(",
"item",
")",
":",
"yield",
"subitem",
"else",
":",
"yield",
"item"
] | Flattens a sequence e.g. |[(1, 2), (3, (4, 5))] -> [1, 2, 3, 4, 5]|
@seq: #tuple, #list or :class:UserList
-> yields an iterator
..
l = [(1, 2), (3, 4)]
for x in flatten(l):
print(x)
.. | [
"Flattens",
"a",
"sequence",
"e",
".",
"g",
".",
"|",
"[",
"(",
"1",
"2",
")",
"(",
"3",
"(",
"4",
"5",
"))",
"]",
"-",
">",
"[",
"1",
"2",
"3",
"4",
"5",
"]",
"|"
] | train | https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/tools/lists.py#L59-L78 |
jaredLunde/vital-tools | vital/tools/lists.py | randrange | def randrange(seq):
""" Yields random values from @seq until @seq is empty """
seq = seq.copy()
choose = rng().choice
remove = seq.remove
for x in range(len(seq)):
y = choose(seq)
remove(y)
yield y | python | def randrange(seq):
""" Yields random values from @seq until @seq is empty """
seq = seq.copy()
choose = rng().choice
remove = seq.remove
for x in range(len(seq)):
y = choose(seq)
remove(y)
yield y | [
"def",
"randrange",
"(",
"seq",
")",
":",
"seq",
"=",
"seq",
".",
"copy",
"(",
")",
"choose",
"=",
"rng",
"(",
")",
".",
"choice",
"remove",
"=",
"seq",
".",
"remove",
"for",
"x",
"in",
"range",
"(",
"len",
"(",
"seq",
")",
")",
":",
"y",
"=",
"choose",
"(",
"seq",
")",
"remove",
"(",
"y",
")",
"yield",
"y"
] | Yields random values from @seq until @seq is empty | [
"Yields",
"random",
"values",
"from"
] | train | https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/tools/lists.py#L91-L99 |
Vital-Fernandez/dazer | bin/lib/ssp_functions/ssp_Hector_Fit3D_tools.py | linear_least_squares | def linear_least_squares(a, b, residuals=False):
"""
Return the least-squares solution to a linear matrix equation.
Solves the equation `a x = b` by computing a vector `x` that
minimizes the Euclidean 2-norm `|| b - a x ||^2`. The equation may
be under-, well-, or over- determined (i.e., the number of
linearly independent rows of `a` can be less than, equal to, or
greater than its number of linearly independent columns). If `a`
is square and of full rank, then `x` (but for round-off error) is
the "exact" solution of the equation.
Parameters
----------
a : (M, N) array_like
"Coefficient" matrix.
b : (M,) array_like
Ordinate or "dependent variable" values.
residuals : bool
Compute the residuals associated with the least-squares solution
Returns
-------
x : (M,) ndarray
Least-squares solution. The shape of `x` depends on the shape of
`b`.
residuals : int (Optional)
Sums of residuals; squared Euclidean 2-norm for each column in
``b - a*x``.
"""
# Copyright (c) 2013 Alexandre Drouin. All rights reserved.
# From https://gist.github.com/aldro61/5889795
from warnings import warn
# from scipy.linalg.fblas import dgemm
from scipy.linalg.blas import dgemm
# if type(a) != np.ndarray or not a.flags['C_CONTIGUOUS']:
# warn('Matrix a is not a C-contiguous numpy array. The solver will create a copy, which will result' + \
# ' in increased memory usage.')
a = np.asarray(a, order='c')
i = dgemm(alpha=1.0, a=a.T, b=a.T, trans_b=True)
x = np.linalg.solve(i, dgemm(alpha=1.0, a=a.T, b=b)).flatten()
if residuals:
return x, np.linalg.norm(np.dot(a, x) - b)
else:
return x | python | def linear_least_squares(a, b, residuals=False):
"""
Return the least-squares solution to a linear matrix equation.
Solves the equation `a x = b` by computing a vector `x` that
minimizes the Euclidean 2-norm `|| b - a x ||^2`. The equation may
be under-, well-, or over- determined (i.e., the number of
linearly independent rows of `a` can be less than, equal to, or
greater than its number of linearly independent columns). If `a`
is square and of full rank, then `x` (but for round-off error) is
the "exact" solution of the equation.
Parameters
----------
a : (M, N) array_like
"Coefficient" matrix.
b : (M,) array_like
Ordinate or "dependent variable" values.
residuals : bool
Compute the residuals associated with the least-squares solution
Returns
-------
x : (M,) ndarray
Least-squares solution. The shape of `x` depends on the shape of
`b`.
residuals : int (Optional)
Sums of residuals; squared Euclidean 2-norm for each column in
``b - a*x``.
"""
# Copyright (c) 2013 Alexandre Drouin. All rights reserved.
# From https://gist.github.com/aldro61/5889795
from warnings import warn
# from scipy.linalg.fblas import dgemm
from scipy.linalg.blas import dgemm
# if type(a) != np.ndarray or not a.flags['C_CONTIGUOUS']:
# warn('Matrix a is not a C-contiguous numpy array. The solver will create a copy, which will result' + \
# ' in increased memory usage.')
a = np.asarray(a, order='c')
i = dgemm(alpha=1.0, a=a.T, b=a.T, trans_b=True)
x = np.linalg.solve(i, dgemm(alpha=1.0, a=a.T, b=b)).flatten()
if residuals:
return x, np.linalg.norm(np.dot(a, x) - b)
else:
return x | [
"def",
"linear_least_squares",
"(",
"a",
",",
"b",
",",
"residuals",
"=",
"False",
")",
":",
"# Copyright (c) 2013 Alexandre Drouin. All rights reserved.",
"# From https://gist.github.com/aldro61/5889795",
"from",
"warnings",
"import",
"warn",
"# from scipy.linalg.fblas import dgemm",
"from",
"scipy",
".",
"linalg",
".",
"blas",
"import",
"dgemm",
"# if type(a) != np.ndarray or not a.flags['C_CONTIGUOUS']:",
"# warn('Matrix a is not a C-contiguous numpy array. The solver will create a copy, which will result' + \\",
"# ' in increased memory usage.')",
"a",
"=",
"np",
".",
"asarray",
"(",
"a",
",",
"order",
"=",
"'c'",
")",
"i",
"=",
"dgemm",
"(",
"alpha",
"=",
"1.0",
",",
"a",
"=",
"a",
".",
"T",
",",
"b",
"=",
"a",
".",
"T",
",",
"trans_b",
"=",
"True",
")",
"x",
"=",
"np",
".",
"linalg",
".",
"solve",
"(",
"i",
",",
"dgemm",
"(",
"alpha",
"=",
"1.0",
",",
"a",
"=",
"a",
".",
"T",
",",
"b",
"=",
"b",
")",
")",
".",
"flatten",
"(",
")",
"if",
"residuals",
":",
"return",
"x",
",",
"np",
".",
"linalg",
".",
"norm",
"(",
"np",
".",
"dot",
"(",
"a",
",",
"x",
")",
"-",
"b",
")",
"else",
":",
"return",
"x"
] | Return the least-squares solution to a linear matrix equation.
Solves the equation `a x = b` by computing a vector `x` that
minimizes the Euclidean 2-norm `|| b - a x ||^2`. The equation may
be under-, well-, or over- determined (i.e., the number of
linearly independent rows of `a` can be less than, equal to, or
greater than its number of linearly independent columns). If `a`
is square and of full rank, then `x` (but for round-off error) is
the "exact" solution of the equation.
Parameters
----------
a : (M, N) array_like
"Coefficient" matrix.
b : (M,) array_like
Ordinate or "dependent variable" values.
residuals : bool
Compute the residuals associated with the least-squares solution
Returns
-------
x : (M,) ndarray
Least-squares solution. The shape of `x` depends on the shape of
`b`.
residuals : int (Optional)
Sums of residuals; squared Euclidean 2-norm for each column in
``b - a*x``. | [
"Return",
"the",
"least",
"-",
"squares",
"solution",
"to",
"a",
"linear",
"matrix",
"equation",
".",
"Solves",
"the",
"equation",
"a",
"x",
"=",
"b",
"by",
"computing",
"a",
"vector",
"x",
"that",
"minimizes",
"the",
"Euclidean",
"2",
"-",
"norm",
"||",
"b",
"-",
"a",
"x",
"||^2",
".",
"The",
"equation",
"may",
"be",
"under",
"-",
"well",
"-",
"or",
"over",
"-",
"determined",
"(",
"i",
".",
"e",
".",
"the",
"number",
"of",
"linearly",
"independent",
"rows",
"of",
"a",
"can",
"be",
"less",
"than",
"equal",
"to",
"or",
"greater",
"than",
"its",
"number",
"of",
"linearly",
"independent",
"columns",
")",
".",
"If",
"a",
"is",
"square",
"and",
"of",
"full",
"rank",
"then",
"x",
"(",
"but",
"for",
"round",
"-",
"off",
"error",
")",
"is",
"the",
"exact",
"solution",
"of",
"the",
"equation",
".",
"Parameters",
"----------",
"a",
":",
"(",
"M",
"N",
")",
"array_like",
"Coefficient",
"matrix",
".",
"b",
":",
"(",
"M",
")",
"array_like",
"Ordinate",
"or",
"dependent",
"variable",
"values",
".",
"residuals",
":",
"bool",
"Compute",
"the",
"residuals",
"associated",
"with",
"the",
"least",
"-",
"squares",
"solution",
"Returns",
"-------",
"x",
":",
"(",
"M",
")",
"ndarray",
"Least",
"-",
"squares",
"solution",
".",
"The",
"shape",
"of",
"x",
"depends",
"on",
"the",
"shape",
"of",
"b",
".",
"residuals",
":",
"int",
"(",
"Optional",
")",
"Sums",
"of",
"residuals",
";",
"squared",
"Euclidean",
"2",
"-",
"norm",
"for",
"each",
"column",
"in",
"b",
"-",
"a",
"*",
"x",
"."
] | train | https://github.com/Vital-Fernandez/dazer/blob/3c9ae8ae6d40ea33f22cc20dc11365d6d6e65244/bin/lib/ssp_functions/ssp_Hector_Fit3D_tools.py#L14-L55 |
cons3rt/pycons3rt | pycons3rt/aliasip.py | validate_ip_address | def validate_ip_address(ip_address):
"""Validate the ip_address
:param ip_address: (str) IP address
:return: (bool) True if the ip_address is valid
"""
# Validate the IP address
log = logging.getLogger(mod_logger + '.validate_ip_address')
if not isinstance(ip_address, basestring):
log.warn('ip_address argument is not a string')
return False
# Ensure there are 3 dots
num_dots = 0
for c in ip_address:
if c == '.':
num_dots += 1
if num_dots != 3:
log.info('Not a valid IP address: {i}'.format(i=ip_address))
return False
# Use the socket module to test
try:
socket.inet_aton(ip_address)
except socket.error as e:
log.info('Not a valid IP address: {i}\n{e}'.format(i=ip_address, e=e))
return False
else:
log.info('Validated IP address: %s', ip_address)
return True | python | def validate_ip_address(ip_address):
"""Validate the ip_address
:param ip_address: (str) IP address
:return: (bool) True if the ip_address is valid
"""
# Validate the IP address
log = logging.getLogger(mod_logger + '.validate_ip_address')
if not isinstance(ip_address, basestring):
log.warn('ip_address argument is not a string')
return False
# Ensure there are 3 dots
num_dots = 0
for c in ip_address:
if c == '.':
num_dots += 1
if num_dots != 3:
log.info('Not a valid IP address: {i}'.format(i=ip_address))
return False
# Use the socket module to test
try:
socket.inet_aton(ip_address)
except socket.error as e:
log.info('Not a valid IP address: {i}\n{e}'.format(i=ip_address, e=e))
return False
else:
log.info('Validated IP address: %s', ip_address)
return True | [
"def",
"validate_ip_address",
"(",
"ip_address",
")",
":",
"# Validate the IP address",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.validate_ip_address'",
")",
"if",
"not",
"isinstance",
"(",
"ip_address",
",",
"basestring",
")",
":",
"log",
".",
"warn",
"(",
"'ip_address argument is not a string'",
")",
"return",
"False",
"# Ensure there are 3 dots",
"num_dots",
"=",
"0",
"for",
"c",
"in",
"ip_address",
":",
"if",
"c",
"==",
"'.'",
":",
"num_dots",
"+=",
"1",
"if",
"num_dots",
"!=",
"3",
":",
"log",
".",
"info",
"(",
"'Not a valid IP address: {i}'",
".",
"format",
"(",
"i",
"=",
"ip_address",
")",
")",
"return",
"False",
"# Use the socket module to test",
"try",
":",
"socket",
".",
"inet_aton",
"(",
"ip_address",
")",
"except",
"socket",
".",
"error",
"as",
"e",
":",
"log",
".",
"info",
"(",
"'Not a valid IP address: {i}\\n{e}'",
".",
"format",
"(",
"i",
"=",
"ip_address",
",",
"e",
"=",
"e",
")",
")",
"return",
"False",
"else",
":",
"log",
".",
"info",
"(",
"'Validated IP address: %s'",
",",
"ip_address",
")",
"return",
"True"
] | Validate the ip_address
:param ip_address: (str) IP address
:return: (bool) True if the ip_address is valid | [
"Validate",
"the",
"ip_address"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/aliasip.py#L32-L61 |
cons3rt/pycons3rt | pycons3rt/aliasip.py | ip_addr | def ip_addr():
"""Uses the ip addr command to enumerate IP addresses by device
:return: (dict) Containing device: ip_address
"""
log = logging.getLogger(mod_logger + '.ip_addr')
log.debug('Running the ip addr command...')
ip_addr_output = {}
command = ['ip', 'addr']
try:
ip_addr_result = run_command(command, timeout_sec=20)
except CommandError:
_, ex, trace = sys.exc_info()
msg = 'There was a problem running command: {c}'.format(c=' '.join(command))
raise CommandError, msg, trace
ip_addr_lines = ip_addr_result['output'].split('\n')
for line in ip_addr_lines:
line = line.strip()
if line.startswith('inet6'):
continue
elif line.startswith('inet'):
parts = line.split()
try:
ip_address = parts[1].strip().split('/')[0]
except KeyError:
continue
else:
if not validate_ip_address(ip_address):
continue
else:
for part in parts:
part = part.strip()
if part.strip().startswith('eth') or part.strip().startswith('eno') or \
part.strip().startswith('ens'):
device = part
ip_addr_output[device] = ip_address
return ip_addr_output | python | def ip_addr():
"""Uses the ip addr command to enumerate IP addresses by device
:return: (dict) Containing device: ip_address
"""
log = logging.getLogger(mod_logger + '.ip_addr')
log.debug('Running the ip addr command...')
ip_addr_output = {}
command = ['ip', 'addr']
try:
ip_addr_result = run_command(command, timeout_sec=20)
except CommandError:
_, ex, trace = sys.exc_info()
msg = 'There was a problem running command: {c}'.format(c=' '.join(command))
raise CommandError, msg, trace
ip_addr_lines = ip_addr_result['output'].split('\n')
for line in ip_addr_lines:
line = line.strip()
if line.startswith('inet6'):
continue
elif line.startswith('inet'):
parts = line.split()
try:
ip_address = parts[1].strip().split('/')[0]
except KeyError:
continue
else:
if not validate_ip_address(ip_address):
continue
else:
for part in parts:
part = part.strip()
if part.strip().startswith('eth') or part.strip().startswith('eno') or \
part.strip().startswith('ens'):
device = part
ip_addr_output[device] = ip_address
return ip_addr_output | [
"def",
"ip_addr",
"(",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.ip_addr'",
")",
"log",
".",
"debug",
"(",
"'Running the ip addr command...'",
")",
"ip_addr_output",
"=",
"{",
"}",
"command",
"=",
"[",
"'ip'",
",",
"'addr'",
"]",
"try",
":",
"ip_addr_result",
"=",
"run_command",
"(",
"command",
",",
"timeout_sec",
"=",
"20",
")",
"except",
"CommandError",
":",
"_",
",",
"ex",
",",
"trace",
"=",
"sys",
".",
"exc_info",
"(",
")",
"msg",
"=",
"'There was a problem running command: {c}'",
".",
"format",
"(",
"c",
"=",
"' '",
".",
"join",
"(",
"command",
")",
")",
"raise",
"CommandError",
",",
"msg",
",",
"trace",
"ip_addr_lines",
"=",
"ip_addr_result",
"[",
"'output'",
"]",
".",
"split",
"(",
"'\\n'",
")",
"for",
"line",
"in",
"ip_addr_lines",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"line",
".",
"startswith",
"(",
"'inet6'",
")",
":",
"continue",
"elif",
"line",
".",
"startswith",
"(",
"'inet'",
")",
":",
"parts",
"=",
"line",
".",
"split",
"(",
")",
"try",
":",
"ip_address",
"=",
"parts",
"[",
"1",
"]",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'/'",
")",
"[",
"0",
"]",
"except",
"KeyError",
":",
"continue",
"else",
":",
"if",
"not",
"validate_ip_address",
"(",
"ip_address",
")",
":",
"continue",
"else",
":",
"for",
"part",
"in",
"parts",
":",
"part",
"=",
"part",
".",
"strip",
"(",
")",
"if",
"part",
".",
"strip",
"(",
")",
".",
"startswith",
"(",
"'eth'",
")",
"or",
"part",
".",
"strip",
"(",
")",
".",
"startswith",
"(",
"'eno'",
")",
"or",
"part",
".",
"strip",
"(",
")",
".",
"startswith",
"(",
"'ens'",
")",
":",
"device",
"=",
"part",
"ip_addr_output",
"[",
"device",
"]",
"=",
"ip_address",
"return",
"ip_addr_output"
] | Uses the ip addr command to enumerate IP addresses by device
:return: (dict) Containing device: ip_address | [
"Uses",
"the",
"ip",
"addr",
"command",
"to",
"enumerate",
"IP",
"addresses",
"by",
"device"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/aliasip.py#L64-L103 |
cons3rt/pycons3rt | pycons3rt/aliasip.py | alias_ip_address | def alias_ip_address(ip_address, interface, aws=False):
"""Adds an IP alias to a specific interface
Adds an ip address as an alias to the specified interface on
Linux systems.
:param ip_address: (str) IP address to set as an alias
:param interface: (str) The interface number or full device name, if
an int is provided assumes the device name is eth<i>
:param aws (bool) True to perform additional AWS config
:return: None
"""
log = logging.getLogger(mod_logger + '.alias_ip_address')
# Validate args
if not isinstance(ip_address, basestring):
msg = 'ip_address argument is not a string'
log.error(msg)
raise TypeError(msg)
# Validate the IP address
if not validate_ip_address(ip_address):
msg = 'The provided IP address arg is invalid: {i}'.format(i=ip_address)
log.error(msg)
raise ValueError(msg)
# Determine if the interface provided is a full device name
try:
int(interface)
except ValueError:
if isinstance(interface, basestring):
device_name = str(interface)
log.info('Full device name provided, will attempt to alias: {d}'.format(d=device_name))
else:
raise TypeError('Provided interface arg must be an int or str')
else:
device_name = 'eth{i}'.format(i=interface)
log.info('Integer provided as interface, using device name: {d}'.format(d=device_name))
# Add alias
command = ['ifconfig', '{d}:0'.format(d=device_name), ip_address, 'up']
log.info('Running command to bring up the alias: {c}'.format(c=' '.join(command)))
try:
result = run_command(command)
except CommandError:
_, ex, trace = sys.exc_info()
log.warn('CommandError: There was a problem running command: {c}\n{e}'.format(
c=' '.join(command), e=str(ex)))
else:
log.info('Command produced output:\n{o}'.format(o=result['output']))
if int(result['code']) != 0:
log.warn('ifconfig up command produced exit code: {c} and output:\n{o}'.format(
c=result['code'], o=result['output']))
else:
log.info('ifconfig up exited successfully')
# Create interface file from the existing file
base_ifcfg = os.path.abspath(os.path.join(os.sep, 'etc', 'sysconfig', 'network-scripts', 'ifcfg-{d}'.format(
d=device_name)))
alias_ifcfg = base_ifcfg + ':0'
log.info('Creating interface config file: {f}'.format(f=alias_ifcfg))
# Ensure the base config file exists
if not os.path.isfile(base_ifcfg):
raise OSError('Required interface config file not found: {f}'.format(f=base_ifcfg))
else:
log.info('Found base interface config file: {f}'.format(f=base_ifcfg))
# Delete the existing interface file if it exists
if os.path.isfile(alias_ifcfg):
log.info('Alias interface configuration file already exists, removing: {f}'.format(f=alias_ifcfg))
try:
os.remove(alias_ifcfg)
except OSError:
_, ex, trace = sys.exc_info()
msg = 'OSError: There was a problem removing existing alias config file: {f}\n{e}'.format(
f=alias_ifcfg, e=str(ex))
raise OSError, msg, trace
else:
log.info('No existing alias interface configuration exists yet: {f}'.format(f=alias_ifcfg))
# Create the interface file
log.info('Gathering entries from file: {f}...'.format(f=base_ifcfg))
ifcfg_entries = {}
try:
with open(base_ifcfg, 'r') as f:
for line in f:
if '=' in line:
parts = line.split('=')
if len(parts) == 2:
parts[0] = parts[0].strip()
parts[1] = parts[1].translate(None, '"').strip()
ifcfg_entries[parts[0]] = parts[1]
except(IOError, OSError):
_, ex, trace = sys.exc_info()
msg = 'Unable to read file: {f}\n{e}'.format(f=base_ifcfg, e=str(ex))
raise OSError, msg, trace
# Defined the ifcfg file entries for the alias
ifcfg_entries['IPADDR'] = ip_address
ifcfg_entries['NETMASK'] = '255.255.255.0'
ifcfg_entries['DEVICE'] = '{d}:0'.format(d=device_name)
ifcfg_entries['NAME'] = '{d}:0'.format(d=device_name)
log.info('Creating file: {f}'.format(f=alias_ifcfg))
try:
with open(alias_ifcfg, 'a') as f:
for var, val in ifcfg_entries.iteritems():
out_str = str(var) + '="' + str(val) + '"\n'
log.info('Adding entry to %s: %s', alias_ifcfg, out_str)
f.write(out_str)
except(IOError, OSError):
_, ex, trace = sys.exc_info()
msg = 'Unable to write to file: {f}\n{e}'.format(f=alias_ifcfg, e=str(ex))
raise OSError, msg, trace
# Performing additional configuration for AWS
if aws:
log.info('Checking if this host is actually on AWS...')
if is_aws():
log.info('Performing additional configuration for AWS...')
try:
ec2 = EC2Util()
ec2.add_secondary_ip(ip_address, interface)
except EC2UtilError:
_, ex, trace = sys.exc_info()
msg = 'Unable to instruct AWS to add a secondary IP address <{ip}> on interface <{d}>\n{e}'.format(
ip=ip_address, d=device_name, e=str(ex))
raise OSError, msg, trace
else:
log.info('AWS added the secondary IP address <{ip}> on interface <{d}>'.format(
ip=ip_address, d=device_name))
else:
log.warn('This system is not on AWS, not performing additional configuration')
log.info('Restarting networking to ensure the changes take effect...')
try:
service_network_restart()
except CommandError:
_, ex, trace = sys.exc_info()
msg = 'CommandError: There was a problem restarting network services\n{e}'.format(e=str(ex))
raise NetworkRestartError, msg, trace
# Verify the alias was created
log.info('Verifying the alias was successfully created...')
command = ['/sbin/ifconfig']
try:
result = run_command(command)
except CommandError:
_, ex, trace = sys.exc_info()
log.warn('CommandError: Unable to run ifconfig to verify the IP alias was created\n{e}'.format(e=str(ex)))
return
# Check for the alias
if '{d}:0'.format(d=device_name) not in result['output']:
log.warn('The alias was not created yet, system reboot may be required: {d}:0'.format(d=device_name))
else:
log.info('Alias created successfully!') | python | def alias_ip_address(ip_address, interface, aws=False):
"""Adds an IP alias to a specific interface
Adds an ip address as an alias to the specified interface on
Linux systems.
:param ip_address: (str) IP address to set as an alias
:param interface: (str) The interface number or full device name, if
an int is provided assumes the device name is eth<i>
:param aws (bool) True to perform additional AWS config
:return: None
"""
log = logging.getLogger(mod_logger + '.alias_ip_address')
# Validate args
if not isinstance(ip_address, basestring):
msg = 'ip_address argument is not a string'
log.error(msg)
raise TypeError(msg)
# Validate the IP address
if not validate_ip_address(ip_address):
msg = 'The provided IP address arg is invalid: {i}'.format(i=ip_address)
log.error(msg)
raise ValueError(msg)
# Determine if the interface provided is a full device name
try:
int(interface)
except ValueError:
if isinstance(interface, basestring):
device_name = str(interface)
log.info('Full device name provided, will attempt to alias: {d}'.format(d=device_name))
else:
raise TypeError('Provided interface arg must be an int or str')
else:
device_name = 'eth{i}'.format(i=interface)
log.info('Integer provided as interface, using device name: {d}'.format(d=device_name))
# Add alias
command = ['ifconfig', '{d}:0'.format(d=device_name), ip_address, 'up']
log.info('Running command to bring up the alias: {c}'.format(c=' '.join(command)))
try:
result = run_command(command)
except CommandError:
_, ex, trace = sys.exc_info()
log.warn('CommandError: There was a problem running command: {c}\n{e}'.format(
c=' '.join(command), e=str(ex)))
else:
log.info('Command produced output:\n{o}'.format(o=result['output']))
if int(result['code']) != 0:
log.warn('ifconfig up command produced exit code: {c} and output:\n{o}'.format(
c=result['code'], o=result['output']))
else:
log.info('ifconfig up exited successfully')
# Create interface file from the existing file
base_ifcfg = os.path.abspath(os.path.join(os.sep, 'etc', 'sysconfig', 'network-scripts', 'ifcfg-{d}'.format(
d=device_name)))
alias_ifcfg = base_ifcfg + ':0'
log.info('Creating interface config file: {f}'.format(f=alias_ifcfg))
# Ensure the base config file exists
if not os.path.isfile(base_ifcfg):
raise OSError('Required interface config file not found: {f}'.format(f=base_ifcfg))
else:
log.info('Found base interface config file: {f}'.format(f=base_ifcfg))
# Delete the existing interface file if it exists
if os.path.isfile(alias_ifcfg):
log.info('Alias interface configuration file already exists, removing: {f}'.format(f=alias_ifcfg))
try:
os.remove(alias_ifcfg)
except OSError:
_, ex, trace = sys.exc_info()
msg = 'OSError: There was a problem removing existing alias config file: {f}\n{e}'.format(
f=alias_ifcfg, e=str(ex))
raise OSError, msg, trace
else:
log.info('No existing alias interface configuration exists yet: {f}'.format(f=alias_ifcfg))
# Create the interface file
log.info('Gathering entries from file: {f}...'.format(f=base_ifcfg))
ifcfg_entries = {}
try:
with open(base_ifcfg, 'r') as f:
for line in f:
if '=' in line:
parts = line.split('=')
if len(parts) == 2:
parts[0] = parts[0].strip()
parts[1] = parts[1].translate(None, '"').strip()
ifcfg_entries[parts[0]] = parts[1]
except(IOError, OSError):
_, ex, trace = sys.exc_info()
msg = 'Unable to read file: {f}\n{e}'.format(f=base_ifcfg, e=str(ex))
raise OSError, msg, trace
# Defined the ifcfg file entries for the alias
ifcfg_entries['IPADDR'] = ip_address
ifcfg_entries['NETMASK'] = '255.255.255.0'
ifcfg_entries['DEVICE'] = '{d}:0'.format(d=device_name)
ifcfg_entries['NAME'] = '{d}:0'.format(d=device_name)
log.info('Creating file: {f}'.format(f=alias_ifcfg))
try:
with open(alias_ifcfg, 'a') as f:
for var, val in ifcfg_entries.iteritems():
out_str = str(var) + '="' + str(val) + '"\n'
log.info('Adding entry to %s: %s', alias_ifcfg, out_str)
f.write(out_str)
except(IOError, OSError):
_, ex, trace = sys.exc_info()
msg = 'Unable to write to file: {f}\n{e}'.format(f=alias_ifcfg, e=str(ex))
raise OSError, msg, trace
# Performing additional configuration for AWS
if aws:
log.info('Checking if this host is actually on AWS...')
if is_aws():
log.info('Performing additional configuration for AWS...')
try:
ec2 = EC2Util()
ec2.add_secondary_ip(ip_address, interface)
except EC2UtilError:
_, ex, trace = sys.exc_info()
msg = 'Unable to instruct AWS to add a secondary IP address <{ip}> on interface <{d}>\n{e}'.format(
ip=ip_address, d=device_name, e=str(ex))
raise OSError, msg, trace
else:
log.info('AWS added the secondary IP address <{ip}> on interface <{d}>'.format(
ip=ip_address, d=device_name))
else:
log.warn('This system is not on AWS, not performing additional configuration')
log.info('Restarting networking to ensure the changes take effect...')
try:
service_network_restart()
except CommandError:
_, ex, trace = sys.exc_info()
msg = 'CommandError: There was a problem restarting network services\n{e}'.format(e=str(ex))
raise NetworkRestartError, msg, trace
# Verify the alias was created
log.info('Verifying the alias was successfully created...')
command = ['/sbin/ifconfig']
try:
result = run_command(command)
except CommandError:
_, ex, trace = sys.exc_info()
log.warn('CommandError: Unable to run ifconfig to verify the IP alias was created\n{e}'.format(e=str(ex)))
return
# Check for the alias
if '{d}:0'.format(d=device_name) not in result['output']:
log.warn('The alias was not created yet, system reboot may be required: {d}:0'.format(d=device_name))
else:
log.info('Alias created successfully!') | [
"def",
"alias_ip_address",
"(",
"ip_address",
",",
"interface",
",",
"aws",
"=",
"False",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.alias_ip_address'",
")",
"# Validate args",
"if",
"not",
"isinstance",
"(",
"ip_address",
",",
"basestring",
")",
":",
"msg",
"=",
"'ip_address argument is not a string'",
"log",
".",
"error",
"(",
"msg",
")",
"raise",
"TypeError",
"(",
"msg",
")",
"# Validate the IP address",
"if",
"not",
"validate_ip_address",
"(",
"ip_address",
")",
":",
"msg",
"=",
"'The provided IP address arg is invalid: {i}'",
".",
"format",
"(",
"i",
"=",
"ip_address",
")",
"log",
".",
"error",
"(",
"msg",
")",
"raise",
"ValueError",
"(",
"msg",
")",
"# Determine if the interface provided is a full device name",
"try",
":",
"int",
"(",
"interface",
")",
"except",
"ValueError",
":",
"if",
"isinstance",
"(",
"interface",
",",
"basestring",
")",
":",
"device_name",
"=",
"str",
"(",
"interface",
")",
"log",
".",
"info",
"(",
"'Full device name provided, will attempt to alias: {d}'",
".",
"format",
"(",
"d",
"=",
"device_name",
")",
")",
"else",
":",
"raise",
"TypeError",
"(",
"'Provided interface arg must be an int or str'",
")",
"else",
":",
"device_name",
"=",
"'eth{i}'",
".",
"format",
"(",
"i",
"=",
"interface",
")",
"log",
".",
"info",
"(",
"'Integer provided as interface, using device name: {d}'",
".",
"format",
"(",
"d",
"=",
"device_name",
")",
")",
"# Add alias",
"command",
"=",
"[",
"'ifconfig'",
",",
"'{d}:0'",
".",
"format",
"(",
"d",
"=",
"device_name",
")",
",",
"ip_address",
",",
"'up'",
"]",
"log",
".",
"info",
"(",
"'Running command to bring up the alias: {c}'",
".",
"format",
"(",
"c",
"=",
"' '",
".",
"join",
"(",
"command",
")",
")",
")",
"try",
":",
"result",
"=",
"run_command",
"(",
"command",
")",
"except",
"CommandError",
":",
"_",
",",
"ex",
",",
"trace",
"=",
"sys",
".",
"exc_info",
"(",
")",
"log",
".",
"warn",
"(",
"'CommandError: There was a problem running command: {c}\\n{e}'",
".",
"format",
"(",
"c",
"=",
"' '",
".",
"join",
"(",
"command",
")",
",",
"e",
"=",
"str",
"(",
"ex",
")",
")",
")",
"else",
":",
"log",
".",
"info",
"(",
"'Command produced output:\\n{o}'",
".",
"format",
"(",
"o",
"=",
"result",
"[",
"'output'",
"]",
")",
")",
"if",
"int",
"(",
"result",
"[",
"'code'",
"]",
")",
"!=",
"0",
":",
"log",
".",
"warn",
"(",
"'ifconfig up command produced exit code: {c} and output:\\n{o}'",
".",
"format",
"(",
"c",
"=",
"result",
"[",
"'code'",
"]",
",",
"o",
"=",
"result",
"[",
"'output'",
"]",
")",
")",
"else",
":",
"log",
".",
"info",
"(",
"'ifconfig up exited successfully'",
")",
"# Create interface file from the existing file",
"base_ifcfg",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"sep",
",",
"'etc'",
",",
"'sysconfig'",
",",
"'network-scripts'",
",",
"'ifcfg-{d}'",
".",
"format",
"(",
"d",
"=",
"device_name",
")",
")",
")",
"alias_ifcfg",
"=",
"base_ifcfg",
"+",
"':0'",
"log",
".",
"info",
"(",
"'Creating interface config file: {f}'",
".",
"format",
"(",
"f",
"=",
"alias_ifcfg",
")",
")",
"# Ensure the base config file exists",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"base_ifcfg",
")",
":",
"raise",
"OSError",
"(",
"'Required interface config file not found: {f}'",
".",
"format",
"(",
"f",
"=",
"base_ifcfg",
")",
")",
"else",
":",
"log",
".",
"info",
"(",
"'Found base interface config file: {f}'",
".",
"format",
"(",
"f",
"=",
"base_ifcfg",
")",
")",
"# Delete the existing interface file if it exists",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"alias_ifcfg",
")",
":",
"log",
".",
"info",
"(",
"'Alias interface configuration file already exists, removing: {f}'",
".",
"format",
"(",
"f",
"=",
"alias_ifcfg",
")",
")",
"try",
":",
"os",
".",
"remove",
"(",
"alias_ifcfg",
")",
"except",
"OSError",
":",
"_",
",",
"ex",
",",
"trace",
"=",
"sys",
".",
"exc_info",
"(",
")",
"msg",
"=",
"'OSError: There was a problem removing existing alias config file: {f}\\n{e}'",
".",
"format",
"(",
"f",
"=",
"alias_ifcfg",
",",
"e",
"=",
"str",
"(",
"ex",
")",
")",
"raise",
"OSError",
",",
"msg",
",",
"trace",
"else",
":",
"log",
".",
"info",
"(",
"'No existing alias interface configuration exists yet: {f}'",
".",
"format",
"(",
"f",
"=",
"alias_ifcfg",
")",
")",
"# Create the interface file",
"log",
".",
"info",
"(",
"'Gathering entries from file: {f}...'",
".",
"format",
"(",
"f",
"=",
"base_ifcfg",
")",
")",
"ifcfg_entries",
"=",
"{",
"}",
"try",
":",
"with",
"open",
"(",
"base_ifcfg",
",",
"'r'",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"if",
"'='",
"in",
"line",
":",
"parts",
"=",
"line",
".",
"split",
"(",
"'='",
")",
"if",
"len",
"(",
"parts",
")",
"==",
"2",
":",
"parts",
"[",
"0",
"]",
"=",
"parts",
"[",
"0",
"]",
".",
"strip",
"(",
")",
"parts",
"[",
"1",
"]",
"=",
"parts",
"[",
"1",
"]",
".",
"translate",
"(",
"None",
",",
"'\"'",
")",
".",
"strip",
"(",
")",
"ifcfg_entries",
"[",
"parts",
"[",
"0",
"]",
"]",
"=",
"parts",
"[",
"1",
"]",
"except",
"(",
"IOError",
",",
"OSError",
")",
":",
"_",
",",
"ex",
",",
"trace",
"=",
"sys",
".",
"exc_info",
"(",
")",
"msg",
"=",
"'Unable to read file: {f}\\n{e}'",
".",
"format",
"(",
"f",
"=",
"base_ifcfg",
",",
"e",
"=",
"str",
"(",
"ex",
")",
")",
"raise",
"OSError",
",",
"msg",
",",
"trace",
"# Defined the ifcfg file entries for the alias",
"ifcfg_entries",
"[",
"'IPADDR'",
"]",
"=",
"ip_address",
"ifcfg_entries",
"[",
"'NETMASK'",
"]",
"=",
"'255.255.255.0'",
"ifcfg_entries",
"[",
"'DEVICE'",
"]",
"=",
"'{d}:0'",
".",
"format",
"(",
"d",
"=",
"device_name",
")",
"ifcfg_entries",
"[",
"'NAME'",
"]",
"=",
"'{d}:0'",
".",
"format",
"(",
"d",
"=",
"device_name",
")",
"log",
".",
"info",
"(",
"'Creating file: {f}'",
".",
"format",
"(",
"f",
"=",
"alias_ifcfg",
")",
")",
"try",
":",
"with",
"open",
"(",
"alias_ifcfg",
",",
"'a'",
")",
"as",
"f",
":",
"for",
"var",
",",
"val",
"in",
"ifcfg_entries",
".",
"iteritems",
"(",
")",
":",
"out_str",
"=",
"str",
"(",
"var",
")",
"+",
"'=\"'",
"+",
"str",
"(",
"val",
")",
"+",
"'\"\\n'",
"log",
".",
"info",
"(",
"'Adding entry to %s: %s'",
",",
"alias_ifcfg",
",",
"out_str",
")",
"f",
".",
"write",
"(",
"out_str",
")",
"except",
"(",
"IOError",
",",
"OSError",
")",
":",
"_",
",",
"ex",
",",
"trace",
"=",
"sys",
".",
"exc_info",
"(",
")",
"msg",
"=",
"'Unable to write to file: {f}\\n{e}'",
".",
"format",
"(",
"f",
"=",
"alias_ifcfg",
",",
"e",
"=",
"str",
"(",
"ex",
")",
")",
"raise",
"OSError",
",",
"msg",
",",
"trace",
"# Performing additional configuration for AWS",
"if",
"aws",
":",
"log",
".",
"info",
"(",
"'Checking if this host is actually on AWS...'",
")",
"if",
"is_aws",
"(",
")",
":",
"log",
".",
"info",
"(",
"'Performing additional configuration for AWS...'",
")",
"try",
":",
"ec2",
"=",
"EC2Util",
"(",
")",
"ec2",
".",
"add_secondary_ip",
"(",
"ip_address",
",",
"interface",
")",
"except",
"EC2UtilError",
":",
"_",
",",
"ex",
",",
"trace",
"=",
"sys",
".",
"exc_info",
"(",
")",
"msg",
"=",
"'Unable to instruct AWS to add a secondary IP address <{ip}> on interface <{d}>\\n{e}'",
".",
"format",
"(",
"ip",
"=",
"ip_address",
",",
"d",
"=",
"device_name",
",",
"e",
"=",
"str",
"(",
"ex",
")",
")",
"raise",
"OSError",
",",
"msg",
",",
"trace",
"else",
":",
"log",
".",
"info",
"(",
"'AWS added the secondary IP address <{ip}> on interface <{d}>'",
".",
"format",
"(",
"ip",
"=",
"ip_address",
",",
"d",
"=",
"device_name",
")",
")",
"else",
":",
"log",
".",
"warn",
"(",
"'This system is not on AWS, not performing additional configuration'",
")",
"log",
".",
"info",
"(",
"'Restarting networking to ensure the changes take effect...'",
")",
"try",
":",
"service_network_restart",
"(",
")",
"except",
"CommandError",
":",
"_",
",",
"ex",
",",
"trace",
"=",
"sys",
".",
"exc_info",
"(",
")",
"msg",
"=",
"'CommandError: There was a problem restarting network services\\n{e}'",
".",
"format",
"(",
"e",
"=",
"str",
"(",
"ex",
")",
")",
"raise",
"NetworkRestartError",
",",
"msg",
",",
"trace",
"# Verify the alias was created",
"log",
".",
"info",
"(",
"'Verifying the alias was successfully created...'",
")",
"command",
"=",
"[",
"'/sbin/ifconfig'",
"]",
"try",
":",
"result",
"=",
"run_command",
"(",
"command",
")",
"except",
"CommandError",
":",
"_",
",",
"ex",
",",
"trace",
"=",
"sys",
".",
"exc_info",
"(",
")",
"log",
".",
"warn",
"(",
"'CommandError: Unable to run ifconfig to verify the IP alias was created\\n{e}'",
".",
"format",
"(",
"e",
"=",
"str",
"(",
"ex",
")",
")",
")",
"return",
"# Check for the alias",
"if",
"'{d}:0'",
".",
"format",
"(",
"d",
"=",
"device_name",
")",
"not",
"in",
"result",
"[",
"'output'",
"]",
":",
"log",
".",
"warn",
"(",
"'The alias was not created yet, system reboot may be required: {d}:0'",
".",
"format",
"(",
"d",
"=",
"device_name",
")",
")",
"else",
":",
"log",
".",
"info",
"(",
"'Alias created successfully!'",
")"
] | Adds an IP alias to a specific interface
Adds an ip address as an alias to the specified interface on
Linux systems.
:param ip_address: (str) IP address to set as an alias
:param interface: (str) The interface number or full device name, if
an int is provided assumes the device name is eth<i>
:param aws (bool) True to perform additional AWS config
:return: None | [
"Adds",
"an",
"IP",
"alias",
"to",
"a",
"specific",
"interface"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/aliasip.py#L106-L263 |
cons3rt/pycons3rt | pycons3rt/aliasip.py | set_source_ip_for_interface | def set_source_ip_for_interface(source_ip_address, desired_source_ip_address, device_num=0):
"""Configures the source IP address for a Linux interface
:param source_ip_address: (str) Source IP address to change
:param desired_source_ip_address: (str) IP address to configure as the source in outgoing packets
:param device_num: (int) Integer interface device number to configure
:return: None
:raises: TypeError, ValueError, OSError
"""
log = logging.getLogger(mod_logger + '.set_source_ip_for_interface')
if not isinstance(source_ip_address, basestring):
msg = 'arg source_ip_address must be a string'
log.error(msg)
raise TypeError(msg)
if not isinstance(desired_source_ip_address, basestring):
msg = 'arg desired_source_ip_address must be a string'
log.error(msg)
raise TypeError(msg)
if not validate_ip_address(ip_address=source_ip_address):
msg = 'The arg source_ip_address was found to be an invalid IP address. Please pass a valid IP address'
log.error(msg)
raise ValueError(msg)
if not validate_ip_address(ip_address=desired_source_ip_address):
msg = 'The arg desired_source_ip_address was found to be an invalid IP address. Please pass a valid IP address'
log.error(msg)
raise ValueError(msg)
# Determine the device name based on the device_num
log.debug('Attempting to determine the device name based on the device_num arg...')
try:
int(device_num)
except ValueError:
if isinstance(device_num, basestring):
device_name = device_num
log.info('Provided device_num is not an int, assuming it is the full device name: {d}'.format(
d=device_name))
else:
raise TypeError('device_num arg must be a string or int')
else:
device_name = 'eth{n}'.format(n=str(device_num))
log.info('Provided device_num is an int, assuming device name is: {d}'.format(d=device_name))
# Build the command
# iptables -t nat -I POSTROUTING -o eth0 -s ${RA_ORIGINAL_IP} -j SNAT --to-source
command = ['iptables', '-t', 'nat', '-I', 'POSTROUTING', '-o', device_name, '-s',
source_ip_address, '-j', 'SNAT', '--to-source', desired_source_ip_address]
log.info('Running command: {c}'.format(c=command))
try:
result = run_command(command, timeout_sec=20)
except CommandError:
_, ex, trace = sys.exc_info()
msg = 'There was a problem running iptables command: {c}\n{e}'.format(c=' '.join(command), e=str(ex))
log.error(msg)
raise OSError, msg, trace
if int(result['code']) != 0:
msg = 'The iptables command produced an error with exit code: {c}, and output:\n{o}'.format(
c=result['code'], o=result['output'])
log.error(msg)
raise OSError(msg)
log.info('Successfully configured the source IP for {d} to be: {i}'.format(
d=device_name, i=desired_source_ip_address)) | python | def set_source_ip_for_interface(source_ip_address, desired_source_ip_address, device_num=0):
"""Configures the source IP address for a Linux interface
:param source_ip_address: (str) Source IP address to change
:param desired_source_ip_address: (str) IP address to configure as the source in outgoing packets
:param device_num: (int) Integer interface device number to configure
:return: None
:raises: TypeError, ValueError, OSError
"""
log = logging.getLogger(mod_logger + '.set_source_ip_for_interface')
if not isinstance(source_ip_address, basestring):
msg = 'arg source_ip_address must be a string'
log.error(msg)
raise TypeError(msg)
if not isinstance(desired_source_ip_address, basestring):
msg = 'arg desired_source_ip_address must be a string'
log.error(msg)
raise TypeError(msg)
if not validate_ip_address(ip_address=source_ip_address):
msg = 'The arg source_ip_address was found to be an invalid IP address. Please pass a valid IP address'
log.error(msg)
raise ValueError(msg)
if not validate_ip_address(ip_address=desired_source_ip_address):
msg = 'The arg desired_source_ip_address was found to be an invalid IP address. Please pass a valid IP address'
log.error(msg)
raise ValueError(msg)
# Determine the device name based on the device_num
log.debug('Attempting to determine the device name based on the device_num arg...')
try:
int(device_num)
except ValueError:
if isinstance(device_num, basestring):
device_name = device_num
log.info('Provided device_num is not an int, assuming it is the full device name: {d}'.format(
d=device_name))
else:
raise TypeError('device_num arg must be a string or int')
else:
device_name = 'eth{n}'.format(n=str(device_num))
log.info('Provided device_num is an int, assuming device name is: {d}'.format(d=device_name))
# Build the command
# iptables -t nat -I POSTROUTING -o eth0 -s ${RA_ORIGINAL_IP} -j SNAT --to-source
command = ['iptables', '-t', 'nat', '-I', 'POSTROUTING', '-o', device_name, '-s',
source_ip_address, '-j', 'SNAT', '--to-source', desired_source_ip_address]
log.info('Running command: {c}'.format(c=command))
try:
result = run_command(command, timeout_sec=20)
except CommandError:
_, ex, trace = sys.exc_info()
msg = 'There was a problem running iptables command: {c}\n{e}'.format(c=' '.join(command), e=str(ex))
log.error(msg)
raise OSError, msg, trace
if int(result['code']) != 0:
msg = 'The iptables command produced an error with exit code: {c}, and output:\n{o}'.format(
c=result['code'], o=result['output'])
log.error(msg)
raise OSError(msg)
log.info('Successfully configured the source IP for {d} to be: {i}'.format(
d=device_name, i=desired_source_ip_address)) | [
"def",
"set_source_ip_for_interface",
"(",
"source_ip_address",
",",
"desired_source_ip_address",
",",
"device_num",
"=",
"0",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.set_source_ip_for_interface'",
")",
"if",
"not",
"isinstance",
"(",
"source_ip_address",
",",
"basestring",
")",
":",
"msg",
"=",
"'arg source_ip_address must be a string'",
"log",
".",
"error",
"(",
"msg",
")",
"raise",
"TypeError",
"(",
"msg",
")",
"if",
"not",
"isinstance",
"(",
"desired_source_ip_address",
",",
"basestring",
")",
":",
"msg",
"=",
"'arg desired_source_ip_address must be a string'",
"log",
".",
"error",
"(",
"msg",
")",
"raise",
"TypeError",
"(",
"msg",
")",
"if",
"not",
"validate_ip_address",
"(",
"ip_address",
"=",
"source_ip_address",
")",
":",
"msg",
"=",
"'The arg source_ip_address was found to be an invalid IP address. Please pass a valid IP address'",
"log",
".",
"error",
"(",
"msg",
")",
"raise",
"ValueError",
"(",
"msg",
")",
"if",
"not",
"validate_ip_address",
"(",
"ip_address",
"=",
"desired_source_ip_address",
")",
":",
"msg",
"=",
"'The arg desired_source_ip_address was found to be an invalid IP address. Please pass a valid IP address'",
"log",
".",
"error",
"(",
"msg",
")",
"raise",
"ValueError",
"(",
"msg",
")",
"# Determine the device name based on the device_num",
"log",
".",
"debug",
"(",
"'Attempting to determine the device name based on the device_num arg...'",
")",
"try",
":",
"int",
"(",
"device_num",
")",
"except",
"ValueError",
":",
"if",
"isinstance",
"(",
"device_num",
",",
"basestring",
")",
":",
"device_name",
"=",
"device_num",
"log",
".",
"info",
"(",
"'Provided device_num is not an int, assuming it is the full device name: {d}'",
".",
"format",
"(",
"d",
"=",
"device_name",
")",
")",
"else",
":",
"raise",
"TypeError",
"(",
"'device_num arg must be a string or int'",
")",
"else",
":",
"device_name",
"=",
"'eth{n}'",
".",
"format",
"(",
"n",
"=",
"str",
"(",
"device_num",
")",
")",
"log",
".",
"info",
"(",
"'Provided device_num is an int, assuming device name is: {d}'",
".",
"format",
"(",
"d",
"=",
"device_name",
")",
")",
"# Build the command",
"# iptables -t nat -I POSTROUTING -o eth0 -s ${RA_ORIGINAL_IP} -j SNAT --to-source",
"command",
"=",
"[",
"'iptables'",
",",
"'-t'",
",",
"'nat'",
",",
"'-I'",
",",
"'POSTROUTING'",
",",
"'-o'",
",",
"device_name",
",",
"'-s'",
",",
"source_ip_address",
",",
"'-j'",
",",
"'SNAT'",
",",
"'--to-source'",
",",
"desired_source_ip_address",
"]",
"log",
".",
"info",
"(",
"'Running command: {c}'",
".",
"format",
"(",
"c",
"=",
"command",
")",
")",
"try",
":",
"result",
"=",
"run_command",
"(",
"command",
",",
"timeout_sec",
"=",
"20",
")",
"except",
"CommandError",
":",
"_",
",",
"ex",
",",
"trace",
"=",
"sys",
".",
"exc_info",
"(",
")",
"msg",
"=",
"'There was a problem running iptables command: {c}\\n{e}'",
".",
"format",
"(",
"c",
"=",
"' '",
".",
"join",
"(",
"command",
")",
",",
"e",
"=",
"str",
"(",
"ex",
")",
")",
"log",
".",
"error",
"(",
"msg",
")",
"raise",
"OSError",
",",
"msg",
",",
"trace",
"if",
"int",
"(",
"result",
"[",
"'code'",
"]",
")",
"!=",
"0",
":",
"msg",
"=",
"'The iptables command produced an error with exit code: {c}, and output:\\n{o}'",
".",
"format",
"(",
"c",
"=",
"result",
"[",
"'code'",
"]",
",",
"o",
"=",
"result",
"[",
"'output'",
"]",
")",
"log",
".",
"error",
"(",
"msg",
")",
"raise",
"OSError",
"(",
"msg",
")",
"log",
".",
"info",
"(",
"'Successfully configured the source IP for {d} to be: {i}'",
".",
"format",
"(",
"d",
"=",
"device_name",
",",
"i",
"=",
"desired_source_ip_address",
")",
")"
] | Configures the source IP address for a Linux interface
:param source_ip_address: (str) Source IP address to change
:param desired_source_ip_address: (str) IP address to configure as the source in outgoing packets
:param device_num: (int) Integer interface device number to configure
:return: None
:raises: TypeError, ValueError, OSError | [
"Configures",
"the",
"source",
"IP",
"address",
"for",
"a",
"Linux",
"interface"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/aliasip.py#L266-L328 |
ktsstudio/tornkts | tornkts/handlers/object_handler.py | ObjectHandler.save_logic | def save_logic(self, some_object):
"""
Перед сохранением в методе save вызывается этот метод
:param some_object: сохраненный объект
"""
some_object.validate_model()
some_object.save()
self.send_success_response(data=some_object.to_dict()) | python | def save_logic(self, some_object):
"""
Перед сохранением в методе save вызывается этот метод
:param some_object: сохраненный объект
"""
some_object.validate_model()
some_object.save()
self.send_success_response(data=some_object.to_dict()) | [
"def",
"save_logic",
"(",
"self",
",",
"some_object",
")",
":",
"some_object",
".",
"validate_model",
"(",
")",
"some_object",
".",
"save",
"(",
")",
"self",
".",
"send_success_response",
"(",
"data",
"=",
"some_object",
".",
"to_dict",
"(",
")",
")"
] | Перед сохранением в методе save вызывается этот метод
:param some_object: сохраненный объект | [
"Перед",
"сохранением",
"в",
"методе",
"save",
"вызывается",
"этот",
"метод",
":",
"param",
"some_object",
":",
"сохраненный",
"объект"
] | train | https://github.com/ktsstudio/tornkts/blob/db47e4550426282960a7e4486dcc4399c8d52e02/tornkts/handlers/object_handler.py#L80-L87 |
novopl/peltak | src/peltak/core/shell.py | fmt | def fmt(msg, *args, **kw):
# type: (str, *Any, **Any) -> str
""" Generate shell color opcodes from a pretty coloring syntax. """
global is_tty
if len(args) or len(kw):
msg = msg.format(*args, **kw)
opcode_subst = '\x1b[\\1m' if is_tty else ''
return re.sub(r'<(\d{1,2})>', opcode_subst, msg) | python | def fmt(msg, *args, **kw):
# type: (str, *Any, **Any) -> str
""" Generate shell color opcodes from a pretty coloring syntax. """
global is_tty
if len(args) or len(kw):
msg = msg.format(*args, **kw)
opcode_subst = '\x1b[\\1m' if is_tty else ''
return re.sub(r'<(\d{1,2})>', opcode_subst, msg) | [
"def",
"fmt",
"(",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"# type: (str, *Any, **Any) -> str",
"global",
"is_tty",
"if",
"len",
"(",
"args",
")",
"or",
"len",
"(",
"kw",
")",
":",
"msg",
"=",
"msg",
".",
"format",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"opcode_subst",
"=",
"'\\x1b[\\\\1m'",
"if",
"is_tty",
"else",
"''",
"return",
"re",
".",
"sub",
"(",
"r'<(\\d{1,2})>'",
",",
"opcode_subst",
",",
"msg",
")"
] | Generate shell color opcodes from a pretty coloring syntax. | [
"Generate",
"shell",
"color",
"opcodes",
"from",
"a",
"pretty",
"coloring",
"syntax",
"."
] | train | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/core/shell.py#L55-L64 |
novopl/peltak | src/peltak/core/shell.py | cprint | def cprint(msg, *args, **kw):
# type: (str, *Any, **Any) -> None
""" Print colored message to stdout. """
if len(args) or len(kw):
msg = msg.format(*args, **kw)
print(fmt('{}<0>'.format(msg))) | python | def cprint(msg, *args, **kw):
# type: (str, *Any, **Any) -> None
""" Print colored message to stdout. """
if len(args) or len(kw):
msg = msg.format(*args, **kw)
print(fmt('{}<0>'.format(msg))) | [
"def",
"cprint",
"(",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"# type: (str, *Any, **Any) -> None",
"if",
"len",
"(",
"args",
")",
"or",
"len",
"(",
"kw",
")",
":",
"msg",
"=",
"msg",
".",
"format",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"print",
"(",
"fmt",
"(",
"'{}<0>'",
".",
"format",
"(",
"msg",
")",
")",
")"
] | Print colored message to stdout. | [
"Print",
"colored",
"message",
"to",
"stdout",
"."
] | train | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/core/shell.py#L67-L73 |
novopl/peltak | src/peltak/core/shell.py | run | def run(cmd,
capture=False,
shell=True,
env=None,
exit_on_error=None,
never_pretend=False):
# type: (str, bool, bool, Dict[str, str], bool) -> ExecResult
""" Run a shell command.
Args:
cmd (str):
The shell command to execute.
shell (bool):
Same as in `subprocess.Popen`.
capture (bool):
If set to True, it will capture the standard input/error instead of
just piping it to the caller stdout/stderr.
env (dict[str, str]):
The subprocess environment variables.
exit_on_error (bool):
If set to **True**, on failure it will call `sys.exit` with the
return code for the executed command.
never_pretend (bool):
If set to **True** the command will always be executed, even if
context.get('pretend') is set to True. If set to **False** or not
given, if the `pretend` context value is **True**, this function
will only print the command it would execute and then return
a fake result.
Returns:
ExecResult: The execution result containing the return code and output
(if capture was set to *True*).
"""
if context.get('pretend', False) and not never_pretend:
cprint('<90>{}', cmd)
return ExecResult(
cmd,
0, # retcode
'', # stdout
'', # stderr
True, # succeeded
False, # failed
)
if context.get('verbose', 0) > 2:
cprint('<90>{}', cmd)
options = {
'bufsize': 1, # line buffered
'shell': shell
}
if exit_on_error is None:
exit_on_error = not capture
if capture:
options.update({
'stdout': subprocess.PIPE,
'stderr': subprocess.PIPE,
})
if env is not None:
options['env'] = dict(os.environ)
options['env'].update(env)
p = subprocess.Popen(cmd, **options)
stdout, stderr = p.communicate()
try:
if stdout is not None:
stdout = stdout.decode('utf-8')
if stderr is not None:
stderr = stderr.decode('utf-8')
except AttributeError:
# 'str' has no attribute 'decode'
pass
if exit_on_error and p.returncode != 0:
sys.exit(p.returncode)
return ExecResult(
cmd,
p.returncode,
stdout,
stderr,
p.returncode == 0,
p.returncode != 0
) | python | def run(cmd,
capture=False,
shell=True,
env=None,
exit_on_error=None,
never_pretend=False):
# type: (str, bool, bool, Dict[str, str], bool) -> ExecResult
""" Run a shell command.
Args:
cmd (str):
The shell command to execute.
shell (bool):
Same as in `subprocess.Popen`.
capture (bool):
If set to True, it will capture the standard input/error instead of
just piping it to the caller stdout/stderr.
env (dict[str, str]):
The subprocess environment variables.
exit_on_error (bool):
If set to **True**, on failure it will call `sys.exit` with the
return code for the executed command.
never_pretend (bool):
If set to **True** the command will always be executed, even if
context.get('pretend') is set to True. If set to **False** or not
given, if the `pretend` context value is **True**, this function
will only print the command it would execute and then return
a fake result.
Returns:
ExecResult: The execution result containing the return code and output
(if capture was set to *True*).
"""
if context.get('pretend', False) and not never_pretend:
cprint('<90>{}', cmd)
return ExecResult(
cmd,
0, # retcode
'', # stdout
'', # stderr
True, # succeeded
False, # failed
)
if context.get('verbose', 0) > 2:
cprint('<90>{}', cmd)
options = {
'bufsize': 1, # line buffered
'shell': shell
}
if exit_on_error is None:
exit_on_error = not capture
if capture:
options.update({
'stdout': subprocess.PIPE,
'stderr': subprocess.PIPE,
})
if env is not None:
options['env'] = dict(os.environ)
options['env'].update(env)
p = subprocess.Popen(cmd, **options)
stdout, stderr = p.communicate()
try:
if stdout is not None:
stdout = stdout.decode('utf-8')
if stderr is not None:
stderr = stderr.decode('utf-8')
except AttributeError:
# 'str' has no attribute 'decode'
pass
if exit_on_error and p.returncode != 0:
sys.exit(p.returncode)
return ExecResult(
cmd,
p.returncode,
stdout,
stderr,
p.returncode == 0,
p.returncode != 0
) | [
"def",
"run",
"(",
"cmd",
",",
"capture",
"=",
"False",
",",
"shell",
"=",
"True",
",",
"env",
"=",
"None",
",",
"exit_on_error",
"=",
"None",
",",
"never_pretend",
"=",
"False",
")",
":",
"# type: (str, bool, bool, Dict[str, str], bool) -> ExecResult",
"if",
"context",
".",
"get",
"(",
"'pretend'",
",",
"False",
")",
"and",
"not",
"never_pretend",
":",
"cprint",
"(",
"'<90>{}'",
",",
"cmd",
")",
"return",
"ExecResult",
"(",
"cmd",
",",
"0",
",",
"# retcode",
"''",
",",
"# stdout",
"''",
",",
"# stderr",
"True",
",",
"# succeeded",
"False",
",",
"# failed",
")",
"if",
"context",
".",
"get",
"(",
"'verbose'",
",",
"0",
")",
">",
"2",
":",
"cprint",
"(",
"'<90>{}'",
",",
"cmd",
")",
"options",
"=",
"{",
"'bufsize'",
":",
"1",
",",
"# line buffered",
"'shell'",
":",
"shell",
"}",
"if",
"exit_on_error",
"is",
"None",
":",
"exit_on_error",
"=",
"not",
"capture",
"if",
"capture",
":",
"options",
".",
"update",
"(",
"{",
"'stdout'",
":",
"subprocess",
".",
"PIPE",
",",
"'stderr'",
":",
"subprocess",
".",
"PIPE",
",",
"}",
")",
"if",
"env",
"is",
"not",
"None",
":",
"options",
"[",
"'env'",
"]",
"=",
"dict",
"(",
"os",
".",
"environ",
")",
"options",
"[",
"'env'",
"]",
".",
"update",
"(",
"env",
")",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd",
",",
"*",
"*",
"options",
")",
"stdout",
",",
"stderr",
"=",
"p",
".",
"communicate",
"(",
")",
"try",
":",
"if",
"stdout",
"is",
"not",
"None",
":",
"stdout",
"=",
"stdout",
".",
"decode",
"(",
"'utf-8'",
")",
"if",
"stderr",
"is",
"not",
"None",
":",
"stderr",
"=",
"stderr",
".",
"decode",
"(",
"'utf-8'",
")",
"except",
"AttributeError",
":",
"# 'str' has no attribute 'decode'",
"pass",
"if",
"exit_on_error",
"and",
"p",
".",
"returncode",
"!=",
"0",
":",
"sys",
".",
"exit",
"(",
"p",
".",
"returncode",
")",
"return",
"ExecResult",
"(",
"cmd",
",",
"p",
".",
"returncode",
",",
"stdout",
",",
"stderr",
",",
"p",
".",
"returncode",
"==",
"0",
",",
"p",
".",
"returncode",
"!=",
"0",
")"
] | Run a shell command.
Args:
cmd (str):
The shell command to execute.
shell (bool):
Same as in `subprocess.Popen`.
capture (bool):
If set to True, it will capture the standard input/error instead of
just piping it to the caller stdout/stderr.
env (dict[str, str]):
The subprocess environment variables.
exit_on_error (bool):
If set to **True**, on failure it will call `sys.exit` with the
return code for the executed command.
never_pretend (bool):
If set to **True** the command will always be executed, even if
context.get('pretend') is set to True. If set to **False** or not
given, if the `pretend` context value is **True**, this function
will only print the command it would execute and then return
a fake result.
Returns:
ExecResult: The execution result containing the return code and output
(if capture was set to *True*). | [
"Run",
"a",
"shell",
"command",
"."
] | train | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/core/shell.py#L76-L164 |
bitesofcode/pyramid_restful | pyramid_restful/utils.py | get_payload | def get_payload(request):
"""
Extracts the request's payload information.
This method will merge the URL parameter information
and the JSON body of the request together to generate
a dictionary of key<->value pairings.
This method assumes that the JSON body being provided
is also a key-value map, if it is not, then an HTTPBadRequest
exception will be raised.
:param request: <pyramid.request.Request>
:return: <dict>
"""
# always extract values from the URL
payload = dict(request.params.mixed())
# provide override capability from the JSON body
try:
json_data = request.json_body
# no JSON body was found, pyramid raises an error
# in this situation
except StandardError:
pass
else:
if not isinstance(json_data, dict):
raise HTTPBadRequest('JSON body must be a key=value pairing')
else:
payload.update(json_data)
return payload | python | def get_payload(request):
"""
Extracts the request's payload information.
This method will merge the URL parameter information
and the JSON body of the request together to generate
a dictionary of key<->value pairings.
This method assumes that the JSON body being provided
is also a key-value map, if it is not, then an HTTPBadRequest
exception will be raised.
:param request: <pyramid.request.Request>
:return: <dict>
"""
# always extract values from the URL
payload = dict(request.params.mixed())
# provide override capability from the JSON body
try:
json_data = request.json_body
# no JSON body was found, pyramid raises an error
# in this situation
except StandardError:
pass
else:
if not isinstance(json_data, dict):
raise HTTPBadRequest('JSON body must be a key=value pairing')
else:
payload.update(json_data)
return payload | [
"def",
"get_payload",
"(",
"request",
")",
":",
"# always extract values from the URL",
"payload",
"=",
"dict",
"(",
"request",
".",
"params",
".",
"mixed",
"(",
")",
")",
"# provide override capability from the JSON body",
"try",
":",
"json_data",
"=",
"request",
".",
"json_body",
"# no JSON body was found, pyramid raises an error",
"# in this situation",
"except",
"StandardError",
":",
"pass",
"else",
":",
"if",
"not",
"isinstance",
"(",
"json_data",
",",
"dict",
")",
":",
"raise",
"HTTPBadRequest",
"(",
"'JSON body must be a key=value pairing'",
")",
"else",
":",
"payload",
".",
"update",
"(",
"json_data",
")",
"return",
"payload"
] | Extracts the request's payload information.
This method will merge the URL parameter information
and the JSON body of the request together to generate
a dictionary of key<->value pairings.
This method assumes that the JSON body being provided
is also a key-value map, if it is not, then an HTTPBadRequest
exception will be raised.
:param request: <pyramid.request.Request>
:return: <dict> | [
"Extracts",
"the",
"request",
"s",
"payload",
"information",
".",
"This",
"method",
"will",
"merge",
"the",
"URL",
"parameter",
"information",
"and",
"the",
"JSON",
"body",
"of",
"the",
"request",
"together",
"to",
"generate",
"a",
"dictionary",
"of",
"key<",
"-",
">",
"value",
"pairings",
"."
] | train | https://github.com/bitesofcode/pyramid_restful/blob/0f1eccb2c61b9bd6add03b461d4e4d7901c957da/pyramid_restful/utils.py#L4-L37 |
cons3rt/pycons3rt | pycons3rt/assetmailer.py | main | def main():
"""Handles external calling for this module
Execute this python module and provide the args shown below to
external call this module to send email messages!
:return: None
"""
log = logging.getLogger(mod_logger + '.main')
parser = argparse.ArgumentParser(description='This module allows sending email messages.')
parser.add_argument('-f', '--file', help='Full path to a plain text file', required=False)
parser.add_argument('-s', '--sender', help='Email address of the sender', required=False)
parser.add_argument('-r', '--recipient', help='Email address of the recipient', required=False)
args = parser.parse_args()
am = AssetMailer()
err = None
if args.file:
try:
am.send_text_file(text_file=args.file, sender=args.sender, recipient=args.recipient)
except AssetMailerError:
_, ex, trace = sys.exc_info()
err = '{n}: There was a problem sending email with file {f} from sender {s} to recipient {r}:\n{e}'.format(
n=ex.__class__.__name__, f=args.file, s=args.sender, r=args.recipient, e=str(ex))
log.error(err)
else:
try:
am.send_cons3rt_agent_logs()
except AssetMailerError:
_, ex, trace = sys.exc_info()
err = '{n}: There was a problem sending cons3rt agent log files:\n{e}'.format(
n=ex.__class__.__name__, e=str(ex))
log.error(err)
if err is None:
log.info('Successfully send email') | python | def main():
"""Handles external calling for this module
Execute this python module and provide the args shown below to
external call this module to send email messages!
:return: None
"""
log = logging.getLogger(mod_logger + '.main')
parser = argparse.ArgumentParser(description='This module allows sending email messages.')
parser.add_argument('-f', '--file', help='Full path to a plain text file', required=False)
parser.add_argument('-s', '--sender', help='Email address of the sender', required=False)
parser.add_argument('-r', '--recipient', help='Email address of the recipient', required=False)
args = parser.parse_args()
am = AssetMailer()
err = None
if args.file:
try:
am.send_text_file(text_file=args.file, sender=args.sender, recipient=args.recipient)
except AssetMailerError:
_, ex, trace = sys.exc_info()
err = '{n}: There was a problem sending email with file {f} from sender {s} to recipient {r}:\n{e}'.format(
n=ex.__class__.__name__, f=args.file, s=args.sender, r=args.recipient, e=str(ex))
log.error(err)
else:
try:
am.send_cons3rt_agent_logs()
except AssetMailerError:
_, ex, trace = sys.exc_info()
err = '{n}: There was a problem sending cons3rt agent log files:\n{e}'.format(
n=ex.__class__.__name__, e=str(ex))
log.error(err)
if err is None:
log.info('Successfully send email') | [
"def",
"main",
"(",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.main'",
")",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'This module allows sending email messages.'",
")",
"parser",
".",
"add_argument",
"(",
"'-f'",
",",
"'--file'",
",",
"help",
"=",
"'Full path to a plain text file'",
",",
"required",
"=",
"False",
")",
"parser",
".",
"add_argument",
"(",
"'-s'",
",",
"'--sender'",
",",
"help",
"=",
"'Email address of the sender'",
",",
"required",
"=",
"False",
")",
"parser",
".",
"add_argument",
"(",
"'-r'",
",",
"'--recipient'",
",",
"help",
"=",
"'Email address of the recipient'",
",",
"required",
"=",
"False",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"am",
"=",
"AssetMailer",
"(",
")",
"err",
"=",
"None",
"if",
"args",
".",
"file",
":",
"try",
":",
"am",
".",
"send_text_file",
"(",
"text_file",
"=",
"args",
".",
"file",
",",
"sender",
"=",
"args",
".",
"sender",
",",
"recipient",
"=",
"args",
".",
"recipient",
")",
"except",
"AssetMailerError",
":",
"_",
",",
"ex",
",",
"trace",
"=",
"sys",
".",
"exc_info",
"(",
")",
"err",
"=",
"'{n}: There was a problem sending email with file {f} from sender {s} to recipient {r}:\\n{e}'",
".",
"format",
"(",
"n",
"=",
"ex",
".",
"__class__",
".",
"__name__",
",",
"f",
"=",
"args",
".",
"file",
",",
"s",
"=",
"args",
".",
"sender",
",",
"r",
"=",
"args",
".",
"recipient",
",",
"e",
"=",
"str",
"(",
"ex",
")",
")",
"log",
".",
"error",
"(",
"err",
")",
"else",
":",
"try",
":",
"am",
".",
"send_cons3rt_agent_logs",
"(",
")",
"except",
"AssetMailerError",
":",
"_",
",",
"ex",
",",
"trace",
"=",
"sys",
".",
"exc_info",
"(",
")",
"err",
"=",
"'{n}: There was a problem sending cons3rt agent log files:\\n{e}'",
".",
"format",
"(",
"n",
"=",
"ex",
".",
"__class__",
".",
"__name__",
",",
"e",
"=",
"str",
"(",
"ex",
")",
")",
"log",
".",
"error",
"(",
"err",
")",
"if",
"err",
"is",
"None",
":",
"log",
".",
"info",
"(",
"'Successfully send email'",
")"
] | Handles external calling for this module
Execute this python module and provide the args shown below to
external call this module to send email messages!
:return: None | [
"Handles",
"external",
"calling",
"for",
"this",
"module"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/assetmailer.py#L178-L212 |
cons3rt/pycons3rt | pycons3rt/assetmailer.py | AssetMailer.send_cons3rt_agent_logs | def send_cons3rt_agent_logs(self):
"""Send the cons3rt agent log file
:return:
"""
log = logging.getLogger(self.cls_logger + '.send_cons3rt_agent_logs')
if self.cons3rt_agent_log_dir is None:
log.warn('There is not CONS3RT agent log directory on this system')
return
log.debug('Searching for log files in directory: {d}'.format(d=self.cons3rt_agent_log_dir))
for item in os.listdir(self.cons3rt_agent_log_dir):
item_path = os.path.join(self.cons3rt_agent_log_dir, item)
if os.path.isfile(item_path):
log.info('Sending email with cons3rt agent log file: {f}'.format(f=item_path))
try:
self.send_text_file(text_file=item_path)
except (TypeError, OSError, AssetMailerError):
_, ex, trace = sys.exc_info()
msg = '{n}: There was a problem sending CONS3RT agent log file: {f}\n{e}'.format(
n=ex.__class__.__name__, f=item_path, e=str(ex))
raise AssetMailerError, msg, trace
else:
log.info('Successfully sent email with file: {f}'.format(f=item_path)) | python | def send_cons3rt_agent_logs(self):
"""Send the cons3rt agent log file
:return:
"""
log = logging.getLogger(self.cls_logger + '.send_cons3rt_agent_logs')
if self.cons3rt_agent_log_dir is None:
log.warn('There is not CONS3RT agent log directory on this system')
return
log.debug('Searching for log files in directory: {d}'.format(d=self.cons3rt_agent_log_dir))
for item in os.listdir(self.cons3rt_agent_log_dir):
item_path = os.path.join(self.cons3rt_agent_log_dir, item)
if os.path.isfile(item_path):
log.info('Sending email with cons3rt agent log file: {f}'.format(f=item_path))
try:
self.send_text_file(text_file=item_path)
except (TypeError, OSError, AssetMailerError):
_, ex, trace = sys.exc_info()
msg = '{n}: There was a problem sending CONS3RT agent log file: {f}\n{e}'.format(
n=ex.__class__.__name__, f=item_path, e=str(ex))
raise AssetMailerError, msg, trace
else:
log.info('Successfully sent email with file: {f}'.format(f=item_path)) | [
"def",
"send_cons3rt_agent_logs",
"(",
"self",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"self",
".",
"cls_logger",
"+",
"'.send_cons3rt_agent_logs'",
")",
"if",
"self",
".",
"cons3rt_agent_log_dir",
"is",
"None",
":",
"log",
".",
"warn",
"(",
"'There is not CONS3RT agent log directory on this system'",
")",
"return",
"log",
".",
"debug",
"(",
"'Searching for log files in directory: {d}'",
".",
"format",
"(",
"d",
"=",
"self",
".",
"cons3rt_agent_log_dir",
")",
")",
"for",
"item",
"in",
"os",
".",
"listdir",
"(",
"self",
".",
"cons3rt_agent_log_dir",
")",
":",
"item_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"cons3rt_agent_log_dir",
",",
"item",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"item_path",
")",
":",
"log",
".",
"info",
"(",
"'Sending email with cons3rt agent log file: {f}'",
".",
"format",
"(",
"f",
"=",
"item_path",
")",
")",
"try",
":",
"self",
".",
"send_text_file",
"(",
"text_file",
"=",
"item_path",
")",
"except",
"(",
"TypeError",
",",
"OSError",
",",
"AssetMailerError",
")",
":",
"_",
",",
"ex",
",",
"trace",
"=",
"sys",
".",
"exc_info",
"(",
")",
"msg",
"=",
"'{n}: There was a problem sending CONS3RT agent log file: {f}\\n{e}'",
".",
"format",
"(",
"n",
"=",
"ex",
".",
"__class__",
".",
"__name__",
",",
"f",
"=",
"item_path",
",",
"e",
"=",
"str",
"(",
"ex",
")",
")",
"raise",
"AssetMailerError",
",",
"msg",
",",
"trace",
"else",
":",
"log",
".",
"info",
"(",
"'Successfully sent email with file: {f}'",
".",
"format",
"(",
"f",
"=",
"item_path",
")",
")"
] | Send the cons3rt agent log file
:return: | [
"Send",
"the",
"cons3rt",
"agent",
"log",
"file"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/assetmailer.py#L63-L87 |
cons3rt/pycons3rt | pycons3rt/assetmailer.py | AssetMailer.send_text_file | def send_text_file(self, text_file, sender=None, recipient=None):
"""Sends an email with the contents of the provided text file
:return: None
"""
log = logging.getLogger(self.cls_logger + '.send_text_file')
if not isinstance(text_file, basestring):
msg = 'arg text_file must be a string, found type: {t}'.format(t=text_file.__class__.__name__)
raise AssetMailerError(msg)
if not os.path.isfile(text_file):
msg = 'The provided text_file was not found or is not a file: {f}'.format(f=text_file)
raise AssetMailerError(msg)
# Determine sender/recipient
if sender is None:
sender = default_sender_email
if recipient is None:
recipient = self.recipient_email
# Set the email subject
file_name = text_file.split(os.path.sep)[-1]
subject = self.subject + file_name
# Read the input text file
try:
fp = open(text_file, 'rb')
mail_message = MIMEText(fp.read())
fp.close()
except OSError:
_, ex, trace = sys.exc_info()
msg = '{n}: There was a problem reading text file: {f}\n{e}'.format(
n=ex.__class__.__name__, f=text_file, e=str(ex))
raise AssetMailerError, msg, trace
# Configure the mail message
mail_message['Subject'] = subject
mail_message['From'] = sender
mail_message['To'] = recipient
# Configure the SMTP server
log.debug('Configuring the SMTP server...')
try:
s = smtplib.SMTP(self.smtp_server)
except (smtplib.SMTPConnectError, socket.timeout, socket.error):
_, ex, trace = sys.exc_info()
msg = '{n}: There was a problem connecting to SMTP server: {s}\n{e}'.format(
n=ex.__class__.__name__, s=self.smtp_server, e=str(ex))
raise AssetMailerError, msg, trace
# Set the SMTP log level
# s.set_debuglevel(debuglevel=__debug__)
# Set the SMTP server to be localhost
log.debug('Sending email with subject {s} to {e}...'.format(s=subject, e=recipient))
try:
s.sendmail(sender, [recipient], mail_message.as_string())
except smtplib.SMTPRecipientsRefused:
_, ex, trace = sys.exc_info()
msg = '{n}: All recipients were refused, nobody got the mail: {r}:\n{e}'.format(
n=ex.__class__.__name__, r=recipient, e=str(ex))
raise AssetMailerError, msg, trace
except smtplib.SMTPSenderRefused:
_, ex, trace = sys.exc_info()
msg = '{n}: The server did not accept the sender address: {s}:\n{e}'.format(
n=ex.__class__.__name__, s=sender, e=str(ex))
raise AssetMailerError, msg, trace
except smtplib.SMTPHeloError:
_, ex, trace = sys.exc_info()
msg = '{n}: The server did not respond to the HELO greeting\n{e}'.format(
n=ex.__class__.__name__, e=str(ex))
raise AssetMailerError, msg, trace
except smtplib.SMTPDataError:
_, ex, trace = sys.exc_info()
msg = '{n}: The server replied with an unexpected error code (other than a refusal of a recipient)\n{e}'.\
format(n=ex.__class__.__name__, r=recipient, e=str(ex))
raise AssetMailerError, msg, trace
except smtplib.SMTPConnectError:
_, ex, trace = sys.exc_info()
msg = '{n}: There was a connection error\n{e}'. \
format(n=ex.__class__.__name__, r=recipient, e=str(ex))
raise AssetMailerError, msg, trace
else:
log.info('Sent email to: {r}'.format(r=recipient))
finally:
s.quit() | python | def send_text_file(self, text_file, sender=None, recipient=None):
"""Sends an email with the contents of the provided text file
:return: None
"""
log = logging.getLogger(self.cls_logger + '.send_text_file')
if not isinstance(text_file, basestring):
msg = 'arg text_file must be a string, found type: {t}'.format(t=text_file.__class__.__name__)
raise AssetMailerError(msg)
if not os.path.isfile(text_file):
msg = 'The provided text_file was not found or is not a file: {f}'.format(f=text_file)
raise AssetMailerError(msg)
# Determine sender/recipient
if sender is None:
sender = default_sender_email
if recipient is None:
recipient = self.recipient_email
# Set the email subject
file_name = text_file.split(os.path.sep)[-1]
subject = self.subject + file_name
# Read the input text file
try:
fp = open(text_file, 'rb')
mail_message = MIMEText(fp.read())
fp.close()
except OSError:
_, ex, trace = sys.exc_info()
msg = '{n}: There was a problem reading text file: {f}\n{e}'.format(
n=ex.__class__.__name__, f=text_file, e=str(ex))
raise AssetMailerError, msg, trace
# Configure the mail message
mail_message['Subject'] = subject
mail_message['From'] = sender
mail_message['To'] = recipient
# Configure the SMTP server
log.debug('Configuring the SMTP server...')
try:
s = smtplib.SMTP(self.smtp_server)
except (smtplib.SMTPConnectError, socket.timeout, socket.error):
_, ex, trace = sys.exc_info()
msg = '{n}: There was a problem connecting to SMTP server: {s}\n{e}'.format(
n=ex.__class__.__name__, s=self.smtp_server, e=str(ex))
raise AssetMailerError, msg, trace
# Set the SMTP log level
# s.set_debuglevel(debuglevel=__debug__)
# Set the SMTP server to be localhost
log.debug('Sending email with subject {s} to {e}...'.format(s=subject, e=recipient))
try:
s.sendmail(sender, [recipient], mail_message.as_string())
except smtplib.SMTPRecipientsRefused:
_, ex, trace = sys.exc_info()
msg = '{n}: All recipients were refused, nobody got the mail: {r}:\n{e}'.format(
n=ex.__class__.__name__, r=recipient, e=str(ex))
raise AssetMailerError, msg, trace
except smtplib.SMTPSenderRefused:
_, ex, trace = sys.exc_info()
msg = '{n}: The server did not accept the sender address: {s}:\n{e}'.format(
n=ex.__class__.__name__, s=sender, e=str(ex))
raise AssetMailerError, msg, trace
except smtplib.SMTPHeloError:
_, ex, trace = sys.exc_info()
msg = '{n}: The server did not respond to the HELO greeting\n{e}'.format(
n=ex.__class__.__name__, e=str(ex))
raise AssetMailerError, msg, trace
except smtplib.SMTPDataError:
_, ex, trace = sys.exc_info()
msg = '{n}: The server replied with an unexpected error code (other than a refusal of a recipient)\n{e}'.\
format(n=ex.__class__.__name__, r=recipient, e=str(ex))
raise AssetMailerError, msg, trace
except smtplib.SMTPConnectError:
_, ex, trace = sys.exc_info()
msg = '{n}: There was a connection error\n{e}'. \
format(n=ex.__class__.__name__, r=recipient, e=str(ex))
raise AssetMailerError, msg, trace
else:
log.info('Sent email to: {r}'.format(r=recipient))
finally:
s.quit() | [
"def",
"send_text_file",
"(",
"self",
",",
"text_file",
",",
"sender",
"=",
"None",
",",
"recipient",
"=",
"None",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"self",
".",
"cls_logger",
"+",
"'.send_text_file'",
")",
"if",
"not",
"isinstance",
"(",
"text_file",
",",
"basestring",
")",
":",
"msg",
"=",
"'arg text_file must be a string, found type: {t}'",
".",
"format",
"(",
"t",
"=",
"text_file",
".",
"__class__",
".",
"__name__",
")",
"raise",
"AssetMailerError",
"(",
"msg",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"text_file",
")",
":",
"msg",
"=",
"'The provided text_file was not found or is not a file: {f}'",
".",
"format",
"(",
"f",
"=",
"text_file",
")",
"raise",
"AssetMailerError",
"(",
"msg",
")",
"# Determine sender/recipient",
"if",
"sender",
"is",
"None",
":",
"sender",
"=",
"default_sender_email",
"if",
"recipient",
"is",
"None",
":",
"recipient",
"=",
"self",
".",
"recipient_email",
"# Set the email subject",
"file_name",
"=",
"text_file",
".",
"split",
"(",
"os",
".",
"path",
".",
"sep",
")",
"[",
"-",
"1",
"]",
"subject",
"=",
"self",
".",
"subject",
"+",
"file_name",
"# Read the input text file",
"try",
":",
"fp",
"=",
"open",
"(",
"text_file",
",",
"'rb'",
")",
"mail_message",
"=",
"MIMEText",
"(",
"fp",
".",
"read",
"(",
")",
")",
"fp",
".",
"close",
"(",
")",
"except",
"OSError",
":",
"_",
",",
"ex",
",",
"trace",
"=",
"sys",
".",
"exc_info",
"(",
")",
"msg",
"=",
"'{n}: There was a problem reading text file: {f}\\n{e}'",
".",
"format",
"(",
"n",
"=",
"ex",
".",
"__class__",
".",
"__name__",
",",
"f",
"=",
"text_file",
",",
"e",
"=",
"str",
"(",
"ex",
")",
")",
"raise",
"AssetMailerError",
",",
"msg",
",",
"trace",
"# Configure the mail message",
"mail_message",
"[",
"'Subject'",
"]",
"=",
"subject",
"mail_message",
"[",
"'From'",
"]",
"=",
"sender",
"mail_message",
"[",
"'To'",
"]",
"=",
"recipient",
"# Configure the SMTP server",
"log",
".",
"debug",
"(",
"'Configuring the SMTP server...'",
")",
"try",
":",
"s",
"=",
"smtplib",
".",
"SMTP",
"(",
"self",
".",
"smtp_server",
")",
"except",
"(",
"smtplib",
".",
"SMTPConnectError",
",",
"socket",
".",
"timeout",
",",
"socket",
".",
"error",
")",
":",
"_",
",",
"ex",
",",
"trace",
"=",
"sys",
".",
"exc_info",
"(",
")",
"msg",
"=",
"'{n}: There was a problem connecting to SMTP server: {s}\\n{e}'",
".",
"format",
"(",
"n",
"=",
"ex",
".",
"__class__",
".",
"__name__",
",",
"s",
"=",
"self",
".",
"smtp_server",
",",
"e",
"=",
"str",
"(",
"ex",
")",
")",
"raise",
"AssetMailerError",
",",
"msg",
",",
"trace",
"# Set the SMTP log level",
"# s.set_debuglevel(debuglevel=__debug__)",
"# Set the SMTP server to be localhost",
"log",
".",
"debug",
"(",
"'Sending email with subject {s} to {e}...'",
".",
"format",
"(",
"s",
"=",
"subject",
",",
"e",
"=",
"recipient",
")",
")",
"try",
":",
"s",
".",
"sendmail",
"(",
"sender",
",",
"[",
"recipient",
"]",
",",
"mail_message",
".",
"as_string",
"(",
")",
")",
"except",
"smtplib",
".",
"SMTPRecipientsRefused",
":",
"_",
",",
"ex",
",",
"trace",
"=",
"sys",
".",
"exc_info",
"(",
")",
"msg",
"=",
"'{n}: All recipients were refused, nobody got the mail: {r}:\\n{e}'",
".",
"format",
"(",
"n",
"=",
"ex",
".",
"__class__",
".",
"__name__",
",",
"r",
"=",
"recipient",
",",
"e",
"=",
"str",
"(",
"ex",
")",
")",
"raise",
"AssetMailerError",
",",
"msg",
",",
"trace",
"except",
"smtplib",
".",
"SMTPSenderRefused",
":",
"_",
",",
"ex",
",",
"trace",
"=",
"sys",
".",
"exc_info",
"(",
")",
"msg",
"=",
"'{n}: The server did not accept the sender address: {s}:\\n{e}'",
".",
"format",
"(",
"n",
"=",
"ex",
".",
"__class__",
".",
"__name__",
",",
"s",
"=",
"sender",
",",
"e",
"=",
"str",
"(",
"ex",
")",
")",
"raise",
"AssetMailerError",
",",
"msg",
",",
"trace",
"except",
"smtplib",
".",
"SMTPHeloError",
":",
"_",
",",
"ex",
",",
"trace",
"=",
"sys",
".",
"exc_info",
"(",
")",
"msg",
"=",
"'{n}: The server did not respond to the HELO greeting\\n{e}'",
".",
"format",
"(",
"n",
"=",
"ex",
".",
"__class__",
".",
"__name__",
",",
"e",
"=",
"str",
"(",
"ex",
")",
")",
"raise",
"AssetMailerError",
",",
"msg",
",",
"trace",
"except",
"smtplib",
".",
"SMTPDataError",
":",
"_",
",",
"ex",
",",
"trace",
"=",
"sys",
".",
"exc_info",
"(",
")",
"msg",
"=",
"'{n}: The server replied with an unexpected error code (other than a refusal of a recipient)\\n{e}'",
".",
"format",
"(",
"n",
"=",
"ex",
".",
"__class__",
".",
"__name__",
",",
"r",
"=",
"recipient",
",",
"e",
"=",
"str",
"(",
"ex",
")",
")",
"raise",
"AssetMailerError",
",",
"msg",
",",
"trace",
"except",
"smtplib",
".",
"SMTPConnectError",
":",
"_",
",",
"ex",
",",
"trace",
"=",
"sys",
".",
"exc_info",
"(",
")",
"msg",
"=",
"'{n}: There was a connection error\\n{e}'",
".",
"format",
"(",
"n",
"=",
"ex",
".",
"__class__",
".",
"__name__",
",",
"r",
"=",
"recipient",
",",
"e",
"=",
"str",
"(",
"ex",
")",
")",
"raise",
"AssetMailerError",
",",
"msg",
",",
"trace",
"else",
":",
"log",
".",
"info",
"(",
"'Sent email to: {r}'",
".",
"format",
"(",
"r",
"=",
"recipient",
")",
")",
"finally",
":",
"s",
".",
"quit",
"(",
")"
] | Sends an email with the contents of the provided text file
:return: None | [
"Sends",
"an",
"email",
"with",
"the",
"contents",
"of",
"the",
"provided",
"text",
"file"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/assetmailer.py#L89-L175 |
kajala/django-jutil | jutil/command.py | get_date_range_by_name | def get_date_range_by_name(name: str, today: datetime=None, tz=None) -> (datetime, datetime):
"""
:param name: yesterday, last_month
:param today: Optional current datetime. Default is now().
:param tz: Optional timezone. Default is UTC.
:return: datetime (begin, end)
"""
if today is None:
today = datetime.utcnow()
if name == 'last_month':
return last_month(today, tz)
elif name == 'last_week':
return last_week(today, tz)
elif name == 'this_month':
return this_month(today, tz)
elif name == 'last_year':
return last_year(today, tz)
elif name == 'yesterday':
return yesterday(today, tz)
elif name == 'today':
begin = today.replace(hour=0, minute=0, second=0, microsecond=0)
end = begin + timedelta(hours=24)
return localize_time_range(begin, end, tz)
else:
m = re.match(r'^plus_minus_(\d+)d$', name)
if m:
days = int(m.group(1))
return localize_time_range(today - timedelta(days=days), today + timedelta(days=days), tz)
m = re.match(r'^prev_(\d+)d$', name)
if m:
days = int(m.group(1))
return localize_time_range(today - timedelta(days=days), today, tz)
m = re.match(r'^next_(\d+)d$', name)
if m:
days = int(m.group(1))
return localize_time_range(today, today + timedelta(days=days), tz)
raise ValueError('Invalid date range name: {}'.format(name)) | python | def get_date_range_by_name(name: str, today: datetime=None, tz=None) -> (datetime, datetime):
"""
:param name: yesterday, last_month
:param today: Optional current datetime. Default is now().
:param tz: Optional timezone. Default is UTC.
:return: datetime (begin, end)
"""
if today is None:
today = datetime.utcnow()
if name == 'last_month':
return last_month(today, tz)
elif name == 'last_week':
return last_week(today, tz)
elif name == 'this_month':
return this_month(today, tz)
elif name == 'last_year':
return last_year(today, tz)
elif name == 'yesterday':
return yesterday(today, tz)
elif name == 'today':
begin = today.replace(hour=0, minute=0, second=0, microsecond=0)
end = begin + timedelta(hours=24)
return localize_time_range(begin, end, tz)
else:
m = re.match(r'^plus_minus_(\d+)d$', name)
if m:
days = int(m.group(1))
return localize_time_range(today - timedelta(days=days), today + timedelta(days=days), tz)
m = re.match(r'^prev_(\d+)d$', name)
if m:
days = int(m.group(1))
return localize_time_range(today - timedelta(days=days), today, tz)
m = re.match(r'^next_(\d+)d$', name)
if m:
days = int(m.group(1))
return localize_time_range(today, today + timedelta(days=days), tz)
raise ValueError('Invalid date range name: {}'.format(name)) | [
"def",
"get_date_range_by_name",
"(",
"name",
":",
"str",
",",
"today",
":",
"datetime",
"=",
"None",
",",
"tz",
"=",
"None",
")",
"->",
"(",
"datetime",
",",
"datetime",
")",
":",
"if",
"today",
"is",
"None",
":",
"today",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"if",
"name",
"==",
"'last_month'",
":",
"return",
"last_month",
"(",
"today",
",",
"tz",
")",
"elif",
"name",
"==",
"'last_week'",
":",
"return",
"last_week",
"(",
"today",
",",
"tz",
")",
"elif",
"name",
"==",
"'this_month'",
":",
"return",
"this_month",
"(",
"today",
",",
"tz",
")",
"elif",
"name",
"==",
"'last_year'",
":",
"return",
"last_year",
"(",
"today",
",",
"tz",
")",
"elif",
"name",
"==",
"'yesterday'",
":",
"return",
"yesterday",
"(",
"today",
",",
"tz",
")",
"elif",
"name",
"==",
"'today'",
":",
"begin",
"=",
"today",
".",
"replace",
"(",
"hour",
"=",
"0",
",",
"minute",
"=",
"0",
",",
"second",
"=",
"0",
",",
"microsecond",
"=",
"0",
")",
"end",
"=",
"begin",
"+",
"timedelta",
"(",
"hours",
"=",
"24",
")",
"return",
"localize_time_range",
"(",
"begin",
",",
"end",
",",
"tz",
")",
"else",
":",
"m",
"=",
"re",
".",
"match",
"(",
"r'^plus_minus_(\\d+)d$'",
",",
"name",
")",
"if",
"m",
":",
"days",
"=",
"int",
"(",
"m",
".",
"group",
"(",
"1",
")",
")",
"return",
"localize_time_range",
"(",
"today",
"-",
"timedelta",
"(",
"days",
"=",
"days",
")",
",",
"today",
"+",
"timedelta",
"(",
"days",
"=",
"days",
")",
",",
"tz",
")",
"m",
"=",
"re",
".",
"match",
"(",
"r'^prev_(\\d+)d$'",
",",
"name",
")",
"if",
"m",
":",
"days",
"=",
"int",
"(",
"m",
".",
"group",
"(",
"1",
")",
")",
"return",
"localize_time_range",
"(",
"today",
"-",
"timedelta",
"(",
"days",
"=",
"days",
")",
",",
"today",
",",
"tz",
")",
"m",
"=",
"re",
".",
"match",
"(",
"r'^next_(\\d+)d$'",
",",
"name",
")",
"if",
"m",
":",
"days",
"=",
"int",
"(",
"m",
".",
"group",
"(",
"1",
")",
")",
"return",
"localize_time_range",
"(",
"today",
",",
"today",
"+",
"timedelta",
"(",
"days",
"=",
"days",
")",
",",
"tz",
")",
"raise",
"ValueError",
"(",
"'Invalid date range name: {}'",
".",
"format",
"(",
"name",
")",
")"
] | :param name: yesterday, last_month
:param today: Optional current datetime. Default is now().
:param tz: Optional timezone. Default is UTC.
:return: datetime (begin, end) | [
":",
"param",
"name",
":",
"yesterday",
"last_month",
":",
"param",
"today",
":",
"Optional",
"current",
"datetime",
".",
"Default",
"is",
"now",
"()",
".",
":",
"param",
"tz",
":",
"Optional",
"timezone",
".",
"Default",
"is",
"UTC",
".",
":",
"return",
":",
"datetime",
"(",
"begin",
"end",
")"
] | train | https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/command.py#L50-L86 |
kajala/django-jutil | jutil/command.py | parse_date_range_arguments | def parse_date_range_arguments(options: dict, default_range='last_month') -> (datetime, datetime, list):
"""
:param options:
:param default_range: Default datetime range to return if no other selected
:return: begin, end, [(begin1,end1), (begin2,end2), ...]
"""
begin, end = get_date_range_by_name(default_range)
for range_name in TIME_RANGE_NAMES:
if options.get(range_name):
begin, end = get_date_range_by_name(range_name)
if options.get('begin'):
t = parse(options['begin'], default=datetime(2000, 1, 1))
begin = pytz.utc.localize(t)
end = now()
if options.get('end'):
end = pytz.utc.localize(parse(options['end'], default=datetime(2000, 1, 1)))
step_type = None
after_end = end
for step_name in TIME_STEP_NAMES:
if options.get(step_name):
step_type = getattr(rrule, step_name.upper())
if rrule.DAILY == step_type:
after_end += timedelta(days=1)
if rrule.WEEKLY == step_type:
after_end += timedelta(days=7)
if rrule.MONTHLY == step_type:
after_end += timedelta(days=31)
steps = None
if step_type:
begins = [t for t in rrule.rrule(step_type, dtstart=begin, until=after_end)]
steps = [(begins[i], begins[i+1]) for i in range(len(begins)-1)]
if steps is None:
steps = [(begin, end)]
return begin, end, steps | python | def parse_date_range_arguments(options: dict, default_range='last_month') -> (datetime, datetime, list):
"""
:param options:
:param default_range: Default datetime range to return if no other selected
:return: begin, end, [(begin1,end1), (begin2,end2), ...]
"""
begin, end = get_date_range_by_name(default_range)
for range_name in TIME_RANGE_NAMES:
if options.get(range_name):
begin, end = get_date_range_by_name(range_name)
if options.get('begin'):
t = parse(options['begin'], default=datetime(2000, 1, 1))
begin = pytz.utc.localize(t)
end = now()
if options.get('end'):
end = pytz.utc.localize(parse(options['end'], default=datetime(2000, 1, 1)))
step_type = None
after_end = end
for step_name in TIME_STEP_NAMES:
if options.get(step_name):
step_type = getattr(rrule, step_name.upper())
if rrule.DAILY == step_type:
after_end += timedelta(days=1)
if rrule.WEEKLY == step_type:
after_end += timedelta(days=7)
if rrule.MONTHLY == step_type:
after_end += timedelta(days=31)
steps = None
if step_type:
begins = [t for t in rrule.rrule(step_type, dtstart=begin, until=after_end)]
steps = [(begins[i], begins[i+1]) for i in range(len(begins)-1)]
if steps is None:
steps = [(begin, end)]
return begin, end, steps | [
"def",
"parse_date_range_arguments",
"(",
"options",
":",
"dict",
",",
"default_range",
"=",
"'last_month'",
")",
"->",
"(",
"datetime",
",",
"datetime",
",",
"list",
")",
":",
"begin",
",",
"end",
"=",
"get_date_range_by_name",
"(",
"default_range",
")",
"for",
"range_name",
"in",
"TIME_RANGE_NAMES",
":",
"if",
"options",
".",
"get",
"(",
"range_name",
")",
":",
"begin",
",",
"end",
"=",
"get_date_range_by_name",
"(",
"range_name",
")",
"if",
"options",
".",
"get",
"(",
"'begin'",
")",
":",
"t",
"=",
"parse",
"(",
"options",
"[",
"'begin'",
"]",
",",
"default",
"=",
"datetime",
"(",
"2000",
",",
"1",
",",
"1",
")",
")",
"begin",
"=",
"pytz",
".",
"utc",
".",
"localize",
"(",
"t",
")",
"end",
"=",
"now",
"(",
")",
"if",
"options",
".",
"get",
"(",
"'end'",
")",
":",
"end",
"=",
"pytz",
".",
"utc",
".",
"localize",
"(",
"parse",
"(",
"options",
"[",
"'end'",
"]",
",",
"default",
"=",
"datetime",
"(",
"2000",
",",
"1",
",",
"1",
")",
")",
")",
"step_type",
"=",
"None",
"after_end",
"=",
"end",
"for",
"step_name",
"in",
"TIME_STEP_NAMES",
":",
"if",
"options",
".",
"get",
"(",
"step_name",
")",
":",
"step_type",
"=",
"getattr",
"(",
"rrule",
",",
"step_name",
".",
"upper",
"(",
")",
")",
"if",
"rrule",
".",
"DAILY",
"==",
"step_type",
":",
"after_end",
"+=",
"timedelta",
"(",
"days",
"=",
"1",
")",
"if",
"rrule",
".",
"WEEKLY",
"==",
"step_type",
":",
"after_end",
"+=",
"timedelta",
"(",
"days",
"=",
"7",
")",
"if",
"rrule",
".",
"MONTHLY",
"==",
"step_type",
":",
"after_end",
"+=",
"timedelta",
"(",
"days",
"=",
"31",
")",
"steps",
"=",
"None",
"if",
"step_type",
":",
"begins",
"=",
"[",
"t",
"for",
"t",
"in",
"rrule",
".",
"rrule",
"(",
"step_type",
",",
"dtstart",
"=",
"begin",
",",
"until",
"=",
"after_end",
")",
"]",
"steps",
"=",
"[",
"(",
"begins",
"[",
"i",
"]",
",",
"begins",
"[",
"i",
"+",
"1",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"begins",
")",
"-",
"1",
")",
"]",
"if",
"steps",
"is",
"None",
":",
"steps",
"=",
"[",
"(",
"begin",
",",
"end",
")",
"]",
"return",
"begin",
",",
"end",
",",
"steps"
] | :param options:
:param default_range: Default datetime range to return if no other selected
:return: begin, end, [(begin1,end1), (begin2,end2), ...] | [
":",
"param",
"options",
":",
":",
"param",
"default_range",
":",
"Default",
"datetime",
"range",
"to",
"return",
"if",
"no",
"other",
"selected",
":",
"return",
":",
"begin",
"end",
"[",
"(",
"begin1",
"end1",
")",
"(",
"begin2",
"end2",
")",
"...",
"]"
] | train | https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/command.py#L89-L123 |
Vital-Fernandez/dazer | bin/lib/Astro_Libraries/Abundances_Class.py | Chemical_Analysis_pyneb.load_elements | def load_elements(self):
#Set atomic data
#atomicData.setDataFile('he_i_rec_Pal12-Pal13.fits')
atomicData.setDataFile('s_iii_coll_HRS12.dat')
#Default: 's_iii_atom_PKW09.dat'
'S3: All energy and A values: Podobedova, Kelleher, and Wiese 2009, J. Phys. Chem. Ref. Data, Vol.'
'S3: collision strengths: Tayal & Gupta 1999, ApJ, 526, 544'
#New Atomic data s_iii_coll_HRS12.dat
'S3: All energy and A values: Podobedova, Kelleher, and Wiese 2009, J. Phys. Chem. Ref. Data, Vol.'
'S3: collision strengths: Hudson, Ramsbottom & Scott 2012, ApJ, 750, 65'
#Declare ions
self.S2_atom = Atom('S', 2)
self.S3_atom = Atom('S', 3)
self.Ar3_atom = Atom('Ar', 3)
self.Ar4_atom = Atom('Ar', 4)
self.N2_atom = Atom('N', 2)
self.O2_atom = Atom('O', 2)
self.O3_atom = Atom('O', 3)
self.H1_atom = RecAtom('H', 1)
self.He1_atom = RecAtom('He', 1)
self.He2_atom = RecAtom('He', 2)
#Pyneb objects
self.diags = Diagnostics()
#Ohrs 2016 relation for the OI_SI gradient
self.logSI_OI_Gradient = random.normal(-1.53, 0.05, size = self.MC_array_len) # random.normal(-1.78, 0.03, size = self.MC_array_len)
self.OI_SI = power(10, -self.logSI_OI_Gradient)
#Theoretical ratios
self.S3_ratio = self.S3_atom.getEmissivity(10000, 100, wave = 9531) / self.S3_atom.getEmissivity(10000, 100, wave = 9069)
self.S3_9000_ratio = random.normal(self.S3_atom.getEmissivity(10000, 100, wave = 9531) / self.S3_atom.getEmissivity(10000, 100, wave = 9069), 0.01, size = self.MC_array_len)
self.N2_6000_ratio = self.N2_atom.getEmissivity(10000, 100, wave = 6584) / self.N2_atom.getEmissivity(10000, 100, wave = 6548)
self.O3_5000_ratio = self.O3_atom.getEmissivity(10000, 100, wave = 5007) / self.O3_atom.getEmissivity(10000, 100, wave = 4959)
#Factors to speed calculations
self.lines_factors = {}
self.lines_factors['S3_9069A'] = 1 + self.S3_ratio
self.lines_factors['S3_9531A'] = 1 + 1/self.S3_ratio
#Cloudy models for the SIV contribution
self.m_SIV_correction = random.normal(1.1628, 0.00559, size = self.MC_array_len)
self.n_SIV_correction = random.normal(0.0470, 0.0097, size = self.MC_array_len)
#self.m_SIV_correction = random.normal(1.109, 0.01, size = self.MC_array_len)
#self.n_SIV_correction = random.normal(0.135, 0.0173, size = self.MC_array_len)
#CHAOS relation TNII-TSIII
#T[SIII] = 1.312(+-0.075)T[NII]-0.313(+-0.058)
#TNII = (0.762+-0.044)*TSIII + 0.239+-0.046
self.m_TNII_correction = random.normal(0.762, 0.044, size = self.MC_array_len)
self.n_TNII_correction = random.normal(0.239, 0.046, size = self.MC_array_len)
#Truncated gaussian for the density
lower_trunc, upper_trunc = (1.0 - 50.0) / 25.0, (100 - 50) / 25.0
self.Truncated_gaussian = truncnorm(lower_trunc, upper_trunc, loc = 50, scale = 25)
print '-Elements loaded\n'
return | python | def load_elements(self):
#Set atomic data
#atomicData.setDataFile('he_i_rec_Pal12-Pal13.fits')
atomicData.setDataFile('s_iii_coll_HRS12.dat')
#Default: 's_iii_atom_PKW09.dat'
'S3: All energy and A values: Podobedova, Kelleher, and Wiese 2009, J. Phys. Chem. Ref. Data, Vol.'
'S3: collision strengths: Tayal & Gupta 1999, ApJ, 526, 544'
#New Atomic data s_iii_coll_HRS12.dat
'S3: All energy and A values: Podobedova, Kelleher, and Wiese 2009, J. Phys. Chem. Ref. Data, Vol.'
'S3: collision strengths: Hudson, Ramsbottom & Scott 2012, ApJ, 750, 65'
#Declare ions
self.S2_atom = Atom('S', 2)
self.S3_atom = Atom('S', 3)
self.Ar3_atom = Atom('Ar', 3)
self.Ar4_atom = Atom('Ar', 4)
self.N2_atom = Atom('N', 2)
self.O2_atom = Atom('O', 2)
self.O3_atom = Atom('O', 3)
self.H1_atom = RecAtom('H', 1)
self.He1_atom = RecAtom('He', 1)
self.He2_atom = RecAtom('He', 2)
#Pyneb objects
self.diags = Diagnostics()
#Ohrs 2016 relation for the OI_SI gradient
self.logSI_OI_Gradient = random.normal(-1.53, 0.05, size = self.MC_array_len) # random.normal(-1.78, 0.03, size = self.MC_array_len)
self.OI_SI = power(10, -self.logSI_OI_Gradient)
#Theoretical ratios
self.S3_ratio = self.S3_atom.getEmissivity(10000, 100, wave = 9531) / self.S3_atom.getEmissivity(10000, 100, wave = 9069)
self.S3_9000_ratio = random.normal(self.S3_atom.getEmissivity(10000, 100, wave = 9531) / self.S3_atom.getEmissivity(10000, 100, wave = 9069), 0.01, size = self.MC_array_len)
self.N2_6000_ratio = self.N2_atom.getEmissivity(10000, 100, wave = 6584) / self.N2_atom.getEmissivity(10000, 100, wave = 6548)
self.O3_5000_ratio = self.O3_atom.getEmissivity(10000, 100, wave = 5007) / self.O3_atom.getEmissivity(10000, 100, wave = 4959)
#Factors to speed calculations
self.lines_factors = {}
self.lines_factors['S3_9069A'] = 1 + self.S3_ratio
self.lines_factors['S3_9531A'] = 1 + 1/self.S3_ratio
#Cloudy models for the SIV contribution
self.m_SIV_correction = random.normal(1.1628, 0.00559, size = self.MC_array_len)
self.n_SIV_correction = random.normal(0.0470, 0.0097, size = self.MC_array_len)
#self.m_SIV_correction = random.normal(1.109, 0.01, size = self.MC_array_len)
#self.n_SIV_correction = random.normal(0.135, 0.0173, size = self.MC_array_len)
#CHAOS relation TNII-TSIII
#T[SIII] = 1.312(+-0.075)T[NII]-0.313(+-0.058)
#TNII = (0.762+-0.044)*TSIII + 0.239+-0.046
self.m_TNII_correction = random.normal(0.762, 0.044, size = self.MC_array_len)
self.n_TNII_correction = random.normal(0.239, 0.046, size = self.MC_array_len)
#Truncated gaussian for the density
lower_trunc, upper_trunc = (1.0 - 50.0) / 25.0, (100 - 50) / 25.0
self.Truncated_gaussian = truncnorm(lower_trunc, upper_trunc, loc = 50, scale = 25)
print '-Elements loaded\n'
return | [
"def",
"load_elements",
"(",
"self",
")",
":",
"#Set atomic data ",
"#atomicData.setDataFile('he_i_rec_Pal12-Pal13.fits')",
"atomicData",
".",
"setDataFile",
"(",
"'s_iii_coll_HRS12.dat'",
")",
"#Default: 's_iii_atom_PKW09.dat' ",
"'S3: collision strengths: Tayal & Gupta 1999, ApJ, 526, 544'",
"#New Atomic data s_iii_coll_HRS12.dat",
"'S3: All energy and A values: Podobedova, Kelleher, and Wiese 2009, J. Phys. Chem. Ref. Data, Vol.'",
"'S3: collision strengths: Hudson, Ramsbottom & Scott 2012, ApJ, 750, 65'",
"#Declare ions",
"self",
".",
"S2_atom",
"=",
"Atom",
"(",
"'S'",
",",
"2",
")",
"self",
".",
"S3_atom",
"=",
"Atom",
"(",
"'S'",
",",
"3",
")",
"self",
".",
"Ar3_atom",
"=",
"Atom",
"(",
"'Ar'",
",",
"3",
")",
"self",
".",
"Ar4_atom",
"=",
"Atom",
"(",
"'Ar'",
",",
"4",
")",
"self",
".",
"N2_atom",
"=",
"Atom",
"(",
"'N'",
",",
"2",
")",
"self",
".",
"O2_atom",
"=",
"Atom",
"(",
"'O'",
",",
"2",
")",
"self",
".",
"O3_atom",
"=",
"Atom",
"(",
"'O'",
",",
"3",
")",
"self",
".",
"H1_atom",
"=",
"RecAtom",
"(",
"'H'",
",",
"1",
")",
"self",
".",
"He1_atom",
"=",
"RecAtom",
"(",
"'He'",
",",
"1",
")",
"self",
".",
"He2_atom",
"=",
"RecAtom",
"(",
"'He'",
",",
"2",
")",
"#Pyneb objects",
"self",
".",
"diags",
"=",
"Diagnostics",
"(",
")",
"#Ohrs 2016 relation for the OI_SI gradient",
"self",
".",
"logSI_OI_Gradient",
"=",
"random",
".",
"normal",
"(",
"-",
"1.53",
",",
"0.05",
",",
"size",
"=",
"self",
".",
"MC_array_len",
")",
"# random.normal(-1.78, 0.03, size = self.MC_array_len)",
"self",
".",
"OI_SI",
"=",
"power",
"(",
"10",
",",
"-",
"self",
".",
"logSI_OI_Gradient",
")",
"#Theoretical ratios",
"self",
".",
"S3_ratio",
"=",
"self",
".",
"S3_atom",
".",
"getEmissivity",
"(",
"10000",
",",
"100",
",",
"wave",
"=",
"9531",
")",
"/",
"self",
".",
"S3_atom",
".",
"getEmissivity",
"(",
"10000",
",",
"100",
",",
"wave",
"=",
"9069",
")",
"self",
".",
"S3_9000_ratio",
"=",
"random",
".",
"normal",
"(",
"self",
".",
"S3_atom",
".",
"getEmissivity",
"(",
"10000",
",",
"100",
",",
"wave",
"=",
"9531",
")",
"/",
"self",
".",
"S3_atom",
".",
"getEmissivity",
"(",
"10000",
",",
"100",
",",
"wave",
"=",
"9069",
")",
",",
"0.01",
",",
"size",
"=",
"self",
".",
"MC_array_len",
")",
"self",
".",
"N2_6000_ratio",
"=",
"self",
".",
"N2_atom",
".",
"getEmissivity",
"(",
"10000",
",",
"100",
",",
"wave",
"=",
"6584",
")",
"/",
"self",
".",
"N2_atom",
".",
"getEmissivity",
"(",
"10000",
",",
"100",
",",
"wave",
"=",
"6548",
")",
"self",
".",
"O3_5000_ratio",
"=",
"self",
".",
"O3_atom",
".",
"getEmissivity",
"(",
"10000",
",",
"100",
",",
"wave",
"=",
"5007",
")",
"/",
"self",
".",
"O3_atom",
".",
"getEmissivity",
"(",
"10000",
",",
"100",
",",
"wave",
"=",
"4959",
")",
"#Factors to speed calculations",
"self",
".",
"lines_factors",
"=",
"{",
"}",
"self",
".",
"lines_factors",
"[",
"'S3_9069A'",
"]",
"=",
"1",
"+",
"self",
".",
"S3_ratio",
"self",
".",
"lines_factors",
"[",
"'S3_9531A'",
"]",
"=",
"1",
"+",
"1",
"/",
"self",
".",
"S3_ratio",
"#Cloudy models for the SIV contribution",
"self",
".",
"m_SIV_correction",
"=",
"random",
".",
"normal",
"(",
"1.1628",
",",
"0.00559",
",",
"size",
"=",
"self",
".",
"MC_array_len",
")",
"self",
".",
"n_SIV_correction",
"=",
"random",
".",
"normal",
"(",
"0.0470",
",",
"0.0097",
",",
"size",
"=",
"self",
".",
"MC_array_len",
")",
"#self.m_SIV_correction = random.normal(1.109, 0.01, size = self.MC_array_len)",
"#self.n_SIV_correction = random.normal(0.135, 0.0173, size = self.MC_array_len)",
"#CHAOS relation TNII-TSIII",
"#T[SIII] = 1.312(+-0.075)T[NII]-0.313(+-0.058)",
"#TNII = (0.762+-0.044)*TSIII + 0.239+-0.046",
"self",
".",
"m_TNII_correction",
"=",
"random",
".",
"normal",
"(",
"0.762",
",",
"0.044",
",",
"size",
"=",
"self",
".",
"MC_array_len",
")",
"self",
".",
"n_TNII_correction",
"=",
"random",
".",
"normal",
"(",
"0.239",
",",
"0.046",
",",
"size",
"=",
"self",
".",
"MC_array_len",
")",
"#Truncated gaussian for the density",
"lower_trunc",
",",
"upper_trunc",
"=",
"(",
"1.0",
"-",
"50.0",
")",
"/",
"25.0",
",",
"(",
"100",
"-",
"50",
")",
"/",
"25.0",
"self",
".",
"Truncated_gaussian",
"=",
"truncnorm",
"(",
"lower_trunc",
",",
"upper_trunc",
",",
"loc",
"=",
"50",
",",
"scale",
"=",
"25",
")",
"print",
"'-Elements loaded\\n'",
"return"
] | S3: All energy and A values: Podobedova, Kelleher, and Wiese 2009, J. Phys. Chem. Ref. Data, Vol. | [
"S3",
":",
"All",
"energy",
"and",
"A",
"values",
":",
"Podobedova",
"Kelleher",
"and",
"Wiese",
"2009",
"J",
".",
"Phys",
".",
"Chem",
".",
"Ref",
".",
"Data",
"Vol",
"."
] | train | https://github.com/Vital-Fernandez/dazer/blob/3c9ae8ae6d40ea33f22cc20dc11365d6d6e65244/bin/lib/Astro_Libraries/Abundances_Class.py#L23-L87 |
cons3rt/pycons3rt | pycons3rt/pygit.py | git_clone | def git_clone(url, clone_dir, branch='master', username=None, password=None, max_retries=10, retry_sec=30,
git_cmd=None):
"""Clones a git url
:param url: (str) Git URL in https or ssh
:param clone_dir: (str) Path to the desired destination dir
:param branch: (str) branch to clone
:param username: (str) username for the git repo
:param password: (str) password for the git repo
:param max_retries: (int) the number of attempt to clone the git repo
:param retry_sec: (int) number of seconds in between retries of the git clone
:param git_cmd: (str) Path to git executable (required on Windows)
:return: None
:raises: PyGitError
"""
log = logging.getLogger(mod_logger + '.git_clone')
if not isinstance(url, basestring):
msg = 'url arg must be a string'
log.error(msg)
raise PyGitError(msg)
if not isinstance(clone_dir, basestring):
msg = 'clone_dir arg must be a string'
log.error(msg)
raise PyGitError(msg)
if not isinstance(max_retries, int):
msg = 'max_retries arg must be an int'
log.error(msg)
raise PyGitError(msg)
if not isinstance(retry_sec, int):
msg = 'retry_sec arg must be an int'
log.error(msg)
raise PyGitError(msg)
# Configure username/password if provided
if url.startswith('https://') and username is not None and password is not None:
stripped_url = str(url)[8:]
log.info('Encoding password: {p}'.format(p=password))
encoded_password = encode_password(password=password)
clone_url = 'https://{u}:{p}@{v}'.format(u=username, p=encoded_password, v=stripped_url)
log.info('Configured username/password for the GIT Clone URL: {u}'.format(u=url))
else:
clone_url = str(url)
# Find the git command
if git_cmd is None:
log.info('Git executable not provided, attempting to determine (this will only work on *NIX platforms...')
command = ['which', 'git']
try:
result = run_command(command)
except CommandError:
_, ex, trace = sys.exc_info()
msg = 'Unable to find the git executable\n{e}'.format(e=str(ex))
log.error(msg)
raise PyGitError, msg, trace
else:
git_cmd = result['output']
if not os.path.isfile(git_cmd):
msg = 'Could not find git command: {g}'.format(g=git_cmd)
log.error(msg)
raise PyGitError(msg)
# Build a git clone or git pull command based on the existence of the clone directory
if os.path.isdir(clone_dir):
log.debug('Git repo directory already exists, updating repo in: {d}'.format(d=clone_dir))
os.chdir(clone_dir)
command = [git_cmd, 'pull']
else:
# Create a subdirectory to clone into
log.debug('Creating the repo directory: {d}'.format(d=clone_dir))
try:
mkdir_p(clone_dir)
except CommandError:
_, ex, trace = sys.exc_info()
msg = 'Unable to create source directory: {d}\n{e}'.format(d=clone_dir, e=str(ex))
log.error(msg)
raise PyGitError, msg, trace
# Create the git clone command
command = [git_cmd, 'clone', '-b', branch, clone_url, clone_dir]
# Run the git command
log.info('Running git command: {c}'.format(c=command))
for i in range(max_retries):
attempt_num = i + 1
log.info('Attempt #{n} to git clone the repository...'.format(n=attempt_num))
try:
result = run_command(command)
except CommandError:
_, ex, trace = sys.exc_info()
log.warn('There was a problem running the git command: {c}\n{e}'.format(c=command, e=str(ex)))
else:
if result['code'] != 0:
log.warn('The git command {g} failed and returned exit code: {c}\n{o}'.format(
g=command, c=result['code'], o=result['output']))
else:
log.info('Successfully cloned/updated GIT repo: {u}'.format(u=url))
return
if attempt_num == max_retries:
msg = 'Attempted unsuccessfully to clone the git repo after {n} attempts'.format(n=attempt_num)
log.error(msg)
raise PyGitError(msg)
log.info('Waiting to retry the git clone in {t} seconds...'.format(t=retry_sec))
time.sleep(retry_sec) | python | def git_clone(url, clone_dir, branch='master', username=None, password=None, max_retries=10, retry_sec=30,
git_cmd=None):
"""Clones a git url
:param url: (str) Git URL in https or ssh
:param clone_dir: (str) Path to the desired destination dir
:param branch: (str) branch to clone
:param username: (str) username for the git repo
:param password: (str) password for the git repo
:param max_retries: (int) the number of attempt to clone the git repo
:param retry_sec: (int) number of seconds in between retries of the git clone
:param git_cmd: (str) Path to git executable (required on Windows)
:return: None
:raises: PyGitError
"""
log = logging.getLogger(mod_logger + '.git_clone')
if not isinstance(url, basestring):
msg = 'url arg must be a string'
log.error(msg)
raise PyGitError(msg)
if not isinstance(clone_dir, basestring):
msg = 'clone_dir arg must be a string'
log.error(msg)
raise PyGitError(msg)
if not isinstance(max_retries, int):
msg = 'max_retries arg must be an int'
log.error(msg)
raise PyGitError(msg)
if not isinstance(retry_sec, int):
msg = 'retry_sec arg must be an int'
log.error(msg)
raise PyGitError(msg)
# Configure username/password if provided
if url.startswith('https://') and username is not None and password is not None:
stripped_url = str(url)[8:]
log.info('Encoding password: {p}'.format(p=password))
encoded_password = encode_password(password=password)
clone_url = 'https://{u}:{p}@{v}'.format(u=username, p=encoded_password, v=stripped_url)
log.info('Configured username/password for the GIT Clone URL: {u}'.format(u=url))
else:
clone_url = str(url)
# Find the git command
if git_cmd is None:
log.info('Git executable not provided, attempting to determine (this will only work on *NIX platforms...')
command = ['which', 'git']
try:
result = run_command(command)
except CommandError:
_, ex, trace = sys.exc_info()
msg = 'Unable to find the git executable\n{e}'.format(e=str(ex))
log.error(msg)
raise PyGitError, msg, trace
else:
git_cmd = result['output']
if not os.path.isfile(git_cmd):
msg = 'Could not find git command: {g}'.format(g=git_cmd)
log.error(msg)
raise PyGitError(msg)
# Build a git clone or git pull command based on the existence of the clone directory
if os.path.isdir(clone_dir):
log.debug('Git repo directory already exists, updating repo in: {d}'.format(d=clone_dir))
os.chdir(clone_dir)
command = [git_cmd, 'pull']
else:
# Create a subdirectory to clone into
log.debug('Creating the repo directory: {d}'.format(d=clone_dir))
try:
mkdir_p(clone_dir)
except CommandError:
_, ex, trace = sys.exc_info()
msg = 'Unable to create source directory: {d}\n{e}'.format(d=clone_dir, e=str(ex))
log.error(msg)
raise PyGitError, msg, trace
# Create the git clone command
command = [git_cmd, 'clone', '-b', branch, clone_url, clone_dir]
# Run the git command
log.info('Running git command: {c}'.format(c=command))
for i in range(max_retries):
attempt_num = i + 1
log.info('Attempt #{n} to git clone the repository...'.format(n=attempt_num))
try:
result = run_command(command)
except CommandError:
_, ex, trace = sys.exc_info()
log.warn('There was a problem running the git command: {c}\n{e}'.format(c=command, e=str(ex)))
else:
if result['code'] != 0:
log.warn('The git command {g} failed and returned exit code: {c}\n{o}'.format(
g=command, c=result['code'], o=result['output']))
else:
log.info('Successfully cloned/updated GIT repo: {u}'.format(u=url))
return
if attempt_num == max_retries:
msg = 'Attempted unsuccessfully to clone the git repo after {n} attempts'.format(n=attempt_num)
log.error(msg)
raise PyGitError(msg)
log.info('Waiting to retry the git clone in {t} seconds...'.format(t=retry_sec))
time.sleep(retry_sec) | [
"def",
"git_clone",
"(",
"url",
",",
"clone_dir",
",",
"branch",
"=",
"'master'",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"max_retries",
"=",
"10",
",",
"retry_sec",
"=",
"30",
",",
"git_cmd",
"=",
"None",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.git_clone'",
")",
"if",
"not",
"isinstance",
"(",
"url",
",",
"basestring",
")",
":",
"msg",
"=",
"'url arg must be a string'",
"log",
".",
"error",
"(",
"msg",
")",
"raise",
"PyGitError",
"(",
"msg",
")",
"if",
"not",
"isinstance",
"(",
"clone_dir",
",",
"basestring",
")",
":",
"msg",
"=",
"'clone_dir arg must be a string'",
"log",
".",
"error",
"(",
"msg",
")",
"raise",
"PyGitError",
"(",
"msg",
")",
"if",
"not",
"isinstance",
"(",
"max_retries",
",",
"int",
")",
":",
"msg",
"=",
"'max_retries arg must be an int'",
"log",
".",
"error",
"(",
"msg",
")",
"raise",
"PyGitError",
"(",
"msg",
")",
"if",
"not",
"isinstance",
"(",
"retry_sec",
",",
"int",
")",
":",
"msg",
"=",
"'retry_sec arg must be an int'",
"log",
".",
"error",
"(",
"msg",
")",
"raise",
"PyGitError",
"(",
"msg",
")",
"# Configure username/password if provided",
"if",
"url",
".",
"startswith",
"(",
"'https://'",
")",
"and",
"username",
"is",
"not",
"None",
"and",
"password",
"is",
"not",
"None",
":",
"stripped_url",
"=",
"str",
"(",
"url",
")",
"[",
"8",
":",
"]",
"log",
".",
"info",
"(",
"'Encoding password: {p}'",
".",
"format",
"(",
"p",
"=",
"password",
")",
")",
"encoded_password",
"=",
"encode_password",
"(",
"password",
"=",
"password",
")",
"clone_url",
"=",
"'https://{u}:{p}@{v}'",
".",
"format",
"(",
"u",
"=",
"username",
",",
"p",
"=",
"encoded_password",
",",
"v",
"=",
"stripped_url",
")",
"log",
".",
"info",
"(",
"'Configured username/password for the GIT Clone URL: {u}'",
".",
"format",
"(",
"u",
"=",
"url",
")",
")",
"else",
":",
"clone_url",
"=",
"str",
"(",
"url",
")",
"# Find the git command",
"if",
"git_cmd",
"is",
"None",
":",
"log",
".",
"info",
"(",
"'Git executable not provided, attempting to determine (this will only work on *NIX platforms...'",
")",
"command",
"=",
"[",
"'which'",
",",
"'git'",
"]",
"try",
":",
"result",
"=",
"run_command",
"(",
"command",
")",
"except",
"CommandError",
":",
"_",
",",
"ex",
",",
"trace",
"=",
"sys",
".",
"exc_info",
"(",
")",
"msg",
"=",
"'Unable to find the git executable\\n{e}'",
".",
"format",
"(",
"e",
"=",
"str",
"(",
"ex",
")",
")",
"log",
".",
"error",
"(",
"msg",
")",
"raise",
"PyGitError",
",",
"msg",
",",
"trace",
"else",
":",
"git_cmd",
"=",
"result",
"[",
"'output'",
"]",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"git_cmd",
")",
":",
"msg",
"=",
"'Could not find git command: {g}'",
".",
"format",
"(",
"g",
"=",
"git_cmd",
")",
"log",
".",
"error",
"(",
"msg",
")",
"raise",
"PyGitError",
"(",
"msg",
")",
"# Build a git clone or git pull command based on the existence of the clone directory",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"clone_dir",
")",
":",
"log",
".",
"debug",
"(",
"'Git repo directory already exists, updating repo in: {d}'",
".",
"format",
"(",
"d",
"=",
"clone_dir",
")",
")",
"os",
".",
"chdir",
"(",
"clone_dir",
")",
"command",
"=",
"[",
"git_cmd",
",",
"'pull'",
"]",
"else",
":",
"# Create a subdirectory to clone into",
"log",
".",
"debug",
"(",
"'Creating the repo directory: {d}'",
".",
"format",
"(",
"d",
"=",
"clone_dir",
")",
")",
"try",
":",
"mkdir_p",
"(",
"clone_dir",
")",
"except",
"CommandError",
":",
"_",
",",
"ex",
",",
"trace",
"=",
"sys",
".",
"exc_info",
"(",
")",
"msg",
"=",
"'Unable to create source directory: {d}\\n{e}'",
".",
"format",
"(",
"d",
"=",
"clone_dir",
",",
"e",
"=",
"str",
"(",
"ex",
")",
")",
"log",
".",
"error",
"(",
"msg",
")",
"raise",
"PyGitError",
",",
"msg",
",",
"trace",
"# Create the git clone command",
"command",
"=",
"[",
"git_cmd",
",",
"'clone'",
",",
"'-b'",
",",
"branch",
",",
"clone_url",
",",
"clone_dir",
"]",
"# Run the git command",
"log",
".",
"info",
"(",
"'Running git command: {c}'",
".",
"format",
"(",
"c",
"=",
"command",
")",
")",
"for",
"i",
"in",
"range",
"(",
"max_retries",
")",
":",
"attempt_num",
"=",
"i",
"+",
"1",
"log",
".",
"info",
"(",
"'Attempt #{n} to git clone the repository...'",
".",
"format",
"(",
"n",
"=",
"attempt_num",
")",
")",
"try",
":",
"result",
"=",
"run_command",
"(",
"command",
")",
"except",
"CommandError",
":",
"_",
",",
"ex",
",",
"trace",
"=",
"sys",
".",
"exc_info",
"(",
")",
"log",
".",
"warn",
"(",
"'There was a problem running the git command: {c}\\n{e}'",
".",
"format",
"(",
"c",
"=",
"command",
",",
"e",
"=",
"str",
"(",
"ex",
")",
")",
")",
"else",
":",
"if",
"result",
"[",
"'code'",
"]",
"!=",
"0",
":",
"log",
".",
"warn",
"(",
"'The git command {g} failed and returned exit code: {c}\\n{o}'",
".",
"format",
"(",
"g",
"=",
"command",
",",
"c",
"=",
"result",
"[",
"'code'",
"]",
",",
"o",
"=",
"result",
"[",
"'output'",
"]",
")",
")",
"else",
":",
"log",
".",
"info",
"(",
"'Successfully cloned/updated GIT repo: {u}'",
".",
"format",
"(",
"u",
"=",
"url",
")",
")",
"return",
"if",
"attempt_num",
"==",
"max_retries",
":",
"msg",
"=",
"'Attempted unsuccessfully to clone the git repo after {n} attempts'",
".",
"format",
"(",
"n",
"=",
"attempt_num",
")",
"log",
".",
"error",
"(",
"msg",
")",
"raise",
"PyGitError",
"(",
"msg",
")",
"log",
".",
"info",
"(",
"'Waiting to retry the git clone in {t} seconds...'",
".",
"format",
"(",
"t",
"=",
"retry_sec",
")",
")",
"time",
".",
"sleep",
"(",
"retry_sec",
")"
] | Clones a git url
:param url: (str) Git URL in https or ssh
:param clone_dir: (str) Path to the desired destination dir
:param branch: (str) branch to clone
:param username: (str) username for the git repo
:param password: (str) password for the git repo
:param max_retries: (int) the number of attempt to clone the git repo
:param retry_sec: (int) number of seconds in between retries of the git clone
:param git_cmd: (str) Path to git executable (required on Windows)
:return: None
:raises: PyGitError | [
"Clones",
"a",
"git",
"url"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/pygit.py#L30-L134 |
cons3rt/pycons3rt | pycons3rt/pygit.py | encode_password | def encode_password(password):
"""Performs URL encoding for passwords
:param password: (str) password to encode
:return: (str) encoded password
"""
log = logging.getLogger(mod_logger + '.password_encoder')
log.debug('Encoding password: {p}'.format(p=password))
encoded_password = ''
for c in password:
encoded_password += encode_character(char=c)
log.debug('Encoded password: {p}'.format(p=encoded_password))
return encoded_password | python | def encode_password(password):
"""Performs URL encoding for passwords
:param password: (str) password to encode
:return: (str) encoded password
"""
log = logging.getLogger(mod_logger + '.password_encoder')
log.debug('Encoding password: {p}'.format(p=password))
encoded_password = ''
for c in password:
encoded_password += encode_character(char=c)
log.debug('Encoded password: {p}'.format(p=encoded_password))
return encoded_password | [
"def",
"encode_password",
"(",
"password",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.password_encoder'",
")",
"log",
".",
"debug",
"(",
"'Encoding password: {p}'",
".",
"format",
"(",
"p",
"=",
"password",
")",
")",
"encoded_password",
"=",
"''",
"for",
"c",
"in",
"password",
":",
"encoded_password",
"+=",
"encode_character",
"(",
"char",
"=",
"c",
")",
"log",
".",
"debug",
"(",
"'Encoded password: {p}'",
".",
"format",
"(",
"p",
"=",
"encoded_password",
")",
")",
"return",
"encoded_password"
] | Performs URL encoding for passwords
:param password: (str) password to encode
:return: (str) encoded password | [
"Performs",
"URL",
"encoding",
"for",
"passwords"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/pygit.py#L137-L149 |
cons3rt/pycons3rt | pycons3rt/pygit.py | encode_character | def encode_character(char):
"""Returns URL encoding for a single character
:param char (str) Single character to encode
:returns (str) URL-encoded character
"""
if char == '!': return '%21'
elif char == '"': return '%22'
elif char == '#': return '%23'
elif char == '$': return '%24'
elif char == '%': return '%25'
elif char == '&': return '%26'
elif char == '\'': return '%27'
elif char == '(': return '%28'
elif char == ')': return '%29'
elif char == '*': return '%2A'
elif char == '+': return '%2B'
elif char == ',': return '%2C'
elif char == '-': return '%2D'
elif char == '.': return '%2E'
elif char == '/': return '%2F'
elif char == ':': return '%3A'
elif char == ';': return '%3B'
elif char == '<': return '%3C'
elif char == '=': return '%3D'
elif char == '>': return '%3E'
elif char == '?': return '%3F'
elif char == '@': return '%40'
elif char == '[': return '%5B'
elif char == '\\': return '%5C'
elif char == ']': return '%5D'
elif char == '^': return '%5E'
elif char == '_': return '%5F'
elif char == '`': return '%60'
elif char == '{': return '%7B'
elif char == '|': return '%7C'
elif char == '}': return '%7D'
elif char == '~': return '%7E'
elif char == ' ': return '%7F'
else: return char | python | def encode_character(char):
"""Returns URL encoding for a single character
:param char (str) Single character to encode
:returns (str) URL-encoded character
"""
if char == '!': return '%21'
elif char == '"': return '%22'
elif char == '#': return '%23'
elif char == '$': return '%24'
elif char == '%': return '%25'
elif char == '&': return '%26'
elif char == '\'': return '%27'
elif char == '(': return '%28'
elif char == ')': return '%29'
elif char == '*': return '%2A'
elif char == '+': return '%2B'
elif char == ',': return '%2C'
elif char == '-': return '%2D'
elif char == '.': return '%2E'
elif char == '/': return '%2F'
elif char == ':': return '%3A'
elif char == ';': return '%3B'
elif char == '<': return '%3C'
elif char == '=': return '%3D'
elif char == '>': return '%3E'
elif char == '?': return '%3F'
elif char == '@': return '%40'
elif char == '[': return '%5B'
elif char == '\\': return '%5C'
elif char == ']': return '%5D'
elif char == '^': return '%5E'
elif char == '_': return '%5F'
elif char == '`': return '%60'
elif char == '{': return '%7B'
elif char == '|': return '%7C'
elif char == '}': return '%7D'
elif char == '~': return '%7E'
elif char == ' ': return '%7F'
else: return char | [
"def",
"encode_character",
"(",
"char",
")",
":",
"if",
"char",
"==",
"'!'",
":",
"return",
"'%21'",
"elif",
"char",
"==",
"'\"'",
":",
"return",
"'%22'",
"elif",
"char",
"==",
"'#'",
":",
"return",
"'%23'",
"elif",
"char",
"==",
"'$'",
":",
"return",
"'%24'",
"elif",
"char",
"==",
"'%'",
":",
"return",
"'%25'",
"elif",
"char",
"==",
"'&'",
":",
"return",
"'%26'",
"elif",
"char",
"==",
"'\\''",
":",
"return",
"'%27'",
"elif",
"char",
"==",
"'('",
":",
"return",
"'%28'",
"elif",
"char",
"==",
"')'",
":",
"return",
"'%29'",
"elif",
"char",
"==",
"'*'",
":",
"return",
"'%2A'",
"elif",
"char",
"==",
"'+'",
":",
"return",
"'%2B'",
"elif",
"char",
"==",
"','",
":",
"return",
"'%2C'",
"elif",
"char",
"==",
"'-'",
":",
"return",
"'%2D'",
"elif",
"char",
"==",
"'.'",
":",
"return",
"'%2E'",
"elif",
"char",
"==",
"'/'",
":",
"return",
"'%2F'",
"elif",
"char",
"==",
"':'",
":",
"return",
"'%3A'",
"elif",
"char",
"==",
"';'",
":",
"return",
"'%3B'",
"elif",
"char",
"==",
"'<'",
":",
"return",
"'%3C'",
"elif",
"char",
"==",
"'='",
":",
"return",
"'%3D'",
"elif",
"char",
"==",
"'>'",
":",
"return",
"'%3E'",
"elif",
"char",
"==",
"'?'",
":",
"return",
"'%3F'",
"elif",
"char",
"==",
"'@'",
":",
"return",
"'%40'",
"elif",
"char",
"==",
"'['",
":",
"return",
"'%5B'",
"elif",
"char",
"==",
"'\\\\'",
":",
"return",
"'%5C'",
"elif",
"char",
"==",
"']'",
":",
"return",
"'%5D'",
"elif",
"char",
"==",
"'^'",
":",
"return",
"'%5E'",
"elif",
"char",
"==",
"'_'",
":",
"return",
"'%5F'",
"elif",
"char",
"==",
"'`'",
":",
"return",
"'%60'",
"elif",
"char",
"==",
"'{'",
":",
"return",
"'%7B'",
"elif",
"char",
"==",
"'|'",
":",
"return",
"'%7C'",
"elif",
"char",
"==",
"'}'",
":",
"return",
"'%7D'",
"elif",
"char",
"==",
"'~'",
":",
"return",
"'%7E'",
"elif",
"char",
"==",
"' '",
":",
"return",
"'%7F'",
"else",
":",
"return",
"char"
] | Returns URL encoding for a single character
:param char (str) Single character to encode
:returns (str) URL-encoded character | [
"Returns",
"URL",
"encoding",
"for",
"a",
"single",
"character"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/pygit.py#L152-L191 |
isogeo/isogeo-api-py-minsdk | isogeo_pysdk/samples/results_parser.py | search_tags_as_filters | def search_tags_as_filters(tags):
"""Get different tags as dicts ready to use as dropdown lists."""
# set dicts
actions = {}
contacts = {}
formats = {}
inspire = {}
keywords = {}
licenses = {}
md_types = dict()
owners = defaultdict(str)
srs = {}
unused = {}
# 0/1 values
compliance = 0
type_dataset = 0
# parsing tags
print(len(tags.keys()))
i = 0
for tag in sorted(tags.keys()):
i += 1
# actions
if tag.startswith("action"):
actions[tags.get(tag, tag)] = tag
continue
# compliance INSPIRE
elif tag.startswith("conformity"):
compliance = 1
continue
# contacts
elif tag.startswith("contact"):
contacts[tags.get(tag)] = tag
continue
# formats
elif tag.startswith("format"):
formats[tags.get(tag)] = tag
continue
# INSPIRE themes
elif tag.startswith("keyword:inspire"):
inspire[tags.get(tag)] = tag
continue
# keywords
elif tag.startswith("keyword:isogeo"):
keywords[tags.get(tag)] = tag
continue
# licenses
elif tag.startswith("license"):
licenses[tags.get(tag)] = tag
continue
# owners
elif tag.startswith("owner"):
owners[tags.get(tag)] = tag
continue
# SRS
elif tag.startswith("coordinate-system"):
srs[tags.get(tag)] = tag
continue
# types
elif tag.startswith("type"):
md_types[tags.get(tag)] = tag
if tag in ("type:vector-dataset", "type:raster-dataset"):
type_dataset += 1
else:
pass
continue
# ignored tags
else:
unused[tags.get(tag)] = tag
continue
# override API tags to allow all datasets filter - see #
if type_dataset == 2:
md_types["Donnée"] = "type:dataset"
else:
pass
# printing
# print("There are:"
# "\n{} actions"
# "\n{} contacts"
# "\n{} formats"
# "\n{} INSPIRE themes"
# "\n{} keywords"
# "\n{} licenses"
# "\n{} owners"
# "\n{} SRS"
# "\n{} types"
# "\n{} unused".format(len(actions),
# len(contacts),
# len(formats),
# len(inspire),
# len(keywords),
# len(licenses),
# len(owners),
# len(srs),
# len(md_types),
# len(unused)
# ))
# storing dicts
tags_parsed = {
"actions": actions,
"compliance": compliance,
"contacts": contacts,
"formats": formats,
"inspire": inspire,
"keywords": keywords,
"licenses": licenses,
"owners": owners,
"srs": srs,
"types": md_types,
"unused": unused,
}
# method ending
return tags_parsed | python | def search_tags_as_filters(tags):
"""Get different tags as dicts ready to use as dropdown lists."""
# set dicts
actions = {}
contacts = {}
formats = {}
inspire = {}
keywords = {}
licenses = {}
md_types = dict()
owners = defaultdict(str)
srs = {}
unused = {}
# 0/1 values
compliance = 0
type_dataset = 0
# parsing tags
print(len(tags.keys()))
i = 0
for tag in sorted(tags.keys()):
i += 1
# actions
if tag.startswith("action"):
actions[tags.get(tag, tag)] = tag
continue
# compliance INSPIRE
elif tag.startswith("conformity"):
compliance = 1
continue
# contacts
elif tag.startswith("contact"):
contacts[tags.get(tag)] = tag
continue
# formats
elif tag.startswith("format"):
formats[tags.get(tag)] = tag
continue
# INSPIRE themes
elif tag.startswith("keyword:inspire"):
inspire[tags.get(tag)] = tag
continue
# keywords
elif tag.startswith("keyword:isogeo"):
keywords[tags.get(tag)] = tag
continue
# licenses
elif tag.startswith("license"):
licenses[tags.get(tag)] = tag
continue
# owners
elif tag.startswith("owner"):
owners[tags.get(tag)] = tag
continue
# SRS
elif tag.startswith("coordinate-system"):
srs[tags.get(tag)] = tag
continue
# types
elif tag.startswith("type"):
md_types[tags.get(tag)] = tag
if tag in ("type:vector-dataset", "type:raster-dataset"):
type_dataset += 1
else:
pass
continue
# ignored tags
else:
unused[tags.get(tag)] = tag
continue
# override API tags to allow all datasets filter - see #
if type_dataset == 2:
md_types["Donnée"] = "type:dataset"
else:
pass
# printing
# print("There are:"
# "\n{} actions"
# "\n{} contacts"
# "\n{} formats"
# "\n{} INSPIRE themes"
# "\n{} keywords"
# "\n{} licenses"
# "\n{} owners"
# "\n{} SRS"
# "\n{} types"
# "\n{} unused".format(len(actions),
# len(contacts),
# len(formats),
# len(inspire),
# len(keywords),
# len(licenses),
# len(owners),
# len(srs),
# len(md_types),
# len(unused)
# ))
# storing dicts
tags_parsed = {
"actions": actions,
"compliance": compliance,
"contacts": contacts,
"formats": formats,
"inspire": inspire,
"keywords": keywords,
"licenses": licenses,
"owners": owners,
"srs": srs,
"types": md_types,
"unused": unused,
}
# method ending
return tags_parsed | [
"def",
"search_tags_as_filters",
"(",
"tags",
")",
":",
"# set dicts",
"actions",
"=",
"{",
"}",
"contacts",
"=",
"{",
"}",
"formats",
"=",
"{",
"}",
"inspire",
"=",
"{",
"}",
"keywords",
"=",
"{",
"}",
"licenses",
"=",
"{",
"}",
"md_types",
"=",
"dict",
"(",
")",
"owners",
"=",
"defaultdict",
"(",
"str",
")",
"srs",
"=",
"{",
"}",
"unused",
"=",
"{",
"}",
"# 0/1 values",
"compliance",
"=",
"0",
"type_dataset",
"=",
"0",
"# parsing tags",
"print",
"(",
"len",
"(",
"tags",
".",
"keys",
"(",
")",
")",
")",
"i",
"=",
"0",
"for",
"tag",
"in",
"sorted",
"(",
"tags",
".",
"keys",
"(",
")",
")",
":",
"i",
"+=",
"1",
"# actions",
"if",
"tag",
".",
"startswith",
"(",
"\"action\"",
")",
":",
"actions",
"[",
"tags",
".",
"get",
"(",
"tag",
",",
"tag",
")",
"]",
"=",
"tag",
"continue",
"# compliance INSPIRE",
"elif",
"tag",
".",
"startswith",
"(",
"\"conformity\"",
")",
":",
"compliance",
"=",
"1",
"continue",
"# contacts",
"elif",
"tag",
".",
"startswith",
"(",
"\"contact\"",
")",
":",
"contacts",
"[",
"tags",
".",
"get",
"(",
"tag",
")",
"]",
"=",
"tag",
"continue",
"# formats",
"elif",
"tag",
".",
"startswith",
"(",
"\"format\"",
")",
":",
"formats",
"[",
"tags",
".",
"get",
"(",
"tag",
")",
"]",
"=",
"tag",
"continue",
"# INSPIRE themes",
"elif",
"tag",
".",
"startswith",
"(",
"\"keyword:inspire\"",
")",
":",
"inspire",
"[",
"tags",
".",
"get",
"(",
"tag",
")",
"]",
"=",
"tag",
"continue",
"# keywords",
"elif",
"tag",
".",
"startswith",
"(",
"\"keyword:isogeo\"",
")",
":",
"keywords",
"[",
"tags",
".",
"get",
"(",
"tag",
")",
"]",
"=",
"tag",
"continue",
"# licenses",
"elif",
"tag",
".",
"startswith",
"(",
"\"license\"",
")",
":",
"licenses",
"[",
"tags",
".",
"get",
"(",
"tag",
")",
"]",
"=",
"tag",
"continue",
"# owners",
"elif",
"tag",
".",
"startswith",
"(",
"\"owner\"",
")",
":",
"owners",
"[",
"tags",
".",
"get",
"(",
"tag",
")",
"]",
"=",
"tag",
"continue",
"# SRS",
"elif",
"tag",
".",
"startswith",
"(",
"\"coordinate-system\"",
")",
":",
"srs",
"[",
"tags",
".",
"get",
"(",
"tag",
")",
"]",
"=",
"tag",
"continue",
"# types",
"elif",
"tag",
".",
"startswith",
"(",
"\"type\"",
")",
":",
"md_types",
"[",
"tags",
".",
"get",
"(",
"tag",
")",
"]",
"=",
"tag",
"if",
"tag",
"in",
"(",
"\"type:vector-dataset\"",
",",
"\"type:raster-dataset\"",
")",
":",
"type_dataset",
"+=",
"1",
"else",
":",
"pass",
"continue",
"# ignored tags",
"else",
":",
"unused",
"[",
"tags",
".",
"get",
"(",
"tag",
")",
"]",
"=",
"tag",
"continue",
"# override API tags to allow all datasets filter - see #",
"if",
"type_dataset",
"==",
"2",
":",
"md_types",
"[",
"\"Donnée\"]",
" ",
" ",
"type:dataset\"",
"else",
":",
"pass",
"# printing",
"# print(\"There are:\"",
"# \"\\n{} actions\"",
"# \"\\n{} contacts\"",
"# \"\\n{} formats\"",
"# \"\\n{} INSPIRE themes\"",
"# \"\\n{} keywords\"",
"# \"\\n{} licenses\"",
"# \"\\n{} owners\"",
"# \"\\n{} SRS\"",
"# \"\\n{} types\"",
"# \"\\n{} unused\".format(len(actions),",
"# len(contacts),",
"# len(formats),",
"# len(inspire),",
"# len(keywords),",
"# len(licenses),",
"# len(owners),",
"# len(srs),",
"# len(md_types),",
"# len(unused)",
"# ))",
"# storing dicts",
"tags_parsed",
"=",
"{",
"\"actions\"",
":",
"actions",
",",
"\"compliance\"",
":",
"compliance",
",",
"\"contacts\"",
":",
"contacts",
",",
"\"formats\"",
":",
"formats",
",",
"\"inspire\"",
":",
"inspire",
",",
"\"keywords\"",
":",
"keywords",
",",
"\"licenses\"",
":",
"licenses",
",",
"\"owners\"",
":",
"owners",
",",
"\"srs\"",
":",
"srs",
",",
"\"types\"",
":",
"md_types",
",",
"\"unused\"",
":",
"unused",
",",
"}",
"# method ending",
"return",
"tags_parsed"
] | Get different tags as dicts ready to use as dropdown lists. | [
"Get",
"different",
"tags",
"as",
"dicts",
"ready",
"to",
"use",
"as",
"dropdown",
"lists",
"."
] | train | https://github.com/isogeo/isogeo-api-py-minsdk/blob/57a604be92c7767b26abd247012cc1a584b386a0/isogeo_pysdk/samples/results_parser.py#L28-L141 |
ktsstudio/tornkts | tornkts/modules/verification/verification_model.py | Verification.generate | def generate(self, verified, keygen):
"""
:param verified: телефон или email (verified_entity)
:param keygen: функция генерации ключа
:return:
"""
return Verification(
verified_entity=verified,
key=keygen(),
verified=False
) | python | def generate(self, verified, keygen):
"""
:param verified: телефон или email (verified_entity)
:param keygen: функция генерации ключа
:return:
"""
return Verification(
verified_entity=verified,
key=keygen(),
verified=False
) | [
"def",
"generate",
"(",
"self",
",",
"verified",
",",
"keygen",
")",
":",
"return",
"Verification",
"(",
"verified_entity",
"=",
"verified",
",",
"key",
"=",
"keygen",
"(",
")",
",",
"verified",
"=",
"False",
")"
] | :param verified: телефон или email (verified_entity)
:param keygen: функция генерации ключа
:return: | [
":",
"param",
"verified",
":",
"телефон",
"или",
"email",
"(",
"verified_entity",
")",
":",
"param",
"keygen",
":",
"функция",
"генерации",
"ключа",
":",
"return",
":"
] | train | https://github.com/ktsstudio/tornkts/blob/db47e4550426282960a7e4486dcc4399c8d52e02/tornkts/modules/verification/verification_model.py#L12-L22 |
kajala/django-jutil | jutil/validators.py | iban_bank_info | def iban_bank_info(v: str) -> (str, str):
"""
Returns BIC code and bank name from IBAN number.
:param v: IBAN account number
:return: (BIC code, bank name) or ('', '') if not found / unsupported country
"""
v = iban_filter(v)
if v[:2] == 'FI':
return fi_iban_bank_info(v)
else:
return '', '' | python | def iban_bank_info(v: str) -> (str, str):
"""
Returns BIC code and bank name from IBAN number.
:param v: IBAN account number
:return: (BIC code, bank name) or ('', '') if not found / unsupported country
"""
v = iban_filter(v)
if v[:2] == 'FI':
return fi_iban_bank_info(v)
else:
return '', '' | [
"def",
"iban_bank_info",
"(",
"v",
":",
"str",
")",
"->",
"(",
"str",
",",
"str",
")",
":",
"v",
"=",
"iban_filter",
"(",
"v",
")",
"if",
"v",
"[",
":",
"2",
"]",
"==",
"'FI'",
":",
"return",
"fi_iban_bank_info",
"(",
"v",
")",
"else",
":",
"return",
"''",
",",
"''"
] | Returns BIC code and bank name from IBAN number.
:param v: IBAN account number
:return: (BIC code, bank name) or ('', '') if not found / unsupported country | [
"Returns",
"BIC",
"code",
"and",
"bank",
"name",
"from",
"IBAN",
"number",
".",
":",
"param",
"v",
":",
"IBAN",
"account",
"number",
":",
"return",
":",
"(",
"BIC",
"code",
"bank",
"name",
")",
"or",
"(",
")",
"if",
"not",
"found",
"/",
"unsupported",
"country"
] | train | https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/validators.py#L116-L126 |
kajala/django-jutil | jutil/validators.py | fi_payment_reference_number | def fi_payment_reference_number(num: str):
"""
Appends Finland reference number checksum to existing number.
:param num: At least 3 digits
:return: Number plus checksum
"""
assert isinstance(num, str)
num = STRIP_WHITESPACE.sub('', num)
num = re.sub(r'^0+', '', num)
assert len(num) >= 3
weights = [7, 3, 1]
weighed_sum = 0
numlen = len(num)
for j in range(numlen):
weighed_sum += int(num[numlen - 1 - j]) * weights[j % 3]
return num + str((10 - (weighed_sum % 10)) % 10) | python | def fi_payment_reference_number(num: str):
"""
Appends Finland reference number checksum to existing number.
:param num: At least 3 digits
:return: Number plus checksum
"""
assert isinstance(num, str)
num = STRIP_WHITESPACE.sub('', num)
num = re.sub(r'^0+', '', num)
assert len(num) >= 3
weights = [7, 3, 1]
weighed_sum = 0
numlen = len(num)
for j in range(numlen):
weighed_sum += int(num[numlen - 1 - j]) * weights[j % 3]
return num + str((10 - (weighed_sum % 10)) % 10) | [
"def",
"fi_payment_reference_number",
"(",
"num",
":",
"str",
")",
":",
"assert",
"isinstance",
"(",
"num",
",",
"str",
")",
"num",
"=",
"STRIP_WHITESPACE",
".",
"sub",
"(",
"''",
",",
"num",
")",
"num",
"=",
"re",
".",
"sub",
"(",
"r'^0+'",
",",
"''",
",",
"num",
")",
"assert",
"len",
"(",
"num",
")",
">=",
"3",
"weights",
"=",
"[",
"7",
",",
"3",
",",
"1",
"]",
"weighed_sum",
"=",
"0",
"numlen",
"=",
"len",
"(",
"num",
")",
"for",
"j",
"in",
"range",
"(",
"numlen",
")",
":",
"weighed_sum",
"+=",
"int",
"(",
"num",
"[",
"numlen",
"-",
"1",
"-",
"j",
"]",
")",
"*",
"weights",
"[",
"j",
"%",
"3",
"]",
"return",
"num",
"+",
"str",
"(",
"(",
"10",
"-",
"(",
"weighed_sum",
"%",
"10",
")",
")",
"%",
"10",
")"
] | Appends Finland reference number checksum to existing number.
:param num: At least 3 digits
:return: Number plus checksum | [
"Appends",
"Finland",
"reference",
"number",
"checksum",
"to",
"existing",
"number",
".",
":",
"param",
"num",
":",
"At",
"least",
"3",
"digits",
":",
"return",
":",
"Number",
"plus",
"checksum"
] | train | https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/validators.py#L154-L169 |
kajala/django-jutil | jutil/validators.py | iso_payment_reference_validator | def iso_payment_reference_validator(v: str):
"""
Validates ISO reference number checksum.
:param v: Reference number
"""
num = ''
v = STRIP_WHITESPACE.sub('', v)
for ch in v[4:] + v[0:4]:
x = ord(ch)
if ord('0') <= x <= ord('9'):
num += ch
else:
x -= 55
if x < 10 or x > 35:
raise ValidationError(_('Invalid payment reference: {}').format(v))
num += str(x)
res = Decimal(num) % Decimal('97')
if res != Decimal('1'):
raise ValidationError(_('Invalid payment reference: {}').format(v)) | python | def iso_payment_reference_validator(v: str):
"""
Validates ISO reference number checksum.
:param v: Reference number
"""
num = ''
v = STRIP_WHITESPACE.sub('', v)
for ch in v[4:] + v[0:4]:
x = ord(ch)
if ord('0') <= x <= ord('9'):
num += ch
else:
x -= 55
if x < 10 or x > 35:
raise ValidationError(_('Invalid payment reference: {}').format(v))
num += str(x)
res = Decimal(num) % Decimal('97')
if res != Decimal('1'):
raise ValidationError(_('Invalid payment reference: {}').format(v)) | [
"def",
"iso_payment_reference_validator",
"(",
"v",
":",
"str",
")",
":",
"num",
"=",
"''",
"v",
"=",
"STRIP_WHITESPACE",
".",
"sub",
"(",
"''",
",",
"v",
")",
"for",
"ch",
"in",
"v",
"[",
"4",
":",
"]",
"+",
"v",
"[",
"0",
":",
"4",
"]",
":",
"x",
"=",
"ord",
"(",
"ch",
")",
"if",
"ord",
"(",
"'0'",
")",
"<=",
"x",
"<=",
"ord",
"(",
"'9'",
")",
":",
"num",
"+=",
"ch",
"else",
":",
"x",
"-=",
"55",
"if",
"x",
"<",
"10",
"or",
"x",
">",
"35",
":",
"raise",
"ValidationError",
"(",
"_",
"(",
"'Invalid payment reference: {}'",
")",
".",
"format",
"(",
"v",
")",
")",
"num",
"+=",
"str",
"(",
"x",
")",
"res",
"=",
"Decimal",
"(",
"num",
")",
"%",
"Decimal",
"(",
"'97'",
")",
"if",
"res",
"!=",
"Decimal",
"(",
"'1'",
")",
":",
"raise",
"ValidationError",
"(",
"_",
"(",
"'Invalid payment reference: {}'",
")",
".",
"format",
"(",
"v",
")",
")"
] | Validates ISO reference number checksum.
:param v: Reference number | [
"Validates",
"ISO",
"reference",
"number",
"checksum",
".",
":",
"param",
"v",
":",
"Reference",
"number"
] | train | https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/validators.py#L178-L196 |
kajala/django-jutil | jutil/validators.py | fi_iban_bank_info | def fi_iban_bank_info(v: str) -> (str, str):
"""
Returns BIC code and bank name from FI IBAN number.
:param v: IBAN account number
:return: (BIC code, bank name) or ('', '') if not found
"""
from jutil.bank_const_fi import FI_BIC_BY_ACCOUNT_NUMBER, FI_BANK_NAME_BY_BIC
v = iban_filter(v)
bic = FI_BIC_BY_ACCOUNT_NUMBER.get(v[4:7], None)
return (bic, FI_BANK_NAME_BY_BIC[bic]) if bic is not None else ('', '') | python | def fi_iban_bank_info(v: str) -> (str, str):
"""
Returns BIC code and bank name from FI IBAN number.
:param v: IBAN account number
:return: (BIC code, bank name) or ('', '') if not found
"""
from jutil.bank_const_fi import FI_BIC_BY_ACCOUNT_NUMBER, FI_BANK_NAME_BY_BIC
v = iban_filter(v)
bic = FI_BIC_BY_ACCOUNT_NUMBER.get(v[4:7], None)
return (bic, FI_BANK_NAME_BY_BIC[bic]) if bic is not None else ('', '') | [
"def",
"fi_iban_bank_info",
"(",
"v",
":",
"str",
")",
"->",
"(",
"str",
",",
"str",
")",
":",
"from",
"jutil",
".",
"bank_const_fi",
"import",
"FI_BIC_BY_ACCOUNT_NUMBER",
",",
"FI_BANK_NAME_BY_BIC",
"v",
"=",
"iban_filter",
"(",
"v",
")",
"bic",
"=",
"FI_BIC_BY_ACCOUNT_NUMBER",
".",
"get",
"(",
"v",
"[",
"4",
":",
"7",
"]",
",",
"None",
")",
"return",
"(",
"bic",
",",
"FI_BANK_NAME_BY_BIC",
"[",
"bic",
"]",
")",
"if",
"bic",
"is",
"not",
"None",
"else",
"(",
"''",
",",
"''",
")"
] | Returns BIC code and bank name from FI IBAN number.
:param v: IBAN account number
:return: (BIC code, bank name) or ('', '') if not found | [
"Returns",
"BIC",
"code",
"and",
"bank",
"name",
"from",
"FI",
"IBAN",
"number",
".",
":",
"param",
"v",
":",
"IBAN",
"account",
"number",
":",
"return",
":",
"(",
"BIC",
"code",
"bank",
"name",
")",
"or",
"(",
")",
"if",
"not",
"found"
] | train | https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/validators.py#L203-L212 |
kajala/django-jutil | jutil/validators.py | se_clearing_code_bank_info | def se_clearing_code_bank_info(clearing: str) -> (str, int):
"""
Returns Sweden bank info by clearning code.
:param clearing: 4-digit clearing code
:return: (Bank name, account digit count) or ('', None) if not found
"""
from jutil.bank_const_se import SE_BANK_CLEARING_LIST
for name, begin, end, acc_digits in SE_BANK_CLEARING_LIST:
if begin <= clearing <= end:
return name, acc_digits
return '', None | python | def se_clearing_code_bank_info(clearing: str) -> (str, int):
"""
Returns Sweden bank info by clearning code.
:param clearing: 4-digit clearing code
:return: (Bank name, account digit count) or ('', None) if not found
"""
from jutil.bank_const_se import SE_BANK_CLEARING_LIST
for name, begin, end, acc_digits in SE_BANK_CLEARING_LIST:
if begin <= clearing <= end:
return name, acc_digits
return '', None | [
"def",
"se_clearing_code_bank_info",
"(",
"clearing",
":",
"str",
")",
"->",
"(",
"str",
",",
"int",
")",
":",
"from",
"jutil",
".",
"bank_const_se",
"import",
"SE_BANK_CLEARING_LIST",
"for",
"name",
",",
"begin",
",",
"end",
",",
"acc_digits",
"in",
"SE_BANK_CLEARING_LIST",
":",
"if",
"begin",
"<=",
"clearing",
"<=",
"end",
":",
"return",
"name",
",",
"acc_digits",
"return",
"''",
",",
"None"
] | Returns Sweden bank info by clearning code.
:param clearing: 4-digit clearing code
:return: (Bank name, account digit count) or ('', None) if not found | [
"Returns",
"Sweden",
"bank",
"info",
"by",
"clearning",
"code",
".",
":",
"param",
"clearing",
":",
"4",
"-",
"digit",
"clearing",
"code",
":",
"return",
":",
"(",
"Bank",
"name",
"account",
"digit",
"count",
")",
"or",
"(",
"None",
")",
"if",
"not",
"found"
] | train | https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/validators.py#L323-L333 |
Vital-Fernandez/dazer | bin/lib/Astro_Libraries/spectrum_fitting/plot_tools.py | _histplot_bins | def _histplot_bins(column, bins=100):
"""Helper to get bins for histplot."""
col_min = np.min(column)
col_max = np.max(column)
return range(col_min, col_max + 2, max((col_max - col_min) // bins, 1)) | python | def _histplot_bins(column, bins=100):
"""Helper to get bins for histplot."""
col_min = np.min(column)
col_max = np.max(column)
return range(col_min, col_max + 2, max((col_max - col_min) // bins, 1)) | [
"def",
"_histplot_bins",
"(",
"column",
",",
"bins",
"=",
"100",
")",
":",
"col_min",
"=",
"np",
".",
"min",
"(",
"column",
")",
"col_max",
"=",
"np",
".",
"max",
"(",
"column",
")",
"return",
"range",
"(",
"col_min",
",",
"col_max",
"+",
"2",
",",
"max",
"(",
"(",
"col_max",
"-",
"col_min",
")",
"//",
"bins",
",",
"1",
")",
")"
] | Helper to get bins for histplot. | [
"Helper",
"to",
"get",
"bins",
"for",
"histplot",
"."
] | train | https://github.com/Vital-Fernandez/dazer/blob/3c9ae8ae6d40ea33f22cc20dc11365d6d6e65244/bin/lib/Astro_Libraries/spectrum_fitting/plot_tools.py#L27-L31 |
jaredLunde/vital-tools | vital/tools/http.py | http_date | def http_date(value):
""" Formats the @value in required HTTP style
@value: :class:datetime.datetime, #int, #float, #str time-like object
-> #str HTTP-style formatted date
(c)2014, Marcel Hellkamp
"""
if isinstance(value, datetime.datetime):
value = value.utctimetuple()
elif isinstance(value, (int, float)):
value = time.gmtime(value)
if not isinstance(value, str):
value = time.strftime("%a, %d %b %Y %H:%M:%S GMT", value)
return value | python | def http_date(value):
""" Formats the @value in required HTTP style
@value: :class:datetime.datetime, #int, #float, #str time-like object
-> #str HTTP-style formatted date
(c)2014, Marcel Hellkamp
"""
if isinstance(value, datetime.datetime):
value = value.utctimetuple()
elif isinstance(value, (int, float)):
value = time.gmtime(value)
if not isinstance(value, str):
value = time.strftime("%a, %d %b %Y %H:%M:%S GMT", value)
return value | [
"def",
"http_date",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"datetime",
".",
"datetime",
")",
":",
"value",
"=",
"value",
".",
"utctimetuple",
"(",
")",
"elif",
"isinstance",
"(",
"value",
",",
"(",
"int",
",",
"float",
")",
")",
":",
"value",
"=",
"time",
".",
"gmtime",
"(",
"value",
")",
"if",
"not",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"value",
"=",
"time",
".",
"strftime",
"(",
"\"%a, %d %b %Y %H:%M:%S GMT\"",
",",
"value",
")",
"return",
"value"
] | Formats the @value in required HTTP style
@value: :class:datetime.datetime, #int, #float, #str time-like object
-> #str HTTP-style formatted date
(c)2014, Marcel Hellkamp | [
"Formats",
"the",
"@value",
"in",
"required",
"HTTP",
"style"
] | train | https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/tools/http.py#L25-L40 |
jaredLunde/vital-tools | vital/tools/http.py | parse_auth | def parse_auth(header):
""" Parse rfc2617 HTTP authentication header string (basic) and return
(user,pass) tuple or None
(c)2014, Marcel Hellkamp
"""
try:
method, data = header.split(None, 1)
if method.lower() == 'basic':
data = base64.b64decode(uniorbytes(data, bytes))
user, pwd = uniorbytes(data).split(':', 1)
return user, pwd
except (KeyError, AttributeError, ValueError):
return (None, None) | python | def parse_auth(header):
""" Parse rfc2617 HTTP authentication header string (basic) and return
(user,pass) tuple or None
(c)2014, Marcel Hellkamp
"""
try:
method, data = header.split(None, 1)
if method.lower() == 'basic':
data = base64.b64decode(uniorbytes(data, bytes))
user, pwd = uniorbytes(data).split(':', 1)
return user, pwd
except (KeyError, AttributeError, ValueError):
return (None, None) | [
"def",
"parse_auth",
"(",
"header",
")",
":",
"try",
":",
"method",
",",
"data",
"=",
"header",
".",
"split",
"(",
"None",
",",
"1",
")",
"if",
"method",
".",
"lower",
"(",
")",
"==",
"'basic'",
":",
"data",
"=",
"base64",
".",
"b64decode",
"(",
"uniorbytes",
"(",
"data",
",",
"bytes",
")",
")",
"user",
",",
"pwd",
"=",
"uniorbytes",
"(",
"data",
")",
".",
"split",
"(",
"':'",
",",
"1",
")",
"return",
"user",
",",
"pwd",
"except",
"(",
"KeyError",
",",
"AttributeError",
",",
"ValueError",
")",
":",
"return",
"(",
"None",
",",
"None",
")"
] | Parse rfc2617 HTTP authentication header string (basic) and return
(user,pass) tuple or None
(c)2014, Marcel Hellkamp | [
"Parse",
"rfc2617",
"HTTP",
"authentication",
"header",
"string",
"(",
"basic",
")",
"and",
"return",
"(",
"user",
"pass",
")",
"tuple",
"or",
"None",
"(",
"c",
")",
"2014",
"Marcel",
"Hellkamp"
] | train | https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/tools/http.py#L54-L66 |
azaghal/django-pydenticon | django_pydenticon/views.py | image | def image(request, data):
"""
Generates identicon image based on passed data.
Arguments:
data - Data which should be used for generating an identicon. This data
will be used in order to create a digest which is used for generating the
identicon. If the data passed is a hex digest already, the digest will be
used as-is.
Returns:
Identicon image in raw format.
"""
# Get image width, height, padding, and format from GET parameters, or
# fall-back to default values from settings.
try:
width = int(request.GET.get("w", PYDENTICON_WIDTH))
except ValueError:
raise SuspiciousOperation("Identicon width must be a positive integer.")
try:
height = int(request.GET.get("h", PYDENTICON_HEIGHT))
except ValueError:
raise SuspiciousOperation("Identicon height must be a positive integer.")
output_format = request.GET.get("f", PYDENTICON_FORMAT)
try:
padding = [int(p) for p in request.GET["p"].split(",")]
except KeyError:
padding = PYDENTICON_PADDING
except ValueError:
raise SuspiciousOperation("Identicon padding must consist out of 4 positive integers separated with commas.")
if "i" in request.GET:
inverted = request.GET.get("i")
if inverted.lower() == "true":
inverted = True
elif inverted.lower() == "false":
inverted = False
else:
raise SuspiciousOperation("Inversion parameter must be a boolean (true/false).")
else:
inverted = PYDENTICON_INVERT
# Validate the input parameters.
if not isinstance(width, int) or width <= 0:
raise SuspiciousOperation("Identicon width must be a positive integer.")
if not isinstance(height, int) or height <= 0:
raise SuspiciousOperation("Identicon height must be a positive integer.")
if not all([isinstance(p, int) and p >= 0 for p in padding]) or len(padding) != 4:
raise SuspiciousOperation("Padding must be a 4-element tuple consisting out of positive integers.")
# Set-up correct content type based on requested identicon format.
if output_format == "png":
content_type = "image/png"
elif output_format == "ascii":
content_type = "text/plain"
else:
raise SuspiciousOperation("Unsupported identicon format requested - '%s' % output_format")
# Initialise a generator.
generator = Generator(PYDENTICON_ROWS, PYDENTICON_COLUMNS,
foreground = PYDENTICON_FOREGROUND, background = PYDENTICON_BACKGROUND,
digest = PYDENTICON_DIGEST)
# Generate the identicion.
content = generator.generate(data, width, height, padding=padding, output_format=output_format, inverted=inverted)
# Create and return the response.
response = HttpResponse(content, content_type=content_type)
return response | python | def image(request, data):
"""
Generates identicon image based on passed data.
Arguments:
data - Data which should be used for generating an identicon. This data
will be used in order to create a digest which is used for generating the
identicon. If the data passed is a hex digest already, the digest will be
used as-is.
Returns:
Identicon image in raw format.
"""
# Get image width, height, padding, and format from GET parameters, or
# fall-back to default values from settings.
try:
width = int(request.GET.get("w", PYDENTICON_WIDTH))
except ValueError:
raise SuspiciousOperation("Identicon width must be a positive integer.")
try:
height = int(request.GET.get("h", PYDENTICON_HEIGHT))
except ValueError:
raise SuspiciousOperation("Identicon height must be a positive integer.")
output_format = request.GET.get("f", PYDENTICON_FORMAT)
try:
padding = [int(p) for p in request.GET["p"].split(",")]
except KeyError:
padding = PYDENTICON_PADDING
except ValueError:
raise SuspiciousOperation("Identicon padding must consist out of 4 positive integers separated with commas.")
if "i" in request.GET:
inverted = request.GET.get("i")
if inverted.lower() == "true":
inverted = True
elif inverted.lower() == "false":
inverted = False
else:
raise SuspiciousOperation("Inversion parameter must be a boolean (true/false).")
else:
inverted = PYDENTICON_INVERT
# Validate the input parameters.
if not isinstance(width, int) or width <= 0:
raise SuspiciousOperation("Identicon width must be a positive integer.")
if not isinstance(height, int) or height <= 0:
raise SuspiciousOperation("Identicon height must be a positive integer.")
if not all([isinstance(p, int) and p >= 0 for p in padding]) or len(padding) != 4:
raise SuspiciousOperation("Padding must be a 4-element tuple consisting out of positive integers.")
# Set-up correct content type based on requested identicon format.
if output_format == "png":
content_type = "image/png"
elif output_format == "ascii":
content_type = "text/plain"
else:
raise SuspiciousOperation("Unsupported identicon format requested - '%s' % output_format")
# Initialise a generator.
generator = Generator(PYDENTICON_ROWS, PYDENTICON_COLUMNS,
foreground = PYDENTICON_FOREGROUND, background = PYDENTICON_BACKGROUND,
digest = PYDENTICON_DIGEST)
# Generate the identicion.
content = generator.generate(data, width, height, padding=padding, output_format=output_format, inverted=inverted)
# Create and return the response.
response = HttpResponse(content, content_type=content_type)
return response | [
"def",
"image",
"(",
"request",
",",
"data",
")",
":",
"# Get image width, height, padding, and format from GET parameters, or",
"# fall-back to default values from settings.",
"try",
":",
"width",
"=",
"int",
"(",
"request",
".",
"GET",
".",
"get",
"(",
"\"w\"",
",",
"PYDENTICON_WIDTH",
")",
")",
"except",
"ValueError",
":",
"raise",
"SuspiciousOperation",
"(",
"\"Identicon width must be a positive integer.\"",
")",
"try",
":",
"height",
"=",
"int",
"(",
"request",
".",
"GET",
".",
"get",
"(",
"\"h\"",
",",
"PYDENTICON_HEIGHT",
")",
")",
"except",
"ValueError",
":",
"raise",
"SuspiciousOperation",
"(",
"\"Identicon height must be a positive integer.\"",
")",
"output_format",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"\"f\"",
",",
"PYDENTICON_FORMAT",
")",
"try",
":",
"padding",
"=",
"[",
"int",
"(",
"p",
")",
"for",
"p",
"in",
"request",
".",
"GET",
"[",
"\"p\"",
"]",
".",
"split",
"(",
"\",\"",
")",
"]",
"except",
"KeyError",
":",
"padding",
"=",
"PYDENTICON_PADDING",
"except",
"ValueError",
":",
"raise",
"SuspiciousOperation",
"(",
"\"Identicon padding must consist out of 4 positive integers separated with commas.\"",
")",
"if",
"\"i\"",
"in",
"request",
".",
"GET",
":",
"inverted",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"\"i\"",
")",
"if",
"inverted",
".",
"lower",
"(",
")",
"==",
"\"true\"",
":",
"inverted",
"=",
"True",
"elif",
"inverted",
".",
"lower",
"(",
")",
"==",
"\"false\"",
":",
"inverted",
"=",
"False",
"else",
":",
"raise",
"SuspiciousOperation",
"(",
"\"Inversion parameter must be a boolean (true/false).\"",
")",
"else",
":",
"inverted",
"=",
"PYDENTICON_INVERT",
"# Validate the input parameters.",
"if",
"not",
"isinstance",
"(",
"width",
",",
"int",
")",
"or",
"width",
"<=",
"0",
":",
"raise",
"SuspiciousOperation",
"(",
"\"Identicon width must be a positive integer.\"",
")",
"if",
"not",
"isinstance",
"(",
"height",
",",
"int",
")",
"or",
"height",
"<=",
"0",
":",
"raise",
"SuspiciousOperation",
"(",
"\"Identicon height must be a positive integer.\"",
")",
"if",
"not",
"all",
"(",
"[",
"isinstance",
"(",
"p",
",",
"int",
")",
"and",
"p",
">=",
"0",
"for",
"p",
"in",
"padding",
"]",
")",
"or",
"len",
"(",
"padding",
")",
"!=",
"4",
":",
"raise",
"SuspiciousOperation",
"(",
"\"Padding must be a 4-element tuple consisting out of positive integers.\"",
")",
"# Set-up correct content type based on requested identicon format.",
"if",
"output_format",
"==",
"\"png\"",
":",
"content_type",
"=",
"\"image/png\"",
"elif",
"output_format",
"==",
"\"ascii\"",
":",
"content_type",
"=",
"\"text/plain\"",
"else",
":",
"raise",
"SuspiciousOperation",
"(",
"\"Unsupported identicon format requested - '%s' % output_format\"",
")",
"# Initialise a generator.",
"generator",
"=",
"Generator",
"(",
"PYDENTICON_ROWS",
",",
"PYDENTICON_COLUMNS",
",",
"foreground",
"=",
"PYDENTICON_FOREGROUND",
",",
"background",
"=",
"PYDENTICON_BACKGROUND",
",",
"digest",
"=",
"PYDENTICON_DIGEST",
")",
"# Generate the identicion.",
"content",
"=",
"generator",
".",
"generate",
"(",
"data",
",",
"width",
",",
"height",
",",
"padding",
"=",
"padding",
",",
"output_format",
"=",
"output_format",
",",
"inverted",
"=",
"inverted",
")",
"# Create and return the response.",
"response",
"=",
"HttpResponse",
"(",
"content",
",",
"content_type",
"=",
"content_type",
")",
"return",
"response"
] | Generates identicon image based on passed data.
Arguments:
data - Data which should be used for generating an identicon. This data
will be used in order to create a digest which is used for generating the
identicon. If the data passed is a hex digest already, the digest will be
used as-is.
Returns:
Identicon image in raw format. | [
"Generates",
"identicon",
"image",
"based",
"on",
"passed",
"data",
"."
] | train | https://github.com/azaghal/django-pydenticon/blob/dd21a87693505614eb5ce1da6ff1b6146d341b2c/django_pydenticon/views.py#L14-L85 |
novopl/peltak | src/peltak/extra/gitflow/commands/hotfix.py | rename | def rename(name):
# type: (str) -> None
""" Give the currently developed hotfix a new name. """
from peltak.extra.gitflow import logic
if name is None:
name = click.prompt('Hotfix name')
logic.hotfix.rename(name) | python | def rename(name):
# type: (str) -> None
""" Give the currently developed hotfix a new name. """
from peltak.extra.gitflow import logic
if name is None:
name = click.prompt('Hotfix name')
logic.hotfix.rename(name) | [
"def",
"rename",
"(",
"name",
")",
":",
"# type: (str) -> None",
"from",
"peltak",
".",
"extra",
".",
"gitflow",
"import",
"logic",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"click",
".",
"prompt",
"(",
"'Hotfix name'",
")",
"logic",
".",
"hotfix",
".",
"rename",
"(",
"name",
")"
] | Give the currently developed hotfix a new name. | [
"Give",
"the",
"currently",
"developed",
"hotfix",
"a",
"new",
"name",
"."
] | train | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/gitflow/commands/hotfix.py#L53-L61 |
jaredLunde/vital-tools | vital/cache/decorators.py | local_lru | def local_lru(obj):
""" Property that maps to a key in a local dict-like attribute.
self._cache must be an OrderedDict
self._cache_size must be defined as LRU size
..
class Foo(object):
def __init__(self, cache_size=5000):
self._cache = OrderedDict()
self._cache_size = cache_size
@local_lru
def expensive_meth(self, arg):
pass
..
"""
@wraps(obj)
def memoizer(*args, **kwargs):
instance = args[0]
lru_size = instance._cache_size
if lru_size:
cache = instance._cache
key = str((args, kwargs))
try:
r = cache.pop(key)
cache[key] = r
except KeyError:
if len(cache) >= lru_size:
cache.popitem(last=False)
r = cache[key] = obj(*args, **kwargs)
return r
return obj(*args, **kwargs)
return memoizer | python | def local_lru(obj):
""" Property that maps to a key in a local dict-like attribute.
self._cache must be an OrderedDict
self._cache_size must be defined as LRU size
..
class Foo(object):
def __init__(self, cache_size=5000):
self._cache = OrderedDict()
self._cache_size = cache_size
@local_lru
def expensive_meth(self, arg):
pass
..
"""
@wraps(obj)
def memoizer(*args, **kwargs):
instance = args[0]
lru_size = instance._cache_size
if lru_size:
cache = instance._cache
key = str((args, kwargs))
try:
r = cache.pop(key)
cache[key] = r
except KeyError:
if len(cache) >= lru_size:
cache.popitem(last=False)
r = cache[key] = obj(*args, **kwargs)
return r
return obj(*args, **kwargs)
return memoizer | [
"def",
"local_lru",
"(",
"obj",
")",
":",
"@",
"wraps",
"(",
"obj",
")",
"def",
"memoizer",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"instance",
"=",
"args",
"[",
"0",
"]",
"lru_size",
"=",
"instance",
".",
"_cache_size",
"if",
"lru_size",
":",
"cache",
"=",
"instance",
".",
"_cache",
"key",
"=",
"str",
"(",
"(",
"args",
",",
"kwargs",
")",
")",
"try",
":",
"r",
"=",
"cache",
".",
"pop",
"(",
"key",
")",
"cache",
"[",
"key",
"]",
"=",
"r",
"except",
"KeyError",
":",
"if",
"len",
"(",
"cache",
")",
">=",
"lru_size",
":",
"cache",
".",
"popitem",
"(",
"last",
"=",
"False",
")",
"r",
"=",
"cache",
"[",
"key",
"]",
"=",
"obj",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"r",
"return",
"obj",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"memoizer"
] | Property that maps to a key in a local dict-like attribute.
self._cache must be an OrderedDict
self._cache_size must be defined as LRU size
..
class Foo(object):
def __init__(self, cache_size=5000):
self._cache = OrderedDict()
self._cache_size = cache_size
@local_lru
def expensive_meth(self, arg):
pass
.. | [
"Property",
"that",
"maps",
"to",
"a",
"key",
"in",
"a",
"local",
"dict",
"-",
"like",
"attribute",
".",
"self",
".",
"_cache",
"must",
"be",
"an",
"OrderedDict",
"self",
".",
"_cache_size",
"must",
"be",
"defined",
"as",
"LRU",
"size",
"..",
"class",
"Foo",
"(",
"object",
")",
":"
] | train | https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/cache/decorators.py#L42-L74 |
jaredLunde/vital-tools | vital/cache/decorators.py | typed_lru | def typed_lru(maxsize, types=None):
""" :func:functools.lru_cache wrapper which allows you to prevent object
types outside of @types from being cached.
The main use case for this is preventing unhashable type errors when
you still want to cache some results.
..
from vital.cache import typed_lru
@typed_lru(300, (str, int))
def some_expensive_func():
pass
@typed_lru(300, str)
def some_expensive_func2():
pass
@typed_lru(300, collections.Hashable)
def some_expensive_func3():
pass
..
"""
types = types or collections.Hashable
def lru(obj):
@lru_cache(maxsize)
def _lru_cache(*args, **kwargs):
return obj(*args, **kwargs)
@wraps(obj)
def _convenience(*args, **kwargs):
broken = False
for arg in args:
if not isinstance(arg, types):
broken = True
break
for arg, val in kwargs.items():
if not isinstance(arg, types) and isinstance(val, types):
broken = True
break
if not broken:
try:
return _lru_cache(*args, **kwargs)
except TypeError:
return obj(*args, **kwargs)
return obj(*args, **kwargs)
return _convenience
return lru | python | def typed_lru(maxsize, types=None):
""" :func:functools.lru_cache wrapper which allows you to prevent object
types outside of @types from being cached.
The main use case for this is preventing unhashable type errors when
you still want to cache some results.
..
from vital.cache import typed_lru
@typed_lru(300, (str, int))
def some_expensive_func():
pass
@typed_lru(300, str)
def some_expensive_func2():
pass
@typed_lru(300, collections.Hashable)
def some_expensive_func3():
pass
..
"""
types = types or collections.Hashable
def lru(obj):
@lru_cache(maxsize)
def _lru_cache(*args, **kwargs):
return obj(*args, **kwargs)
@wraps(obj)
def _convenience(*args, **kwargs):
broken = False
for arg in args:
if not isinstance(arg, types):
broken = True
break
for arg, val in kwargs.items():
if not isinstance(arg, types) and isinstance(val, types):
broken = True
break
if not broken:
try:
return _lru_cache(*args, **kwargs)
except TypeError:
return obj(*args, **kwargs)
return obj(*args, **kwargs)
return _convenience
return lru | [
"def",
"typed_lru",
"(",
"maxsize",
",",
"types",
"=",
"None",
")",
":",
"types",
"=",
"types",
"or",
"collections",
".",
"Hashable",
"def",
"lru",
"(",
"obj",
")",
":",
"@",
"lru_cache",
"(",
"maxsize",
")",
"def",
"_lru_cache",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"obj",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"@",
"wraps",
"(",
"obj",
")",
"def",
"_convenience",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"broken",
"=",
"False",
"for",
"arg",
"in",
"args",
":",
"if",
"not",
"isinstance",
"(",
"arg",
",",
"types",
")",
":",
"broken",
"=",
"True",
"break",
"for",
"arg",
",",
"val",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"not",
"isinstance",
"(",
"arg",
",",
"types",
")",
"and",
"isinstance",
"(",
"val",
",",
"types",
")",
":",
"broken",
"=",
"True",
"break",
"if",
"not",
"broken",
":",
"try",
":",
"return",
"_lru_cache",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"TypeError",
":",
"return",
"obj",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"obj",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"_convenience",
"return",
"lru"
] | :func:functools.lru_cache wrapper which allows you to prevent object
types outside of @types from being cached.
The main use case for this is preventing unhashable type errors when
you still want to cache some results.
..
from vital.cache import typed_lru
@typed_lru(300, (str, int))
def some_expensive_func():
pass
@typed_lru(300, str)
def some_expensive_func2():
pass
@typed_lru(300, collections.Hashable)
def some_expensive_func3():
pass
.. | [
":",
"func",
":",
"functools",
".",
"lru_cache",
"wrapper",
"which",
"allows",
"you",
"to",
"prevent",
"object",
"types",
"outside",
"of",
"@types",
"from",
"being",
"cached",
"."
] | train | https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/cache/decorators.py#L77-L124 |
jaredLunde/vital-tools | vital/cache/decorators.py | local_expiring_lru | def local_expiring_lru(obj):
""" Property that maps to a key in a local dict-like attribute.
self._cache must be an OrderedDict
self._cache_size must be defined as LRU size
self._cache_ttl is the expiration time in seconds
..
class Foo(object):
def __init__(self, cache_size=5000, cache_ttl=600):
self._cache = OrderedDict()
self._cache_size = cache_size
self._cache_ttl = cache_ttl
@local_expiring_lru
def expensive_meth(self, arg):
pass
..
"""
@wraps(obj)
def memoizer(*args, **kwargs):
instance = args[0]
lru_size = instance._cache_size
cache_ttl = instance._cache_ttl
if lru_size and cache_ttl:
cache = instance._cache
kargs = list(args)
kargs[0] = id(instance)
key = str((kargs, kwargs))
try:
r = list(cache.pop(key))
if r[1] < datetime.datetime.utcnow():
r[0] = None
else:
cache[key] = r
except (KeyError, AssertionError):
if len(cache) >= lru_size:
cache.popitem(last=False)
r = cache[key] = (
obj(*args, **kwargs),
datetime.datetime.utcnow() + datetime.timedelta(
seconds=cache_ttl)
)
if r[0]:
return r[0]
return obj(*args, **kwargs)
return memoizer | python | def local_expiring_lru(obj):
""" Property that maps to a key in a local dict-like attribute.
self._cache must be an OrderedDict
self._cache_size must be defined as LRU size
self._cache_ttl is the expiration time in seconds
..
class Foo(object):
def __init__(self, cache_size=5000, cache_ttl=600):
self._cache = OrderedDict()
self._cache_size = cache_size
self._cache_ttl = cache_ttl
@local_expiring_lru
def expensive_meth(self, arg):
pass
..
"""
@wraps(obj)
def memoizer(*args, **kwargs):
instance = args[0]
lru_size = instance._cache_size
cache_ttl = instance._cache_ttl
if lru_size and cache_ttl:
cache = instance._cache
kargs = list(args)
kargs[0] = id(instance)
key = str((kargs, kwargs))
try:
r = list(cache.pop(key))
if r[1] < datetime.datetime.utcnow():
r[0] = None
else:
cache[key] = r
except (KeyError, AssertionError):
if len(cache) >= lru_size:
cache.popitem(last=False)
r = cache[key] = (
obj(*args, **kwargs),
datetime.datetime.utcnow() + datetime.timedelta(
seconds=cache_ttl)
)
if r[0]:
return r[0]
return obj(*args, **kwargs)
return memoizer | [
"def",
"local_expiring_lru",
"(",
"obj",
")",
":",
"@",
"wraps",
"(",
"obj",
")",
"def",
"memoizer",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"instance",
"=",
"args",
"[",
"0",
"]",
"lru_size",
"=",
"instance",
".",
"_cache_size",
"cache_ttl",
"=",
"instance",
".",
"_cache_ttl",
"if",
"lru_size",
"and",
"cache_ttl",
":",
"cache",
"=",
"instance",
".",
"_cache",
"kargs",
"=",
"list",
"(",
"args",
")",
"kargs",
"[",
"0",
"]",
"=",
"id",
"(",
"instance",
")",
"key",
"=",
"str",
"(",
"(",
"kargs",
",",
"kwargs",
")",
")",
"try",
":",
"r",
"=",
"list",
"(",
"cache",
".",
"pop",
"(",
"key",
")",
")",
"if",
"r",
"[",
"1",
"]",
"<",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
":",
"r",
"[",
"0",
"]",
"=",
"None",
"else",
":",
"cache",
"[",
"key",
"]",
"=",
"r",
"except",
"(",
"KeyError",
",",
"AssertionError",
")",
":",
"if",
"len",
"(",
"cache",
")",
">=",
"lru_size",
":",
"cache",
".",
"popitem",
"(",
"last",
"=",
"False",
")",
"r",
"=",
"cache",
"[",
"key",
"]",
"=",
"(",
"obj",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
",",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"+",
"datetime",
".",
"timedelta",
"(",
"seconds",
"=",
"cache_ttl",
")",
")",
"if",
"r",
"[",
"0",
"]",
":",
"return",
"r",
"[",
"0",
"]",
"return",
"obj",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"memoizer"
] | Property that maps to a key in a local dict-like attribute.
self._cache must be an OrderedDict
self._cache_size must be defined as LRU size
self._cache_ttl is the expiration time in seconds
..
class Foo(object):
def __init__(self, cache_size=5000, cache_ttl=600):
self._cache = OrderedDict()
self._cache_size = cache_size
self._cache_ttl = cache_ttl
@local_expiring_lru
def expensive_meth(self, arg):
pass
.. | [
"Property",
"that",
"maps",
"to",
"a",
"key",
"in",
"a",
"local",
"dict",
"-",
"like",
"attribute",
".",
"self",
".",
"_cache",
"must",
"be",
"an",
"OrderedDict",
"self",
".",
"_cache_size",
"must",
"be",
"defined",
"as",
"LRU",
"size",
"self",
".",
"_cache_ttl",
"is",
"the",
"expiration",
"time",
"in",
"seconds",
"..",
"class",
"Foo",
"(",
"object",
")",
":"
] | train | https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/cache/decorators.py#L127-L172 |
novopl/peltak | src/peltak/core/context.py | GlobalContext.get | def get(self, name, *default):
# type: (str, Any) -> Any
""" Get context value with the given name and optional default.
Args:
name (str):
The name of the context value.
*default (Any):
If given and the key doesn't not exist, this will be returned
instead. If it's not given and the context value does not exist,
`AttributeError` will be raised
Returns:
The requested context value. If the value does not exist it will
return `default` if give or raise `AttributeError`.
Raises:
AttributeError: If the value does not exist and `default` was not
given.
"""
curr = self.values
for part in name.split('.'):
if part in curr:
curr = curr[part]
elif default:
return default[0]
else:
fmt = "Context value '{}' does not exist:\n{}"
raise AttributeError(fmt.format(
name, util.yaml_dump(self.values)
))
return curr | python | def get(self, name, *default):
# type: (str, Any) -> Any
""" Get context value with the given name and optional default.
Args:
name (str):
The name of the context value.
*default (Any):
If given and the key doesn't not exist, this will be returned
instead. If it's not given and the context value does not exist,
`AttributeError` will be raised
Returns:
The requested context value. If the value does not exist it will
return `default` if give or raise `AttributeError`.
Raises:
AttributeError: If the value does not exist and `default` was not
given.
"""
curr = self.values
for part in name.split('.'):
if part in curr:
curr = curr[part]
elif default:
return default[0]
else:
fmt = "Context value '{}' does not exist:\n{}"
raise AttributeError(fmt.format(
name, util.yaml_dump(self.values)
))
return curr | [
"def",
"get",
"(",
"self",
",",
"name",
",",
"*",
"default",
")",
":",
"# type: (str, Any) -> Any",
"curr",
"=",
"self",
".",
"values",
"for",
"part",
"in",
"name",
".",
"split",
"(",
"'.'",
")",
":",
"if",
"part",
"in",
"curr",
":",
"curr",
"=",
"curr",
"[",
"part",
"]",
"elif",
"default",
":",
"return",
"default",
"[",
"0",
"]",
"else",
":",
"fmt",
"=",
"\"Context value '{}' does not exist:\\n{}\"",
"raise",
"AttributeError",
"(",
"fmt",
".",
"format",
"(",
"name",
",",
"util",
".",
"yaml_dump",
"(",
"self",
".",
"values",
")",
")",
")",
"return",
"curr"
] | Get context value with the given name and optional default.
Args:
name (str):
The name of the context value.
*default (Any):
If given and the key doesn't not exist, this will be returned
instead. If it's not given and the context value does not exist,
`AttributeError` will be raised
Returns:
The requested context value. If the value does not exist it will
return `default` if give or raise `AttributeError`.
Raises:
AttributeError: If the value does not exist and `default` was not
given. | [
"Get",
"context",
"value",
"with",
"the",
"given",
"name",
"and",
"optional",
"default",
"."
] | train | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/core/context.py#L57-L90 |
novopl/peltak | src/peltak/core/context.py | GlobalContext.set | def set(self, name, value):
""" Set context value.
Args:
name (str):
The name of the context value to change.
value (Any):
The new value for the selected context value
"""
curr = self.values
parts = name.split('.')
for i, part in enumerate(parts[:-1]):
try:
curr = curr.setdefault(part, {})
except AttributeError:
raise InvalidPath('.'.join(parts[:i + 1]))
try:
curr[parts[-1]] = value
except TypeError:
raise InvalidPath('.'.join(parts[:-1])) | python | def set(self, name, value):
""" Set context value.
Args:
name (str):
The name of the context value to change.
value (Any):
The new value for the selected context value
"""
curr = self.values
parts = name.split('.')
for i, part in enumerate(parts[:-1]):
try:
curr = curr.setdefault(part, {})
except AttributeError:
raise InvalidPath('.'.join(parts[:i + 1]))
try:
curr[parts[-1]] = value
except TypeError:
raise InvalidPath('.'.join(parts[:-1])) | [
"def",
"set",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"curr",
"=",
"self",
".",
"values",
"parts",
"=",
"name",
".",
"split",
"(",
"'.'",
")",
"for",
"i",
",",
"part",
"in",
"enumerate",
"(",
"parts",
"[",
":",
"-",
"1",
"]",
")",
":",
"try",
":",
"curr",
"=",
"curr",
".",
"setdefault",
"(",
"part",
",",
"{",
"}",
")",
"except",
"AttributeError",
":",
"raise",
"InvalidPath",
"(",
"'.'",
".",
"join",
"(",
"parts",
"[",
":",
"i",
"+",
"1",
"]",
")",
")",
"try",
":",
"curr",
"[",
"parts",
"[",
"-",
"1",
"]",
"]",
"=",
"value",
"except",
"TypeError",
":",
"raise",
"InvalidPath",
"(",
"'.'",
".",
"join",
"(",
"parts",
"[",
":",
"-",
"1",
"]",
")",
")"
] | Set context value.
Args:
name (str):
The name of the context value to change.
value (Any):
The new value for the selected context value | [
"Set",
"context",
"value",
"."
] | train | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/core/context.py#L92-L113 |
cons3rt/pycons3rt | pycons3rt/pyjavakeys.py | alias_exists | def alias_exists(alias, keystore_path=None, keystore_password='changeit'):
"""Checks if an alias already exists in a keystore
:param alias:
:param keystore_path:
:param keystore_password:
:return: (bool) True when the alias already exists in the keystore
:raises: OSError
"""
log = logging.getLogger(mod_logger + '.alias_exists')
if not isinstance(alias, basestring):
msg = 'alias arg must be a string'
log.error(msg)
raise OSError(msg)
# Ensure JAVA_HOME is set
log.debug('Determining JAVA_HOME...')
try:
java_home = os.environ['JAVA_HOME']
except KeyError:
msg = 'JAVA_HOME is required but not set'
log.error(msg)
raise OSError(msg)
# Ensure keytool can be found
keytool = os.path.join(java_home, 'bin', 'keytool')
if not os.path.isfile(keytool):
msg = 'keytool file not found: {f}'.format(f=keytool)
log.error(msg)
raise OSError(msg)
# Find the cacerts file
if keystore_path is None:
keystore_path = os.path.join(java_home, 'lib', 'security', 'cacerts')
# If the JRE cacerts location is not found, look for the JDK cacerts
if not os.path .isfile(keystore_path):
keystore_path = os.path.join(java_home, 'jre', 'lib', 'security', 'cacerts')
if not os.path.isfile(keystore_path):
msg = 'Unable to file cacerts file'
log.error(msg)
raise OSError(msg)
log.info('Checking keystore {k} for alias: {a}...'.format(k=keystore_path, a=alias))
# Build the keytool command
command = [keytool, '-keystore', keystore_path, '-storepass', keystore_password, '-list']
# Running the keytool list command
log.debug('Running the keytool list command...')
try:
result = run_command(command)
except CommandError:
_, ex, trace = sys.exc_info()
msg = 'There was a problem running keytool on keystore: {k}\n{e}'.format(k=keystore_path, e=str(ex))
log.error(msg)
raise OSError, msg, trace
if result['code'] != 0:
msg = 'keytool command exited with a non-zero code: {c}, and produced output: {o}'.format(
c=result['code'], o=result['output'])
log.error(msg)
raise OSError(msg)
# Check for the alias in the output
if alias in result['output']:
log.info('Found alias {a} in keystore: {k}'.format(a=alias, k=keystore_path))
return True
else:
log.info('Alias {a} was not found in keystore: {k}'.format(a=alias, k=keystore_path))
return False | python | def alias_exists(alias, keystore_path=None, keystore_password='changeit'):
"""Checks if an alias already exists in a keystore
:param alias:
:param keystore_path:
:param keystore_password:
:return: (bool) True when the alias already exists in the keystore
:raises: OSError
"""
log = logging.getLogger(mod_logger + '.alias_exists')
if not isinstance(alias, basestring):
msg = 'alias arg must be a string'
log.error(msg)
raise OSError(msg)
# Ensure JAVA_HOME is set
log.debug('Determining JAVA_HOME...')
try:
java_home = os.environ['JAVA_HOME']
except KeyError:
msg = 'JAVA_HOME is required but not set'
log.error(msg)
raise OSError(msg)
# Ensure keytool can be found
keytool = os.path.join(java_home, 'bin', 'keytool')
if not os.path.isfile(keytool):
msg = 'keytool file not found: {f}'.format(f=keytool)
log.error(msg)
raise OSError(msg)
# Find the cacerts file
if keystore_path is None:
keystore_path = os.path.join(java_home, 'lib', 'security', 'cacerts')
# If the JRE cacerts location is not found, look for the JDK cacerts
if not os.path .isfile(keystore_path):
keystore_path = os.path.join(java_home, 'jre', 'lib', 'security', 'cacerts')
if not os.path.isfile(keystore_path):
msg = 'Unable to file cacerts file'
log.error(msg)
raise OSError(msg)
log.info('Checking keystore {k} for alias: {a}...'.format(k=keystore_path, a=alias))
# Build the keytool command
command = [keytool, '-keystore', keystore_path, '-storepass', keystore_password, '-list']
# Running the keytool list command
log.debug('Running the keytool list command...')
try:
result = run_command(command)
except CommandError:
_, ex, trace = sys.exc_info()
msg = 'There was a problem running keytool on keystore: {k}\n{e}'.format(k=keystore_path, e=str(ex))
log.error(msg)
raise OSError, msg, trace
if result['code'] != 0:
msg = 'keytool command exited with a non-zero code: {c}, and produced output: {o}'.format(
c=result['code'], o=result['output'])
log.error(msg)
raise OSError(msg)
# Check for the alias in the output
if alias in result['output']:
log.info('Found alias {a} in keystore: {k}'.format(a=alias, k=keystore_path))
return True
else:
log.info('Alias {a} was not found in keystore: {k}'.format(a=alias, k=keystore_path))
return False | [
"def",
"alias_exists",
"(",
"alias",
",",
"keystore_path",
"=",
"None",
",",
"keystore_password",
"=",
"'changeit'",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.alias_exists'",
")",
"if",
"not",
"isinstance",
"(",
"alias",
",",
"basestring",
")",
":",
"msg",
"=",
"'alias arg must be a string'",
"log",
".",
"error",
"(",
"msg",
")",
"raise",
"OSError",
"(",
"msg",
")",
"# Ensure JAVA_HOME is set",
"log",
".",
"debug",
"(",
"'Determining JAVA_HOME...'",
")",
"try",
":",
"java_home",
"=",
"os",
".",
"environ",
"[",
"'JAVA_HOME'",
"]",
"except",
"KeyError",
":",
"msg",
"=",
"'JAVA_HOME is required but not set'",
"log",
".",
"error",
"(",
"msg",
")",
"raise",
"OSError",
"(",
"msg",
")",
"# Ensure keytool can be found",
"keytool",
"=",
"os",
".",
"path",
".",
"join",
"(",
"java_home",
",",
"'bin'",
",",
"'keytool'",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"keytool",
")",
":",
"msg",
"=",
"'keytool file not found: {f}'",
".",
"format",
"(",
"f",
"=",
"keytool",
")",
"log",
".",
"error",
"(",
"msg",
")",
"raise",
"OSError",
"(",
"msg",
")",
"# Find the cacerts file",
"if",
"keystore_path",
"is",
"None",
":",
"keystore_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"java_home",
",",
"'lib'",
",",
"'security'",
",",
"'cacerts'",
")",
"# If the JRE cacerts location is not found, look for the JDK cacerts",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"keystore_path",
")",
":",
"keystore_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"java_home",
",",
"'jre'",
",",
"'lib'",
",",
"'security'",
",",
"'cacerts'",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"keystore_path",
")",
":",
"msg",
"=",
"'Unable to file cacerts file'",
"log",
".",
"error",
"(",
"msg",
")",
"raise",
"OSError",
"(",
"msg",
")",
"log",
".",
"info",
"(",
"'Checking keystore {k} for alias: {a}...'",
".",
"format",
"(",
"k",
"=",
"keystore_path",
",",
"a",
"=",
"alias",
")",
")",
"# Build the keytool command",
"command",
"=",
"[",
"keytool",
",",
"'-keystore'",
",",
"keystore_path",
",",
"'-storepass'",
",",
"keystore_password",
",",
"'-list'",
"]",
"# Running the keytool list command",
"log",
".",
"debug",
"(",
"'Running the keytool list command...'",
")",
"try",
":",
"result",
"=",
"run_command",
"(",
"command",
")",
"except",
"CommandError",
":",
"_",
",",
"ex",
",",
"trace",
"=",
"sys",
".",
"exc_info",
"(",
")",
"msg",
"=",
"'There was a problem running keytool on keystore: {k}\\n{e}'",
".",
"format",
"(",
"k",
"=",
"keystore_path",
",",
"e",
"=",
"str",
"(",
"ex",
")",
")",
"log",
".",
"error",
"(",
"msg",
")",
"raise",
"OSError",
",",
"msg",
",",
"trace",
"if",
"result",
"[",
"'code'",
"]",
"!=",
"0",
":",
"msg",
"=",
"'keytool command exited with a non-zero code: {c}, and produced output: {o}'",
".",
"format",
"(",
"c",
"=",
"result",
"[",
"'code'",
"]",
",",
"o",
"=",
"result",
"[",
"'output'",
"]",
")",
"log",
".",
"error",
"(",
"msg",
")",
"raise",
"OSError",
"(",
"msg",
")",
"# Check for the alias in the output",
"if",
"alias",
"in",
"result",
"[",
"'output'",
"]",
":",
"log",
".",
"info",
"(",
"'Found alias {a} in keystore: {k}'",
".",
"format",
"(",
"a",
"=",
"alias",
",",
"k",
"=",
"keystore_path",
")",
")",
"return",
"True",
"else",
":",
"log",
".",
"info",
"(",
"'Alias {a} was not found in keystore: {k}'",
".",
"format",
"(",
"a",
"=",
"alias",
",",
"k",
"=",
"keystore_path",
")",
")",
"return",
"False"
] | Checks if an alias already exists in a keystore
:param alias:
:param keystore_path:
:param keystore_password:
:return: (bool) True when the alias already exists in the keystore
:raises: OSError | [
"Checks",
"if",
"an",
"alias",
"already",
"exists",
"in",
"a",
"keystore"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/pyjavakeys.py#L34-L103 |
MarcAureleCoste/sqla-filters | src/sqla_filters/nodes/base/base.py | TreeNode.filter | def filter(self, query: Query, entity: type) -> Tuple[Query, Any]:
"""Define the filter function that every node must to implement.
:param query: The sqlalchemy query.
:type query: Query
:param entity: The entity model.
:type entity: type
:return: The filtered query.
:rtype: Tuple[Query, Any]
"""
raise NotImplementedError('You must implement this.') | python | def filter(self, query: Query, entity: type) -> Tuple[Query, Any]:
"""Define the filter function that every node must to implement.
:param query: The sqlalchemy query.
:type query: Query
:param entity: The entity model.
:type entity: type
:return: The filtered query.
:rtype: Tuple[Query, Any]
"""
raise NotImplementedError('You must implement this.') | [
"def",
"filter",
"(",
"self",
",",
"query",
":",
"Query",
",",
"entity",
":",
"type",
")",
"->",
"Tuple",
"[",
"Query",
",",
"Any",
"]",
":",
"raise",
"NotImplementedError",
"(",
"'You must implement this.'",
")"
] | Define the filter function that every node must to implement.
:param query: The sqlalchemy query.
:type query: Query
:param entity: The entity model.
:type entity: type
:return: The filtered query.
:rtype: Tuple[Query, Any] | [
"Define",
"the",
"filter",
"function",
"that",
"every",
"node",
"must",
"to",
"implement",
"."
] | train | https://github.com/MarcAureleCoste/sqla-filters/blob/a9596f660a11d275bf0e831ecd9e502b0af2a087/src/sqla_filters/nodes/base/base.py#L50-L62 |
MarcAureleCoste/sqla-filters | src/sqla_filters/nodes/base/base.py | BaseOperationalNode._extract_relations | def _extract_relations(self, attribute: str) -> Tuple[List[str], str]:
"""Split and return the list of relation(s) and the attribute.
:param attribute:
:type attribute: str
:return: A tuple where the first element is the list of related
entities and the second is the attribute.
:rtype: Tuple[List[str], str]
"""
splitted = attribute.split(self._attr_sep)
return (splitted[:-1], splitted[-1]) | python | def _extract_relations(self, attribute: str) -> Tuple[List[str], str]:
"""Split and return the list of relation(s) and the attribute.
:param attribute:
:type attribute: str
:return: A tuple where the first element is the list of related
entities and the second is the attribute.
:rtype: Tuple[List[str], str]
"""
splitted = attribute.split(self._attr_sep)
return (splitted[:-1], splitted[-1]) | [
"def",
"_extract_relations",
"(",
"self",
",",
"attribute",
":",
"str",
")",
"->",
"Tuple",
"[",
"List",
"[",
"str",
"]",
",",
"str",
"]",
":",
"splitted",
"=",
"attribute",
".",
"split",
"(",
"self",
".",
"_attr_sep",
")",
"return",
"(",
"splitted",
"[",
":",
"-",
"1",
"]",
",",
"splitted",
"[",
"-",
"1",
"]",
")"
] | Split and return the list of relation(s) and the attribute.
:param attribute:
:type attribute: str
:return: A tuple where the first element is the list of related
entities and the second is the attribute.
:rtype: Tuple[List[str], str] | [
"Split",
"and",
"return",
"the",
"list",
"of",
"relation",
"(",
"s",
")",
"and",
"the",
"attribute",
"."
] | train | https://github.com/MarcAureleCoste/sqla-filters/blob/a9596f660a11d275bf0e831ecd9e502b0af2a087/src/sqla_filters/nodes/base/base.py#L104-L115 |
MarcAureleCoste/sqla-filters | src/sqla_filters/nodes/base/base.py | BaseOperationalNode._get_relation | def _get_relation(self, related_model: type, relations: List[str]) -> Tuple[Optional[List[type]], Optional[type]]:
"""Transform the list of relation to list of class.
:param related_mode: The model of the query.
:type related_mode: type
:param relations: The relation list get from the `_extract_relations`.
:type relations: List[str]
:return: Tuple with the list of relations (class) and the second
element is the last relation class.
:rtype: Tuple[Optional[List[type]], Optional[type]]
"""
relations_list, last_relation = [], related_model
for relation in relations:
relationship = getattr(last_relation, relation, None)
if relationship is None:
return (None, None)
last_relation = relationship.mapper.class_
relations_list.append(last_relation)
return (relations_list, last_relation) | python | def _get_relation(self, related_model: type, relations: List[str]) -> Tuple[Optional[List[type]], Optional[type]]:
"""Transform the list of relation to list of class.
:param related_mode: The model of the query.
:type related_mode: type
:param relations: The relation list get from the `_extract_relations`.
:type relations: List[str]
:return: Tuple with the list of relations (class) and the second
element is the last relation class.
:rtype: Tuple[Optional[List[type]], Optional[type]]
"""
relations_list, last_relation = [], related_model
for relation in relations:
relationship = getattr(last_relation, relation, None)
if relationship is None:
return (None, None)
last_relation = relationship.mapper.class_
relations_list.append(last_relation)
return (relations_list, last_relation) | [
"def",
"_get_relation",
"(",
"self",
",",
"related_model",
":",
"type",
",",
"relations",
":",
"List",
"[",
"str",
"]",
")",
"->",
"Tuple",
"[",
"Optional",
"[",
"List",
"[",
"type",
"]",
"]",
",",
"Optional",
"[",
"type",
"]",
"]",
":",
"relations_list",
",",
"last_relation",
"=",
"[",
"]",
",",
"related_model",
"for",
"relation",
"in",
"relations",
":",
"relationship",
"=",
"getattr",
"(",
"last_relation",
",",
"relation",
",",
"None",
")",
"if",
"relationship",
"is",
"None",
":",
"return",
"(",
"None",
",",
"None",
")",
"last_relation",
"=",
"relationship",
".",
"mapper",
".",
"class_",
"relations_list",
".",
"append",
"(",
"last_relation",
")",
"return",
"(",
"relations_list",
",",
"last_relation",
")"
] | Transform the list of relation to list of class.
:param related_mode: The model of the query.
:type related_mode: type
:param relations: The relation list get from the `_extract_relations`.
:type relations: List[str]
:return: Tuple with the list of relations (class) and the second
element is the last relation class.
:rtype: Tuple[Optional[List[type]], Optional[type]] | [
"Transform",
"the",
"list",
"of",
"relation",
"to",
"list",
"of",
"class",
"."
] | train | https://github.com/MarcAureleCoste/sqla-filters/blob/a9596f660a11d275bf0e831ecd9e502b0af2a087/src/sqla_filters/nodes/base/base.py#L117-L137 |
MarcAureleCoste/sqla-filters | src/sqla_filters/nodes/base/base.py | BaseOperationalNode._join_tables | def _join_tables(self, query: Query, join_models: Optional[List[type]]) -> Query:
"""Method to make the join when relation is found.
:param query: The sqlalchemy query.
:type query: Query
:param join_models: The list of joined models get from the method
`_get_relation`.
:type join_models: Optional[List[type]]
:return: The new Query with the joined tables.
:rtype: Query
"""
joined_query = query
# Create the list of already joined entities
joined_tables = [mapper.class_ for mapper in query._join_entities]
if join_models:
for j_model in join_models:
if not j_model in joined_tables:
# /!\ join return a new query /!\
joined_query = joined_query.join(j_model)
return joined_query | python | def _join_tables(self, query: Query, join_models: Optional[List[type]]) -> Query:
"""Method to make the join when relation is found.
:param query: The sqlalchemy query.
:type query: Query
:param join_models: The list of joined models get from the method
`_get_relation`.
:type join_models: Optional[List[type]]
:return: The new Query with the joined tables.
:rtype: Query
"""
joined_query = query
# Create the list of already joined entities
joined_tables = [mapper.class_ for mapper in query._join_entities]
if join_models:
for j_model in join_models:
if not j_model in joined_tables:
# /!\ join return a new query /!\
joined_query = joined_query.join(j_model)
return joined_query | [
"def",
"_join_tables",
"(",
"self",
",",
"query",
":",
"Query",
",",
"join_models",
":",
"Optional",
"[",
"List",
"[",
"type",
"]",
"]",
")",
"->",
"Query",
":",
"joined_query",
"=",
"query",
"# Create the list of already joined entities",
"joined_tables",
"=",
"[",
"mapper",
".",
"class_",
"for",
"mapper",
"in",
"query",
".",
"_join_entities",
"]",
"if",
"join_models",
":",
"for",
"j_model",
"in",
"join_models",
":",
"if",
"not",
"j_model",
"in",
"joined_tables",
":",
"# /!\\ join return a new query /!\\",
"joined_query",
"=",
"joined_query",
".",
"join",
"(",
"j_model",
")",
"return",
"joined_query"
] | Method to make the join when relation is found.
:param query: The sqlalchemy query.
:type query: Query
:param join_models: The list of joined models get from the method
`_get_relation`.
:type join_models: Optional[List[type]]
:return: The new Query with the joined tables.
:rtype: Query | [
"Method",
"to",
"make",
"the",
"join",
"when",
"relation",
"is",
"found",
"."
] | train | https://github.com/MarcAureleCoste/sqla-filters/blob/a9596f660a11d275bf0e831ecd9e502b0af2a087/src/sqla_filters/nodes/base/base.py#L139-L160 |
MarcAureleCoste/sqla-filters | src/sqla_filters/nodes/base/base.py | BaseLogicalNode.filter | def filter(self, query: Query, entity: type) -> Tuple[Query, Any]:
"""Apply the `_method` to all childs of the node.
:param query: The sqlachemy query.
:type query: Query
:param entity: The entity model of the query.
:type entity: type
:return: A tuple with in first place the updated query and in second
place the list of filters to apply to the query.
:rtype: Tuple[Query, Any]
"""
new_query = query
c_filter_list = []
for child in self._childs:
new_query, f_list = child.filter(new_query, entity)
c_filter_list.append(f_list)
return (
new_query,
self._method(*c_filter_list)
) | python | def filter(self, query: Query, entity: type) -> Tuple[Query, Any]:
"""Apply the `_method` to all childs of the node.
:param query: The sqlachemy query.
:type query: Query
:param entity: The entity model of the query.
:type entity: type
:return: A tuple with in first place the updated query and in second
place the list of filters to apply to the query.
:rtype: Tuple[Query, Any]
"""
new_query = query
c_filter_list = []
for child in self._childs:
new_query, f_list = child.filter(new_query, entity)
c_filter_list.append(f_list)
return (
new_query,
self._method(*c_filter_list)
) | [
"def",
"filter",
"(",
"self",
",",
"query",
":",
"Query",
",",
"entity",
":",
"type",
")",
"->",
"Tuple",
"[",
"Query",
",",
"Any",
"]",
":",
"new_query",
"=",
"query",
"c_filter_list",
"=",
"[",
"]",
"for",
"child",
"in",
"self",
".",
"_childs",
":",
"new_query",
",",
"f_list",
"=",
"child",
".",
"filter",
"(",
"new_query",
",",
"entity",
")",
"c_filter_list",
".",
"append",
"(",
"f_list",
")",
"return",
"(",
"new_query",
",",
"self",
".",
"_method",
"(",
"*",
"c_filter_list",
")",
")"
] | Apply the `_method` to all childs of the node.
:param query: The sqlachemy query.
:type query: Query
:param entity: The entity model of the query.
:type entity: type
:return: A tuple with in first place the updated query and in second
place the list of filters to apply to the query.
:rtype: Tuple[Query, Any] | [
"Apply",
"the",
"_method",
"to",
"all",
"childs",
"of",
"the",
"node",
".",
":",
"param",
"query",
":",
"The",
"sqlachemy",
"query",
".",
":",
"type",
"query",
":",
"Query"
] | train | https://github.com/MarcAureleCoste/sqla-filters/blob/a9596f660a11d275bf0e831ecd9e502b0af2a087/src/sqla_filters/nodes/base/base.py#L207-L228 |
kajala/django-jutil | jutil/sms.py | send_sms | def send_sms(phone: str, message: str, sender: str='', **kw):
"""
Sends SMS via Kajala Group SMS API. Contact [email protected] for access.
:param phone: Phone number
:param message: Message to be esnd
:param sender: Sender (max 11 characters)
:param kw: Variable key-value pairs to be sent to SMS API
:return: Response from requests.post
"""
if not hasattr(settings, 'SMS_TOKEN'):
raise Exception('Invalid configuration: settings.SMS_TOKEN missing')
if not sender:
sender = settings.SMS_SENDER_NAME
if not sender:
raise Exception('Invalid configuration: settings.SMS_SENDER_NAME missing')
headers = {
'Content-Type': 'application/json',
'Authorization': 'Token ' + settings.SMS_TOKEN,
}
data = {
'dst': phone_filter(phone),
'msg': message,
'src': sender,
}
for k, v in kw.items():
data[k] = v
return requests.post("https://sms.kajala.com/api/sms/", json=data, headers=headers) | python | def send_sms(phone: str, message: str, sender: str='', **kw):
"""
Sends SMS via Kajala Group SMS API. Contact [email protected] for access.
:param phone: Phone number
:param message: Message to be esnd
:param sender: Sender (max 11 characters)
:param kw: Variable key-value pairs to be sent to SMS API
:return: Response from requests.post
"""
if not hasattr(settings, 'SMS_TOKEN'):
raise Exception('Invalid configuration: settings.SMS_TOKEN missing')
if not sender:
sender = settings.SMS_SENDER_NAME
if not sender:
raise Exception('Invalid configuration: settings.SMS_SENDER_NAME missing')
headers = {
'Content-Type': 'application/json',
'Authorization': 'Token ' + settings.SMS_TOKEN,
}
data = {
'dst': phone_filter(phone),
'msg': message,
'src': sender,
}
for k, v in kw.items():
data[k] = v
return requests.post("https://sms.kajala.com/api/sms/", json=data, headers=headers) | [
"def",
"send_sms",
"(",
"phone",
":",
"str",
",",
"message",
":",
"str",
",",
"sender",
":",
"str",
"=",
"''",
",",
"*",
"*",
"kw",
")",
":",
"if",
"not",
"hasattr",
"(",
"settings",
",",
"'SMS_TOKEN'",
")",
":",
"raise",
"Exception",
"(",
"'Invalid configuration: settings.SMS_TOKEN missing'",
")",
"if",
"not",
"sender",
":",
"sender",
"=",
"settings",
".",
"SMS_SENDER_NAME",
"if",
"not",
"sender",
":",
"raise",
"Exception",
"(",
"'Invalid configuration: settings.SMS_SENDER_NAME missing'",
")",
"headers",
"=",
"{",
"'Content-Type'",
":",
"'application/json'",
",",
"'Authorization'",
":",
"'Token '",
"+",
"settings",
".",
"SMS_TOKEN",
",",
"}",
"data",
"=",
"{",
"'dst'",
":",
"phone_filter",
"(",
"phone",
")",
",",
"'msg'",
":",
"message",
",",
"'src'",
":",
"sender",
",",
"}",
"for",
"k",
",",
"v",
"in",
"kw",
".",
"items",
"(",
")",
":",
"data",
"[",
"k",
"]",
"=",
"v",
"return",
"requests",
".",
"post",
"(",
"\"https://sms.kajala.com/api/sms/\"",
",",
"json",
"=",
"data",
",",
"headers",
"=",
"headers",
")"
] | Sends SMS via Kajala Group SMS API. Contact [email protected] for access.
:param phone: Phone number
:param message: Message to be esnd
:param sender: Sender (max 11 characters)
:param kw: Variable key-value pairs to be sent to SMS API
:return: Response from requests.post | [
"Sends",
"SMS",
"via",
"Kajala",
"Group",
"SMS",
"API",
".",
"Contact",
"info"
] | train | https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/sms.py#L6-L32 |
isogeo/isogeo-api-py-minsdk | isogeo_pysdk/samples/dev_perfs_sync_async.py | _meta_get_resource_sync | def _meta_get_resource_sync(md_uuid):
"""Just a meta func to get execution time"""
isogeo.resource(id_resource=md_uuid)
elapsed = default_timer() - START_TIME
time_completed_at = "{:5.2f}s".format(elapsed)
print("{0:<30} {1:>20}".format(md_uuid, time_completed_at))
return | python | def _meta_get_resource_sync(md_uuid):
"""Just a meta func to get execution time"""
isogeo.resource(id_resource=md_uuid)
elapsed = default_timer() - START_TIME
time_completed_at = "{:5.2f}s".format(elapsed)
print("{0:<30} {1:>20}".format(md_uuid, time_completed_at))
return | [
"def",
"_meta_get_resource_sync",
"(",
"md_uuid",
")",
":",
"isogeo",
".",
"resource",
"(",
"id_resource",
"=",
"md_uuid",
")",
"elapsed",
"=",
"default_timer",
"(",
")",
"-",
"START_TIME",
"time_completed_at",
"=",
"\"{:5.2f}s\"",
".",
"format",
"(",
"elapsed",
")",
"print",
"(",
"\"{0:<30} {1:>20}\"",
".",
"format",
"(",
"md_uuid",
",",
"time_completed_at",
")",
")",
"return"
] | Just a meta func to get execution time | [
"Just",
"a",
"meta",
"func",
"to",
"get",
"execution",
"time"
] | train | https://github.com/isogeo/isogeo-api-py-minsdk/blob/57a604be92c7767b26abd247012cc1a584b386a0/isogeo_pysdk/samples/dev_perfs_sync_async.py#L35-L43 |
Varkal/chuda | chuda/commands.py | Command.setup | def setup(self, app):
'''
Setup properties from parent app on the command
'''
self.logger = app.logger
self.shell.logger = self.logger
if not self.command_name:
raise EmptyCommandNameException()
self.app = app
self.arguments_declaration = self.arguments
self.arguments = app.arguments
if self.use_subconfig:
_init_config(self)
else:
self.config = self.app.config | python | def setup(self, app):
'''
Setup properties from parent app on the command
'''
self.logger = app.logger
self.shell.logger = self.logger
if not self.command_name:
raise EmptyCommandNameException()
self.app = app
self.arguments_declaration = self.arguments
self.arguments = app.arguments
if self.use_subconfig:
_init_config(self)
else:
self.config = self.app.config | [
"def",
"setup",
"(",
"self",
",",
"app",
")",
":",
"self",
".",
"logger",
"=",
"app",
".",
"logger",
"self",
".",
"shell",
".",
"logger",
"=",
"self",
".",
"logger",
"if",
"not",
"self",
".",
"command_name",
":",
"raise",
"EmptyCommandNameException",
"(",
")",
"self",
".",
"app",
"=",
"app",
"self",
".",
"arguments_declaration",
"=",
"self",
".",
"arguments",
"self",
".",
"arguments",
"=",
"app",
".",
"arguments",
"if",
"self",
".",
"use_subconfig",
":",
"_init_config",
"(",
"self",
")",
"else",
":",
"self",
".",
"config",
"=",
"self",
".",
"app",
".",
"config"
] | Setup properties from parent app on the command | [
"Setup",
"properties",
"from",
"parent",
"app",
"on",
"the",
"command"
] | train | https://github.com/Varkal/chuda/blob/0d93b716dede35231c21be97bcc19a656655983f/chuda/commands.py#L92-L109 |
kajala/django-jutil | jutil/middleware.py | LogExceptionMiddleware.process_exception | def process_exception(self, request, e):
"""
Logs exception error message and sends email to ADMINS if hostname is not testserver and DEBUG=False.
:param request: HttpRequest
:param e: Exception
"""
from jutil.email import send_email
assert isinstance(request, HttpRequest)
full_path = request.get_full_path()
user = request.user
msg = '{full_path}\n{err} (IP={ip}, user={user}) {trace}'.format(full_path=full_path, user=user, ip=get_real_ip(request), err=e, trace=str(traceback.format_exc()))
logger.error(msg)
hostname = request.get_host()
if not settings.DEBUG and hostname != 'testserver':
send_email(settings.ADMINS, 'Error @ {}'.format(hostname), msg)
return None | python | def process_exception(self, request, e):
"""
Logs exception error message and sends email to ADMINS if hostname is not testserver and DEBUG=False.
:param request: HttpRequest
:param e: Exception
"""
from jutil.email import send_email
assert isinstance(request, HttpRequest)
full_path = request.get_full_path()
user = request.user
msg = '{full_path}\n{err} (IP={ip}, user={user}) {trace}'.format(full_path=full_path, user=user, ip=get_real_ip(request), err=e, trace=str(traceback.format_exc()))
logger.error(msg)
hostname = request.get_host()
if not settings.DEBUG and hostname != 'testserver':
send_email(settings.ADMINS, 'Error @ {}'.format(hostname), msg)
return None | [
"def",
"process_exception",
"(",
"self",
",",
"request",
",",
"e",
")",
":",
"from",
"jutil",
".",
"email",
"import",
"send_email",
"assert",
"isinstance",
"(",
"request",
",",
"HttpRequest",
")",
"full_path",
"=",
"request",
".",
"get_full_path",
"(",
")",
"user",
"=",
"request",
".",
"user",
"msg",
"=",
"'{full_path}\\n{err} (IP={ip}, user={user}) {trace}'",
".",
"format",
"(",
"full_path",
"=",
"full_path",
",",
"user",
"=",
"user",
",",
"ip",
"=",
"get_real_ip",
"(",
"request",
")",
",",
"err",
"=",
"e",
",",
"trace",
"=",
"str",
"(",
"traceback",
".",
"format_exc",
"(",
")",
")",
")",
"logger",
".",
"error",
"(",
"msg",
")",
"hostname",
"=",
"request",
".",
"get_host",
"(",
")",
"if",
"not",
"settings",
".",
"DEBUG",
"and",
"hostname",
"!=",
"'testserver'",
":",
"send_email",
"(",
"settings",
".",
"ADMINS",
",",
"'Error @ {}'",
".",
"format",
"(",
"hostname",
")",
",",
"msg",
")",
"return",
"None"
] | Logs exception error message and sends email to ADMINS if hostname is not testserver and DEBUG=False.
:param request: HttpRequest
:param e: Exception | [
"Logs",
"exception",
"error",
"message",
"and",
"sends",
"email",
"to",
"ADMINS",
"if",
"hostname",
"is",
"not",
"testserver",
"and",
"DEBUG",
"=",
"False",
".",
":",
"param",
"request",
":",
"HttpRequest",
":",
"param",
"e",
":",
"Exception"
] | train | https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/middleware.py#L47-L63 |
cfobel/pygtk3-helpers | pygtk3_helpers/delegates.py | get_first_builder_window | def get_first_builder_window(builder):
"""Get the first toplevel widget in a Gtk.Builder hierarchy.
This is mostly used for guessing purposes, and an explicit naming is
always going to be a better situation.
"""
for obj in builder.get_objects():
if isinstance(obj, Gtk.Window):
# first window
return obj | python | def get_first_builder_window(builder):
"""Get the first toplevel widget in a Gtk.Builder hierarchy.
This is mostly used for guessing purposes, and an explicit naming is
always going to be a better situation.
"""
for obj in builder.get_objects():
if isinstance(obj, Gtk.Window):
# first window
return obj | [
"def",
"get_first_builder_window",
"(",
"builder",
")",
":",
"for",
"obj",
"in",
"builder",
".",
"get_objects",
"(",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"Gtk",
".",
"Window",
")",
":",
"# first window",
"return",
"obj"
] | Get the first toplevel widget in a Gtk.Builder hierarchy.
This is mostly used for guessing purposes, and an explicit naming is
always going to be a better situation. | [
"Get",
"the",
"first",
"toplevel",
"widget",
"in",
"a",
"Gtk",
".",
"Builder",
"hierarchy",
"."
] | train | https://github.com/cfobel/pygtk3-helpers/blob/ae793cb34a5c1bbe40cc83bb8a6084f0eeed2519/pygtk3_helpers/delegates.py#L20-L29 |
cfobel/pygtk3-helpers | pygtk3_helpers/delegates.py | BaseDelegate.add_slave | def add_slave(self, slave, container_name="widget"):
"""Add a slave delegate
"""
cont = getattr(self, container_name, None)
if cont is None:
raise AttributeError(
'Container name must be a member of the delegate')
cont.add(slave.widget)
self.slaves.append(slave)
return slave | python | def add_slave(self, slave, container_name="widget"):
"""Add a slave delegate
"""
cont = getattr(self, container_name, None)
if cont is None:
raise AttributeError(
'Container name must be a member of the delegate')
cont.add(slave.widget)
self.slaves.append(slave)
return slave | [
"def",
"add_slave",
"(",
"self",
",",
"slave",
",",
"container_name",
"=",
"\"widget\"",
")",
":",
"cont",
"=",
"getattr",
"(",
"self",
",",
"container_name",
",",
"None",
")",
"if",
"cont",
"is",
"None",
":",
"raise",
"AttributeError",
"(",
"'Container name must be a member of the delegate'",
")",
"cont",
".",
"add",
"(",
"slave",
".",
"widget",
")",
"self",
".",
"slaves",
".",
"append",
"(",
"slave",
")",
"return",
"slave"
] | Add a slave delegate | [
"Add",
"a",
"slave",
"delegate"
] | train | https://github.com/cfobel/pygtk3-helpers/blob/ae793cb34a5c1bbe40cc83bb8a6084f0eeed2519/pygtk3_helpers/delegates.py#L103-L112 |
cfobel/pygtk3-helpers | pygtk3_helpers/delegates.py | SlaveView.get_builder_toplevel | def get_builder_toplevel(self, builder):
"""Get the toplevel widget from a Gtk.Builder file.
The slave view implementation first searches for the widget named as
self.toplevel_name (which defaults to "main". If this is missing, the
first toplevel widget is discovered in the Builder file, and it's
immediate child is used as the toplevel widget for the delegate.
"""
toplevel = builder.get_object(self.toplevel_name)
if toplevel is None:
toplevel = get_first_builder_window(builder).child
if toplevel is not None:
#XXX: what to do if a developer
# gave the name of a window instead of its child
toplevel.get_parent().remove(toplevel)
return toplevel | python | def get_builder_toplevel(self, builder):
"""Get the toplevel widget from a Gtk.Builder file.
The slave view implementation first searches for the widget named as
self.toplevel_name (which defaults to "main". If this is missing, the
first toplevel widget is discovered in the Builder file, and it's
immediate child is used as the toplevel widget for the delegate.
"""
toplevel = builder.get_object(self.toplevel_name)
if toplevel is None:
toplevel = get_first_builder_window(builder).child
if toplevel is not None:
#XXX: what to do if a developer
# gave the name of a window instead of its child
toplevel.get_parent().remove(toplevel)
return toplevel | [
"def",
"get_builder_toplevel",
"(",
"self",
",",
"builder",
")",
":",
"toplevel",
"=",
"builder",
".",
"get_object",
"(",
"self",
".",
"toplevel_name",
")",
"if",
"toplevel",
"is",
"None",
":",
"toplevel",
"=",
"get_first_builder_window",
"(",
"builder",
")",
".",
"child",
"if",
"toplevel",
"is",
"not",
"None",
":",
"#XXX: what to do if a developer",
"# gave the name of a window instead of its child",
"toplevel",
".",
"get_parent",
"(",
")",
".",
"remove",
"(",
"toplevel",
")",
"return",
"toplevel"
] | Get the toplevel widget from a Gtk.Builder file.
The slave view implementation first searches for the widget named as
self.toplevel_name (which defaults to "main". If this is missing, the
first toplevel widget is discovered in the Builder file, and it's
immediate child is used as the toplevel widget for the delegate. | [
"Get",
"the",
"toplevel",
"widget",
"from",
"a",
"Gtk",
".",
"Builder",
"file",
"."
] | train | https://github.com/cfobel/pygtk3-helpers/blob/ae793cb34a5c1bbe40cc83bb8a6084f0eeed2519/pygtk3_helpers/delegates.py#L231-L246 |
cfobel/pygtk3-helpers | pygtk3_helpers/delegates.py | SlaveView.show_and_run | def show_and_run(self):
"""Show the main widget in a window and run the gtk loop"""
if not self._ui_ready:
self.prepare_ui()
self.display_widget = Gtk.Window()
self.display_widget.add(self.widget)
self.display_widget.show()
self.display_widget.connect('destroy', lambda *args: self.hide_and_quit())
BaseDelegate.show_and_run(self) | python | def show_and_run(self):
"""Show the main widget in a window and run the gtk loop"""
if not self._ui_ready:
self.prepare_ui()
self.display_widget = Gtk.Window()
self.display_widget.add(self.widget)
self.display_widget.show()
self.display_widget.connect('destroy', lambda *args: self.hide_and_quit())
BaseDelegate.show_and_run(self) | [
"def",
"show_and_run",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_ui_ready",
":",
"self",
".",
"prepare_ui",
"(",
")",
"self",
".",
"display_widget",
"=",
"Gtk",
".",
"Window",
"(",
")",
"self",
".",
"display_widget",
".",
"add",
"(",
"self",
".",
"widget",
")",
"self",
".",
"display_widget",
".",
"show",
"(",
")",
"self",
".",
"display_widget",
".",
"connect",
"(",
"'destroy'",
",",
"lambda",
"*",
"args",
":",
"self",
".",
"hide_and_quit",
"(",
")",
")",
"BaseDelegate",
".",
"show_and_run",
"(",
"self",
")"
] | Show the main widget in a window and run the gtk loop | [
"Show",
"the",
"main",
"widget",
"in",
"a",
"window",
"and",
"run",
"the",
"gtk",
"loop"
] | train | https://github.com/cfobel/pygtk3-helpers/blob/ae793cb34a5c1bbe40cc83bb8a6084f0eeed2519/pygtk3_helpers/delegates.py#L251-L259 |
cfobel/pygtk3-helpers | pygtk3_helpers/delegates.py | ToplevelView.get_builder_toplevel | def get_builder_toplevel(self, builder):
"""Get the toplevel widget from a Gtk.Builder file.
The main view implementation first searches for the widget named as
self.toplevel_name (which defaults to "main". If this is missing, or not
a Gtk.Window, the first toplevel window found in the Gtk.Builder is
used.
"""
toplevel = builder.get_object(self.toplevel_name)
if not GObject.type_is_a(toplevel, Gtk.Window):
toplevel = None
if toplevel is None:
toplevel = get_first_builder_window(builder)
return toplevel | python | def get_builder_toplevel(self, builder):
"""Get the toplevel widget from a Gtk.Builder file.
The main view implementation first searches for the widget named as
self.toplevel_name (which defaults to "main". If this is missing, or not
a Gtk.Window, the first toplevel window found in the Gtk.Builder is
used.
"""
toplevel = builder.get_object(self.toplevel_name)
if not GObject.type_is_a(toplevel, Gtk.Window):
toplevel = None
if toplevel is None:
toplevel = get_first_builder_window(builder)
return toplevel | [
"def",
"get_builder_toplevel",
"(",
"self",
",",
"builder",
")",
":",
"toplevel",
"=",
"builder",
".",
"get_object",
"(",
"self",
".",
"toplevel_name",
")",
"if",
"not",
"GObject",
".",
"type_is_a",
"(",
"toplevel",
",",
"Gtk",
".",
"Window",
")",
":",
"toplevel",
"=",
"None",
"if",
"toplevel",
"is",
"None",
":",
"toplevel",
"=",
"get_first_builder_window",
"(",
"builder",
")",
"return",
"toplevel"
] | Get the toplevel widget from a Gtk.Builder file.
The main view implementation first searches for the widget named as
self.toplevel_name (which defaults to "main". If this is missing, or not
a Gtk.Window, the first toplevel window found in the Gtk.Builder is
used. | [
"Get",
"the",
"toplevel",
"widget",
"from",
"a",
"Gtk",
".",
"Builder",
"file",
"."
] | train | https://github.com/cfobel/pygtk3-helpers/blob/ae793cb34a5c1bbe40cc83bb8a6084f0eeed2519/pygtk3_helpers/delegates.py#L265-L278 |
InformaticsMatters/pipelines-utils | src/python/pipelines_utils/utils.py | round_sig | def round_sig(x, sig):
"""Round the number to the specified number of significant figures"""
return round(x, sig - int(floor(log10(abs(x)))) - 1) | python | def round_sig(x, sig):
"""Round the number to the specified number of significant figures"""
return round(x, sig - int(floor(log10(abs(x)))) - 1) | [
"def",
"round_sig",
"(",
"x",
",",
"sig",
")",
":",
"return",
"round",
"(",
"x",
",",
"sig",
"-",
"int",
"(",
"floor",
"(",
"log10",
"(",
"abs",
"(",
"x",
")",
")",
")",
")",
"-",
"1",
")"
] | Round the number to the specified number of significant figures | [
"Round",
"the",
"number",
"to",
"the",
"specified",
"number",
"of",
"significant",
"figures"
] | train | https://github.com/InformaticsMatters/pipelines-utils/blob/058aa6eceeff28c4ae402f6f58c58720bff0298e/src/python/pipelines_utils/utils.py#L30-L32 |
InformaticsMatters/pipelines-utils | src/python/pipelines_utils/utils.py | open_file | def open_file(filename, as_text=False):
"""Open the file gunzipping it if it ends with .gz.
If as_text the file is opened in text mode,
otherwise the file's opened in binary mode."""
if filename.lower().endswith('.gz'):
if as_text:
return gzip.open(filename, 'rt')
else:
return gzip.open(filename, 'rb')
else:
if as_text:
return open(filename, 'rt')
else:
return open(filename, 'rb') | python | def open_file(filename, as_text=False):
"""Open the file gunzipping it if it ends with .gz.
If as_text the file is opened in text mode,
otherwise the file's opened in binary mode."""
if filename.lower().endswith('.gz'):
if as_text:
return gzip.open(filename, 'rt')
else:
return gzip.open(filename, 'rb')
else:
if as_text:
return open(filename, 'rt')
else:
return open(filename, 'rb') | [
"def",
"open_file",
"(",
"filename",
",",
"as_text",
"=",
"False",
")",
":",
"if",
"filename",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"'.gz'",
")",
":",
"if",
"as_text",
":",
"return",
"gzip",
".",
"open",
"(",
"filename",
",",
"'rt'",
")",
"else",
":",
"return",
"gzip",
".",
"open",
"(",
"filename",
",",
"'rb'",
")",
"else",
":",
"if",
"as_text",
":",
"return",
"open",
"(",
"filename",
",",
"'rt'",
")",
"else",
":",
"return",
"open",
"(",
"filename",
",",
"'rb'",
")"
] | Open the file gunzipping it if it ends with .gz.
If as_text the file is opened in text mode,
otherwise the file's opened in binary mode. | [
"Open",
"the",
"file",
"gunzipping",
"it",
"if",
"it",
"ends",
"with",
".",
"gz",
".",
"If",
"as_text",
"the",
"file",
"is",
"opened",
"in",
"text",
"mode",
"otherwise",
"the",
"file",
"s",
"opened",
"in",
"binary",
"mode",
"."
] | train | https://github.com/InformaticsMatters/pipelines-utils/blob/058aa6eceeff28c4ae402f6f58c58720bff0298e/src/python/pipelines_utils/utils.py#L35-L48 |
InformaticsMatters/pipelines-utils | src/python/pipelines_utils/utils.py | create_simple_writer | def create_simple_writer(outputDef, defaultOutput, outputFormat, fieldNames,
compress=True, valueClassMappings=None,
datasetMetaProps=None, fieldMetaProps=None):
"""Create a simple writer suitable for writing flat data
e.g. as BasicObject or TSV."""
if not outputDef:
outputBase = defaultOutput
else:
outputBase = outputDef
if outputFormat == 'json':
write_squonk_datasetmetadata(outputBase, True, valueClassMappings,
datasetMetaProps, fieldMetaProps)
return BasicObjectWriter(open_output(outputDef, 'data', compress)), outputBase
elif outputFormat == 'tsv':
return TsvWriter(open_output(outputDef, 'tsv', compress), fieldNames), outputBase
else:
raise ValueError("Unsupported format: " + outputFormat) | python | def create_simple_writer(outputDef, defaultOutput, outputFormat, fieldNames,
compress=True, valueClassMappings=None,
datasetMetaProps=None, fieldMetaProps=None):
"""Create a simple writer suitable for writing flat data
e.g. as BasicObject or TSV."""
if not outputDef:
outputBase = defaultOutput
else:
outputBase = outputDef
if outputFormat == 'json':
write_squonk_datasetmetadata(outputBase, True, valueClassMappings,
datasetMetaProps, fieldMetaProps)
return BasicObjectWriter(open_output(outputDef, 'data', compress)), outputBase
elif outputFormat == 'tsv':
return TsvWriter(open_output(outputDef, 'tsv', compress), fieldNames), outputBase
else:
raise ValueError("Unsupported format: " + outputFormat) | [
"def",
"create_simple_writer",
"(",
"outputDef",
",",
"defaultOutput",
",",
"outputFormat",
",",
"fieldNames",
",",
"compress",
"=",
"True",
",",
"valueClassMappings",
"=",
"None",
",",
"datasetMetaProps",
"=",
"None",
",",
"fieldMetaProps",
"=",
"None",
")",
":",
"if",
"not",
"outputDef",
":",
"outputBase",
"=",
"defaultOutput",
"else",
":",
"outputBase",
"=",
"outputDef",
"if",
"outputFormat",
"==",
"'json'",
":",
"write_squonk_datasetmetadata",
"(",
"outputBase",
",",
"True",
",",
"valueClassMappings",
",",
"datasetMetaProps",
",",
"fieldMetaProps",
")",
"return",
"BasicObjectWriter",
"(",
"open_output",
"(",
"outputDef",
",",
"'data'",
",",
"compress",
")",
")",
",",
"outputBase",
"elif",
"outputFormat",
"==",
"'tsv'",
":",
"return",
"TsvWriter",
"(",
"open_output",
"(",
"outputDef",
",",
"'tsv'",
",",
"compress",
")",
",",
"fieldNames",
")",
",",
"outputBase",
"else",
":",
"raise",
"ValueError",
"(",
"\"Unsupported format: \"",
"+",
"outputFormat",
")"
] | Create a simple writer suitable for writing flat data
e.g. as BasicObject or TSV. | [
"Create",
"a",
"simple",
"writer",
"suitable",
"for",
"writing",
"flat",
"data",
"e",
".",
"g",
".",
"as",
"BasicObject",
"or",
"TSV",
"."
] | train | https://github.com/InformaticsMatters/pipelines-utils/blob/058aa6eceeff28c4ae402f6f58c58720bff0298e/src/python/pipelines_utils/utils.py#L51-L71 |
InformaticsMatters/pipelines-utils | src/python/pipelines_utils/utils.py | write_squonk_datasetmetadata | def write_squonk_datasetmetadata(outputBase, thinOutput, valueClassMappings, datasetMetaProps, fieldMetaProps):
"""This is a temp hack to write the minimal metadata that Squonk needs.
Will needs to be replaced with something that allows something more complete to be written.
:param outputBase: Base name for the file to write to
:param thinOutput: Write only new data, not structures. Result type will be BasicObject
:param valueClasses: A dict that describes the Java class of the value properties (used by Squonk)
:param datasetMetaProps: A dict with metadata properties that describe the datset as a whole.
The keys used for these metadata are up to the user, but common ones include source, description, created, history.
:param fieldMetaProps: A list of dicts with the additional field metadata. Each dict has a key named fieldName whose value
is the name of the field being described, and a key name values wholes values is a map of metadata properties.
The keys used for these metadata are up to the user, but common ones include source, description, created, history.
"""
meta = {}
props = {}
# TODO add created property - how to handle date formats?
if datasetMetaProps:
props.update(datasetMetaProps)
if fieldMetaProps:
meta["fieldMetaProps"] = fieldMetaProps
if len(props) > 0:
meta["properties"] = props
if valueClassMappings:
meta["valueClassMappings"] = valueClassMappings
if thinOutput:
meta['type'] = 'org.squonk.types.BasicObject'
else:
meta['type'] = 'org.squonk.types.MoleculeObject'
s = json.dumps(meta)
meta = open(outputBase + '.metadata', 'w')
meta.write(s)
meta.close() | python | def write_squonk_datasetmetadata(outputBase, thinOutput, valueClassMappings, datasetMetaProps, fieldMetaProps):
"""This is a temp hack to write the minimal metadata that Squonk needs.
Will needs to be replaced with something that allows something more complete to be written.
:param outputBase: Base name for the file to write to
:param thinOutput: Write only new data, not structures. Result type will be BasicObject
:param valueClasses: A dict that describes the Java class of the value properties (used by Squonk)
:param datasetMetaProps: A dict with metadata properties that describe the datset as a whole.
The keys used for these metadata are up to the user, but common ones include source, description, created, history.
:param fieldMetaProps: A list of dicts with the additional field metadata. Each dict has a key named fieldName whose value
is the name of the field being described, and a key name values wholes values is a map of metadata properties.
The keys used for these metadata are up to the user, but common ones include source, description, created, history.
"""
meta = {}
props = {}
# TODO add created property - how to handle date formats?
if datasetMetaProps:
props.update(datasetMetaProps)
if fieldMetaProps:
meta["fieldMetaProps"] = fieldMetaProps
if len(props) > 0:
meta["properties"] = props
if valueClassMappings:
meta["valueClassMappings"] = valueClassMappings
if thinOutput:
meta['type'] = 'org.squonk.types.BasicObject'
else:
meta['type'] = 'org.squonk.types.MoleculeObject'
s = json.dumps(meta)
meta = open(outputBase + '.metadata', 'w')
meta.write(s)
meta.close() | [
"def",
"write_squonk_datasetmetadata",
"(",
"outputBase",
",",
"thinOutput",
",",
"valueClassMappings",
",",
"datasetMetaProps",
",",
"fieldMetaProps",
")",
":",
"meta",
"=",
"{",
"}",
"props",
"=",
"{",
"}",
"# TODO add created property - how to handle date formats?",
"if",
"datasetMetaProps",
":",
"props",
".",
"update",
"(",
"datasetMetaProps",
")",
"if",
"fieldMetaProps",
":",
"meta",
"[",
"\"fieldMetaProps\"",
"]",
"=",
"fieldMetaProps",
"if",
"len",
"(",
"props",
")",
">",
"0",
":",
"meta",
"[",
"\"properties\"",
"]",
"=",
"props",
"if",
"valueClassMappings",
":",
"meta",
"[",
"\"valueClassMappings\"",
"]",
"=",
"valueClassMappings",
"if",
"thinOutput",
":",
"meta",
"[",
"'type'",
"]",
"=",
"'org.squonk.types.BasicObject'",
"else",
":",
"meta",
"[",
"'type'",
"]",
"=",
"'org.squonk.types.MoleculeObject'",
"s",
"=",
"json",
".",
"dumps",
"(",
"meta",
")",
"meta",
"=",
"open",
"(",
"outputBase",
"+",
"'.metadata'",
",",
"'w'",
")",
"meta",
".",
"write",
"(",
"s",
")",
"meta",
".",
"close",
"(",
")"
] | This is a temp hack to write the minimal metadata that Squonk needs.
Will needs to be replaced with something that allows something more complete to be written.
:param outputBase: Base name for the file to write to
:param thinOutput: Write only new data, not structures. Result type will be BasicObject
:param valueClasses: A dict that describes the Java class of the value properties (used by Squonk)
:param datasetMetaProps: A dict with metadata properties that describe the datset as a whole.
The keys used for these metadata are up to the user, but common ones include source, description, created, history.
:param fieldMetaProps: A list of dicts with the additional field metadata. Each dict has a key named fieldName whose value
is the name of the field being described, and a key name values wholes values is a map of metadata properties.
The keys used for these metadata are up to the user, but common ones include source, description, created, history. | [
"This",
"is",
"a",
"temp",
"hack",
"to",
"write",
"the",
"minimal",
"metadata",
"that",
"Squonk",
"needs",
".",
"Will",
"needs",
"to",
"be",
"replaced",
"with",
"something",
"that",
"allows",
"something",
"more",
"complete",
"to",
"be",
"written",
"."
] | train | https://github.com/InformaticsMatters/pipelines-utils/blob/058aa6eceeff28c4ae402f6f58c58720bff0298e/src/python/pipelines_utils/utils.py#L90-L124 |
InformaticsMatters/pipelines-utils | src/python/pipelines_utils/utils.py | write_metrics | def write_metrics(baseName, values):
"""Write the metrics data
:param baseName: The base name of the output files.
e.g. extensions will be appended to this base name
:param values dictionary of values to write
"""
m = open(baseName + '_metrics.txt', 'w')
for key in values:
m.write(key + '=' + str(values[key]) + "\n")
m.flush()
m.close() | python | def write_metrics(baseName, values):
"""Write the metrics data
:param baseName: The base name of the output files.
e.g. extensions will be appended to this base name
:param values dictionary of values to write
"""
m = open(baseName + '_metrics.txt', 'w')
for key in values:
m.write(key + '=' + str(values[key]) + "\n")
m.flush()
m.close() | [
"def",
"write_metrics",
"(",
"baseName",
",",
"values",
")",
":",
"m",
"=",
"open",
"(",
"baseName",
"+",
"'_metrics.txt'",
",",
"'w'",
")",
"for",
"key",
"in",
"values",
":",
"m",
".",
"write",
"(",
"key",
"+",
"'='",
"+",
"str",
"(",
"values",
"[",
"key",
"]",
")",
"+",
"\"\\n\"",
")",
"m",
".",
"flush",
"(",
")",
"m",
".",
"close",
"(",
")"
] | Write the metrics data
:param baseName: The base name of the output files.
e.g. extensions will be appended to this base name
:param values dictionary of values to write | [
"Write",
"the",
"metrics",
"data"
] | train | https://github.com/InformaticsMatters/pipelines-utils/blob/058aa6eceeff28c4ae402f6f58c58720bff0298e/src/python/pipelines_utils/utils.py#L127-L138 |
InformaticsMatters/pipelines-utils | src/python/pipelines_utils/utils.py | generate_molecule_object_dict | def generate_molecule_object_dict(source, format, values):
"""Generate a dictionary that represents a Squonk MoleculeObject when
written as JSON
:param source: Molecules in molfile or smiles format
:param format: The format of the molecule. Either 'mol' or 'smiles'
:param values: Optional dict of values (properties) for the MoleculeObject
"""
m = {"uuid": str(uuid.uuid4()), "source": source, "format": format}
if values:
m["values"] = values
return m | python | def generate_molecule_object_dict(source, format, values):
"""Generate a dictionary that represents a Squonk MoleculeObject when
written as JSON
:param source: Molecules in molfile or smiles format
:param format: The format of the molecule. Either 'mol' or 'smiles'
:param values: Optional dict of values (properties) for the MoleculeObject
"""
m = {"uuid": str(uuid.uuid4()), "source": source, "format": format}
if values:
m["values"] = values
return m | [
"def",
"generate_molecule_object_dict",
"(",
"source",
",",
"format",
",",
"values",
")",
":",
"m",
"=",
"{",
"\"uuid\"",
":",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
",",
"\"source\"",
":",
"source",
",",
"\"format\"",
":",
"format",
"}",
"if",
"values",
":",
"m",
"[",
"\"values\"",
"]",
"=",
"values",
"return",
"m"
] | Generate a dictionary that represents a Squonk MoleculeObject when
written as JSON
:param source: Molecules in molfile or smiles format
:param format: The format of the molecule. Either 'mol' or 'smiles'
:param values: Optional dict of values (properties) for the MoleculeObject | [
"Generate",
"a",
"dictionary",
"that",
"represents",
"a",
"Squonk",
"MoleculeObject",
"when",
"written",
"as",
"JSON"
] | train | https://github.com/InformaticsMatters/pipelines-utils/blob/058aa6eceeff28c4ae402f6f58c58720bff0298e/src/python/pipelines_utils/utils.py#L141-L152 |
InformaticsMatters/pipelines-utils | src/python/pipelines_utils/utils.py | get_undecorated_calling_module | def get_undecorated_calling_module():
"""Returns the module name of the caller's calling module.
If a.py makes a call to b() in b.py, b() can get the name of the
calling module (i.e. a) by calling get_undecorated_calling_module().
The module also includes its full path.
As the name suggests, this does not work for decorated functions.
"""
frame = inspect.stack()[2]
module = inspect.getmodule(frame[0])
# Return the module's file and its path
# and omit the extension...
# so /a/c.py becomes /a/c
return module.__file__.rsplit('.', 1)[0] | python | def get_undecorated_calling_module():
"""Returns the module name of the caller's calling module.
If a.py makes a call to b() in b.py, b() can get the name of the
calling module (i.e. a) by calling get_undecorated_calling_module().
The module also includes its full path.
As the name suggests, this does not work for decorated functions.
"""
frame = inspect.stack()[2]
module = inspect.getmodule(frame[0])
# Return the module's file and its path
# and omit the extension...
# so /a/c.py becomes /a/c
return module.__file__.rsplit('.', 1)[0] | [
"def",
"get_undecorated_calling_module",
"(",
")",
":",
"frame",
"=",
"inspect",
".",
"stack",
"(",
")",
"[",
"2",
"]",
"module",
"=",
"inspect",
".",
"getmodule",
"(",
"frame",
"[",
"0",
"]",
")",
"# Return the module's file and its path",
"# and omit the extension...",
"# so /a/c.py becomes /a/c",
"return",
"module",
".",
"__file__",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"[",
"0",
"]"
] | Returns the module name of the caller's calling module.
If a.py makes a call to b() in b.py, b() can get the name of the
calling module (i.e. a) by calling get_undecorated_calling_module().
The module also includes its full path.
As the name suggests, this does not work for decorated functions. | [
"Returns",
"the",
"module",
"name",
"of",
"the",
"caller",
"s",
"calling",
"module",
".",
"If",
"a",
".",
"py",
"makes",
"a",
"call",
"to",
"b",
"()",
"in",
"b",
".",
"py",
"b",
"()",
"can",
"get",
"the",
"name",
"of",
"the",
"calling",
"module",
"(",
"i",
".",
"e",
".",
"a",
")",
"by",
"calling",
"get_undecorated_calling_module",
"()",
"."
] | train | https://github.com/InformaticsMatters/pipelines-utils/blob/058aa6eceeff28c4ae402f6f58c58720bff0298e/src/python/pipelines_utils/utils.py#L155-L169 |
cons3rt/pycons3rt | pycons3rt/nexus.py | query_nexus | def query_nexus(query_url, timeout_sec, basic_auth=None):
"""Queries Nexus for an artifact
:param query_url: (str) Query URL
:param timeout_sec: (int) query timeout
:param basic_auth (HTTPBasicAuth) object or none
:return: requests.Response object
:raises: RuntimeError
"""
log = logging.getLogger(mod_logger + '.query_nexus')
# Attempt to query Nexus
retry_sec = 5
max_retries = 6
try_num = 1
query_success = False
nexus_response = None
while try_num <= max_retries:
if query_success:
break
log.debug('Attempt # {n} of {m} to query the Nexus URL: {u}'.format(n=try_num, u=query_url, m=max_retries))
try:
nexus_response = requests.get(query_url, auth=basic_auth, stream=True, timeout=timeout_sec)
except requests.exceptions.Timeout:
_, ex, trace = sys.exc_info()
msg = '{n}: Nexus initial query timed out after {t} seconds:\n{e}'.format(
n=ex.__class__.__name__, t=timeout_sec, r=retry_sec, e=str(ex))
log.warn(msg)
if try_num < max_retries:
log.info('Retrying query in {t} sec...'.format(t=retry_sec))
time.sleep(retry_sec)
except (requests.exceptions.RequestException, requests.exceptions.ConnectionError):
_, ex, trace = sys.exc_info()
msg = '{n}: Nexus initial query failed with the following exception:\n{e}'.format(
n=ex.__class__.__name__, r=retry_sec, e=str(ex))
log.warn(msg)
if try_num < max_retries:
log.info('Retrying query in {t} sec...'.format(t=retry_sec))
time.sleep(retry_sec)
else:
query_success = True
try_num += 1
if not query_success:
msg = 'Unable to query Nexus after {m} attempts using URL: {u}'.format(
u=query_url, m=max_retries)
log.error(msg)
raise RuntimeError(msg)
if nexus_response.status_code != 200:
msg = 'Nexus request returned code {c}, unable to query Nexus using URL: {u}'.format(
u=query_url, c=nexus_response.status_code)
log.error(msg)
raise RuntimeError(msg)
return nexus_response | python | def query_nexus(query_url, timeout_sec, basic_auth=None):
"""Queries Nexus for an artifact
:param query_url: (str) Query URL
:param timeout_sec: (int) query timeout
:param basic_auth (HTTPBasicAuth) object or none
:return: requests.Response object
:raises: RuntimeError
"""
log = logging.getLogger(mod_logger + '.query_nexus')
# Attempt to query Nexus
retry_sec = 5
max_retries = 6
try_num = 1
query_success = False
nexus_response = None
while try_num <= max_retries:
if query_success:
break
log.debug('Attempt # {n} of {m} to query the Nexus URL: {u}'.format(n=try_num, u=query_url, m=max_retries))
try:
nexus_response = requests.get(query_url, auth=basic_auth, stream=True, timeout=timeout_sec)
except requests.exceptions.Timeout:
_, ex, trace = sys.exc_info()
msg = '{n}: Nexus initial query timed out after {t} seconds:\n{e}'.format(
n=ex.__class__.__name__, t=timeout_sec, r=retry_sec, e=str(ex))
log.warn(msg)
if try_num < max_retries:
log.info('Retrying query in {t} sec...'.format(t=retry_sec))
time.sleep(retry_sec)
except (requests.exceptions.RequestException, requests.exceptions.ConnectionError):
_, ex, trace = sys.exc_info()
msg = '{n}: Nexus initial query failed with the following exception:\n{e}'.format(
n=ex.__class__.__name__, r=retry_sec, e=str(ex))
log.warn(msg)
if try_num < max_retries:
log.info('Retrying query in {t} sec...'.format(t=retry_sec))
time.sleep(retry_sec)
else:
query_success = True
try_num += 1
if not query_success:
msg = 'Unable to query Nexus after {m} attempts using URL: {u}'.format(
u=query_url, m=max_retries)
log.error(msg)
raise RuntimeError(msg)
if nexus_response.status_code != 200:
msg = 'Nexus request returned code {c}, unable to query Nexus using URL: {u}'.format(
u=query_url, c=nexus_response.status_code)
log.error(msg)
raise RuntimeError(msg)
return nexus_response | [
"def",
"query_nexus",
"(",
"query_url",
",",
"timeout_sec",
",",
"basic_auth",
"=",
"None",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.query_nexus'",
")",
"# Attempt to query Nexus",
"retry_sec",
"=",
"5",
"max_retries",
"=",
"6",
"try_num",
"=",
"1",
"query_success",
"=",
"False",
"nexus_response",
"=",
"None",
"while",
"try_num",
"<=",
"max_retries",
":",
"if",
"query_success",
":",
"break",
"log",
".",
"debug",
"(",
"'Attempt # {n} of {m} to query the Nexus URL: {u}'",
".",
"format",
"(",
"n",
"=",
"try_num",
",",
"u",
"=",
"query_url",
",",
"m",
"=",
"max_retries",
")",
")",
"try",
":",
"nexus_response",
"=",
"requests",
".",
"get",
"(",
"query_url",
",",
"auth",
"=",
"basic_auth",
",",
"stream",
"=",
"True",
",",
"timeout",
"=",
"timeout_sec",
")",
"except",
"requests",
".",
"exceptions",
".",
"Timeout",
":",
"_",
",",
"ex",
",",
"trace",
"=",
"sys",
".",
"exc_info",
"(",
")",
"msg",
"=",
"'{n}: Nexus initial query timed out after {t} seconds:\\n{e}'",
".",
"format",
"(",
"n",
"=",
"ex",
".",
"__class__",
".",
"__name__",
",",
"t",
"=",
"timeout_sec",
",",
"r",
"=",
"retry_sec",
",",
"e",
"=",
"str",
"(",
"ex",
")",
")",
"log",
".",
"warn",
"(",
"msg",
")",
"if",
"try_num",
"<",
"max_retries",
":",
"log",
".",
"info",
"(",
"'Retrying query in {t} sec...'",
".",
"format",
"(",
"t",
"=",
"retry_sec",
")",
")",
"time",
".",
"sleep",
"(",
"retry_sec",
")",
"except",
"(",
"requests",
".",
"exceptions",
".",
"RequestException",
",",
"requests",
".",
"exceptions",
".",
"ConnectionError",
")",
":",
"_",
",",
"ex",
",",
"trace",
"=",
"sys",
".",
"exc_info",
"(",
")",
"msg",
"=",
"'{n}: Nexus initial query failed with the following exception:\\n{e}'",
".",
"format",
"(",
"n",
"=",
"ex",
".",
"__class__",
".",
"__name__",
",",
"r",
"=",
"retry_sec",
",",
"e",
"=",
"str",
"(",
"ex",
")",
")",
"log",
".",
"warn",
"(",
"msg",
")",
"if",
"try_num",
"<",
"max_retries",
":",
"log",
".",
"info",
"(",
"'Retrying query in {t} sec...'",
".",
"format",
"(",
"t",
"=",
"retry_sec",
")",
")",
"time",
".",
"sleep",
"(",
"retry_sec",
")",
"else",
":",
"query_success",
"=",
"True",
"try_num",
"+=",
"1",
"if",
"not",
"query_success",
":",
"msg",
"=",
"'Unable to query Nexus after {m} attempts using URL: {u}'",
".",
"format",
"(",
"u",
"=",
"query_url",
",",
"m",
"=",
"max_retries",
")",
"log",
".",
"error",
"(",
"msg",
")",
"raise",
"RuntimeError",
"(",
"msg",
")",
"if",
"nexus_response",
".",
"status_code",
"!=",
"200",
":",
"msg",
"=",
"'Nexus request returned code {c}, unable to query Nexus using URL: {u}'",
".",
"format",
"(",
"u",
"=",
"query_url",
",",
"c",
"=",
"nexus_response",
".",
"status_code",
")",
"log",
".",
"error",
"(",
"msg",
")",
"raise",
"RuntimeError",
"(",
"msg",
")",
"return",
"nexus_response"
] | Queries Nexus for an artifact
:param query_url: (str) Query URL
:param timeout_sec: (int) query timeout
:param basic_auth (HTTPBasicAuth) object or none
:return: requests.Response object
:raises: RuntimeError | [
"Queries",
"Nexus",
"for",
"an",
"artifact"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/nexus.py#L39-L93 |
cons3rt/pycons3rt | pycons3rt/nexus.py | get_artifact | def get_artifact(suppress_status=False, nexus_url=sample_nexus_url, timeout_sec=600, overwrite=True,
username=None, password=None, **kwargs):
"""Retrieves an artifact from Nexus
:param suppress_status: (bool) Set to True to suppress printing download status
:param nexus_url: (str) URL of the Nexus Server
:param timeout_sec: (int) Number of seconds to wait before
timing out the artifact retrieval.
:param overwrite: (bool) True overwrites the file on the local system if it exists,
False does will log an INFO message and exist if the file already exists
:param username: (str) username for basic auth
:param password: (str) password for basic auth
:param kwargs:
group_id: (str) The artifact's Group ID in Nexus
artifact_id: (str) The artifact's Artifact ID in Nexus
packaging: (str) The artifact's packaging (e.g. war, zip)
version: (str) Version of the artifact to retrieve (e.g.
LATEST, 4.8.4, 4.9.0-SNAPSHOT)
destination_dir: (str) Full path to the destination directory
classifier: (str) The artifact's classifier (e.g. bin)
:return: None
:raises: TypeError, ValueError, OSError, RuntimeError
"""
log = logging.getLogger(mod_logger + '.get_artifact')
required_args = ['group_id', 'artifact_id', 'packaging', 'version', 'destination_dir']
if not isinstance(overwrite, bool):
msg = 'overwrite arg must be a string, found: {t}'.format(t=overwrite.__class__.__name__)
log.error(msg)
raise TypeError(msg)
if not isinstance(nexus_url, basestring):
msg = 'nexus_url arg must be a string, found: {t}'.format(t=nexus_url.__class__.__name__)
log.error(msg)
raise TypeError(msg)
log.debug('Using Nexus Server URL: {u}'.format(u=nexus_url))
# Ensure the required args are supplied, and that they are all strings
for required_arg in required_args:
try:
assert required_arg in kwargs
except AssertionError:
_, ex, trace = sys.exc_info()
msg = 'A required arg was not supplied. Required args are: group_id, artifact_id, classifier, version, ' \
'packaging and destination_dir\n{e}'.format(e=str(ex))
log.error(msg)
raise ValueError(msg)
if not isinstance(kwargs[required_arg], basestring):
msg = 'Arg {a} should be a string'.format(a=required_arg)
log.error(msg)
raise TypeError(msg)
# Set variables to be used in the REST call
group_id = kwargs['group_id']
artifact_id = kwargs['artifact_id']
version = kwargs['version']
packaging = kwargs['packaging']
destination_dir = kwargs['destination_dir']
# Ensure the destination directory exists
if not os.path.isdir(destination_dir):
log.debug('Specified destination_dir not found on file system, creating: {d}'.format(d=destination_dir))
try:
mkdir_p(destination_dir)
except CommandError:
_, ex, trace = sys.exc_info()
msg = 'Unable to create destination directory: {d}\n{e}'.format(d=destination_dir, e=str(ex))
raise OSError(msg)
# Set the classifier if it was provided
classifier = None
if 'classifier' in kwargs:
if isinstance(kwargs['classifier'], basestring):
classifier = kwargs['classifier']
log.debug('Using classifier: {c}'.format(c=classifier))
else:
log.warn('Arg classifier provided but it was not an instance of basestring')
# Set the repo if it was provided
repo = None
if 'repo' in kwargs:
if isinstance(kwargs['repo'], basestring):
repo = kwargs['repo']
log.debug('Using repo: {r}'.format(r=repo))
# Determine the repo based on the version
if repo is None:
repo_test = version.lower().strip()
log.debug('Checking if the version {v} is a release or snapshot...'.format(v=repo_test))
# Determine the repo based on the version
if ('snapshot' in repo_test) or (repo_test == 'latest'):
repo = 'snapshots'
else:
repo = 'releases'
log.info('Based on the version {v}, determined repo: {r}'.format(v=version, r=repo))
# Construct the parameter string
params = 'g=' + group_id + '&a=' + artifact_id + '&v=' + version + '&r=' + repo + '&p=' + packaging
# Add the classifier if it was provided
if classifier is not None:
params = params + '&c=' + classifier
# Determine the auth based on username and password
basic_auth = None
if (username is not None) and (password is not None):
log.info('Using the provided username/password for basic authentication...')
basic_auth = HTTPBasicAuth(username, password)
# Build the query URL
query_url = nexus_url + '?' + params
# Set up for download attempts
retry_sec = 5
max_retries = 6
try_num = 1
download_success = False
dl_err = None
failed_attempt = False
# Start the retry loop
while try_num <= max_retries:
# Break the loop if the download was successful
if download_success:
break
log.info('Attempting to query Nexus for the Artifact using URL: {u}'.format(u=query_url))
try:
nexus_response = query_nexus(query_url=query_url, timeout_sec=timeout_sec, basic_auth=basic_auth)
except RuntimeError:
_, ex, trace = sys.exc_info()
msg = '{n}: There was a problem querying Nexus URL: {u}\n{e}'.format(
n=ex.__class__.__name__, u=query_url, e=str(ex))
log.error(msg)
raise RuntimeError, msg, trace
# Attempt to get the content-length
file_size = 0
try:
file_size = int(nexus_response.headers['Content-Length'])
except(KeyError, ValueError):
log.debug('Could not get Content-Length, suppressing download status...')
suppress_status = True
else:
log.info('Artifact file size: {s}'.format(s=file_size))
# Determine the full download file path
file_name = nexus_response.url.split('/')[-1]
download_file = os.path.join(destination_dir, file_name)
# Attempt to download the content from the response
log.info('Attempting to download content of size {s} from Nexus to file: {d}'.format(
s=file_size, d=download_file))
# Remove the existing file if it exists, or exit if the file exists, overwrite is set,
# and there was not a previous failed attempted download
if os.path.isfile(download_file) and overwrite:
log.debug('File already exists, removing: {d}'.format(d=download_file))
os.remove(download_file)
elif os.path.isfile(download_file) and not overwrite and not failed_attempt:
log.info('File already downloaded, and overwrite is set to False. The Artifact will '
'not be retrieved from Nexus: {f}. To overwrite the existing downloaded file, '
'set overwrite=True'.format(f=download_file))
return
# Attempt to download content
log.debug('Attempt # {n} of {m} to download content from the Nexus response'.format(n=try_num, m=max_retries))
chunk_size = 1024
file_size_dl = 0
try:
with open(download_file, 'wb') as f:
for chunk in nexus_response.iter_content(chunk_size=chunk_size):
if chunk:
f.write(chunk)
file_size_dl += len(chunk)
status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
status += chr(8)*(len(status)+1)
if not suppress_status:
print(status),
except(requests.exceptions.ConnectionError, requests.exceptions.RequestException, OSError):
_, ex, trace = sys.exc_info()
dl_err = '{n}: There was an error reading content from the Nexus response. Downloaded ' \
'size: {s}.\n{e}'.format(n=ex.__class__.__name__, s=file_size_dl, t=retry_sec, e=str(ex))
failed_attempt = True
log.warn(dl_err)
if try_num < max_retries:
log.info('Retrying download in {t} sec...'.format(t=retry_sec))
time.sleep(retry_sec)
else:
log.info('File download of size {s} completed without error: {f}'.format(s=file_size_dl, f=download_file))
failed_attempt = False
download_success = True
try_num += 1
# Raise an exception if the download did not complete successfully
if not download_success:
msg = 'Unable to download file content from Nexus after {n} attempts'.format(n=max_retries)
if dl_err:
msg += '\n{m}'.format(m=dl_err)
log.error(msg)
raise RuntimeError(msg) | python | def get_artifact(suppress_status=False, nexus_url=sample_nexus_url, timeout_sec=600, overwrite=True,
username=None, password=None, **kwargs):
"""Retrieves an artifact from Nexus
:param suppress_status: (bool) Set to True to suppress printing download status
:param nexus_url: (str) URL of the Nexus Server
:param timeout_sec: (int) Number of seconds to wait before
timing out the artifact retrieval.
:param overwrite: (bool) True overwrites the file on the local system if it exists,
False does will log an INFO message and exist if the file already exists
:param username: (str) username for basic auth
:param password: (str) password for basic auth
:param kwargs:
group_id: (str) The artifact's Group ID in Nexus
artifact_id: (str) The artifact's Artifact ID in Nexus
packaging: (str) The artifact's packaging (e.g. war, zip)
version: (str) Version of the artifact to retrieve (e.g.
LATEST, 4.8.4, 4.9.0-SNAPSHOT)
destination_dir: (str) Full path to the destination directory
classifier: (str) The artifact's classifier (e.g. bin)
:return: None
:raises: TypeError, ValueError, OSError, RuntimeError
"""
log = logging.getLogger(mod_logger + '.get_artifact')
required_args = ['group_id', 'artifact_id', 'packaging', 'version', 'destination_dir']
if not isinstance(overwrite, bool):
msg = 'overwrite arg must be a string, found: {t}'.format(t=overwrite.__class__.__name__)
log.error(msg)
raise TypeError(msg)
if not isinstance(nexus_url, basestring):
msg = 'nexus_url arg must be a string, found: {t}'.format(t=nexus_url.__class__.__name__)
log.error(msg)
raise TypeError(msg)
log.debug('Using Nexus Server URL: {u}'.format(u=nexus_url))
# Ensure the required args are supplied, and that they are all strings
for required_arg in required_args:
try:
assert required_arg in kwargs
except AssertionError:
_, ex, trace = sys.exc_info()
msg = 'A required arg was not supplied. Required args are: group_id, artifact_id, classifier, version, ' \
'packaging and destination_dir\n{e}'.format(e=str(ex))
log.error(msg)
raise ValueError(msg)
if not isinstance(kwargs[required_arg], basestring):
msg = 'Arg {a} should be a string'.format(a=required_arg)
log.error(msg)
raise TypeError(msg)
# Set variables to be used in the REST call
group_id = kwargs['group_id']
artifact_id = kwargs['artifact_id']
version = kwargs['version']
packaging = kwargs['packaging']
destination_dir = kwargs['destination_dir']
# Ensure the destination directory exists
if not os.path.isdir(destination_dir):
log.debug('Specified destination_dir not found on file system, creating: {d}'.format(d=destination_dir))
try:
mkdir_p(destination_dir)
except CommandError:
_, ex, trace = sys.exc_info()
msg = 'Unable to create destination directory: {d}\n{e}'.format(d=destination_dir, e=str(ex))
raise OSError(msg)
# Set the classifier if it was provided
classifier = None
if 'classifier' in kwargs:
if isinstance(kwargs['classifier'], basestring):
classifier = kwargs['classifier']
log.debug('Using classifier: {c}'.format(c=classifier))
else:
log.warn('Arg classifier provided but it was not an instance of basestring')
# Set the repo if it was provided
repo = None
if 'repo' in kwargs:
if isinstance(kwargs['repo'], basestring):
repo = kwargs['repo']
log.debug('Using repo: {r}'.format(r=repo))
# Determine the repo based on the version
if repo is None:
repo_test = version.lower().strip()
log.debug('Checking if the version {v} is a release or snapshot...'.format(v=repo_test))
# Determine the repo based on the version
if ('snapshot' in repo_test) or (repo_test == 'latest'):
repo = 'snapshots'
else:
repo = 'releases'
log.info('Based on the version {v}, determined repo: {r}'.format(v=version, r=repo))
# Construct the parameter string
params = 'g=' + group_id + '&a=' + artifact_id + '&v=' + version + '&r=' + repo + '&p=' + packaging
# Add the classifier if it was provided
if classifier is not None:
params = params + '&c=' + classifier
# Determine the auth based on username and password
basic_auth = None
if (username is not None) and (password is not None):
log.info('Using the provided username/password for basic authentication...')
basic_auth = HTTPBasicAuth(username, password)
# Build the query URL
query_url = nexus_url + '?' + params
# Set up for download attempts
retry_sec = 5
max_retries = 6
try_num = 1
download_success = False
dl_err = None
failed_attempt = False
# Start the retry loop
while try_num <= max_retries:
# Break the loop if the download was successful
if download_success:
break
log.info('Attempting to query Nexus for the Artifact using URL: {u}'.format(u=query_url))
try:
nexus_response = query_nexus(query_url=query_url, timeout_sec=timeout_sec, basic_auth=basic_auth)
except RuntimeError:
_, ex, trace = sys.exc_info()
msg = '{n}: There was a problem querying Nexus URL: {u}\n{e}'.format(
n=ex.__class__.__name__, u=query_url, e=str(ex))
log.error(msg)
raise RuntimeError, msg, trace
# Attempt to get the content-length
file_size = 0
try:
file_size = int(nexus_response.headers['Content-Length'])
except(KeyError, ValueError):
log.debug('Could not get Content-Length, suppressing download status...')
suppress_status = True
else:
log.info('Artifact file size: {s}'.format(s=file_size))
# Determine the full download file path
file_name = nexus_response.url.split('/')[-1]
download_file = os.path.join(destination_dir, file_name)
# Attempt to download the content from the response
log.info('Attempting to download content of size {s} from Nexus to file: {d}'.format(
s=file_size, d=download_file))
# Remove the existing file if it exists, or exit if the file exists, overwrite is set,
# and there was not a previous failed attempted download
if os.path.isfile(download_file) and overwrite:
log.debug('File already exists, removing: {d}'.format(d=download_file))
os.remove(download_file)
elif os.path.isfile(download_file) and not overwrite and not failed_attempt:
log.info('File already downloaded, and overwrite is set to False. The Artifact will '
'not be retrieved from Nexus: {f}. To overwrite the existing downloaded file, '
'set overwrite=True'.format(f=download_file))
return
# Attempt to download content
log.debug('Attempt # {n} of {m} to download content from the Nexus response'.format(n=try_num, m=max_retries))
chunk_size = 1024
file_size_dl = 0
try:
with open(download_file, 'wb') as f:
for chunk in nexus_response.iter_content(chunk_size=chunk_size):
if chunk:
f.write(chunk)
file_size_dl += len(chunk)
status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
status += chr(8)*(len(status)+1)
if not suppress_status:
print(status),
except(requests.exceptions.ConnectionError, requests.exceptions.RequestException, OSError):
_, ex, trace = sys.exc_info()
dl_err = '{n}: There was an error reading content from the Nexus response. Downloaded ' \
'size: {s}.\n{e}'.format(n=ex.__class__.__name__, s=file_size_dl, t=retry_sec, e=str(ex))
failed_attempt = True
log.warn(dl_err)
if try_num < max_retries:
log.info('Retrying download in {t} sec...'.format(t=retry_sec))
time.sleep(retry_sec)
else:
log.info('File download of size {s} completed without error: {f}'.format(s=file_size_dl, f=download_file))
failed_attempt = False
download_success = True
try_num += 1
# Raise an exception if the download did not complete successfully
if not download_success:
msg = 'Unable to download file content from Nexus after {n} attempts'.format(n=max_retries)
if dl_err:
msg += '\n{m}'.format(m=dl_err)
log.error(msg)
raise RuntimeError(msg) | [
"def",
"get_artifact",
"(",
"suppress_status",
"=",
"False",
",",
"nexus_url",
"=",
"sample_nexus_url",
",",
"timeout_sec",
"=",
"600",
",",
"overwrite",
"=",
"True",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.get_artifact'",
")",
"required_args",
"=",
"[",
"'group_id'",
",",
"'artifact_id'",
",",
"'packaging'",
",",
"'version'",
",",
"'destination_dir'",
"]",
"if",
"not",
"isinstance",
"(",
"overwrite",
",",
"bool",
")",
":",
"msg",
"=",
"'overwrite arg must be a string, found: {t}'",
".",
"format",
"(",
"t",
"=",
"overwrite",
".",
"__class__",
".",
"__name__",
")",
"log",
".",
"error",
"(",
"msg",
")",
"raise",
"TypeError",
"(",
"msg",
")",
"if",
"not",
"isinstance",
"(",
"nexus_url",
",",
"basestring",
")",
":",
"msg",
"=",
"'nexus_url arg must be a string, found: {t}'",
".",
"format",
"(",
"t",
"=",
"nexus_url",
".",
"__class__",
".",
"__name__",
")",
"log",
".",
"error",
"(",
"msg",
")",
"raise",
"TypeError",
"(",
"msg",
")",
"log",
".",
"debug",
"(",
"'Using Nexus Server URL: {u}'",
".",
"format",
"(",
"u",
"=",
"nexus_url",
")",
")",
"# Ensure the required args are supplied, and that they are all strings",
"for",
"required_arg",
"in",
"required_args",
":",
"try",
":",
"assert",
"required_arg",
"in",
"kwargs",
"except",
"AssertionError",
":",
"_",
",",
"ex",
",",
"trace",
"=",
"sys",
".",
"exc_info",
"(",
")",
"msg",
"=",
"'A required arg was not supplied. Required args are: group_id, artifact_id, classifier, version, '",
"'packaging and destination_dir\\n{e}'",
".",
"format",
"(",
"e",
"=",
"str",
"(",
"ex",
")",
")",
"log",
".",
"error",
"(",
"msg",
")",
"raise",
"ValueError",
"(",
"msg",
")",
"if",
"not",
"isinstance",
"(",
"kwargs",
"[",
"required_arg",
"]",
",",
"basestring",
")",
":",
"msg",
"=",
"'Arg {a} should be a string'",
".",
"format",
"(",
"a",
"=",
"required_arg",
")",
"log",
".",
"error",
"(",
"msg",
")",
"raise",
"TypeError",
"(",
"msg",
")",
"# Set variables to be used in the REST call",
"group_id",
"=",
"kwargs",
"[",
"'group_id'",
"]",
"artifact_id",
"=",
"kwargs",
"[",
"'artifact_id'",
"]",
"version",
"=",
"kwargs",
"[",
"'version'",
"]",
"packaging",
"=",
"kwargs",
"[",
"'packaging'",
"]",
"destination_dir",
"=",
"kwargs",
"[",
"'destination_dir'",
"]",
"# Ensure the destination directory exists",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"destination_dir",
")",
":",
"log",
".",
"debug",
"(",
"'Specified destination_dir not found on file system, creating: {d}'",
".",
"format",
"(",
"d",
"=",
"destination_dir",
")",
")",
"try",
":",
"mkdir_p",
"(",
"destination_dir",
")",
"except",
"CommandError",
":",
"_",
",",
"ex",
",",
"trace",
"=",
"sys",
".",
"exc_info",
"(",
")",
"msg",
"=",
"'Unable to create destination directory: {d}\\n{e}'",
".",
"format",
"(",
"d",
"=",
"destination_dir",
",",
"e",
"=",
"str",
"(",
"ex",
")",
")",
"raise",
"OSError",
"(",
"msg",
")",
"# Set the classifier if it was provided",
"classifier",
"=",
"None",
"if",
"'classifier'",
"in",
"kwargs",
":",
"if",
"isinstance",
"(",
"kwargs",
"[",
"'classifier'",
"]",
",",
"basestring",
")",
":",
"classifier",
"=",
"kwargs",
"[",
"'classifier'",
"]",
"log",
".",
"debug",
"(",
"'Using classifier: {c}'",
".",
"format",
"(",
"c",
"=",
"classifier",
")",
")",
"else",
":",
"log",
".",
"warn",
"(",
"'Arg classifier provided but it was not an instance of basestring'",
")",
"# Set the repo if it was provided",
"repo",
"=",
"None",
"if",
"'repo'",
"in",
"kwargs",
":",
"if",
"isinstance",
"(",
"kwargs",
"[",
"'repo'",
"]",
",",
"basestring",
")",
":",
"repo",
"=",
"kwargs",
"[",
"'repo'",
"]",
"log",
".",
"debug",
"(",
"'Using repo: {r}'",
".",
"format",
"(",
"r",
"=",
"repo",
")",
")",
"# Determine the repo based on the version",
"if",
"repo",
"is",
"None",
":",
"repo_test",
"=",
"version",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
"log",
".",
"debug",
"(",
"'Checking if the version {v} is a release or snapshot...'",
".",
"format",
"(",
"v",
"=",
"repo_test",
")",
")",
"# Determine the repo based on the version",
"if",
"(",
"'snapshot'",
"in",
"repo_test",
")",
"or",
"(",
"repo_test",
"==",
"'latest'",
")",
":",
"repo",
"=",
"'snapshots'",
"else",
":",
"repo",
"=",
"'releases'",
"log",
".",
"info",
"(",
"'Based on the version {v}, determined repo: {r}'",
".",
"format",
"(",
"v",
"=",
"version",
",",
"r",
"=",
"repo",
")",
")",
"# Construct the parameter string",
"params",
"=",
"'g='",
"+",
"group_id",
"+",
"'&a='",
"+",
"artifact_id",
"+",
"'&v='",
"+",
"version",
"+",
"'&r='",
"+",
"repo",
"+",
"'&p='",
"+",
"packaging",
"# Add the classifier if it was provided",
"if",
"classifier",
"is",
"not",
"None",
":",
"params",
"=",
"params",
"+",
"'&c='",
"+",
"classifier",
"# Determine the auth based on username and password",
"basic_auth",
"=",
"None",
"if",
"(",
"username",
"is",
"not",
"None",
")",
"and",
"(",
"password",
"is",
"not",
"None",
")",
":",
"log",
".",
"info",
"(",
"'Using the provided username/password for basic authentication...'",
")",
"basic_auth",
"=",
"HTTPBasicAuth",
"(",
"username",
",",
"password",
")",
"# Build the query URL",
"query_url",
"=",
"nexus_url",
"+",
"'?'",
"+",
"params",
"# Set up for download attempts",
"retry_sec",
"=",
"5",
"max_retries",
"=",
"6",
"try_num",
"=",
"1",
"download_success",
"=",
"False",
"dl_err",
"=",
"None",
"failed_attempt",
"=",
"False",
"# Start the retry loop",
"while",
"try_num",
"<=",
"max_retries",
":",
"# Break the loop if the download was successful",
"if",
"download_success",
":",
"break",
"log",
".",
"info",
"(",
"'Attempting to query Nexus for the Artifact using URL: {u}'",
".",
"format",
"(",
"u",
"=",
"query_url",
")",
")",
"try",
":",
"nexus_response",
"=",
"query_nexus",
"(",
"query_url",
"=",
"query_url",
",",
"timeout_sec",
"=",
"timeout_sec",
",",
"basic_auth",
"=",
"basic_auth",
")",
"except",
"RuntimeError",
":",
"_",
",",
"ex",
",",
"trace",
"=",
"sys",
".",
"exc_info",
"(",
")",
"msg",
"=",
"'{n}: There was a problem querying Nexus URL: {u}\\n{e}'",
".",
"format",
"(",
"n",
"=",
"ex",
".",
"__class__",
".",
"__name__",
",",
"u",
"=",
"query_url",
",",
"e",
"=",
"str",
"(",
"ex",
")",
")",
"log",
".",
"error",
"(",
"msg",
")",
"raise",
"RuntimeError",
",",
"msg",
",",
"trace",
"# Attempt to get the content-length",
"file_size",
"=",
"0",
"try",
":",
"file_size",
"=",
"int",
"(",
"nexus_response",
".",
"headers",
"[",
"'Content-Length'",
"]",
")",
"except",
"(",
"KeyError",
",",
"ValueError",
")",
":",
"log",
".",
"debug",
"(",
"'Could not get Content-Length, suppressing download status...'",
")",
"suppress_status",
"=",
"True",
"else",
":",
"log",
".",
"info",
"(",
"'Artifact file size: {s}'",
".",
"format",
"(",
"s",
"=",
"file_size",
")",
")",
"# Determine the full download file path",
"file_name",
"=",
"nexus_response",
".",
"url",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
"download_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"destination_dir",
",",
"file_name",
")",
"# Attempt to download the content from the response",
"log",
".",
"info",
"(",
"'Attempting to download content of size {s} from Nexus to file: {d}'",
".",
"format",
"(",
"s",
"=",
"file_size",
",",
"d",
"=",
"download_file",
")",
")",
"# Remove the existing file if it exists, or exit if the file exists, overwrite is set,",
"# and there was not a previous failed attempted download",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"download_file",
")",
"and",
"overwrite",
":",
"log",
".",
"debug",
"(",
"'File already exists, removing: {d}'",
".",
"format",
"(",
"d",
"=",
"download_file",
")",
")",
"os",
".",
"remove",
"(",
"download_file",
")",
"elif",
"os",
".",
"path",
".",
"isfile",
"(",
"download_file",
")",
"and",
"not",
"overwrite",
"and",
"not",
"failed_attempt",
":",
"log",
".",
"info",
"(",
"'File already downloaded, and overwrite is set to False. The Artifact will '",
"'not be retrieved from Nexus: {f}. To overwrite the existing downloaded file, '",
"'set overwrite=True'",
".",
"format",
"(",
"f",
"=",
"download_file",
")",
")",
"return",
"# Attempt to download content",
"log",
".",
"debug",
"(",
"'Attempt # {n} of {m} to download content from the Nexus response'",
".",
"format",
"(",
"n",
"=",
"try_num",
",",
"m",
"=",
"max_retries",
")",
")",
"chunk_size",
"=",
"1024",
"file_size_dl",
"=",
"0",
"try",
":",
"with",
"open",
"(",
"download_file",
",",
"'wb'",
")",
"as",
"f",
":",
"for",
"chunk",
"in",
"nexus_response",
".",
"iter_content",
"(",
"chunk_size",
"=",
"chunk_size",
")",
":",
"if",
"chunk",
":",
"f",
".",
"write",
"(",
"chunk",
")",
"file_size_dl",
"+=",
"len",
"(",
"chunk",
")",
"status",
"=",
"r\"%10d [%3.2f%%]\"",
"%",
"(",
"file_size_dl",
",",
"file_size_dl",
"*",
"100.",
"/",
"file_size",
")",
"status",
"+=",
"chr",
"(",
"8",
")",
"*",
"(",
"len",
"(",
"status",
")",
"+",
"1",
")",
"if",
"not",
"suppress_status",
":",
"print",
"(",
"status",
")",
",",
"except",
"(",
"requests",
".",
"exceptions",
".",
"ConnectionError",
",",
"requests",
".",
"exceptions",
".",
"RequestException",
",",
"OSError",
")",
":",
"_",
",",
"ex",
",",
"trace",
"=",
"sys",
".",
"exc_info",
"(",
")",
"dl_err",
"=",
"'{n}: There was an error reading content from the Nexus response. Downloaded '",
"'size: {s}.\\n{e}'",
".",
"format",
"(",
"n",
"=",
"ex",
".",
"__class__",
".",
"__name__",
",",
"s",
"=",
"file_size_dl",
",",
"t",
"=",
"retry_sec",
",",
"e",
"=",
"str",
"(",
"ex",
")",
")",
"failed_attempt",
"=",
"True",
"log",
".",
"warn",
"(",
"dl_err",
")",
"if",
"try_num",
"<",
"max_retries",
":",
"log",
".",
"info",
"(",
"'Retrying download in {t} sec...'",
".",
"format",
"(",
"t",
"=",
"retry_sec",
")",
")",
"time",
".",
"sleep",
"(",
"retry_sec",
")",
"else",
":",
"log",
".",
"info",
"(",
"'File download of size {s} completed without error: {f}'",
".",
"format",
"(",
"s",
"=",
"file_size_dl",
",",
"f",
"=",
"download_file",
")",
")",
"failed_attempt",
"=",
"False",
"download_success",
"=",
"True",
"try_num",
"+=",
"1",
"# Raise an exception if the download did not complete successfully",
"if",
"not",
"download_success",
":",
"msg",
"=",
"'Unable to download file content from Nexus after {n} attempts'",
".",
"format",
"(",
"n",
"=",
"max_retries",
")",
"if",
"dl_err",
":",
"msg",
"+=",
"'\\n{m}'",
".",
"format",
"(",
"m",
"=",
"dl_err",
")",
"log",
".",
"error",
"(",
"msg",
")",
"raise",
"RuntimeError",
"(",
"msg",
")"
] | Retrieves an artifact from Nexus
:param suppress_status: (bool) Set to True to suppress printing download status
:param nexus_url: (str) URL of the Nexus Server
:param timeout_sec: (int) Number of seconds to wait before
timing out the artifact retrieval.
:param overwrite: (bool) True overwrites the file on the local system if it exists,
False does will log an INFO message and exist if the file already exists
:param username: (str) username for basic auth
:param password: (str) password for basic auth
:param kwargs:
group_id: (str) The artifact's Group ID in Nexus
artifact_id: (str) The artifact's Artifact ID in Nexus
packaging: (str) The artifact's packaging (e.g. war, zip)
version: (str) Version of the artifact to retrieve (e.g.
LATEST, 4.8.4, 4.9.0-SNAPSHOT)
destination_dir: (str) Full path to the destination directory
classifier: (str) The artifact's classifier (e.g. bin)
:return: None
:raises: TypeError, ValueError, OSError, RuntimeError | [
"Retrieves",
"an",
"artifact",
"from",
"Nexus"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/nexus.py#L96-L299 |
cons3rt/pycons3rt | pycons3rt/nexus.py | get_artifact_nexus3 | def get_artifact_nexus3(suppress_status=False, nexus_base_url=sample_nexus_base_url, repository=None,
timeout_sec=600, overwrite=True, username=None, password=None, **kwargs):
"""Retrieves an artifact from the Nexus 3 ReST API
:param suppress_status: (bool) Set to True to suppress printing download status
:param nexus_base_url: (str) Base URL of the Nexus Server (domain name portion only, see sample)
:param repository: (str) Repository to query (e.g. snapshots) if not provided, will attempt to determine
:param timeout_sec: (int) Number of seconds to wait before
timing out the artifact retrieval.
:param overwrite: (bool) True overwrites the file on the local system if it exists,
False does will log an INFO message and exist if the file already exists
:param username: (str) username for basic auth
:param password: (str) password for basic auth
:param kwargs:
group_id: (str) The artifact's Group ID in Nexus
artifact_id: (str) The artifact's Artifact ID in Nexus
packaging: (str) The artifact's packaging (e.g. war, zip)
version: (str) Version of the artifact to retrieve (e.g.
LATEST, 4.8.4, 4.9.0-SNAPSHOT)
destination_dir: (str) Full path to the destination directory
classifier: (str) The artifact's classifier (e.g. bin)
:return: None
:raises: TypeError, ValueError, OSError, RuntimeError
"""
log = logging.getLogger(mod_logger + '.get_artifact_nexus3')
required_args = ['group_id', 'artifact_id', 'packaging', 'version', 'destination_dir']
if not isinstance(overwrite, bool):
msg = 'overwrite arg must be a string, found: {t}'.format(t=overwrite.__class__.__name__)
log.error(msg)
raise TypeError(msg)
if not isinstance(nexus_base_url, basestring):
msg = 'nexus_url arg must be a string, found: {t}'.format(t=nexus_base_url.__class__.__name__)
log.error(msg)
raise TypeError(msg)
log.debug('Using Nexus Server URL: {u}'.format(u=nexus_base_url))
# Ensure the required args are supplied, and that they are all strings
for required_arg in required_args:
try:
assert required_arg in kwargs
except AssertionError:
_, ex, trace = sys.exc_info()
msg = 'A required arg was not supplied. Required args are: group_id, artifact_id, classifier, version, ' \
'packaging and destination_dir\n{e}'.format(e=str(ex))
log.error(msg)
raise ValueError(msg)
if not isinstance(kwargs[required_arg], basestring):
msg = 'Arg {a} should be a string'.format(a=required_arg)
log.error(msg)
raise TypeError(msg)
# Set variables to be used in the REST call
group_id = kwargs['group_id']
artifact_id = kwargs['artifact_id']
version = kwargs['version']
packaging = kwargs['packaging']
destination_dir = kwargs['destination_dir']
# Ensure the destination directory exists
if not os.path.isdir(destination_dir):
log.debug('Specified destination_dir not found on file system, creating: {d}'.format(d=destination_dir))
try:
mkdir_p(destination_dir)
except CommandError:
_, ex, trace = sys.exc_info()
msg = 'Unable to create destination directory: {d}\n{e}'.format(d=destination_dir, e=str(ex))
raise OSError(msg)
# Determine the auth based on username and password
basic_auth = None
if (username is not None) and (password is not None):
log.info('Using the provided username/password for basic authentication...')
basic_auth = HTTPBasicAuth(username, password)
# Set the classifier if it was provided
classifier = None
if 'classifier' in kwargs:
if isinstance(kwargs['classifier'], basestring):
classifier = kwargs['classifier']
log.debug('Using classifier: {c}'.format(c=classifier))
else:
log.warn('Arg classifier provided but it was not an instance of basestring')
# Determine the repository (snapshots or releases)
if not repository:
if 'SNAPSHOT' in version:
repository = 'snapshots'
else:
repository = 'releases'
log.debug('Using repository: {r}'.format(r=repository))
# Compute the query URL
group_id_url = group_id.replace('.', '/')
# Get the Maven metadata
query_url_version = nexus_base_url + '/repository/{r}/{g}/{a}/{v}'.format(
r=repository, g=group_id_url, a=artifact_id, v=version
)
if 'snapshot' in repository.lower():
# Query nexus for metadata to determine the proper file name
query_url_metadata = query_url_version + '/maven-metadata.xml'
log.info('Attempting to query Nexus for the snapshot metadata using URL: {u}'.format(u=query_url_metadata))
try:
nexus_response = query_nexus(query_url=query_url_metadata, timeout_sec=timeout_sec, basic_auth=basic_auth)
except RuntimeError:
_, ex, trace = sys.exc_info()
msg = '{n}: There was a problem querying Nexus URL: {u}\n{e}'.format(
n=ex.__class__.__name__, u=query_url_metadata, e=str(ex))
log.error(msg)
raise RuntimeError, msg, trace
if nexus_response.status_code != 200:
raise RuntimeError('Bad response from Nexus metadata URL [{c}]: {u}'.format(
c=nexus_response.status_code, u=query_url_metadata))
# Parse the XML output
root = ET.fromstring(nexus_response.text)
log.info('Attempting to find the value of the file name...')
try:
value = root.find('versioning').find('snapshotVersions').find('snapshotVersion').find('value')
except AttributeError:
_, ex, trace = sys.exc_info()
msg = 'AttributeError: Unable to find versioning/snapshotVersions/snapshotVersion/value\n{e}'.format(
e=str(ex))
raise ValueError, msg, trace
# Ensure a value was found
if value is None:
raise ValueError('Unable to determine the value of the snapshot version')
# Get the text version
text_version = value.text
log.info('Found version value: {t}'.format(t=text_version))
# Determine the artifact file name
artifact_file_name = '{a}-{t}'.format(
a=artifact_id,
t=text_version
)
else:
# Construct the file name for releases (e.g. cons3rt-backend-install-18.14.0-package-otto.zip)
artifact_file_name = '{a}-{v}'.format(
a=artifact_id,
v=version
)
# Add classifier if provided and packaging
if classifier:
artifact_file_name += '-{c}'.format(c=classifier)
artifact_file_name += '.{p}'.format(p=packaging)
log.info('Using artifact file name: {n}'.format(n=artifact_file_name))
# Determine the full query URL
query_url = query_url_version + '/{n}'.format(n=artifact_file_name)
log.info('Using Nexus query URL: {u}'.format(u=query_url))
# Set up for download attempts
retry_sec = 5
max_retries = 6
try_num = 1
download_success = False
dl_err = None
failed_attempt = False
# Start the retry loop
while try_num <= max_retries:
# Break the loop if the download was successful
if download_success:
break
log.info('Attempting to query Nexus for the Artifact using URL: {u}'.format(u=query_url))
try:
nexus_response = query_nexus(query_url=query_url, timeout_sec=timeout_sec, basic_auth=basic_auth)
except RuntimeError:
_, ex, trace = sys.exc_info()
msg = '{n}: There was a problem querying Nexus URL: {u}\n{e}'.format(
n=ex.__class__.__name__, u=query_url, e=str(ex))
log.error(msg)
raise RuntimeError, msg, trace
# Attempt to get the content-length
file_size = 0
try:
file_size = int(nexus_response.headers['Content-Length'])
except(KeyError, ValueError):
log.debug('Could not get Content-Length, suppressing download status...')
suppress_status = True
else:
log.info('Artifact file size: {s}'.format(s=file_size))
# Determine the full download file path
file_name = nexus_response.url.split('/')[-1]
download_file = os.path.join(destination_dir, file_name)
# Attempt to download the content from the response
log.info('Attempting to download content of size {s} from Nexus to file: {d}'.format(
s=file_size, d=download_file))
# Remove the existing file if it exists, or exit if the file exists, overwrite is set,
# and there was not a previous failed attempted download
if os.path.isfile(download_file) and overwrite:
log.debug('File already exists, removing: {d}'.format(d=download_file))
os.remove(download_file)
elif os.path.isfile(download_file) and not overwrite and not failed_attempt:
log.info('File already downloaded, and overwrite is set to False. The Artifact will '
'not be retrieved from Nexus: {f}. To overwrite the existing downloaded file, '
'set overwrite=True'.format(f=download_file))
return
# Attempt to download content
log.debug('Attempt # {n} of {m} to download content from the Nexus response'.format(n=try_num, m=max_retries))
chunk_size = 1024
file_size_dl = 0
try:
with open(download_file, 'wb') as f:
for chunk in nexus_response.iter_content(chunk_size=chunk_size):
if chunk:
f.write(chunk)
file_size_dl += len(chunk)
status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
status += chr(8)*(len(status)+1)
if not suppress_status:
print(status),
except(requests.exceptions.ConnectionError, requests.exceptions.RequestException, OSError):
_, ex, trace = sys.exc_info()
dl_err = '{n}: There was an error reading content from the Nexus response. Downloaded ' \
'size: {s}.\n{e}'.format(n=ex.__class__.__name__, s=file_size_dl, t=retry_sec, e=str(ex))
failed_attempt = True
log.warn(dl_err)
if try_num < max_retries:
log.info('Retrying download in {t} sec...'.format(t=retry_sec))
time.sleep(retry_sec)
else:
log.info('File download of size {s} completed without error: {f}'.format(s=file_size_dl, f=download_file))
failed_attempt = False
download_success = True
try_num += 1
# Raise an exception if the download did not complete successfully
if not download_success:
msg = 'Unable to download file content from Nexus after {n} attempts'.format(n=max_retries)
if dl_err:
msg += '\n{m}'.format(m=dl_err)
log.error(msg)
raise RuntimeError(msg) | python | def get_artifact_nexus3(suppress_status=False, nexus_base_url=sample_nexus_base_url, repository=None,
timeout_sec=600, overwrite=True, username=None, password=None, **kwargs):
"""Retrieves an artifact from the Nexus 3 ReST API
:param suppress_status: (bool) Set to True to suppress printing download status
:param nexus_base_url: (str) Base URL of the Nexus Server (domain name portion only, see sample)
:param repository: (str) Repository to query (e.g. snapshots) if not provided, will attempt to determine
:param timeout_sec: (int) Number of seconds to wait before
timing out the artifact retrieval.
:param overwrite: (bool) True overwrites the file on the local system if it exists,
False does will log an INFO message and exist if the file already exists
:param username: (str) username for basic auth
:param password: (str) password for basic auth
:param kwargs:
group_id: (str) The artifact's Group ID in Nexus
artifact_id: (str) The artifact's Artifact ID in Nexus
packaging: (str) The artifact's packaging (e.g. war, zip)
version: (str) Version of the artifact to retrieve (e.g.
LATEST, 4.8.4, 4.9.0-SNAPSHOT)
destination_dir: (str) Full path to the destination directory
classifier: (str) The artifact's classifier (e.g. bin)
:return: None
:raises: TypeError, ValueError, OSError, RuntimeError
"""
log = logging.getLogger(mod_logger + '.get_artifact_nexus3')
required_args = ['group_id', 'artifact_id', 'packaging', 'version', 'destination_dir']
if not isinstance(overwrite, bool):
msg = 'overwrite arg must be a string, found: {t}'.format(t=overwrite.__class__.__name__)
log.error(msg)
raise TypeError(msg)
if not isinstance(nexus_base_url, basestring):
msg = 'nexus_url arg must be a string, found: {t}'.format(t=nexus_base_url.__class__.__name__)
log.error(msg)
raise TypeError(msg)
log.debug('Using Nexus Server URL: {u}'.format(u=nexus_base_url))
# Ensure the required args are supplied, and that they are all strings
for required_arg in required_args:
try:
assert required_arg in kwargs
except AssertionError:
_, ex, trace = sys.exc_info()
msg = 'A required arg was not supplied. Required args are: group_id, artifact_id, classifier, version, ' \
'packaging and destination_dir\n{e}'.format(e=str(ex))
log.error(msg)
raise ValueError(msg)
if not isinstance(kwargs[required_arg], basestring):
msg = 'Arg {a} should be a string'.format(a=required_arg)
log.error(msg)
raise TypeError(msg)
# Set variables to be used in the REST call
group_id = kwargs['group_id']
artifact_id = kwargs['artifact_id']
version = kwargs['version']
packaging = kwargs['packaging']
destination_dir = kwargs['destination_dir']
# Ensure the destination directory exists
if not os.path.isdir(destination_dir):
log.debug('Specified destination_dir not found on file system, creating: {d}'.format(d=destination_dir))
try:
mkdir_p(destination_dir)
except CommandError:
_, ex, trace = sys.exc_info()
msg = 'Unable to create destination directory: {d}\n{e}'.format(d=destination_dir, e=str(ex))
raise OSError(msg)
# Determine the auth based on username and password
basic_auth = None
if (username is not None) and (password is not None):
log.info('Using the provided username/password for basic authentication...')
basic_auth = HTTPBasicAuth(username, password)
# Set the classifier if it was provided
classifier = None
if 'classifier' in kwargs:
if isinstance(kwargs['classifier'], basestring):
classifier = kwargs['classifier']
log.debug('Using classifier: {c}'.format(c=classifier))
else:
log.warn('Arg classifier provided but it was not an instance of basestring')
# Determine the repository (snapshots or releases)
if not repository:
if 'SNAPSHOT' in version:
repository = 'snapshots'
else:
repository = 'releases'
log.debug('Using repository: {r}'.format(r=repository))
# Compute the query URL
group_id_url = group_id.replace('.', '/')
# Get the Maven metadata
query_url_version = nexus_base_url + '/repository/{r}/{g}/{a}/{v}'.format(
r=repository, g=group_id_url, a=artifact_id, v=version
)
if 'snapshot' in repository.lower():
# Query nexus for metadata to determine the proper file name
query_url_metadata = query_url_version + '/maven-metadata.xml'
log.info('Attempting to query Nexus for the snapshot metadata using URL: {u}'.format(u=query_url_metadata))
try:
nexus_response = query_nexus(query_url=query_url_metadata, timeout_sec=timeout_sec, basic_auth=basic_auth)
except RuntimeError:
_, ex, trace = sys.exc_info()
msg = '{n}: There was a problem querying Nexus URL: {u}\n{e}'.format(
n=ex.__class__.__name__, u=query_url_metadata, e=str(ex))
log.error(msg)
raise RuntimeError, msg, trace
if nexus_response.status_code != 200:
raise RuntimeError('Bad response from Nexus metadata URL [{c}]: {u}'.format(
c=nexus_response.status_code, u=query_url_metadata))
# Parse the XML output
root = ET.fromstring(nexus_response.text)
log.info('Attempting to find the value of the file name...')
try:
value = root.find('versioning').find('snapshotVersions').find('snapshotVersion').find('value')
except AttributeError:
_, ex, trace = sys.exc_info()
msg = 'AttributeError: Unable to find versioning/snapshotVersions/snapshotVersion/value\n{e}'.format(
e=str(ex))
raise ValueError, msg, trace
# Ensure a value was found
if value is None:
raise ValueError('Unable to determine the value of the snapshot version')
# Get the text version
text_version = value.text
log.info('Found version value: {t}'.format(t=text_version))
# Determine the artifact file name
artifact_file_name = '{a}-{t}'.format(
a=artifact_id,
t=text_version
)
else:
# Construct the file name for releases (e.g. cons3rt-backend-install-18.14.0-package-otto.zip)
artifact_file_name = '{a}-{v}'.format(
a=artifact_id,
v=version
)
# Add classifier if provided and packaging
if classifier:
artifact_file_name += '-{c}'.format(c=classifier)
artifact_file_name += '.{p}'.format(p=packaging)
log.info('Using artifact file name: {n}'.format(n=artifact_file_name))
# Determine the full query URL
query_url = query_url_version + '/{n}'.format(n=artifact_file_name)
log.info('Using Nexus query URL: {u}'.format(u=query_url))
# Set up for download attempts
retry_sec = 5
max_retries = 6
try_num = 1
download_success = False
dl_err = None
failed_attempt = False
# Start the retry loop
while try_num <= max_retries:
# Break the loop if the download was successful
if download_success:
break
log.info('Attempting to query Nexus for the Artifact using URL: {u}'.format(u=query_url))
try:
nexus_response = query_nexus(query_url=query_url, timeout_sec=timeout_sec, basic_auth=basic_auth)
except RuntimeError:
_, ex, trace = sys.exc_info()
msg = '{n}: There was a problem querying Nexus URL: {u}\n{e}'.format(
n=ex.__class__.__name__, u=query_url, e=str(ex))
log.error(msg)
raise RuntimeError, msg, trace
# Attempt to get the content-length
file_size = 0
try:
file_size = int(nexus_response.headers['Content-Length'])
except(KeyError, ValueError):
log.debug('Could not get Content-Length, suppressing download status...')
suppress_status = True
else:
log.info('Artifact file size: {s}'.format(s=file_size))
# Determine the full download file path
file_name = nexus_response.url.split('/')[-1]
download_file = os.path.join(destination_dir, file_name)
# Attempt to download the content from the response
log.info('Attempting to download content of size {s} from Nexus to file: {d}'.format(
s=file_size, d=download_file))
# Remove the existing file if it exists, or exit if the file exists, overwrite is set,
# and there was not a previous failed attempted download
if os.path.isfile(download_file) and overwrite:
log.debug('File already exists, removing: {d}'.format(d=download_file))
os.remove(download_file)
elif os.path.isfile(download_file) and not overwrite and not failed_attempt:
log.info('File already downloaded, and overwrite is set to False. The Artifact will '
'not be retrieved from Nexus: {f}. To overwrite the existing downloaded file, '
'set overwrite=True'.format(f=download_file))
return
# Attempt to download content
log.debug('Attempt # {n} of {m} to download content from the Nexus response'.format(n=try_num, m=max_retries))
chunk_size = 1024
file_size_dl = 0
try:
with open(download_file, 'wb') as f:
for chunk in nexus_response.iter_content(chunk_size=chunk_size):
if chunk:
f.write(chunk)
file_size_dl += len(chunk)
status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
status += chr(8)*(len(status)+1)
if not suppress_status:
print(status),
except(requests.exceptions.ConnectionError, requests.exceptions.RequestException, OSError):
_, ex, trace = sys.exc_info()
dl_err = '{n}: There was an error reading content from the Nexus response. Downloaded ' \
'size: {s}.\n{e}'.format(n=ex.__class__.__name__, s=file_size_dl, t=retry_sec, e=str(ex))
failed_attempt = True
log.warn(dl_err)
if try_num < max_retries:
log.info('Retrying download in {t} sec...'.format(t=retry_sec))
time.sleep(retry_sec)
else:
log.info('File download of size {s} completed without error: {f}'.format(s=file_size_dl, f=download_file))
failed_attempt = False
download_success = True
try_num += 1
# Raise an exception if the download did not complete successfully
if not download_success:
msg = 'Unable to download file content from Nexus after {n} attempts'.format(n=max_retries)
if dl_err:
msg += '\n{m}'.format(m=dl_err)
log.error(msg)
raise RuntimeError(msg) | [
"def",
"get_artifact_nexus3",
"(",
"suppress_status",
"=",
"False",
",",
"nexus_base_url",
"=",
"sample_nexus_base_url",
",",
"repository",
"=",
"None",
",",
"timeout_sec",
"=",
"600",
",",
"overwrite",
"=",
"True",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.get_artifact_nexus3'",
")",
"required_args",
"=",
"[",
"'group_id'",
",",
"'artifact_id'",
",",
"'packaging'",
",",
"'version'",
",",
"'destination_dir'",
"]",
"if",
"not",
"isinstance",
"(",
"overwrite",
",",
"bool",
")",
":",
"msg",
"=",
"'overwrite arg must be a string, found: {t}'",
".",
"format",
"(",
"t",
"=",
"overwrite",
".",
"__class__",
".",
"__name__",
")",
"log",
".",
"error",
"(",
"msg",
")",
"raise",
"TypeError",
"(",
"msg",
")",
"if",
"not",
"isinstance",
"(",
"nexus_base_url",
",",
"basestring",
")",
":",
"msg",
"=",
"'nexus_url arg must be a string, found: {t}'",
".",
"format",
"(",
"t",
"=",
"nexus_base_url",
".",
"__class__",
".",
"__name__",
")",
"log",
".",
"error",
"(",
"msg",
")",
"raise",
"TypeError",
"(",
"msg",
")",
"log",
".",
"debug",
"(",
"'Using Nexus Server URL: {u}'",
".",
"format",
"(",
"u",
"=",
"nexus_base_url",
")",
")",
"# Ensure the required args are supplied, and that they are all strings",
"for",
"required_arg",
"in",
"required_args",
":",
"try",
":",
"assert",
"required_arg",
"in",
"kwargs",
"except",
"AssertionError",
":",
"_",
",",
"ex",
",",
"trace",
"=",
"sys",
".",
"exc_info",
"(",
")",
"msg",
"=",
"'A required arg was not supplied. Required args are: group_id, artifact_id, classifier, version, '",
"'packaging and destination_dir\\n{e}'",
".",
"format",
"(",
"e",
"=",
"str",
"(",
"ex",
")",
")",
"log",
".",
"error",
"(",
"msg",
")",
"raise",
"ValueError",
"(",
"msg",
")",
"if",
"not",
"isinstance",
"(",
"kwargs",
"[",
"required_arg",
"]",
",",
"basestring",
")",
":",
"msg",
"=",
"'Arg {a} should be a string'",
".",
"format",
"(",
"a",
"=",
"required_arg",
")",
"log",
".",
"error",
"(",
"msg",
")",
"raise",
"TypeError",
"(",
"msg",
")",
"# Set variables to be used in the REST call",
"group_id",
"=",
"kwargs",
"[",
"'group_id'",
"]",
"artifact_id",
"=",
"kwargs",
"[",
"'artifact_id'",
"]",
"version",
"=",
"kwargs",
"[",
"'version'",
"]",
"packaging",
"=",
"kwargs",
"[",
"'packaging'",
"]",
"destination_dir",
"=",
"kwargs",
"[",
"'destination_dir'",
"]",
"# Ensure the destination directory exists",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"destination_dir",
")",
":",
"log",
".",
"debug",
"(",
"'Specified destination_dir not found on file system, creating: {d}'",
".",
"format",
"(",
"d",
"=",
"destination_dir",
")",
")",
"try",
":",
"mkdir_p",
"(",
"destination_dir",
")",
"except",
"CommandError",
":",
"_",
",",
"ex",
",",
"trace",
"=",
"sys",
".",
"exc_info",
"(",
")",
"msg",
"=",
"'Unable to create destination directory: {d}\\n{e}'",
".",
"format",
"(",
"d",
"=",
"destination_dir",
",",
"e",
"=",
"str",
"(",
"ex",
")",
")",
"raise",
"OSError",
"(",
"msg",
")",
"# Determine the auth based on username and password",
"basic_auth",
"=",
"None",
"if",
"(",
"username",
"is",
"not",
"None",
")",
"and",
"(",
"password",
"is",
"not",
"None",
")",
":",
"log",
".",
"info",
"(",
"'Using the provided username/password for basic authentication...'",
")",
"basic_auth",
"=",
"HTTPBasicAuth",
"(",
"username",
",",
"password",
")",
"# Set the classifier if it was provided",
"classifier",
"=",
"None",
"if",
"'classifier'",
"in",
"kwargs",
":",
"if",
"isinstance",
"(",
"kwargs",
"[",
"'classifier'",
"]",
",",
"basestring",
")",
":",
"classifier",
"=",
"kwargs",
"[",
"'classifier'",
"]",
"log",
".",
"debug",
"(",
"'Using classifier: {c}'",
".",
"format",
"(",
"c",
"=",
"classifier",
")",
")",
"else",
":",
"log",
".",
"warn",
"(",
"'Arg classifier provided but it was not an instance of basestring'",
")",
"# Determine the repository (snapshots or releases)",
"if",
"not",
"repository",
":",
"if",
"'SNAPSHOT'",
"in",
"version",
":",
"repository",
"=",
"'snapshots'",
"else",
":",
"repository",
"=",
"'releases'",
"log",
".",
"debug",
"(",
"'Using repository: {r}'",
".",
"format",
"(",
"r",
"=",
"repository",
")",
")",
"# Compute the query URL",
"group_id_url",
"=",
"group_id",
".",
"replace",
"(",
"'.'",
",",
"'/'",
")",
"# Get the Maven metadata",
"query_url_version",
"=",
"nexus_base_url",
"+",
"'/repository/{r}/{g}/{a}/{v}'",
".",
"format",
"(",
"r",
"=",
"repository",
",",
"g",
"=",
"group_id_url",
",",
"a",
"=",
"artifact_id",
",",
"v",
"=",
"version",
")",
"if",
"'snapshot'",
"in",
"repository",
".",
"lower",
"(",
")",
":",
"# Query nexus for metadata to determine the proper file name",
"query_url_metadata",
"=",
"query_url_version",
"+",
"'/maven-metadata.xml'",
"log",
".",
"info",
"(",
"'Attempting to query Nexus for the snapshot metadata using URL: {u}'",
".",
"format",
"(",
"u",
"=",
"query_url_metadata",
")",
")",
"try",
":",
"nexus_response",
"=",
"query_nexus",
"(",
"query_url",
"=",
"query_url_metadata",
",",
"timeout_sec",
"=",
"timeout_sec",
",",
"basic_auth",
"=",
"basic_auth",
")",
"except",
"RuntimeError",
":",
"_",
",",
"ex",
",",
"trace",
"=",
"sys",
".",
"exc_info",
"(",
")",
"msg",
"=",
"'{n}: There was a problem querying Nexus URL: {u}\\n{e}'",
".",
"format",
"(",
"n",
"=",
"ex",
".",
"__class__",
".",
"__name__",
",",
"u",
"=",
"query_url_metadata",
",",
"e",
"=",
"str",
"(",
"ex",
")",
")",
"log",
".",
"error",
"(",
"msg",
")",
"raise",
"RuntimeError",
",",
"msg",
",",
"trace",
"if",
"nexus_response",
".",
"status_code",
"!=",
"200",
":",
"raise",
"RuntimeError",
"(",
"'Bad response from Nexus metadata URL [{c}]: {u}'",
".",
"format",
"(",
"c",
"=",
"nexus_response",
".",
"status_code",
",",
"u",
"=",
"query_url_metadata",
")",
")",
"# Parse the XML output",
"root",
"=",
"ET",
".",
"fromstring",
"(",
"nexus_response",
".",
"text",
")",
"log",
".",
"info",
"(",
"'Attempting to find the value of the file name...'",
")",
"try",
":",
"value",
"=",
"root",
".",
"find",
"(",
"'versioning'",
")",
".",
"find",
"(",
"'snapshotVersions'",
")",
".",
"find",
"(",
"'snapshotVersion'",
")",
".",
"find",
"(",
"'value'",
")",
"except",
"AttributeError",
":",
"_",
",",
"ex",
",",
"trace",
"=",
"sys",
".",
"exc_info",
"(",
")",
"msg",
"=",
"'AttributeError: Unable to find versioning/snapshotVersions/snapshotVersion/value\\n{e}'",
".",
"format",
"(",
"e",
"=",
"str",
"(",
"ex",
")",
")",
"raise",
"ValueError",
",",
"msg",
",",
"trace",
"# Ensure a value was found",
"if",
"value",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Unable to determine the value of the snapshot version'",
")",
"# Get the text version",
"text_version",
"=",
"value",
".",
"text",
"log",
".",
"info",
"(",
"'Found version value: {t}'",
".",
"format",
"(",
"t",
"=",
"text_version",
")",
")",
"# Determine the artifact file name",
"artifact_file_name",
"=",
"'{a}-{t}'",
".",
"format",
"(",
"a",
"=",
"artifact_id",
",",
"t",
"=",
"text_version",
")",
"else",
":",
"# Construct the file name for releases (e.g. cons3rt-backend-install-18.14.0-package-otto.zip)",
"artifact_file_name",
"=",
"'{a}-{v}'",
".",
"format",
"(",
"a",
"=",
"artifact_id",
",",
"v",
"=",
"version",
")",
"# Add classifier if provided and packaging",
"if",
"classifier",
":",
"artifact_file_name",
"+=",
"'-{c}'",
".",
"format",
"(",
"c",
"=",
"classifier",
")",
"artifact_file_name",
"+=",
"'.{p}'",
".",
"format",
"(",
"p",
"=",
"packaging",
")",
"log",
".",
"info",
"(",
"'Using artifact file name: {n}'",
".",
"format",
"(",
"n",
"=",
"artifact_file_name",
")",
")",
"# Determine the full query URL",
"query_url",
"=",
"query_url_version",
"+",
"'/{n}'",
".",
"format",
"(",
"n",
"=",
"artifact_file_name",
")",
"log",
".",
"info",
"(",
"'Using Nexus query URL: {u}'",
".",
"format",
"(",
"u",
"=",
"query_url",
")",
")",
"# Set up for download attempts",
"retry_sec",
"=",
"5",
"max_retries",
"=",
"6",
"try_num",
"=",
"1",
"download_success",
"=",
"False",
"dl_err",
"=",
"None",
"failed_attempt",
"=",
"False",
"# Start the retry loop",
"while",
"try_num",
"<=",
"max_retries",
":",
"# Break the loop if the download was successful",
"if",
"download_success",
":",
"break",
"log",
".",
"info",
"(",
"'Attempting to query Nexus for the Artifact using URL: {u}'",
".",
"format",
"(",
"u",
"=",
"query_url",
")",
")",
"try",
":",
"nexus_response",
"=",
"query_nexus",
"(",
"query_url",
"=",
"query_url",
",",
"timeout_sec",
"=",
"timeout_sec",
",",
"basic_auth",
"=",
"basic_auth",
")",
"except",
"RuntimeError",
":",
"_",
",",
"ex",
",",
"trace",
"=",
"sys",
".",
"exc_info",
"(",
")",
"msg",
"=",
"'{n}: There was a problem querying Nexus URL: {u}\\n{e}'",
".",
"format",
"(",
"n",
"=",
"ex",
".",
"__class__",
".",
"__name__",
",",
"u",
"=",
"query_url",
",",
"e",
"=",
"str",
"(",
"ex",
")",
")",
"log",
".",
"error",
"(",
"msg",
")",
"raise",
"RuntimeError",
",",
"msg",
",",
"trace",
"# Attempt to get the content-length",
"file_size",
"=",
"0",
"try",
":",
"file_size",
"=",
"int",
"(",
"nexus_response",
".",
"headers",
"[",
"'Content-Length'",
"]",
")",
"except",
"(",
"KeyError",
",",
"ValueError",
")",
":",
"log",
".",
"debug",
"(",
"'Could not get Content-Length, suppressing download status...'",
")",
"suppress_status",
"=",
"True",
"else",
":",
"log",
".",
"info",
"(",
"'Artifact file size: {s}'",
".",
"format",
"(",
"s",
"=",
"file_size",
")",
")",
"# Determine the full download file path",
"file_name",
"=",
"nexus_response",
".",
"url",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
"download_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"destination_dir",
",",
"file_name",
")",
"# Attempt to download the content from the response",
"log",
".",
"info",
"(",
"'Attempting to download content of size {s} from Nexus to file: {d}'",
".",
"format",
"(",
"s",
"=",
"file_size",
",",
"d",
"=",
"download_file",
")",
")",
"# Remove the existing file if it exists, or exit if the file exists, overwrite is set,",
"# and there was not a previous failed attempted download",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"download_file",
")",
"and",
"overwrite",
":",
"log",
".",
"debug",
"(",
"'File already exists, removing: {d}'",
".",
"format",
"(",
"d",
"=",
"download_file",
")",
")",
"os",
".",
"remove",
"(",
"download_file",
")",
"elif",
"os",
".",
"path",
".",
"isfile",
"(",
"download_file",
")",
"and",
"not",
"overwrite",
"and",
"not",
"failed_attempt",
":",
"log",
".",
"info",
"(",
"'File already downloaded, and overwrite is set to False. The Artifact will '",
"'not be retrieved from Nexus: {f}. To overwrite the existing downloaded file, '",
"'set overwrite=True'",
".",
"format",
"(",
"f",
"=",
"download_file",
")",
")",
"return",
"# Attempt to download content",
"log",
".",
"debug",
"(",
"'Attempt # {n} of {m} to download content from the Nexus response'",
".",
"format",
"(",
"n",
"=",
"try_num",
",",
"m",
"=",
"max_retries",
")",
")",
"chunk_size",
"=",
"1024",
"file_size_dl",
"=",
"0",
"try",
":",
"with",
"open",
"(",
"download_file",
",",
"'wb'",
")",
"as",
"f",
":",
"for",
"chunk",
"in",
"nexus_response",
".",
"iter_content",
"(",
"chunk_size",
"=",
"chunk_size",
")",
":",
"if",
"chunk",
":",
"f",
".",
"write",
"(",
"chunk",
")",
"file_size_dl",
"+=",
"len",
"(",
"chunk",
")",
"status",
"=",
"r\"%10d [%3.2f%%]\"",
"%",
"(",
"file_size_dl",
",",
"file_size_dl",
"*",
"100.",
"/",
"file_size",
")",
"status",
"+=",
"chr",
"(",
"8",
")",
"*",
"(",
"len",
"(",
"status",
")",
"+",
"1",
")",
"if",
"not",
"suppress_status",
":",
"print",
"(",
"status",
")",
",",
"except",
"(",
"requests",
".",
"exceptions",
".",
"ConnectionError",
",",
"requests",
".",
"exceptions",
".",
"RequestException",
",",
"OSError",
")",
":",
"_",
",",
"ex",
",",
"trace",
"=",
"sys",
".",
"exc_info",
"(",
")",
"dl_err",
"=",
"'{n}: There was an error reading content from the Nexus response. Downloaded '",
"'size: {s}.\\n{e}'",
".",
"format",
"(",
"n",
"=",
"ex",
".",
"__class__",
".",
"__name__",
",",
"s",
"=",
"file_size_dl",
",",
"t",
"=",
"retry_sec",
",",
"e",
"=",
"str",
"(",
"ex",
")",
")",
"failed_attempt",
"=",
"True",
"log",
".",
"warn",
"(",
"dl_err",
")",
"if",
"try_num",
"<",
"max_retries",
":",
"log",
".",
"info",
"(",
"'Retrying download in {t} sec...'",
".",
"format",
"(",
"t",
"=",
"retry_sec",
")",
")",
"time",
".",
"sleep",
"(",
"retry_sec",
")",
"else",
":",
"log",
".",
"info",
"(",
"'File download of size {s} completed without error: {f}'",
".",
"format",
"(",
"s",
"=",
"file_size_dl",
",",
"f",
"=",
"download_file",
")",
")",
"failed_attempt",
"=",
"False",
"download_success",
"=",
"True",
"try_num",
"+=",
"1",
"# Raise an exception if the download did not complete successfully",
"if",
"not",
"download_success",
":",
"msg",
"=",
"'Unable to download file content from Nexus after {n} attempts'",
".",
"format",
"(",
"n",
"=",
"max_retries",
")",
"if",
"dl_err",
":",
"msg",
"+=",
"'\\n{m}'",
".",
"format",
"(",
"m",
"=",
"dl_err",
")",
"log",
".",
"error",
"(",
"msg",
")",
"raise",
"RuntimeError",
"(",
"msg",
")"
] | Retrieves an artifact from the Nexus 3 ReST API
:param suppress_status: (bool) Set to True to suppress printing download status
:param nexus_base_url: (str) Base URL of the Nexus Server (domain name portion only, see sample)
:param repository: (str) Repository to query (e.g. snapshots) if not provided, will attempt to determine
:param timeout_sec: (int) Number of seconds to wait before
timing out the artifact retrieval.
:param overwrite: (bool) True overwrites the file on the local system if it exists,
False does will log an INFO message and exist if the file already exists
:param username: (str) username for basic auth
:param password: (str) password for basic auth
:param kwargs:
group_id: (str) The artifact's Group ID in Nexus
artifact_id: (str) The artifact's Artifact ID in Nexus
packaging: (str) The artifact's packaging (e.g. war, zip)
version: (str) Version of the artifact to retrieve (e.g.
LATEST, 4.8.4, 4.9.0-SNAPSHOT)
destination_dir: (str) Full path to the destination directory
classifier: (str) The artifact's classifier (e.g. bin)
:return: None
:raises: TypeError, ValueError, OSError, RuntimeError | [
"Retrieves",
"an",
"artifact",
"from",
"the",
"Nexus",
"3",
"ReST",
"API"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/nexus.py#L302-L553 |
cons3rt/pycons3rt | pycons3rt/nexus.py | main | def main():
"""Handles calling this module as a script
:return: None
"""
log = logging.getLogger(mod_logger + '.main')
parser = argparse.ArgumentParser(description='This Python module retrieves artifacts from Nexus.')
parser.add_argument('-u', '--url', help='Nexus Server URL', required=False)
parser.add_argument('-g', '--groupId', help='Group ID', required=True)
parser.add_argument('-a', '--artifactId', help='Artifact ID', required=True)
parser.add_argument('-v', '--version', help='Artifact Version', required=True)
parser.add_argument('-c', '--classifier', help='Artifact Classifier', required=False)
parser.add_argument('-p', '--packaging', help='Artifact Packaging', required=True)
parser.add_argument('-r', '--repo', help='Nexus repository name', required=False)
parser.add_argument('-d', '--destinationDir', help='Directory to download to', required=True)
parser.add_argument('-n', '--username', help='Directory to download to', required=True)
parser.add_argument('-w', '--password', help='Directory to download to', required=True)
args = parser.parse_args()
try:
get_artifact(
nexus_url=args.url,
group_id=args.groupId,
artifact_id=args.artifactId,
version=args.version,
classifier=args.classifier,
packaging=args.packaging,
repo=args.repo,
destination_dir=args.destinationDir,
username=args.username,
password=args.password
)
except Exception as e:
msg = 'Caught exception {n}, unable for download artifact from Nexus\n{s}'.format(
n=e.__class__.__name__, s=e)
log.error(msg)
return | python | def main():
"""Handles calling this module as a script
:return: None
"""
log = logging.getLogger(mod_logger + '.main')
parser = argparse.ArgumentParser(description='This Python module retrieves artifacts from Nexus.')
parser.add_argument('-u', '--url', help='Nexus Server URL', required=False)
parser.add_argument('-g', '--groupId', help='Group ID', required=True)
parser.add_argument('-a', '--artifactId', help='Artifact ID', required=True)
parser.add_argument('-v', '--version', help='Artifact Version', required=True)
parser.add_argument('-c', '--classifier', help='Artifact Classifier', required=False)
parser.add_argument('-p', '--packaging', help='Artifact Packaging', required=True)
parser.add_argument('-r', '--repo', help='Nexus repository name', required=False)
parser.add_argument('-d', '--destinationDir', help='Directory to download to', required=True)
parser.add_argument('-n', '--username', help='Directory to download to', required=True)
parser.add_argument('-w', '--password', help='Directory to download to', required=True)
args = parser.parse_args()
try:
get_artifact(
nexus_url=args.url,
group_id=args.groupId,
artifact_id=args.artifactId,
version=args.version,
classifier=args.classifier,
packaging=args.packaging,
repo=args.repo,
destination_dir=args.destinationDir,
username=args.username,
password=args.password
)
except Exception as e:
msg = 'Caught exception {n}, unable for download artifact from Nexus\n{s}'.format(
n=e.__class__.__name__, s=e)
log.error(msg)
return | [
"def",
"main",
"(",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.main'",
")",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'This Python module retrieves artifacts from Nexus.'",
")",
"parser",
".",
"add_argument",
"(",
"'-u'",
",",
"'--url'",
",",
"help",
"=",
"'Nexus Server URL'",
",",
"required",
"=",
"False",
")",
"parser",
".",
"add_argument",
"(",
"'-g'",
",",
"'--groupId'",
",",
"help",
"=",
"'Group ID'",
",",
"required",
"=",
"True",
")",
"parser",
".",
"add_argument",
"(",
"'-a'",
",",
"'--artifactId'",
",",
"help",
"=",
"'Artifact ID'",
",",
"required",
"=",
"True",
")",
"parser",
".",
"add_argument",
"(",
"'-v'",
",",
"'--version'",
",",
"help",
"=",
"'Artifact Version'",
",",
"required",
"=",
"True",
")",
"parser",
".",
"add_argument",
"(",
"'-c'",
",",
"'--classifier'",
",",
"help",
"=",
"'Artifact Classifier'",
",",
"required",
"=",
"False",
")",
"parser",
".",
"add_argument",
"(",
"'-p'",
",",
"'--packaging'",
",",
"help",
"=",
"'Artifact Packaging'",
",",
"required",
"=",
"True",
")",
"parser",
".",
"add_argument",
"(",
"'-r'",
",",
"'--repo'",
",",
"help",
"=",
"'Nexus repository name'",
",",
"required",
"=",
"False",
")",
"parser",
".",
"add_argument",
"(",
"'-d'",
",",
"'--destinationDir'",
",",
"help",
"=",
"'Directory to download to'",
",",
"required",
"=",
"True",
")",
"parser",
".",
"add_argument",
"(",
"'-n'",
",",
"'--username'",
",",
"help",
"=",
"'Directory to download to'",
",",
"required",
"=",
"True",
")",
"parser",
".",
"add_argument",
"(",
"'-w'",
",",
"'--password'",
",",
"help",
"=",
"'Directory to download to'",
",",
"required",
"=",
"True",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"try",
":",
"get_artifact",
"(",
"nexus_url",
"=",
"args",
".",
"url",
",",
"group_id",
"=",
"args",
".",
"groupId",
",",
"artifact_id",
"=",
"args",
".",
"artifactId",
",",
"version",
"=",
"args",
".",
"version",
",",
"classifier",
"=",
"args",
".",
"classifier",
",",
"packaging",
"=",
"args",
".",
"packaging",
",",
"repo",
"=",
"args",
".",
"repo",
",",
"destination_dir",
"=",
"args",
".",
"destinationDir",
",",
"username",
"=",
"args",
".",
"username",
",",
"password",
"=",
"args",
".",
"password",
")",
"except",
"Exception",
"as",
"e",
":",
"msg",
"=",
"'Caught exception {n}, unable for download artifact from Nexus\\n{s}'",
".",
"format",
"(",
"n",
"=",
"e",
".",
"__class__",
".",
"__name__",
",",
"s",
"=",
"e",
")",
"log",
".",
"error",
"(",
"msg",
")",
"return"
] | Handles calling this module as a script
:return: None | [
"Handles",
"calling",
"this",
"module",
"as",
"a",
"script"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/nexus.py#L556-L591 |
Josef-Friedrich/phrydy | phrydy/doc.py | get_doc | def get_doc(additional_doc=False,
field_prefix='$',
field_suffix=':',
indent=4):
"""Return a formated string containing documentation about the audio
fields.
"""
if additional_doc:
f = fields.copy()
f.update(additional_doc)
else:
f = fields
field_length = get_max_field_length(f)
field_length = field_length + len(field_prefix) + len(field_suffix) + 4
description_indent = ' ' * (indent + field_length)
output = ''
for field, description in sorted(f.items()):
description = description['description']
field = ' ' * indent + field_prefix + field + ':'
output += field.ljust(field_length) + \
textwrap.fill(
description,
width=78,
initial_indent=description_indent,
subsequent_indent=description_indent
)[field_length:] + '\n\n\n'
return output | python | def get_doc(additional_doc=False,
field_prefix='$',
field_suffix=':',
indent=4):
"""Return a formated string containing documentation about the audio
fields.
"""
if additional_doc:
f = fields.copy()
f.update(additional_doc)
else:
f = fields
field_length = get_max_field_length(f)
field_length = field_length + len(field_prefix) + len(field_suffix) + 4
description_indent = ' ' * (indent + field_length)
output = ''
for field, description in sorted(f.items()):
description = description['description']
field = ' ' * indent + field_prefix + field + ':'
output += field.ljust(field_length) + \
textwrap.fill(
description,
width=78,
initial_indent=description_indent,
subsequent_indent=description_indent
)[field_length:] + '\n\n\n'
return output | [
"def",
"get_doc",
"(",
"additional_doc",
"=",
"False",
",",
"field_prefix",
"=",
"'$'",
",",
"field_suffix",
"=",
"':'",
",",
"indent",
"=",
"4",
")",
":",
"if",
"additional_doc",
":",
"f",
"=",
"fields",
".",
"copy",
"(",
")",
"f",
".",
"update",
"(",
"additional_doc",
")",
"else",
":",
"f",
"=",
"fields",
"field_length",
"=",
"get_max_field_length",
"(",
"f",
")",
"field_length",
"=",
"field_length",
"+",
"len",
"(",
"field_prefix",
")",
"+",
"len",
"(",
"field_suffix",
")",
"+",
"4",
"description_indent",
"=",
"' '",
"*",
"(",
"indent",
"+",
"field_length",
")",
"output",
"=",
"''",
"for",
"field",
",",
"description",
"in",
"sorted",
"(",
"f",
".",
"items",
"(",
")",
")",
":",
"description",
"=",
"description",
"[",
"'description'",
"]",
"field",
"=",
"' '",
"*",
"indent",
"+",
"field_prefix",
"+",
"field",
"+",
"':'",
"output",
"+=",
"field",
".",
"ljust",
"(",
"field_length",
")",
"+",
"textwrap",
".",
"fill",
"(",
"description",
",",
"width",
"=",
"78",
",",
"initial_indent",
"=",
"description_indent",
",",
"subsequent_indent",
"=",
"description_indent",
")",
"[",
"field_length",
":",
"]",
"+",
"'\\n\\n\\n'",
"return",
"output"
] | Return a formated string containing documentation about the audio
fields. | [
"Return",
"a",
"formated",
"string",
"containing",
"documentation",
"about",
"the",
"audio",
"fields",
"."
] | train | https://github.com/Josef-Friedrich/phrydy/blob/aa13755155977b4776e49f79984f9968ac1d74dc/phrydy/doc.py#L413-L440 |
novopl/peltak | src/peltak/extra/docker/client.py | RegistryClient.list_images | def list_images(self):
# type: () -> List[str]
""" List images stored in the registry.
Returns:
list[str]: List of image names.
"""
r = self.get(self.registry_url + '/v2/_catalog', auth=self.auth)
return r.json()['repositories'] | python | def list_images(self):
# type: () -> List[str]
""" List images stored in the registry.
Returns:
list[str]: List of image names.
"""
r = self.get(self.registry_url + '/v2/_catalog', auth=self.auth)
return r.json()['repositories'] | [
"def",
"list_images",
"(",
"self",
")",
":",
"# type: () -> List[str]",
"r",
"=",
"self",
".",
"get",
"(",
"self",
".",
"registry_url",
"+",
"'/v2/_catalog'",
",",
"auth",
"=",
"self",
".",
"auth",
")",
"return",
"r",
".",
"json",
"(",
")",
"[",
"'repositories'",
"]"
] | List images stored in the registry.
Returns:
list[str]: List of image names. | [
"List",
"images",
"stored",
"in",
"the",
"registry",
"."
] | train | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/docker/client.py#L53-L61 |
novopl/peltak | src/peltak/extra/docker/client.py | RegistryClient.list_tags | def list_tags(self, image_name):
# type: (str) -> Iterator[str]
""" List all tags for the given image stored in the registry.
Args:
image_name (str):
The name of the image to query. The image must be present on the
registry for this call to return any values.
Returns:
list[str]: List of tags for that image.
"""
tags_url = self.registry_url + '/v2/{}/tags/list'
r = self.get(tags_url.format(image_name), auth=self.auth)
data = r.json()
if 'tags' in data:
return reversed(sorted(data['tags']))
return [] | python | def list_tags(self, image_name):
# type: (str) -> Iterator[str]
""" List all tags for the given image stored in the registry.
Args:
image_name (str):
The name of the image to query. The image must be present on the
registry for this call to return any values.
Returns:
list[str]: List of tags for that image.
"""
tags_url = self.registry_url + '/v2/{}/tags/list'
r = self.get(tags_url.format(image_name), auth=self.auth)
data = r.json()
if 'tags' in data:
return reversed(sorted(data['tags']))
return [] | [
"def",
"list_tags",
"(",
"self",
",",
"image_name",
")",
":",
"# type: (str) -> Iterator[str]",
"tags_url",
"=",
"self",
".",
"registry_url",
"+",
"'/v2/{}/tags/list'",
"r",
"=",
"self",
".",
"get",
"(",
"tags_url",
".",
"format",
"(",
"image_name",
")",
",",
"auth",
"=",
"self",
".",
"auth",
")",
"data",
"=",
"r",
".",
"json",
"(",
")",
"if",
"'tags'",
"in",
"data",
":",
"return",
"reversed",
"(",
"sorted",
"(",
"data",
"[",
"'tags'",
"]",
")",
")",
"return",
"[",
"]"
] | List all tags for the given image stored in the registry.
Args:
image_name (str):
The name of the image to query. The image must be present on the
registry for this call to return any values.
Returns:
list[str]: List of tags for that image. | [
"List",
"all",
"tags",
"for",
"the",
"given",
"image",
"stored",
"in",
"the",
"registry",
"."
] | train | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/docker/client.py#L63-L82 |
cons3rt/pycons3rt | pycons3rt/asset.py | validate_asset_structure | def validate_asset_structure(asset_dir_path):
"""Checks asset structure validity
:param asset_dir_path: (str) path to the directory containing the asset
:return: (str) Asset name
:raises: Cons3rtAssetStructureError
"""
log = logging.getLogger(mod_logger + '.validate_asset_structure')
log.info('Validating asset directory: {d}'.format(d=asset_dir_path))
# Ensure there is an asset.properties file
asset_props = os.path.join(asset_dir_path, 'asset.properties')
if not os.path.isfile(asset_props):
raise Cons3rtAssetStructureError('Asset properties file not found: {f}'.format(f=asset_props))
# Props to find
install_script_rel_path = None
doc_file_rel_path = None
license_file_rel_path = None
asset_type = None
license_file_path = ''
doc_file_path = ''
asset_name = None
log.info('Reading asset properties file: {f}'.format(f=asset_props))
with open(asset_props, 'r') as f:
for line in f:
if line.strip().startswith('installScript='):
install_script_name = line.strip().split('=')[1]
install_script_rel_path = os.path.join('scripts', install_script_name)
elif line.strip().startswith('documentationFile='):
doc_file_rel_path = line.strip().split('=')[1]
elif line.strip().startswith('licenseFile='):
license_file_rel_path = line.strip().split('=')[1]
elif line.strip().startswith('assetType='):
asset_type = line.strip().split('=')[1]
asset_type = asset_type.lower()
elif line.strip().startswith('name='):
asset_name = line.strip().split('=')[1]
# Ensure a name was provided
if asset_name is None:
raise Cons3rtAssetStructureError('Required property [name] not found in asset properties file: {f}'.format(
f=asset_props))
if asset_name == '':
raise Cons3rtAssetStructureError('Required property [name] found blank in asset properties file: {f}'.format(
f=asset_props))
# Ensure asset_type was provided
if asset_type is None:
raise Cons3rtAssetStructureError('Required property [asset_type] not found in asset properties '
'file: {f}'.format(f=asset_props))
if asset_type == '':
raise Cons3rtAssetStructureError('Required property [asset_type] found blank in asset properties '
'file: {f}'.format(f=asset_props))
log.info('Found installScript={f}'.format(f=install_script_rel_path))
log.info('Found assetType={f}'.format(f=asset_type))
# Verify the doc file exists if specified
if doc_file_rel_path:
log.info('Found documentationFile={f}'.format(f=doc_file_rel_path))
doc_file_path = os.path.join(asset_dir_path, doc_file_rel_path)
if not os.path.isfile(doc_file_path):
raise Cons3rtAssetStructureError('Documentation file not found: {f}'.format(f=doc_file_path))
else:
log.info('Verified documentation file: {f}'.format(f=doc_file_path))
else:
log.info('The documentationFile property was not specified in asset.properties')
# Verify the license file exists if specified
if license_file_rel_path:
log.info('Found licenseFile={f}'.format(f=license_file_rel_path))
license_file_path = os.path.join(asset_dir_path, license_file_rel_path)
if not os.path.isfile(license_file_path):
raise Cons3rtAssetStructureError('License file not found: {f}'.format(f=license_file_path))
else:
log.info('Verified license file: {f}'.format(f=license_file_path))
else:
log.info('The licenseFile property was not specified in asset.properties')
if asset_type == 'software':
if not install_script_rel_path:
raise Cons3rtAssetStructureError('Software asset has an asset.properties missing the installScript '
'prop: {f}'.format(f=asset_props))
else:
install_script_path = os.path.join(asset_dir_path, install_script_rel_path)
if not os.path.isfile(install_script_path):
raise Cons3rtAssetStructureError('Install script file not found: {f}'.format(f=install_script_path))
else:
log.info('Verified install script for software asset: {f}'.format(f=install_script_path))
log.info('Checking items at the root of the asset directory...')
for item in os.listdir(asset_dir_path):
log.info('Checking item: {i}'.format(i=item))
item_path = os.path.join(asset_dir_path, item)
if item_path == license_file_path:
continue
elif item_path == doc_file_path:
continue
elif item_path == asset_props:
continue
elif item in ignore_items:
continue
elif ignore_by_extension(item_path=item_path):
continue
elif item in acceptable_dirs and os.path.isdir(item_path):
continue
else:
if item == 'VERSION':
os.remove(item_path)
log.warn('Deleted file: {f}'.format(f=item_path))
elif item == 'doc':
raise Cons3rtAssetStructureError('Found a doc directory at the asset root, this is not allowed')
elif item in potential_doc_files:
if not doc_file_rel_path:
raise Cons3rtAssetStructureError('Documentation file found but not specified in '
'asset.properties: {f}'.format(f=item_path))
else:
raise Cons3rtAssetStructureError('Extra documentation file found: {f}'.format(f=item_path))
elif item in potential_license_files:
if not license_file_rel_path:
raise Cons3rtAssetStructureError('License file found but not specified in '
'asset.properties: {f}'.format(f=item_path))
else:
raise Cons3rtAssetStructureError('Extra license file found: {f}'.format(f=item_path))
else:
raise Cons3rtAssetStructureError('Found illegal item at the asset root dir: {i}'.format(i=item))
log.info('Validated asset directory successfully: {d}'.format(d=asset_dir_path))
return asset_name | python | def validate_asset_structure(asset_dir_path):
"""Checks asset structure validity
:param asset_dir_path: (str) path to the directory containing the asset
:return: (str) Asset name
:raises: Cons3rtAssetStructureError
"""
log = logging.getLogger(mod_logger + '.validate_asset_structure')
log.info('Validating asset directory: {d}'.format(d=asset_dir_path))
# Ensure there is an asset.properties file
asset_props = os.path.join(asset_dir_path, 'asset.properties')
if not os.path.isfile(asset_props):
raise Cons3rtAssetStructureError('Asset properties file not found: {f}'.format(f=asset_props))
# Props to find
install_script_rel_path = None
doc_file_rel_path = None
license_file_rel_path = None
asset_type = None
license_file_path = ''
doc_file_path = ''
asset_name = None
log.info('Reading asset properties file: {f}'.format(f=asset_props))
with open(asset_props, 'r') as f:
for line in f:
if line.strip().startswith('installScript='):
install_script_name = line.strip().split('=')[1]
install_script_rel_path = os.path.join('scripts', install_script_name)
elif line.strip().startswith('documentationFile='):
doc_file_rel_path = line.strip().split('=')[1]
elif line.strip().startswith('licenseFile='):
license_file_rel_path = line.strip().split('=')[1]
elif line.strip().startswith('assetType='):
asset_type = line.strip().split('=')[1]
asset_type = asset_type.lower()
elif line.strip().startswith('name='):
asset_name = line.strip().split('=')[1]
# Ensure a name was provided
if asset_name is None:
raise Cons3rtAssetStructureError('Required property [name] not found in asset properties file: {f}'.format(
f=asset_props))
if asset_name == '':
raise Cons3rtAssetStructureError('Required property [name] found blank in asset properties file: {f}'.format(
f=asset_props))
# Ensure asset_type was provided
if asset_type is None:
raise Cons3rtAssetStructureError('Required property [asset_type] not found in asset properties '
'file: {f}'.format(f=asset_props))
if asset_type == '':
raise Cons3rtAssetStructureError('Required property [asset_type] found blank in asset properties '
'file: {f}'.format(f=asset_props))
log.info('Found installScript={f}'.format(f=install_script_rel_path))
log.info('Found assetType={f}'.format(f=asset_type))
# Verify the doc file exists if specified
if doc_file_rel_path:
log.info('Found documentationFile={f}'.format(f=doc_file_rel_path))
doc_file_path = os.path.join(asset_dir_path, doc_file_rel_path)
if not os.path.isfile(doc_file_path):
raise Cons3rtAssetStructureError('Documentation file not found: {f}'.format(f=doc_file_path))
else:
log.info('Verified documentation file: {f}'.format(f=doc_file_path))
else:
log.info('The documentationFile property was not specified in asset.properties')
# Verify the license file exists if specified
if license_file_rel_path:
log.info('Found licenseFile={f}'.format(f=license_file_rel_path))
license_file_path = os.path.join(asset_dir_path, license_file_rel_path)
if not os.path.isfile(license_file_path):
raise Cons3rtAssetStructureError('License file not found: {f}'.format(f=license_file_path))
else:
log.info('Verified license file: {f}'.format(f=license_file_path))
else:
log.info('The licenseFile property was not specified in asset.properties')
if asset_type == 'software':
if not install_script_rel_path:
raise Cons3rtAssetStructureError('Software asset has an asset.properties missing the installScript '
'prop: {f}'.format(f=asset_props))
else:
install_script_path = os.path.join(asset_dir_path, install_script_rel_path)
if not os.path.isfile(install_script_path):
raise Cons3rtAssetStructureError('Install script file not found: {f}'.format(f=install_script_path))
else:
log.info('Verified install script for software asset: {f}'.format(f=install_script_path))
log.info('Checking items at the root of the asset directory...')
for item in os.listdir(asset_dir_path):
log.info('Checking item: {i}'.format(i=item))
item_path = os.path.join(asset_dir_path, item)
if item_path == license_file_path:
continue
elif item_path == doc_file_path:
continue
elif item_path == asset_props:
continue
elif item in ignore_items:
continue
elif ignore_by_extension(item_path=item_path):
continue
elif item in acceptable_dirs and os.path.isdir(item_path):
continue
else:
if item == 'VERSION':
os.remove(item_path)
log.warn('Deleted file: {f}'.format(f=item_path))
elif item == 'doc':
raise Cons3rtAssetStructureError('Found a doc directory at the asset root, this is not allowed')
elif item in potential_doc_files:
if not doc_file_rel_path:
raise Cons3rtAssetStructureError('Documentation file found but not specified in '
'asset.properties: {f}'.format(f=item_path))
else:
raise Cons3rtAssetStructureError('Extra documentation file found: {f}'.format(f=item_path))
elif item in potential_license_files:
if not license_file_rel_path:
raise Cons3rtAssetStructureError('License file found but not specified in '
'asset.properties: {f}'.format(f=item_path))
else:
raise Cons3rtAssetStructureError('Extra license file found: {f}'.format(f=item_path))
else:
raise Cons3rtAssetStructureError('Found illegal item at the asset root dir: {i}'.format(i=item))
log.info('Validated asset directory successfully: {d}'.format(d=asset_dir_path))
return asset_name | [
"def",
"validate_asset_structure",
"(",
"asset_dir_path",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.validate_asset_structure'",
")",
"log",
".",
"info",
"(",
"'Validating asset directory: {d}'",
".",
"format",
"(",
"d",
"=",
"asset_dir_path",
")",
")",
"# Ensure there is an asset.properties file",
"asset_props",
"=",
"os",
".",
"path",
".",
"join",
"(",
"asset_dir_path",
",",
"'asset.properties'",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"asset_props",
")",
":",
"raise",
"Cons3rtAssetStructureError",
"(",
"'Asset properties file not found: {f}'",
".",
"format",
"(",
"f",
"=",
"asset_props",
")",
")",
"# Props to find",
"install_script_rel_path",
"=",
"None",
"doc_file_rel_path",
"=",
"None",
"license_file_rel_path",
"=",
"None",
"asset_type",
"=",
"None",
"license_file_path",
"=",
"''",
"doc_file_path",
"=",
"''",
"asset_name",
"=",
"None",
"log",
".",
"info",
"(",
"'Reading asset properties file: {f}'",
".",
"format",
"(",
"f",
"=",
"asset_props",
")",
")",
"with",
"open",
"(",
"asset_props",
",",
"'r'",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"if",
"line",
".",
"strip",
"(",
")",
".",
"startswith",
"(",
"'installScript='",
")",
":",
"install_script_name",
"=",
"line",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'='",
")",
"[",
"1",
"]",
"install_script_rel_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'scripts'",
",",
"install_script_name",
")",
"elif",
"line",
".",
"strip",
"(",
")",
".",
"startswith",
"(",
"'documentationFile='",
")",
":",
"doc_file_rel_path",
"=",
"line",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'='",
")",
"[",
"1",
"]",
"elif",
"line",
".",
"strip",
"(",
")",
".",
"startswith",
"(",
"'licenseFile='",
")",
":",
"license_file_rel_path",
"=",
"line",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'='",
")",
"[",
"1",
"]",
"elif",
"line",
".",
"strip",
"(",
")",
".",
"startswith",
"(",
"'assetType='",
")",
":",
"asset_type",
"=",
"line",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'='",
")",
"[",
"1",
"]",
"asset_type",
"=",
"asset_type",
".",
"lower",
"(",
")",
"elif",
"line",
".",
"strip",
"(",
")",
".",
"startswith",
"(",
"'name='",
")",
":",
"asset_name",
"=",
"line",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'='",
")",
"[",
"1",
"]",
"# Ensure a name was provided",
"if",
"asset_name",
"is",
"None",
":",
"raise",
"Cons3rtAssetStructureError",
"(",
"'Required property [name] not found in asset properties file: {f}'",
".",
"format",
"(",
"f",
"=",
"asset_props",
")",
")",
"if",
"asset_name",
"==",
"''",
":",
"raise",
"Cons3rtAssetStructureError",
"(",
"'Required property [name] found blank in asset properties file: {f}'",
".",
"format",
"(",
"f",
"=",
"asset_props",
")",
")",
"# Ensure asset_type was provided",
"if",
"asset_type",
"is",
"None",
":",
"raise",
"Cons3rtAssetStructureError",
"(",
"'Required property [asset_type] not found in asset properties '",
"'file: {f}'",
".",
"format",
"(",
"f",
"=",
"asset_props",
")",
")",
"if",
"asset_type",
"==",
"''",
":",
"raise",
"Cons3rtAssetStructureError",
"(",
"'Required property [asset_type] found blank in asset properties '",
"'file: {f}'",
".",
"format",
"(",
"f",
"=",
"asset_props",
")",
")",
"log",
".",
"info",
"(",
"'Found installScript={f}'",
".",
"format",
"(",
"f",
"=",
"install_script_rel_path",
")",
")",
"log",
".",
"info",
"(",
"'Found assetType={f}'",
".",
"format",
"(",
"f",
"=",
"asset_type",
")",
")",
"# Verify the doc file exists if specified",
"if",
"doc_file_rel_path",
":",
"log",
".",
"info",
"(",
"'Found documentationFile={f}'",
".",
"format",
"(",
"f",
"=",
"doc_file_rel_path",
")",
")",
"doc_file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"asset_dir_path",
",",
"doc_file_rel_path",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"doc_file_path",
")",
":",
"raise",
"Cons3rtAssetStructureError",
"(",
"'Documentation file not found: {f}'",
".",
"format",
"(",
"f",
"=",
"doc_file_path",
")",
")",
"else",
":",
"log",
".",
"info",
"(",
"'Verified documentation file: {f}'",
".",
"format",
"(",
"f",
"=",
"doc_file_path",
")",
")",
"else",
":",
"log",
".",
"info",
"(",
"'The documentationFile property was not specified in asset.properties'",
")",
"# Verify the license file exists if specified",
"if",
"license_file_rel_path",
":",
"log",
".",
"info",
"(",
"'Found licenseFile={f}'",
".",
"format",
"(",
"f",
"=",
"license_file_rel_path",
")",
")",
"license_file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"asset_dir_path",
",",
"license_file_rel_path",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"license_file_path",
")",
":",
"raise",
"Cons3rtAssetStructureError",
"(",
"'License file not found: {f}'",
".",
"format",
"(",
"f",
"=",
"license_file_path",
")",
")",
"else",
":",
"log",
".",
"info",
"(",
"'Verified license file: {f}'",
".",
"format",
"(",
"f",
"=",
"license_file_path",
")",
")",
"else",
":",
"log",
".",
"info",
"(",
"'The licenseFile property was not specified in asset.properties'",
")",
"if",
"asset_type",
"==",
"'software'",
":",
"if",
"not",
"install_script_rel_path",
":",
"raise",
"Cons3rtAssetStructureError",
"(",
"'Software asset has an asset.properties missing the installScript '",
"'prop: {f}'",
".",
"format",
"(",
"f",
"=",
"asset_props",
")",
")",
"else",
":",
"install_script_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"asset_dir_path",
",",
"install_script_rel_path",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"install_script_path",
")",
":",
"raise",
"Cons3rtAssetStructureError",
"(",
"'Install script file not found: {f}'",
".",
"format",
"(",
"f",
"=",
"install_script_path",
")",
")",
"else",
":",
"log",
".",
"info",
"(",
"'Verified install script for software asset: {f}'",
".",
"format",
"(",
"f",
"=",
"install_script_path",
")",
")",
"log",
".",
"info",
"(",
"'Checking items at the root of the asset directory...'",
")",
"for",
"item",
"in",
"os",
".",
"listdir",
"(",
"asset_dir_path",
")",
":",
"log",
".",
"info",
"(",
"'Checking item: {i}'",
".",
"format",
"(",
"i",
"=",
"item",
")",
")",
"item_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"asset_dir_path",
",",
"item",
")",
"if",
"item_path",
"==",
"license_file_path",
":",
"continue",
"elif",
"item_path",
"==",
"doc_file_path",
":",
"continue",
"elif",
"item_path",
"==",
"asset_props",
":",
"continue",
"elif",
"item",
"in",
"ignore_items",
":",
"continue",
"elif",
"ignore_by_extension",
"(",
"item_path",
"=",
"item_path",
")",
":",
"continue",
"elif",
"item",
"in",
"acceptable_dirs",
"and",
"os",
".",
"path",
".",
"isdir",
"(",
"item_path",
")",
":",
"continue",
"else",
":",
"if",
"item",
"==",
"'VERSION'",
":",
"os",
".",
"remove",
"(",
"item_path",
")",
"log",
".",
"warn",
"(",
"'Deleted file: {f}'",
".",
"format",
"(",
"f",
"=",
"item_path",
")",
")",
"elif",
"item",
"==",
"'doc'",
":",
"raise",
"Cons3rtAssetStructureError",
"(",
"'Found a doc directory at the asset root, this is not allowed'",
")",
"elif",
"item",
"in",
"potential_doc_files",
":",
"if",
"not",
"doc_file_rel_path",
":",
"raise",
"Cons3rtAssetStructureError",
"(",
"'Documentation file found but not specified in '",
"'asset.properties: {f}'",
".",
"format",
"(",
"f",
"=",
"item_path",
")",
")",
"else",
":",
"raise",
"Cons3rtAssetStructureError",
"(",
"'Extra documentation file found: {f}'",
".",
"format",
"(",
"f",
"=",
"item_path",
")",
")",
"elif",
"item",
"in",
"potential_license_files",
":",
"if",
"not",
"license_file_rel_path",
":",
"raise",
"Cons3rtAssetStructureError",
"(",
"'License file found but not specified in '",
"'asset.properties: {f}'",
".",
"format",
"(",
"f",
"=",
"item_path",
")",
")",
"else",
":",
"raise",
"Cons3rtAssetStructureError",
"(",
"'Extra license file found: {f}'",
".",
"format",
"(",
"f",
"=",
"item_path",
")",
")",
"else",
":",
"raise",
"Cons3rtAssetStructureError",
"(",
"'Found illegal item at the asset root dir: {i}'",
".",
"format",
"(",
"i",
"=",
"item",
")",
")",
"log",
".",
"info",
"(",
"'Validated asset directory successfully: {d}'",
".",
"format",
"(",
"d",
"=",
"asset_dir_path",
")",
")",
"return",
"asset_name"
] | Checks asset structure validity
:param asset_dir_path: (str) path to the directory containing the asset
:return: (str) Asset name
:raises: Cons3rtAssetStructureError | [
"Checks",
"asset",
"structure",
"validity"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/asset.py#L122-L253 |
cons3rt/pycons3rt | pycons3rt/asset.py | make_asset_zip | def make_asset_zip(asset_dir_path, destination_directory=None):
"""Given an asset directory path, creates an asset zip file in the provided
destination directory
:param asset_dir_path: (str) path to the directory containing the asset
:param destination_directory: (str) path to the destination directory for
the asset
:return: (str) Path to the asset zip file
:raises: AssetZipCreationError
"""
log = logging.getLogger(mod_logger + '.make_asset_zip')
log.info('Attempting to create an asset zip from directory: {d}'.format(d=asset_dir_path))
# Ensure the path is a directory
if not os.path.isdir(asset_dir_path):
raise AssetZipCreationError('Provided asset_dir_path is not a directory: {d}'.format(d=asset_dir_path))
# Determine a destination directory if not provided
if destination_directory is None:
destination_directory = os.path.join(os.path.expanduser('~'), 'Downloads')
mkdir_p(destination_directory)
# Ensure the destination is a directory
if not os.path.isdir(destination_directory):
raise AssetZipCreationError('Provided destination_directory is not a directory: {d}'.format(
d=destination_directory))
# Validate the asset structure
try:
asset_name = validate_asset_structure(asset_dir_path=asset_dir_path)
except Cons3rtAssetStructureError:
_, ex, trace = sys.exc_info()
msg = 'Cons3rtAssetStructureError: Problem found in the asset structure: {d}\n{e}'.format(
d=asset_dir_path, e=str(ex))
raise AssetZipCreationError, msg, trace
# Determine the asset zip file name (same as asset name without spaces)
zip_file_name = 'asset-' + asset_name.replace(' ', '') + '.zip'
log.info('Using asset zip file name: {n}'.format(n=zip_file_name))
# Determine the zip file path
zip_file_path = os.path.join(destination_directory, zip_file_name)
# Remove existing zip file if it exists
if os.path.isfile(zip_file_path):
log.info('Removing existing asset zip file: {f}'.format(f=zip_file_path))
os.remove(zip_file_path)
# Attempt to create the zip
log.info('Attempting to create asset zip file: {f}'.format(f=zip_file_path))
try:
with contextlib.closing(zipfile.ZipFile(zip_file_path, 'w', allowZip64=True)) as zip_w:
for root, dirs, files in os.walk(asset_dir_path):
for f in files:
skip = False
file_path = os.path.join(root, f)
# Skip files in the ignore directories list
for ignore_dir in ignore_dirs:
if ignore_dir in file_path:
skip = True
break
# Skip file in the ignore files list
for ignore_file in ignore_files:
if f.startswith(ignore_file):
skip = True
break
# Skip if the file ends with the specified extension
if ignore_by_extension(item_path=file_path):
skip = True
if skip:
log.info('Skipping file: {f}'.format(f=file_path))
continue
log.info('Adding file to zip: {f}'.format(f=file_path))
archive_name = os.path.join(root[len(asset_dir_path):], f)
if archive_name.startswith('/'):
log.debug('Trimming the leading char: [/]')
archive_name = archive_name[1:]
log.info('Adding to archive as: {a}'.format(a=archive_name))
zip_w.write(file_path, archive_name)
except Exception:
_, ex, trace = sys.exc_info()
msg = 'Unable to create zip file: {f}\n{e}'.format(f=zip_file_path, e=str(ex))
raise AssetZipCreationError, msg, trace
log.info('Successfully created asset zip file: {f}'.format(f=zip_file_path))
return zip_file_path | python | def make_asset_zip(asset_dir_path, destination_directory=None):
"""Given an asset directory path, creates an asset zip file in the provided
destination directory
:param asset_dir_path: (str) path to the directory containing the asset
:param destination_directory: (str) path to the destination directory for
the asset
:return: (str) Path to the asset zip file
:raises: AssetZipCreationError
"""
log = logging.getLogger(mod_logger + '.make_asset_zip')
log.info('Attempting to create an asset zip from directory: {d}'.format(d=asset_dir_path))
# Ensure the path is a directory
if not os.path.isdir(asset_dir_path):
raise AssetZipCreationError('Provided asset_dir_path is not a directory: {d}'.format(d=asset_dir_path))
# Determine a destination directory if not provided
if destination_directory is None:
destination_directory = os.path.join(os.path.expanduser('~'), 'Downloads')
mkdir_p(destination_directory)
# Ensure the destination is a directory
if not os.path.isdir(destination_directory):
raise AssetZipCreationError('Provided destination_directory is not a directory: {d}'.format(
d=destination_directory))
# Validate the asset structure
try:
asset_name = validate_asset_structure(asset_dir_path=asset_dir_path)
except Cons3rtAssetStructureError:
_, ex, trace = sys.exc_info()
msg = 'Cons3rtAssetStructureError: Problem found in the asset structure: {d}\n{e}'.format(
d=asset_dir_path, e=str(ex))
raise AssetZipCreationError, msg, trace
# Determine the asset zip file name (same as asset name without spaces)
zip_file_name = 'asset-' + asset_name.replace(' ', '') + '.zip'
log.info('Using asset zip file name: {n}'.format(n=zip_file_name))
# Determine the zip file path
zip_file_path = os.path.join(destination_directory, zip_file_name)
# Remove existing zip file if it exists
if os.path.isfile(zip_file_path):
log.info('Removing existing asset zip file: {f}'.format(f=zip_file_path))
os.remove(zip_file_path)
# Attempt to create the zip
log.info('Attempting to create asset zip file: {f}'.format(f=zip_file_path))
try:
with contextlib.closing(zipfile.ZipFile(zip_file_path, 'w', allowZip64=True)) as zip_w:
for root, dirs, files in os.walk(asset_dir_path):
for f in files:
skip = False
file_path = os.path.join(root, f)
# Skip files in the ignore directories list
for ignore_dir in ignore_dirs:
if ignore_dir in file_path:
skip = True
break
# Skip file in the ignore files list
for ignore_file in ignore_files:
if f.startswith(ignore_file):
skip = True
break
# Skip if the file ends with the specified extension
if ignore_by_extension(item_path=file_path):
skip = True
if skip:
log.info('Skipping file: {f}'.format(f=file_path))
continue
log.info('Adding file to zip: {f}'.format(f=file_path))
archive_name = os.path.join(root[len(asset_dir_path):], f)
if archive_name.startswith('/'):
log.debug('Trimming the leading char: [/]')
archive_name = archive_name[1:]
log.info('Adding to archive as: {a}'.format(a=archive_name))
zip_w.write(file_path, archive_name)
except Exception:
_, ex, trace = sys.exc_info()
msg = 'Unable to create zip file: {f}\n{e}'.format(f=zip_file_path, e=str(ex))
raise AssetZipCreationError, msg, trace
log.info('Successfully created asset zip file: {f}'.format(f=zip_file_path))
return zip_file_path | [
"def",
"make_asset_zip",
"(",
"asset_dir_path",
",",
"destination_directory",
"=",
"None",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.make_asset_zip'",
")",
"log",
".",
"info",
"(",
"'Attempting to create an asset zip from directory: {d}'",
".",
"format",
"(",
"d",
"=",
"asset_dir_path",
")",
")",
"# Ensure the path is a directory",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"asset_dir_path",
")",
":",
"raise",
"AssetZipCreationError",
"(",
"'Provided asset_dir_path is not a directory: {d}'",
".",
"format",
"(",
"d",
"=",
"asset_dir_path",
")",
")",
"# Determine a destination directory if not provided",
"if",
"destination_directory",
"is",
"None",
":",
"destination_directory",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~'",
")",
",",
"'Downloads'",
")",
"mkdir_p",
"(",
"destination_directory",
")",
"# Ensure the destination is a directory",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"destination_directory",
")",
":",
"raise",
"AssetZipCreationError",
"(",
"'Provided destination_directory is not a directory: {d}'",
".",
"format",
"(",
"d",
"=",
"destination_directory",
")",
")",
"# Validate the asset structure",
"try",
":",
"asset_name",
"=",
"validate_asset_structure",
"(",
"asset_dir_path",
"=",
"asset_dir_path",
")",
"except",
"Cons3rtAssetStructureError",
":",
"_",
",",
"ex",
",",
"trace",
"=",
"sys",
".",
"exc_info",
"(",
")",
"msg",
"=",
"'Cons3rtAssetStructureError: Problem found in the asset structure: {d}\\n{e}'",
".",
"format",
"(",
"d",
"=",
"asset_dir_path",
",",
"e",
"=",
"str",
"(",
"ex",
")",
")",
"raise",
"AssetZipCreationError",
",",
"msg",
",",
"trace",
"# Determine the asset zip file name (same as asset name without spaces)",
"zip_file_name",
"=",
"'asset-'",
"+",
"asset_name",
".",
"replace",
"(",
"' '",
",",
"''",
")",
"+",
"'.zip'",
"log",
".",
"info",
"(",
"'Using asset zip file name: {n}'",
".",
"format",
"(",
"n",
"=",
"zip_file_name",
")",
")",
"# Determine the zip file path",
"zip_file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"destination_directory",
",",
"zip_file_name",
")",
"# Remove existing zip file if it exists",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"zip_file_path",
")",
":",
"log",
".",
"info",
"(",
"'Removing existing asset zip file: {f}'",
".",
"format",
"(",
"f",
"=",
"zip_file_path",
")",
")",
"os",
".",
"remove",
"(",
"zip_file_path",
")",
"# Attempt to create the zip",
"log",
".",
"info",
"(",
"'Attempting to create asset zip file: {f}'",
".",
"format",
"(",
"f",
"=",
"zip_file_path",
")",
")",
"try",
":",
"with",
"contextlib",
".",
"closing",
"(",
"zipfile",
".",
"ZipFile",
"(",
"zip_file_path",
",",
"'w'",
",",
"allowZip64",
"=",
"True",
")",
")",
"as",
"zip_w",
":",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"asset_dir_path",
")",
":",
"for",
"f",
"in",
"files",
":",
"skip",
"=",
"False",
"file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"f",
")",
"# Skip files in the ignore directories list",
"for",
"ignore_dir",
"in",
"ignore_dirs",
":",
"if",
"ignore_dir",
"in",
"file_path",
":",
"skip",
"=",
"True",
"break",
"# Skip file in the ignore files list",
"for",
"ignore_file",
"in",
"ignore_files",
":",
"if",
"f",
".",
"startswith",
"(",
"ignore_file",
")",
":",
"skip",
"=",
"True",
"break",
"# Skip if the file ends with the specified extension",
"if",
"ignore_by_extension",
"(",
"item_path",
"=",
"file_path",
")",
":",
"skip",
"=",
"True",
"if",
"skip",
":",
"log",
".",
"info",
"(",
"'Skipping file: {f}'",
".",
"format",
"(",
"f",
"=",
"file_path",
")",
")",
"continue",
"log",
".",
"info",
"(",
"'Adding file to zip: {f}'",
".",
"format",
"(",
"f",
"=",
"file_path",
")",
")",
"archive_name",
"=",
"os",
".",
"path",
".",
"join",
"(",
"root",
"[",
"len",
"(",
"asset_dir_path",
")",
":",
"]",
",",
"f",
")",
"if",
"archive_name",
".",
"startswith",
"(",
"'/'",
")",
":",
"log",
".",
"debug",
"(",
"'Trimming the leading char: [/]'",
")",
"archive_name",
"=",
"archive_name",
"[",
"1",
":",
"]",
"log",
".",
"info",
"(",
"'Adding to archive as: {a}'",
".",
"format",
"(",
"a",
"=",
"archive_name",
")",
")",
"zip_w",
".",
"write",
"(",
"file_path",
",",
"archive_name",
")",
"except",
"Exception",
":",
"_",
",",
"ex",
",",
"trace",
"=",
"sys",
".",
"exc_info",
"(",
")",
"msg",
"=",
"'Unable to create zip file: {f}\\n{e}'",
".",
"format",
"(",
"f",
"=",
"zip_file_path",
",",
"e",
"=",
"str",
"(",
"ex",
")",
")",
"raise",
"AssetZipCreationError",
",",
"msg",
",",
"trace",
"log",
".",
"info",
"(",
"'Successfully created asset zip file: {f}'",
".",
"format",
"(",
"f",
"=",
"zip_file_path",
")",
")",
"return",
"zip_file_path"
] | Given an asset directory path, creates an asset zip file in the provided
destination directory
:param asset_dir_path: (str) path to the directory containing the asset
:param destination_directory: (str) path to the destination directory for
the asset
:return: (str) Path to the asset zip file
:raises: AssetZipCreationError | [
"Given",
"an",
"asset",
"directory",
"path",
"creates",
"an",
"asset",
"zip",
"file",
"in",
"the",
"provided",
"destination",
"directory"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/asset.py#L256-L345 |
cons3rt/pycons3rt | pycons3rt/asset.py | validate | def validate(asset_dir):
"""Command line call to validate an asset structure
:param asset_dir: (full path to the asset dir)
:return: (int)
"""
try:
asset_name = validate_asset_structure(asset_dir_path=asset_dir)
except Cons3rtAssetStructureError:
_, ex, trace = sys.exc_info()
msg = 'Cons3rtAssetStructureError: Problem with asset validation\n{e}'.format(e=str(ex))
print('ERROR: {m}'.format(m=msg))
return 1
print('Validated asset with name: {n}'.format(n=asset_name))
return 0 | python | def validate(asset_dir):
"""Command line call to validate an asset structure
:param asset_dir: (full path to the asset dir)
:return: (int)
"""
try:
asset_name = validate_asset_structure(asset_dir_path=asset_dir)
except Cons3rtAssetStructureError:
_, ex, trace = sys.exc_info()
msg = 'Cons3rtAssetStructureError: Problem with asset validation\n{e}'.format(e=str(ex))
print('ERROR: {m}'.format(m=msg))
return 1
print('Validated asset with name: {n}'.format(n=asset_name))
return 0 | [
"def",
"validate",
"(",
"asset_dir",
")",
":",
"try",
":",
"asset_name",
"=",
"validate_asset_structure",
"(",
"asset_dir_path",
"=",
"asset_dir",
")",
"except",
"Cons3rtAssetStructureError",
":",
"_",
",",
"ex",
",",
"trace",
"=",
"sys",
".",
"exc_info",
"(",
")",
"msg",
"=",
"'Cons3rtAssetStructureError: Problem with asset validation\\n{e}'",
".",
"format",
"(",
"e",
"=",
"str",
"(",
"ex",
")",
")",
"print",
"(",
"'ERROR: {m}'",
".",
"format",
"(",
"m",
"=",
"msg",
")",
")",
"return",
"1",
"print",
"(",
"'Validated asset with name: {n}'",
".",
"format",
"(",
"n",
"=",
"asset_name",
")",
")",
"return",
"0"
] | Command line call to validate an asset structure
:param asset_dir: (full path to the asset dir)
:return: (int) | [
"Command",
"line",
"call",
"to",
"validate",
"an",
"asset",
"structure"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/asset.py#L348-L362 |
cons3rt/pycons3rt | pycons3rt/asset.py | create | def create(asset_dir, dest_dir):
"""Command line call to create an asset zip
:param asset_dir: (full path to the asset dir)
:param dest_dir: (full path to the destination directory)
:return: (int)
"""
val = validate(asset_dir=asset_dir)
if val != 0:
return 1
try:
asset_zip = make_asset_zip(asset_dir_path=asset_dir, destination_directory=dest_dir)
except AssetZipCreationError:
_, ex, trace = sys.exc_info()
msg = 'AssetZipCreationError: Problem with asset zip creation\n{e}'.format(e=str(ex))
print('ERROR: {m}'.format(m=msg))
return 1
print('Created asset zip file: {z}'.format(z=asset_zip))
return 0 | python | def create(asset_dir, dest_dir):
"""Command line call to create an asset zip
:param asset_dir: (full path to the asset dir)
:param dest_dir: (full path to the destination directory)
:return: (int)
"""
val = validate(asset_dir=asset_dir)
if val != 0:
return 1
try:
asset_zip = make_asset_zip(asset_dir_path=asset_dir, destination_directory=dest_dir)
except AssetZipCreationError:
_, ex, trace = sys.exc_info()
msg = 'AssetZipCreationError: Problem with asset zip creation\n{e}'.format(e=str(ex))
print('ERROR: {m}'.format(m=msg))
return 1
print('Created asset zip file: {z}'.format(z=asset_zip))
return 0 | [
"def",
"create",
"(",
"asset_dir",
",",
"dest_dir",
")",
":",
"val",
"=",
"validate",
"(",
"asset_dir",
"=",
"asset_dir",
")",
"if",
"val",
"!=",
"0",
":",
"return",
"1",
"try",
":",
"asset_zip",
"=",
"make_asset_zip",
"(",
"asset_dir_path",
"=",
"asset_dir",
",",
"destination_directory",
"=",
"dest_dir",
")",
"except",
"AssetZipCreationError",
":",
"_",
",",
"ex",
",",
"trace",
"=",
"sys",
".",
"exc_info",
"(",
")",
"msg",
"=",
"'AssetZipCreationError: Problem with asset zip creation\\n{e}'",
".",
"format",
"(",
"e",
"=",
"str",
"(",
"ex",
")",
")",
"print",
"(",
"'ERROR: {m}'",
".",
"format",
"(",
"m",
"=",
"msg",
")",
")",
"return",
"1",
"print",
"(",
"'Created asset zip file: {z}'",
".",
"format",
"(",
"z",
"=",
"asset_zip",
")",
")",
"return",
"0"
] | Command line call to create an asset zip
:param asset_dir: (full path to the asset dir)
:param dest_dir: (full path to the destination directory)
:return: (int) | [
"Command",
"line",
"call",
"to",
"create",
"an",
"asset",
"zip"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/asset.py#L365-L383 |
kajala/django-jutil | jutil/model.py | get_object_or_none | def get_object_or_none(cls, **kwargs):
"""
Returns model instance or None if not found.
:param cls: Class or queryset
:param kwargs: Filters for get() call
:return: Object or None
"""
from django.shortcuts import _get_queryset
qs = _get_queryset(cls)
try:
return qs.get(**kwargs)
except qs.model.DoesNotExist:
return None | python | def get_object_or_none(cls, **kwargs):
"""
Returns model instance or None if not found.
:param cls: Class or queryset
:param kwargs: Filters for get() call
:return: Object or None
"""
from django.shortcuts import _get_queryset
qs = _get_queryset(cls)
try:
return qs.get(**kwargs)
except qs.model.DoesNotExist:
return None | [
"def",
"get_object_or_none",
"(",
"cls",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"django",
".",
"shortcuts",
"import",
"_get_queryset",
"qs",
"=",
"_get_queryset",
"(",
"cls",
")",
"try",
":",
"return",
"qs",
".",
"get",
"(",
"*",
"*",
"kwargs",
")",
"except",
"qs",
".",
"model",
".",
"DoesNotExist",
":",
"return",
"None"
] | Returns model instance or None if not found.
:param cls: Class or queryset
:param kwargs: Filters for get() call
:return: Object or None | [
"Returns",
"model",
"instance",
"or",
"None",
"if",
"not",
"found",
".",
":",
"param",
"cls",
":",
"Class",
"or",
"queryset",
":",
"param",
"kwargs",
":",
"Filters",
"for",
"get",
"()",
"call",
":",
"return",
":",
"Object",
"or",
"None"
] | train | https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/model.py#L5-L17 |
kajala/django-jutil | jutil/model.py | get_model_field_label_and_value | def get_model_field_label_and_value(instance, field_name) -> (str, str):
"""
Returns model field label and value.
:param instance: Model instance
:param field_name: Model attribute name
:return: (label, value) tuple
"""
label = field_name
value = str(getattr(instance, field_name))
for f in instance._meta.fields:
if f.attname == field_name:
label = f.verbose_name
if hasattr(f, 'choices') and len(f.choices) > 0:
value = choices_label(f.choices, value)
break
return label, force_text(value) | python | def get_model_field_label_and_value(instance, field_name) -> (str, str):
"""
Returns model field label and value.
:param instance: Model instance
:param field_name: Model attribute name
:return: (label, value) tuple
"""
label = field_name
value = str(getattr(instance, field_name))
for f in instance._meta.fields:
if f.attname == field_name:
label = f.verbose_name
if hasattr(f, 'choices') and len(f.choices) > 0:
value = choices_label(f.choices, value)
break
return label, force_text(value) | [
"def",
"get_model_field_label_and_value",
"(",
"instance",
",",
"field_name",
")",
"->",
"(",
"str",
",",
"str",
")",
":",
"label",
"=",
"field_name",
"value",
"=",
"str",
"(",
"getattr",
"(",
"instance",
",",
"field_name",
")",
")",
"for",
"f",
"in",
"instance",
".",
"_meta",
".",
"fields",
":",
"if",
"f",
".",
"attname",
"==",
"field_name",
":",
"label",
"=",
"f",
".",
"verbose_name",
"if",
"hasattr",
"(",
"f",
",",
"'choices'",
")",
"and",
"len",
"(",
"f",
".",
"choices",
")",
">",
"0",
":",
"value",
"=",
"choices_label",
"(",
"f",
".",
"choices",
",",
"value",
")",
"break",
"return",
"label",
",",
"force_text",
"(",
"value",
")"
] | Returns model field label and value.
:param instance: Model instance
:param field_name: Model attribute name
:return: (label, value) tuple | [
"Returns",
"model",
"field",
"label",
"and",
"value",
".",
":",
"param",
"instance",
":",
"Model",
"instance",
":",
"param",
"field_name",
":",
"Model",
"attribute",
"name",
":",
"return",
":",
"(",
"label",
"value",
")",
"tuple"
] | train | https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/model.py#L20-L35 |
kajala/django-jutil | jutil/model.py | clone_model | def clone_model(instance, cls, commit: bool=True, exclude_fields: tuple=('id',), base_class_suffix: str='_ptr', **kw):
"""
Assigns model fields to new object. Ignores exclude_fields list and
attributes ending with pointer suffix (default '_ptr')
:param instance: Instance to copy
:param cls: Class name
:param commit: Save or not
:param exclude_fields: List of fields to exclude
:param base_class_suffix: End of name for base class pointers, e.g. model Car(Vehicle) has implicit vehicle_ptr
:return: New instance
"""
keys = [f.name for f in cls._meta.fields if f.name not in exclude_fields and not f.name.endswith(base_class_suffix)]
new_instance = cls()
for k in keys:
v = getattr(instance, k)
setattr(new_instance, k, v)
for k, v in kw.items():
setattr(new_instance, k, v)
if commit:
new_instance.save()
return new_instance | python | def clone_model(instance, cls, commit: bool=True, exclude_fields: tuple=('id',), base_class_suffix: str='_ptr', **kw):
"""
Assigns model fields to new object. Ignores exclude_fields list and
attributes ending with pointer suffix (default '_ptr')
:param instance: Instance to copy
:param cls: Class name
:param commit: Save or not
:param exclude_fields: List of fields to exclude
:param base_class_suffix: End of name for base class pointers, e.g. model Car(Vehicle) has implicit vehicle_ptr
:return: New instance
"""
keys = [f.name for f in cls._meta.fields if f.name not in exclude_fields and not f.name.endswith(base_class_suffix)]
new_instance = cls()
for k in keys:
v = getattr(instance, k)
setattr(new_instance, k, v)
for k, v in kw.items():
setattr(new_instance, k, v)
if commit:
new_instance.save()
return new_instance | [
"def",
"clone_model",
"(",
"instance",
",",
"cls",
",",
"commit",
":",
"bool",
"=",
"True",
",",
"exclude_fields",
":",
"tuple",
"=",
"(",
"'id'",
",",
")",
",",
"base_class_suffix",
":",
"str",
"=",
"'_ptr'",
",",
"*",
"*",
"kw",
")",
":",
"keys",
"=",
"[",
"f",
".",
"name",
"for",
"f",
"in",
"cls",
".",
"_meta",
".",
"fields",
"if",
"f",
".",
"name",
"not",
"in",
"exclude_fields",
"and",
"not",
"f",
".",
"name",
".",
"endswith",
"(",
"base_class_suffix",
")",
"]",
"new_instance",
"=",
"cls",
"(",
")",
"for",
"k",
"in",
"keys",
":",
"v",
"=",
"getattr",
"(",
"instance",
",",
"k",
")",
"setattr",
"(",
"new_instance",
",",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"kw",
".",
"items",
"(",
")",
":",
"setattr",
"(",
"new_instance",
",",
"k",
",",
"v",
")",
"if",
"commit",
":",
"new_instance",
".",
"save",
"(",
")",
"return",
"new_instance"
] | Assigns model fields to new object. Ignores exclude_fields list and
attributes ending with pointer suffix (default '_ptr')
:param instance: Instance to copy
:param cls: Class name
:param commit: Save or not
:param exclude_fields: List of fields to exclude
:param base_class_suffix: End of name for base class pointers, e.g. model Car(Vehicle) has implicit vehicle_ptr
:return: New instance | [
"Assigns",
"model",
"fields",
"to",
"new",
"object",
".",
"Ignores",
"exclude_fields",
"list",
"and",
"attributes",
"ending",
"with",
"pointer",
"suffix",
"(",
"default",
"_ptr",
")",
":",
"param",
"instance",
":",
"Instance",
"to",
"copy",
":",
"param",
"cls",
":",
"Class",
"name",
":",
"param",
"commit",
":",
"Save",
"or",
"not",
":",
"param",
"exclude_fields",
":",
"List",
"of",
"fields",
"to",
"exclude",
":",
"param",
"base_class_suffix",
":",
"End",
"of",
"name",
"for",
"base",
"class",
"pointers",
"e",
".",
"g",
".",
"model",
"Car",
"(",
"Vehicle",
")",
"has",
"implicit",
"vehicle_ptr",
":",
"return",
":",
"New",
"instance"
] | train | https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/model.py#L38-L58 |
praekeltfoundation/seed-identity-store | identities/views.py | IdentitySearchList.get_queryset | def get_queryset(self):
"""
This view should return a list of all the Identities
for the supplied query parameters. The query parameters
should be in the form:
{"address_type": "address"}
e.g.
{"msisdn": "+27123"}
{"email": "[email protected]"}
A special query paramater "include_inactive" can also be passed
as False to prevent returning identities for which the addresses
have been set to "inactive"
e.g.
{"include_inactive": False}
"""
query_params = list(self.request.query_params.keys())
# variable that stores criteria to filter identities by
filter_criteria = {}
# variable that stores a list of addresses that should be active
# if the special filter is passed in
exclude_if_address_inactive = []
# Determine from param "include_inactive" whether inactive identities
# should be included in the search results
if "include_inactive" in query_params:
if self.request.query_params["include_inactive"] in [
"False",
"false",
False,
]:
include_inactive = False
else:
include_inactive = True
else:
include_inactive = True # default to True
# Compile a list of criteria to filter the identities by, based on the
# query parameters
for filter in query_params:
if filter in ["include_inactive", "cursor"]:
# Don't add the cursor to the filter_criteria
pass
elif filter.startswith("details__addresses__"):
# Edit the query_param to evaluate the key instead of the value
# and add it to the filter_criteria
filter_criteria[filter + "__has_key"] = self.request.query_params[
filter
]
# Add the address to the list of addresses that should not
# be inactive (tuple e.g ("msisdn", "+27123"))
if include_inactive is False:
exclude_if_address_inactive.append(
(
filter.replace("details__addresses__", ""),
self.request.query_params[filter],
)
)
else:
# Add the normal params to the filter criteria
filter_criteria[filter] = self.request.query_params[filter]
identities = Identity.objects.filter(**filter_criteria)
if include_inactive is False:
# Check through all the identities and exclude ones where the
# addresses are inactive
for identity in identities:
for param in exclude_if_address_inactive:
q_key = identity.details["addresses"][param[0]][param[1]]
if "inactive" in q_key and q_key["inactive"] in [
True,
"True",
"true",
]: # noqa
identities = identities.exclude(id=identity.id)
return identities | python | def get_queryset(self):
"""
This view should return a list of all the Identities
for the supplied query parameters. The query parameters
should be in the form:
{"address_type": "address"}
e.g.
{"msisdn": "+27123"}
{"email": "[email protected]"}
A special query paramater "include_inactive" can also be passed
as False to prevent returning identities for which the addresses
have been set to "inactive"
e.g.
{"include_inactive": False}
"""
query_params = list(self.request.query_params.keys())
# variable that stores criteria to filter identities by
filter_criteria = {}
# variable that stores a list of addresses that should be active
# if the special filter is passed in
exclude_if_address_inactive = []
# Determine from param "include_inactive" whether inactive identities
# should be included in the search results
if "include_inactive" in query_params:
if self.request.query_params["include_inactive"] in [
"False",
"false",
False,
]:
include_inactive = False
else:
include_inactive = True
else:
include_inactive = True # default to True
# Compile a list of criteria to filter the identities by, based on the
# query parameters
for filter in query_params:
if filter in ["include_inactive", "cursor"]:
# Don't add the cursor to the filter_criteria
pass
elif filter.startswith("details__addresses__"):
# Edit the query_param to evaluate the key instead of the value
# and add it to the filter_criteria
filter_criteria[filter + "__has_key"] = self.request.query_params[
filter
]
# Add the address to the list of addresses that should not
# be inactive (tuple e.g ("msisdn", "+27123"))
if include_inactive is False:
exclude_if_address_inactive.append(
(
filter.replace("details__addresses__", ""),
self.request.query_params[filter],
)
)
else:
# Add the normal params to the filter criteria
filter_criteria[filter] = self.request.query_params[filter]
identities = Identity.objects.filter(**filter_criteria)
if include_inactive is False:
# Check through all the identities and exclude ones where the
# addresses are inactive
for identity in identities:
for param in exclude_if_address_inactive:
q_key = identity.details["addresses"][param[0]][param[1]]
if "inactive" in q_key and q_key["inactive"] in [
True,
"True",
"true",
]: # noqa
identities = identities.exclude(id=identity.id)
return identities | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"query_params",
"=",
"list",
"(",
"self",
".",
"request",
".",
"query_params",
".",
"keys",
"(",
")",
")",
"# variable that stores criteria to filter identities by",
"filter_criteria",
"=",
"{",
"}",
"# variable that stores a list of addresses that should be active",
"# if the special filter is passed in",
"exclude_if_address_inactive",
"=",
"[",
"]",
"# Determine from param \"include_inactive\" whether inactive identities",
"# should be included in the search results",
"if",
"\"include_inactive\"",
"in",
"query_params",
":",
"if",
"self",
".",
"request",
".",
"query_params",
"[",
"\"include_inactive\"",
"]",
"in",
"[",
"\"False\"",
",",
"\"false\"",
",",
"False",
",",
"]",
":",
"include_inactive",
"=",
"False",
"else",
":",
"include_inactive",
"=",
"True",
"else",
":",
"include_inactive",
"=",
"True",
"# default to True",
"# Compile a list of criteria to filter the identities by, based on the",
"# query parameters",
"for",
"filter",
"in",
"query_params",
":",
"if",
"filter",
"in",
"[",
"\"include_inactive\"",
",",
"\"cursor\"",
"]",
":",
"# Don't add the cursor to the filter_criteria",
"pass",
"elif",
"filter",
".",
"startswith",
"(",
"\"details__addresses__\"",
")",
":",
"# Edit the query_param to evaluate the key instead of the value",
"# and add it to the filter_criteria",
"filter_criteria",
"[",
"filter",
"+",
"\"__has_key\"",
"]",
"=",
"self",
".",
"request",
".",
"query_params",
"[",
"filter",
"]",
"# Add the address to the list of addresses that should not",
"# be inactive (tuple e.g (\"msisdn\", \"+27123\"))",
"if",
"include_inactive",
"is",
"False",
":",
"exclude_if_address_inactive",
".",
"append",
"(",
"(",
"filter",
".",
"replace",
"(",
"\"details__addresses__\"",
",",
"\"\"",
")",
",",
"self",
".",
"request",
".",
"query_params",
"[",
"filter",
"]",
",",
")",
")",
"else",
":",
"# Add the normal params to the filter criteria",
"filter_criteria",
"[",
"filter",
"]",
"=",
"self",
".",
"request",
".",
"query_params",
"[",
"filter",
"]",
"identities",
"=",
"Identity",
".",
"objects",
".",
"filter",
"(",
"*",
"*",
"filter_criteria",
")",
"if",
"include_inactive",
"is",
"False",
":",
"# Check through all the identities and exclude ones where the",
"# addresses are inactive",
"for",
"identity",
"in",
"identities",
":",
"for",
"param",
"in",
"exclude_if_address_inactive",
":",
"q_key",
"=",
"identity",
".",
"details",
"[",
"\"addresses\"",
"]",
"[",
"param",
"[",
"0",
"]",
"]",
"[",
"param",
"[",
"1",
"]",
"]",
"if",
"\"inactive\"",
"in",
"q_key",
"and",
"q_key",
"[",
"\"inactive\"",
"]",
"in",
"[",
"True",
",",
"\"True\"",
",",
"\"true\"",
",",
"]",
":",
"# noqa",
"identities",
"=",
"identities",
".",
"exclude",
"(",
"id",
"=",
"identity",
".",
"id",
")",
"return",
"identities"
] | This view should return a list of all the Identities
for the supplied query parameters. The query parameters
should be in the form:
{"address_type": "address"}
e.g.
{"msisdn": "+27123"}
{"email": "[email protected]"}
A special query paramater "include_inactive" can also be passed
as False to prevent returning identities for which the addresses
have been set to "inactive"
e.g.
{"include_inactive": False} | [
"This",
"view",
"should",
"return",
"a",
"list",
"of",
"all",
"the",
"Identities",
"for",
"the",
"supplied",
"query",
"parameters",
".",
"The",
"query",
"parameters",
"should",
"be",
"in",
"the",
"form",
":",
"{",
"address_type",
":",
"address",
"}",
"e",
".",
"g",
".",
"{",
"msisdn",
":",
"+",
"27123",
"}",
"{",
"email",
":",
"foo@bar",
".",
"com",
"}"
] | train | https://github.com/praekeltfoundation/seed-identity-store/blob/194e5756b5a74ebce9798c390de958cf5305b105/identities/views.py#L131-L210 |
praekeltfoundation/seed-identity-store | identities/views.py | IdentityAddresses.get_queryset | def get_queryset(self):
"""
This view should return a list of all the addresses the identity has
for the supplied query parameters.
Currently only supports address_type and default params
Always excludes addresses with optedout = True
"""
identity_id = self.kwargs["identity_id"]
address_type = self.kwargs["address_type"]
use_ct = "use_communicate_through" in self.request.query_params
default_only = "default" in self.request.query_params
if use_ct:
identity = Identity.objects.select_related("communicate_through").get(
id=identity_id
)
if identity.communicate_through is not None:
identity = identity.communicate_through
else:
identity = Identity.objects.get(id=identity_id)
addresses = identity.get_addresses_list(address_type, default_only)
return [Address(addr) for addr in addresses] | python | def get_queryset(self):
"""
This view should return a list of all the addresses the identity has
for the supplied query parameters.
Currently only supports address_type and default params
Always excludes addresses with optedout = True
"""
identity_id = self.kwargs["identity_id"]
address_type = self.kwargs["address_type"]
use_ct = "use_communicate_through" in self.request.query_params
default_only = "default" in self.request.query_params
if use_ct:
identity = Identity.objects.select_related("communicate_through").get(
id=identity_id
)
if identity.communicate_through is not None:
identity = identity.communicate_through
else:
identity = Identity.objects.get(id=identity_id)
addresses = identity.get_addresses_list(address_type, default_only)
return [Address(addr) for addr in addresses] | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"identity_id",
"=",
"self",
".",
"kwargs",
"[",
"\"identity_id\"",
"]",
"address_type",
"=",
"self",
".",
"kwargs",
"[",
"\"address_type\"",
"]",
"use_ct",
"=",
"\"use_communicate_through\"",
"in",
"self",
".",
"request",
".",
"query_params",
"default_only",
"=",
"\"default\"",
"in",
"self",
".",
"request",
".",
"query_params",
"if",
"use_ct",
":",
"identity",
"=",
"Identity",
".",
"objects",
".",
"select_related",
"(",
"\"communicate_through\"",
")",
".",
"get",
"(",
"id",
"=",
"identity_id",
")",
"if",
"identity",
".",
"communicate_through",
"is",
"not",
"None",
":",
"identity",
"=",
"identity",
".",
"communicate_through",
"else",
":",
"identity",
"=",
"Identity",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"identity_id",
")",
"addresses",
"=",
"identity",
".",
"get_addresses_list",
"(",
"address_type",
",",
"default_only",
")",
"return",
"[",
"Address",
"(",
"addr",
")",
"for",
"addr",
"in",
"addresses",
"]"
] | This view should return a list of all the addresses the identity has
for the supplied query parameters.
Currently only supports address_type and default params
Always excludes addresses with optedout = True | [
"This",
"view",
"should",
"return",
"a",
"list",
"of",
"all",
"the",
"addresses",
"the",
"identity",
"has",
"for",
"the",
"supplied",
"query",
"parameters",
".",
"Currently",
"only",
"supports",
"address_type",
"and",
"default",
"params",
"Always",
"excludes",
"addresses",
"with",
"optedout",
"=",
"True"
] | train | https://github.com/praekeltfoundation/seed-identity-store/blob/194e5756b5a74ebce9798c390de958cf5305b105/identities/views.py#L279-L299 |
isogeo/isogeo-api-py-minsdk | isogeo_pysdk/checker.py | IsogeoChecker.check_internet_connection | def check_internet_connection(self, remote_server: str = "api.isogeo.com") -> bool:
"""Test if an internet connection is operational.
Src: http://stackoverflow.com/a/20913928/2556577.
:param str remote_server: remote server used to check
"""
try:
# see if we can resolve the host name -- tells us if there is
# a DNS listening
host = socket.gethostbyname(remote_server)
# connect to the host -- tells us if it's reachable
sock = socket.create_connection((host, 80), 2)
sock.close()
return True
except Exception as e:
logging.error(e)
return False | python | def check_internet_connection(self, remote_server: str = "api.isogeo.com") -> bool:
"""Test if an internet connection is operational.
Src: http://stackoverflow.com/a/20913928/2556577.
:param str remote_server: remote server used to check
"""
try:
# see if we can resolve the host name -- tells us if there is
# a DNS listening
host = socket.gethostbyname(remote_server)
# connect to the host -- tells us if it's reachable
sock = socket.create_connection((host, 80), 2)
sock.close()
return True
except Exception as e:
logging.error(e)
return False | [
"def",
"check_internet_connection",
"(",
"self",
",",
"remote_server",
":",
"str",
"=",
"\"api.isogeo.com\"",
")",
"->",
"bool",
":",
"try",
":",
"# see if we can resolve the host name -- tells us if there is",
"# a DNS listening",
"host",
"=",
"socket",
".",
"gethostbyname",
"(",
"remote_server",
")",
"# connect to the host -- tells us if it's reachable",
"sock",
"=",
"socket",
".",
"create_connection",
"(",
"(",
"host",
",",
"80",
")",
",",
"2",
")",
"sock",
".",
"close",
"(",
")",
"return",
"True",
"except",
"Exception",
"as",
"e",
":",
"logging",
".",
"error",
"(",
"e",
")",
"return",
"False"
] | Test if an internet connection is operational.
Src: http://stackoverflow.com/a/20913928/2556577.
:param str remote_server: remote server used to check | [
"Test",
"if",
"an",
"internet",
"connection",
"is",
"operational",
".",
"Src",
":",
"http",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"a",
"/",
"20913928",
"/",
"2556577",
"."
] | train | https://github.com/isogeo/isogeo-api-py-minsdk/blob/57a604be92c7767b26abd247012cc1a584b386a0/isogeo_pysdk/checker.py#L109-L125 |
isogeo/isogeo-api-py-minsdk | isogeo_pysdk/checker.py | IsogeoChecker.check_bearer_validity | def check_bearer_validity(self, token: dict, connect_mtd) -> dict:
"""Check API Bearer token validity.
Isogeo ID delivers authentication bearers which are valid during
a certain time. So this method checks the validity of the token
with a 30 mn anticipation limit, and renews it if necessary.
See: http://tools.ietf.org/html/rfc6750#section-2
FI: 24h = 86400 seconds, 30 mn = 1800, 5 mn = 300
:param tuple token: auth bearer to check.
Structure: (bearer, expiration_date)
:param isogeo_pysdk.connect connect_mtd: method herited
from Isogeo PySDK to get new bearer
"""
warnings.warn(
"Method is now executed as a decorator within the main SDK class. Will be removed in future versions.",
DeprecationWarning,
)
if datetime.now() < token.get("expires_at"):
token = connect_mtd
logging.debug("Token was about to expire, so has been renewed.")
else:
logging.debug("Token is still valid.")
pass
# end of method
return token | python | def check_bearer_validity(self, token: dict, connect_mtd) -> dict:
"""Check API Bearer token validity.
Isogeo ID delivers authentication bearers which are valid during
a certain time. So this method checks the validity of the token
with a 30 mn anticipation limit, and renews it if necessary.
See: http://tools.ietf.org/html/rfc6750#section-2
FI: 24h = 86400 seconds, 30 mn = 1800, 5 mn = 300
:param tuple token: auth bearer to check.
Structure: (bearer, expiration_date)
:param isogeo_pysdk.connect connect_mtd: method herited
from Isogeo PySDK to get new bearer
"""
warnings.warn(
"Method is now executed as a decorator within the main SDK class. Will be removed in future versions.",
DeprecationWarning,
)
if datetime.now() < token.get("expires_at"):
token = connect_mtd
logging.debug("Token was about to expire, so has been renewed.")
else:
logging.debug("Token is still valid.")
pass
# end of method
return token | [
"def",
"check_bearer_validity",
"(",
"self",
",",
"token",
":",
"dict",
",",
"connect_mtd",
")",
"->",
"dict",
":",
"warnings",
".",
"warn",
"(",
"\"Method is now executed as a decorator within the main SDK class. Will be removed in future versions.\"",
",",
"DeprecationWarning",
",",
")",
"if",
"datetime",
".",
"now",
"(",
")",
"<",
"token",
".",
"get",
"(",
"\"expires_at\"",
")",
":",
"token",
"=",
"connect_mtd",
"logging",
".",
"debug",
"(",
"\"Token was about to expire, so has been renewed.\"",
")",
"else",
":",
"logging",
".",
"debug",
"(",
"\"Token is still valid.\"",
")",
"pass",
"# end of method",
"return",
"token"
] | Check API Bearer token validity.
Isogeo ID delivers authentication bearers which are valid during
a certain time. So this method checks the validity of the token
with a 30 mn anticipation limit, and renews it if necessary.
See: http://tools.ietf.org/html/rfc6750#section-2
FI: 24h = 86400 seconds, 30 mn = 1800, 5 mn = 300
:param tuple token: auth bearer to check.
Structure: (bearer, expiration_date)
:param isogeo_pysdk.connect connect_mtd: method herited
from Isogeo PySDK to get new bearer | [
"Check",
"API",
"Bearer",
"token",
"validity",
"."
] | train | https://github.com/isogeo/isogeo-api-py-minsdk/blob/57a604be92c7767b26abd247012cc1a584b386a0/isogeo_pysdk/checker.py#L127-L154 |
isogeo/isogeo-api-py-minsdk | isogeo_pysdk/checker.py | IsogeoChecker.check_api_response | def check_api_response(self, response):
"""Check API response and raise exceptions if needed.
:param requests.models.Response response: request response to check
"""
# check response
if response.status_code == 200:
return True
elif response.status_code >= 400:
logging.error(
"{}: {} - {} - URL: {}".format(
response.status_code,
response.reason,
response.json().get("error"),
response.request.url,
)
)
return False, response.status_code | python | def check_api_response(self, response):
"""Check API response and raise exceptions if needed.
:param requests.models.Response response: request response to check
"""
# check response
if response.status_code == 200:
return True
elif response.status_code >= 400:
logging.error(
"{}: {} - {} - URL: {}".format(
response.status_code,
response.reason,
response.json().get("error"),
response.request.url,
)
)
return False, response.status_code | [
"def",
"check_api_response",
"(",
"self",
",",
"response",
")",
":",
"# check response",
"if",
"response",
".",
"status_code",
"==",
"200",
":",
"return",
"True",
"elif",
"response",
".",
"status_code",
">=",
"400",
":",
"logging",
".",
"error",
"(",
"\"{}: {} - {} - URL: {}\"",
".",
"format",
"(",
"response",
".",
"status_code",
",",
"response",
".",
"reason",
",",
"response",
".",
"json",
"(",
")",
".",
"get",
"(",
"\"error\"",
")",
",",
"response",
".",
"request",
".",
"url",
",",
")",
")",
"return",
"False",
",",
"response",
".",
"status_code"
] | Check API response and raise exceptions if needed.
:param requests.models.Response response: request response to check | [
"Check",
"API",
"response",
"and",
"raise",
"exceptions",
"if",
"needed",
"."
] | train | https://github.com/isogeo/isogeo-api-py-minsdk/blob/57a604be92c7767b26abd247012cc1a584b386a0/isogeo_pysdk/checker.py#L156-L173 |
isogeo/isogeo-api-py-minsdk | isogeo_pysdk/checker.py | IsogeoChecker.check_request_parameters | def check_request_parameters(self, parameters: dict = dict):
"""Check parameters passed to avoid errors and help debug.
:param dict response: search request parameters
"""
# -- SEMANTIC QUERY ---------------------------------------------------
li_args = parameters.get("q").split()
logging.debug(li_args)
# Unicity
li_filters = [i.split(":")[0] for i in li_args]
filters_count = Counter(li_filters)
li_filters_must_be_unique = ("coordinate-system", "format", "owner", "type")
for i in filters_count:
if i in li_filters_must_be_unique and filters_count.get(i) > 1:
raise ValueError(
"This query filter must be unique: {}"
" and it occured {} times.".format(i, filters_count.get(i))
)
# dict
dico_query = FILTER_KEYS.copy()
for i in li_args:
if i.startswith("action"):
dico_query["action"].append(i.split(":")[1:][0])
continue
elif i.startswith("catalog"):
dico_query["catalog"].append(i.split(":")[1:][0])
continue
elif i.startswith("contact") and i.split(":")[1] == "group":
dico_query["contact:group"].append(i.split(":")[1:][1])
continue
elif i.startswith("contact"):
dico_query["contact:isogeo"].append(i.split(":", 1)[1])
continue
elif i.startswith("coordinate-system"):
dico_query["coordinate-system"].append(i.split(":")[1:][0])
continue
elif i.startswith("data-source"):
dico_query["data-source"].append(i.split(":")[1:][0])
continue
elif i.startswith("format"):
dico_query["format"].append(i.split(":")[1:][0])
continue
elif i.startswith("has-no"):
dico_query["has-no"].append(i.split(":")[1:][0])
continue
elif i.startswith("keyword:isogeo"):
dico_query["keyword:isogeo"].append(i.split(":")[1:][1])
continue
elif i.startswith("keyword:inspire-theme"):
dico_query["keyword:inspire-theme"].append(i.split(":")[1:][1])
continue
elif i.startswith("license:isogeo"):
dico_query["license:isogeo"].append(i.split(":")[1:][1:])
continue
elif i.startswith("license"):
dico_query["license:group"].append(i.split(":", 1)[1:][0:])
continue
elif i.startswith("owner"):
dico_query["owner"].append(i.split(":")[1:][0])
continue
elif i.startswith("provider"):
dico_query["provider"].append(i.split(":")[1:][0])
continue
elif i.startswith("share"):
dico_query["share"].append(i.split(":")[1:][0])
continue
elif i.startswith("type"):
dico_query["type"].append(i.split(":")[1:][0])
continue
else:
# logging.debug(i.split(":")[1], i.split(":")[1].isdigit())
dico_query["text"].append(i)
continue
# Values
dico_filters = {i.split(":")[0]: i.split(":")[1:] for i in li_args}
if dico_filters.get("type", ("dataset",))[0].lower() not in FILTER_TYPES:
raise ValueError(
"type value must be one of: {}".format(" | ".join(FILTER_TYPES))
)
elif dico_filters.get("action", ("download",))[0].lower() not in FILTER_ACTIONS:
raise ValueError(
"action value must be one of: {}".format(" | ".join(FILTER_ACTIONS))
)
elif (
dico_filters.get("provider", ("manual",))[0].lower() not in FILTER_PROVIDERS
):
raise ValueError(
"provider value must be one of: {}".format(" | ".join(FILTER_PROVIDERS))
)
else:
logging.debug(dico_filters)
# -- GEOGRAPHIC -------------------------------------------------------
in_box = parameters.get("box")
in_geo = parameters.get("geo")
# geometric relation
in_rel = parameters.get("rel")
if in_rel and in_box is None and in_geo is None:
raise ValueError("'rel' should'nt be used without box or geo.")
elif in_rel not in GEORELATIONS and in_rel is not None:
raise ValueError(
"{} is not a correct value for 'georel'."
" Must be one of: {}.".format(in_rel, " | ".join(GEORELATIONS))
) | python | def check_request_parameters(self, parameters: dict = dict):
"""Check parameters passed to avoid errors and help debug.
:param dict response: search request parameters
"""
# -- SEMANTIC QUERY ---------------------------------------------------
li_args = parameters.get("q").split()
logging.debug(li_args)
# Unicity
li_filters = [i.split(":")[0] for i in li_args]
filters_count = Counter(li_filters)
li_filters_must_be_unique = ("coordinate-system", "format", "owner", "type")
for i in filters_count:
if i in li_filters_must_be_unique and filters_count.get(i) > 1:
raise ValueError(
"This query filter must be unique: {}"
" and it occured {} times.".format(i, filters_count.get(i))
)
# dict
dico_query = FILTER_KEYS.copy()
for i in li_args:
if i.startswith("action"):
dico_query["action"].append(i.split(":")[1:][0])
continue
elif i.startswith("catalog"):
dico_query["catalog"].append(i.split(":")[1:][0])
continue
elif i.startswith("contact") and i.split(":")[1] == "group":
dico_query["contact:group"].append(i.split(":")[1:][1])
continue
elif i.startswith("contact"):
dico_query["contact:isogeo"].append(i.split(":", 1)[1])
continue
elif i.startswith("coordinate-system"):
dico_query["coordinate-system"].append(i.split(":")[1:][0])
continue
elif i.startswith("data-source"):
dico_query["data-source"].append(i.split(":")[1:][0])
continue
elif i.startswith("format"):
dico_query["format"].append(i.split(":")[1:][0])
continue
elif i.startswith("has-no"):
dico_query["has-no"].append(i.split(":")[1:][0])
continue
elif i.startswith("keyword:isogeo"):
dico_query["keyword:isogeo"].append(i.split(":")[1:][1])
continue
elif i.startswith("keyword:inspire-theme"):
dico_query["keyword:inspire-theme"].append(i.split(":")[1:][1])
continue
elif i.startswith("license:isogeo"):
dico_query["license:isogeo"].append(i.split(":")[1:][1:])
continue
elif i.startswith("license"):
dico_query["license:group"].append(i.split(":", 1)[1:][0:])
continue
elif i.startswith("owner"):
dico_query["owner"].append(i.split(":")[1:][0])
continue
elif i.startswith("provider"):
dico_query["provider"].append(i.split(":")[1:][0])
continue
elif i.startswith("share"):
dico_query["share"].append(i.split(":")[1:][0])
continue
elif i.startswith("type"):
dico_query["type"].append(i.split(":")[1:][0])
continue
else:
# logging.debug(i.split(":")[1], i.split(":")[1].isdigit())
dico_query["text"].append(i)
continue
# Values
dico_filters = {i.split(":")[0]: i.split(":")[1:] for i in li_args}
if dico_filters.get("type", ("dataset",))[0].lower() not in FILTER_TYPES:
raise ValueError(
"type value must be one of: {}".format(" | ".join(FILTER_TYPES))
)
elif dico_filters.get("action", ("download",))[0].lower() not in FILTER_ACTIONS:
raise ValueError(
"action value must be one of: {}".format(" | ".join(FILTER_ACTIONS))
)
elif (
dico_filters.get("provider", ("manual",))[0].lower() not in FILTER_PROVIDERS
):
raise ValueError(
"provider value must be one of: {}".format(" | ".join(FILTER_PROVIDERS))
)
else:
logging.debug(dico_filters)
# -- GEOGRAPHIC -------------------------------------------------------
in_box = parameters.get("box")
in_geo = parameters.get("geo")
# geometric relation
in_rel = parameters.get("rel")
if in_rel and in_box is None and in_geo is None:
raise ValueError("'rel' should'nt be used without box or geo.")
elif in_rel not in GEORELATIONS and in_rel is not None:
raise ValueError(
"{} is not a correct value for 'georel'."
" Must be one of: {}.".format(in_rel, " | ".join(GEORELATIONS))
) | [
"def",
"check_request_parameters",
"(",
"self",
",",
"parameters",
":",
"dict",
"=",
"dict",
")",
":",
"# -- SEMANTIC QUERY ---------------------------------------------------",
"li_args",
"=",
"parameters",
".",
"get",
"(",
"\"q\"",
")",
".",
"split",
"(",
")",
"logging",
".",
"debug",
"(",
"li_args",
")",
"# Unicity",
"li_filters",
"=",
"[",
"i",
".",
"split",
"(",
"\":\"",
")",
"[",
"0",
"]",
"for",
"i",
"in",
"li_args",
"]",
"filters_count",
"=",
"Counter",
"(",
"li_filters",
")",
"li_filters_must_be_unique",
"=",
"(",
"\"coordinate-system\"",
",",
"\"format\"",
",",
"\"owner\"",
",",
"\"type\"",
")",
"for",
"i",
"in",
"filters_count",
":",
"if",
"i",
"in",
"li_filters_must_be_unique",
"and",
"filters_count",
".",
"get",
"(",
"i",
")",
">",
"1",
":",
"raise",
"ValueError",
"(",
"\"This query filter must be unique: {}\"",
"\" and it occured {} times.\"",
".",
"format",
"(",
"i",
",",
"filters_count",
".",
"get",
"(",
"i",
")",
")",
")",
"# dict",
"dico_query",
"=",
"FILTER_KEYS",
".",
"copy",
"(",
")",
"for",
"i",
"in",
"li_args",
":",
"if",
"i",
".",
"startswith",
"(",
"\"action\"",
")",
":",
"dico_query",
"[",
"\"action\"",
"]",
".",
"append",
"(",
"i",
".",
"split",
"(",
"\":\"",
")",
"[",
"1",
":",
"]",
"[",
"0",
"]",
")",
"continue",
"elif",
"i",
".",
"startswith",
"(",
"\"catalog\"",
")",
":",
"dico_query",
"[",
"\"catalog\"",
"]",
".",
"append",
"(",
"i",
".",
"split",
"(",
"\":\"",
")",
"[",
"1",
":",
"]",
"[",
"0",
"]",
")",
"continue",
"elif",
"i",
".",
"startswith",
"(",
"\"contact\"",
")",
"and",
"i",
".",
"split",
"(",
"\":\"",
")",
"[",
"1",
"]",
"==",
"\"group\"",
":",
"dico_query",
"[",
"\"contact:group\"",
"]",
".",
"append",
"(",
"i",
".",
"split",
"(",
"\":\"",
")",
"[",
"1",
":",
"]",
"[",
"1",
"]",
")",
"continue",
"elif",
"i",
".",
"startswith",
"(",
"\"contact\"",
")",
":",
"dico_query",
"[",
"\"contact:isogeo\"",
"]",
".",
"append",
"(",
"i",
".",
"split",
"(",
"\":\"",
",",
"1",
")",
"[",
"1",
"]",
")",
"continue",
"elif",
"i",
".",
"startswith",
"(",
"\"coordinate-system\"",
")",
":",
"dico_query",
"[",
"\"coordinate-system\"",
"]",
".",
"append",
"(",
"i",
".",
"split",
"(",
"\":\"",
")",
"[",
"1",
":",
"]",
"[",
"0",
"]",
")",
"continue",
"elif",
"i",
".",
"startswith",
"(",
"\"data-source\"",
")",
":",
"dico_query",
"[",
"\"data-source\"",
"]",
".",
"append",
"(",
"i",
".",
"split",
"(",
"\":\"",
")",
"[",
"1",
":",
"]",
"[",
"0",
"]",
")",
"continue",
"elif",
"i",
".",
"startswith",
"(",
"\"format\"",
")",
":",
"dico_query",
"[",
"\"format\"",
"]",
".",
"append",
"(",
"i",
".",
"split",
"(",
"\":\"",
")",
"[",
"1",
":",
"]",
"[",
"0",
"]",
")",
"continue",
"elif",
"i",
".",
"startswith",
"(",
"\"has-no\"",
")",
":",
"dico_query",
"[",
"\"has-no\"",
"]",
".",
"append",
"(",
"i",
".",
"split",
"(",
"\":\"",
")",
"[",
"1",
":",
"]",
"[",
"0",
"]",
")",
"continue",
"elif",
"i",
".",
"startswith",
"(",
"\"keyword:isogeo\"",
")",
":",
"dico_query",
"[",
"\"keyword:isogeo\"",
"]",
".",
"append",
"(",
"i",
".",
"split",
"(",
"\":\"",
")",
"[",
"1",
":",
"]",
"[",
"1",
"]",
")",
"continue",
"elif",
"i",
".",
"startswith",
"(",
"\"keyword:inspire-theme\"",
")",
":",
"dico_query",
"[",
"\"keyword:inspire-theme\"",
"]",
".",
"append",
"(",
"i",
".",
"split",
"(",
"\":\"",
")",
"[",
"1",
":",
"]",
"[",
"1",
"]",
")",
"continue",
"elif",
"i",
".",
"startswith",
"(",
"\"license:isogeo\"",
")",
":",
"dico_query",
"[",
"\"license:isogeo\"",
"]",
".",
"append",
"(",
"i",
".",
"split",
"(",
"\":\"",
")",
"[",
"1",
":",
"]",
"[",
"1",
":",
"]",
")",
"continue",
"elif",
"i",
".",
"startswith",
"(",
"\"license\"",
")",
":",
"dico_query",
"[",
"\"license:group\"",
"]",
".",
"append",
"(",
"i",
".",
"split",
"(",
"\":\"",
",",
"1",
")",
"[",
"1",
":",
"]",
"[",
"0",
":",
"]",
")",
"continue",
"elif",
"i",
".",
"startswith",
"(",
"\"owner\"",
")",
":",
"dico_query",
"[",
"\"owner\"",
"]",
".",
"append",
"(",
"i",
".",
"split",
"(",
"\":\"",
")",
"[",
"1",
":",
"]",
"[",
"0",
"]",
")",
"continue",
"elif",
"i",
".",
"startswith",
"(",
"\"provider\"",
")",
":",
"dico_query",
"[",
"\"provider\"",
"]",
".",
"append",
"(",
"i",
".",
"split",
"(",
"\":\"",
")",
"[",
"1",
":",
"]",
"[",
"0",
"]",
")",
"continue",
"elif",
"i",
".",
"startswith",
"(",
"\"share\"",
")",
":",
"dico_query",
"[",
"\"share\"",
"]",
".",
"append",
"(",
"i",
".",
"split",
"(",
"\":\"",
")",
"[",
"1",
":",
"]",
"[",
"0",
"]",
")",
"continue",
"elif",
"i",
".",
"startswith",
"(",
"\"type\"",
")",
":",
"dico_query",
"[",
"\"type\"",
"]",
".",
"append",
"(",
"i",
".",
"split",
"(",
"\":\"",
")",
"[",
"1",
":",
"]",
"[",
"0",
"]",
")",
"continue",
"else",
":",
"# logging.debug(i.split(\":\")[1], i.split(\":\")[1].isdigit())",
"dico_query",
"[",
"\"text\"",
"]",
".",
"append",
"(",
"i",
")",
"continue",
"# Values",
"dico_filters",
"=",
"{",
"i",
".",
"split",
"(",
"\":\"",
")",
"[",
"0",
"]",
":",
"i",
".",
"split",
"(",
"\":\"",
")",
"[",
"1",
":",
"]",
"for",
"i",
"in",
"li_args",
"}",
"if",
"dico_filters",
".",
"get",
"(",
"\"type\"",
",",
"(",
"\"dataset\"",
",",
")",
")",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"not",
"in",
"FILTER_TYPES",
":",
"raise",
"ValueError",
"(",
"\"type value must be one of: {}\"",
".",
"format",
"(",
"\" | \"",
".",
"join",
"(",
"FILTER_TYPES",
")",
")",
")",
"elif",
"dico_filters",
".",
"get",
"(",
"\"action\"",
",",
"(",
"\"download\"",
",",
")",
")",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"not",
"in",
"FILTER_ACTIONS",
":",
"raise",
"ValueError",
"(",
"\"action value must be one of: {}\"",
".",
"format",
"(",
"\" | \"",
".",
"join",
"(",
"FILTER_ACTIONS",
")",
")",
")",
"elif",
"(",
"dico_filters",
".",
"get",
"(",
"\"provider\"",
",",
"(",
"\"manual\"",
",",
")",
")",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"not",
"in",
"FILTER_PROVIDERS",
")",
":",
"raise",
"ValueError",
"(",
"\"provider value must be one of: {}\"",
".",
"format",
"(",
"\" | \"",
".",
"join",
"(",
"FILTER_PROVIDERS",
")",
")",
")",
"else",
":",
"logging",
".",
"debug",
"(",
"dico_filters",
")",
"# -- GEOGRAPHIC -------------------------------------------------------",
"in_box",
"=",
"parameters",
".",
"get",
"(",
"\"box\"",
")",
"in_geo",
"=",
"parameters",
".",
"get",
"(",
"\"geo\"",
")",
"# geometric relation",
"in_rel",
"=",
"parameters",
".",
"get",
"(",
"\"rel\"",
")",
"if",
"in_rel",
"and",
"in_box",
"is",
"None",
"and",
"in_geo",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"'rel' should'nt be used without box or geo.\"",
")",
"elif",
"in_rel",
"not",
"in",
"GEORELATIONS",
"and",
"in_rel",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"\"{} is not a correct value for 'georel'.\"",
"\" Must be one of: {}.\"",
".",
"format",
"(",
"in_rel",
",",
"\" | \"",
".",
"join",
"(",
"GEORELATIONS",
")",
")",
")"
] | Check parameters passed to avoid errors and help debug.
:param dict response: search request parameters | [
"Check",
"parameters",
"passed",
"to",
"avoid",
"errors",
"and",
"help",
"debug",
"."
] | train | https://github.com/isogeo/isogeo-api-py-minsdk/blob/57a604be92c7767b26abd247012cc1a584b386a0/isogeo_pysdk/checker.py#L175-L281 |
isogeo/isogeo-api-py-minsdk | isogeo_pysdk/checker.py | IsogeoChecker.check_is_uuid | def check_is_uuid(self, uuid_str: str):
"""Check if it's an Isogeo UUID handling specific form.
:param str uuid_str: UUID string to check
"""
# check uuid type
if not isinstance(uuid_str, str):
raise TypeError("'uuid_str' expected a str value.")
else:
pass
# handle Isogeo specific UUID in XML exports
if "isogeo:metadata" in uuid_str:
uuid_str = "urn:uuid:{}".format(uuid_str.split(":")[-1])
else:
pass
# test it
try:
uid = UUID(uuid_str)
return uid.hex == uuid_str.replace("-", "").replace("urn:uuid:", "")
except ValueError as e:
logging.error(
"uuid ValueError. {} ({}) -- {}".format(type(uuid_str), uuid_str, e)
)
return False | python | def check_is_uuid(self, uuid_str: str):
"""Check if it's an Isogeo UUID handling specific form.
:param str uuid_str: UUID string to check
"""
# check uuid type
if not isinstance(uuid_str, str):
raise TypeError("'uuid_str' expected a str value.")
else:
pass
# handle Isogeo specific UUID in XML exports
if "isogeo:metadata" in uuid_str:
uuid_str = "urn:uuid:{}".format(uuid_str.split(":")[-1])
else:
pass
# test it
try:
uid = UUID(uuid_str)
return uid.hex == uuid_str.replace("-", "").replace("urn:uuid:", "")
except ValueError as e:
logging.error(
"uuid ValueError. {} ({}) -- {}".format(type(uuid_str), uuid_str, e)
)
return False | [
"def",
"check_is_uuid",
"(",
"self",
",",
"uuid_str",
":",
"str",
")",
":",
"# check uuid type",
"if",
"not",
"isinstance",
"(",
"uuid_str",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"'uuid_str' expected a str value.\"",
")",
"else",
":",
"pass",
"# handle Isogeo specific UUID in XML exports",
"if",
"\"isogeo:metadata\"",
"in",
"uuid_str",
":",
"uuid_str",
"=",
"\"urn:uuid:{}\"",
".",
"format",
"(",
"uuid_str",
".",
"split",
"(",
"\":\"",
")",
"[",
"-",
"1",
"]",
")",
"else",
":",
"pass",
"# test it",
"try",
":",
"uid",
"=",
"UUID",
"(",
"uuid_str",
")",
"return",
"uid",
".",
"hex",
"==",
"uuid_str",
".",
"replace",
"(",
"\"-\"",
",",
"\"\"",
")",
".",
"replace",
"(",
"\"urn:uuid:\"",
",",
"\"\"",
")",
"except",
"ValueError",
"as",
"e",
":",
"logging",
".",
"error",
"(",
"\"uuid ValueError. {} ({}) -- {}\"",
".",
"format",
"(",
"type",
"(",
"uuid_str",
")",
",",
"uuid_str",
",",
"e",
")",
")",
"return",
"False"
] | Check if it's an Isogeo UUID handling specific form.
:param str uuid_str: UUID string to check | [
"Check",
"if",
"it",
"s",
"an",
"Isogeo",
"UUID",
"handling",
"specific",
"form",
"."
] | train | https://github.com/isogeo/isogeo-api-py-minsdk/blob/57a604be92c7767b26abd247012cc1a584b386a0/isogeo_pysdk/checker.py#L283-L306 |
isogeo/isogeo-api-py-minsdk | isogeo_pysdk/checker.py | IsogeoChecker.check_edit_tab | def check_edit_tab(self, tab: str, md_type: str):
"""Check if asked tab is part of Isogeo web form and reliable
with metadata type.
:param str tab: tab to check. Must be one one of EDIT_TABS attribute
:param str md_type: metadata type. Must be one one of FILTER_TYPES
"""
# check parameters types
if not isinstance(tab, str):
raise TypeError("'tab' expected a str value.")
else:
pass
if not isinstance(md_type, str):
raise TypeError("'md_type' expected a str value.")
else:
pass
# check parameters values
if tab not in EDIT_TABS:
raise ValueError(
"'{}' isn't a valid edition tab. "
"Available values: {}".format(tab, " | ".join(EDIT_TABS))
)
else:
pass
if md_type not in FILTER_TYPES:
if md_type in FILTER_TYPES.values():
md_type = self._convert_md_type(md_type)
else:
raise ValueError(
"'{}' isn't a valid metadata type. "
"Available values: {}".format(md_type, " | ".join(FILTER_TYPES))
)
else:
pass
# check adequation tab/md_type
if md_type not in EDIT_TABS.get(tab):
raise ValueError(
"'{}' isn't a valid tab for a '{}'' metadata."
" Only for these types: {}.".format(tab, md_type, EDIT_TABS.get(tab))
)
else:
return True | python | def check_edit_tab(self, tab: str, md_type: str):
"""Check if asked tab is part of Isogeo web form and reliable
with metadata type.
:param str tab: tab to check. Must be one one of EDIT_TABS attribute
:param str md_type: metadata type. Must be one one of FILTER_TYPES
"""
# check parameters types
if not isinstance(tab, str):
raise TypeError("'tab' expected a str value.")
else:
pass
if not isinstance(md_type, str):
raise TypeError("'md_type' expected a str value.")
else:
pass
# check parameters values
if tab not in EDIT_TABS:
raise ValueError(
"'{}' isn't a valid edition tab. "
"Available values: {}".format(tab, " | ".join(EDIT_TABS))
)
else:
pass
if md_type not in FILTER_TYPES:
if md_type in FILTER_TYPES.values():
md_type = self._convert_md_type(md_type)
else:
raise ValueError(
"'{}' isn't a valid metadata type. "
"Available values: {}".format(md_type, " | ".join(FILTER_TYPES))
)
else:
pass
# check adequation tab/md_type
if md_type not in EDIT_TABS.get(tab):
raise ValueError(
"'{}' isn't a valid tab for a '{}'' metadata."
" Only for these types: {}.".format(tab, md_type, EDIT_TABS.get(tab))
)
else:
return True | [
"def",
"check_edit_tab",
"(",
"self",
",",
"tab",
":",
"str",
",",
"md_type",
":",
"str",
")",
":",
"# check parameters types",
"if",
"not",
"isinstance",
"(",
"tab",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"'tab' expected a str value.\"",
")",
"else",
":",
"pass",
"if",
"not",
"isinstance",
"(",
"md_type",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"'md_type' expected a str value.\"",
")",
"else",
":",
"pass",
"# check parameters values",
"if",
"tab",
"not",
"in",
"EDIT_TABS",
":",
"raise",
"ValueError",
"(",
"\"'{}' isn't a valid edition tab. \"",
"\"Available values: {}\"",
".",
"format",
"(",
"tab",
",",
"\" | \"",
".",
"join",
"(",
"EDIT_TABS",
")",
")",
")",
"else",
":",
"pass",
"if",
"md_type",
"not",
"in",
"FILTER_TYPES",
":",
"if",
"md_type",
"in",
"FILTER_TYPES",
".",
"values",
"(",
")",
":",
"md_type",
"=",
"self",
".",
"_convert_md_type",
"(",
"md_type",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"'{}' isn't a valid metadata type. \"",
"\"Available values: {}\"",
".",
"format",
"(",
"md_type",
",",
"\" | \"",
".",
"join",
"(",
"FILTER_TYPES",
")",
")",
")",
"else",
":",
"pass",
"# check adequation tab/md_type",
"if",
"md_type",
"not",
"in",
"EDIT_TABS",
".",
"get",
"(",
"tab",
")",
":",
"raise",
"ValueError",
"(",
"\"'{}' isn't a valid tab for a '{}'' metadata.\"",
"\" Only for these types: {}.\"",
".",
"format",
"(",
"tab",
",",
"md_type",
",",
"EDIT_TABS",
".",
"get",
"(",
"tab",
")",
")",
")",
"else",
":",
"return",
"True"
] | Check if asked tab is part of Isogeo web form and reliable
with metadata type.
:param str tab: tab to check. Must be one one of EDIT_TABS attribute
:param str md_type: metadata type. Must be one one of FILTER_TYPES | [
"Check",
"if",
"asked",
"tab",
"is",
"part",
"of",
"Isogeo",
"web",
"form",
"and",
"reliable",
"with",
"metadata",
"type",
"."
] | train | https://github.com/isogeo/isogeo-api-py-minsdk/blob/57a604be92c7767b26abd247012cc1a584b386a0/isogeo_pysdk/checker.py#L308-L349 |
isogeo/isogeo-api-py-minsdk | isogeo_pysdk/checker.py | IsogeoChecker._check_filter_specific_md | def _check_filter_specific_md(self, specific_md: list):
"""Check if specific_md parameter is valid.
:param list specific_md: list of specific metadata UUID to check
"""
if isinstance(specific_md, list):
if len(specific_md) > 0:
# checking UUIDs and poping bad ones
for md in specific_md:
if not self.check_is_uuid(md):
specific_md.remove(md)
logging.error("Metadata UUID is not correct: {}".format(md))
# joining survivors
specific_md = ",".join(specific_md)
else:
specific_md = ""
else:
raise TypeError("'specific_md' expects a list")
return specific_md | python | def _check_filter_specific_md(self, specific_md: list):
"""Check if specific_md parameter is valid.
:param list specific_md: list of specific metadata UUID to check
"""
if isinstance(specific_md, list):
if len(specific_md) > 0:
# checking UUIDs and poping bad ones
for md in specific_md:
if not self.check_is_uuid(md):
specific_md.remove(md)
logging.error("Metadata UUID is not correct: {}".format(md))
# joining survivors
specific_md = ",".join(specific_md)
else:
specific_md = ""
else:
raise TypeError("'specific_md' expects a list")
return specific_md | [
"def",
"_check_filter_specific_md",
"(",
"self",
",",
"specific_md",
":",
"list",
")",
":",
"if",
"isinstance",
"(",
"specific_md",
",",
"list",
")",
":",
"if",
"len",
"(",
"specific_md",
")",
">",
"0",
":",
"# checking UUIDs and poping bad ones",
"for",
"md",
"in",
"specific_md",
":",
"if",
"not",
"self",
".",
"check_is_uuid",
"(",
"md",
")",
":",
"specific_md",
".",
"remove",
"(",
"md",
")",
"logging",
".",
"error",
"(",
"\"Metadata UUID is not correct: {}\"",
".",
"format",
"(",
"md",
")",
")",
"# joining survivors",
"specific_md",
"=",
"\",\"",
".",
"join",
"(",
"specific_md",
")",
"else",
":",
"specific_md",
"=",
"\"\"",
"else",
":",
"raise",
"TypeError",
"(",
"\"'specific_md' expects a list\"",
")",
"return",
"specific_md"
] | Check if specific_md parameter is valid.
:param list specific_md: list of specific metadata UUID to check | [
"Check",
"if",
"specific_md",
"parameter",
"is",
"valid",
"."
] | train | https://github.com/isogeo/isogeo-api-py-minsdk/blob/57a604be92c7767b26abd247012cc1a584b386a0/isogeo_pysdk/checker.py#L352-L370 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.