code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def ParseOptions(cls, options, analysis_plugin):
"""Parses and validates options.
Args:
options (argparse.Namespace): parser options.
analysis_plugin (ViperAnalysisPlugin): analysis plugin to configure.
Raises:
BadConfigObject: when the output module object is of the wrong type.
BadConfigOption: when unable to connect to Viper instance.
"""
if not isinstance(analysis_plugin, viper.ViperAnalysisPlugin):
raise errors.BadConfigObject(
'Analysis plugin is not an instance of ViperAnalysisPlugin')
lookup_hash = cls._ParseStringOption(
options, 'viper_hash', default_value=cls._DEFAULT_HASH)
analysis_plugin.SetLookupHash(lookup_hash)
host = cls._ParseStringOption(
options, 'viper_host', default_value=cls._DEFAULT_HOST)
analysis_plugin.SetHost(host)
port = cls._ParseNumericOption(
options, 'viper_port', default_value=cls._DEFAULT_PORT)
analysis_plugin.SetPort(port)
protocol = cls._ParseStringOption(
options, 'viper_protocol', default_value=cls._DEFAULT_PROTOCOL)
protocol = protocol.lower().strip()
analysis_plugin.SetProtocol(protocol)
if not analysis_plugin.TestConnection():
raise errors.BadConfigOption(
'Unable to connect to Viper {0:s}:{1:d}'.format(host, port)) | Parses and validates options.
Args:
options (argparse.Namespace): parser options.
analysis_plugin (ViperAnalysisPlugin): analysis plugin to configure.
Raises:
BadConfigObject: when the output module object is of the wrong type.
BadConfigOption: when unable to connect to Viper instance. | Below is the the instruction that describes the task:
### Input:
Parses and validates options.
Args:
options (argparse.Namespace): parser options.
analysis_plugin (ViperAnalysisPlugin): analysis plugin to configure.
Raises:
BadConfigObject: when the output module object is of the wrong type.
BadConfigOption: when unable to connect to Viper instance.
### Response:
def ParseOptions(cls, options, analysis_plugin):
"""Parses and validates options.
Args:
options (argparse.Namespace): parser options.
analysis_plugin (ViperAnalysisPlugin): analysis plugin to configure.
Raises:
BadConfigObject: when the output module object is of the wrong type.
BadConfigOption: when unable to connect to Viper instance.
"""
if not isinstance(analysis_plugin, viper.ViperAnalysisPlugin):
raise errors.BadConfigObject(
'Analysis plugin is not an instance of ViperAnalysisPlugin')
lookup_hash = cls._ParseStringOption(
options, 'viper_hash', default_value=cls._DEFAULT_HASH)
analysis_plugin.SetLookupHash(lookup_hash)
host = cls._ParseStringOption(
options, 'viper_host', default_value=cls._DEFAULT_HOST)
analysis_plugin.SetHost(host)
port = cls._ParseNumericOption(
options, 'viper_port', default_value=cls._DEFAULT_PORT)
analysis_plugin.SetPort(port)
protocol = cls._ParseStringOption(
options, 'viper_protocol', default_value=cls._DEFAULT_PROTOCOL)
protocol = protocol.lower().strip()
analysis_plugin.SetProtocol(protocol)
if not analysis_plugin.TestConnection():
raise errors.BadConfigOption(
'Unable to connect to Viper {0:s}:{1:d}'.format(host, port)) |
def main():
"""
Sets up our command line options, prints the usage/help (if warranted), and
runs :py:func:`pyminifier.pyminify` with the given command line options.
"""
usage = '%prog [options] "<input file>"'
if '__main__.py' in sys.argv[0]: # python -m pyminifier
usage = 'pyminifier [options] "<input file>"'
parser = OptionParser(usage=usage, version=__version__)
parser.disable_interspersed_args()
parser.add_option(
"-o", "--outfile",
dest="outfile",
default=None,
help="Save output to the given file.",
metavar="<file path>"
)
parser.add_option(
"-d", "--destdir",
dest="destdir",
default="./minified",
help=("Save output to the given directory. "
"This option is required when handling multiple files. "
"Defaults to './minified' and will be created if not present. "),
metavar="<file path>"
)
parser.add_option(
"--nominify",
action="store_true",
dest="nominify",
default=False,
help="Don't bother minifying (only used with --pyz).",
)
parser.add_option(
"--use-tabs",
action="store_true",
dest="tabs",
default=False,
help="Use tabs for indentation instead of spaces.",
)
parser.add_option(
"--bzip2",
action="store_true",
dest="bzip2",
default=False,
help=("bzip2-compress the result into a self-executing python script. "
"Only works on stand-alone scripts without implicit imports.")
)
parser.add_option(
"--gzip",
action="store_true",
dest="gzip",
default=False,
help=("gzip-compress the result into a self-executing python script. "
"Only works on stand-alone scripts without implicit imports.")
)
if lzma:
parser.add_option(
"--lzma",
action="store_true",
dest="lzma",
default=False,
help=("lzma-compress the result into a self-executing python script. "
"Only works on stand-alone scripts without implicit imports.")
)
parser.add_option(
"--pyz",
dest="pyz",
default=None,
help=("zip-compress the result into a self-executing python script. "
"This will create a new file that includes any necessary implicit"
" (local to the script) modules. Will include/process all files "
"given as arguments to pyminifier.py on the command line."),
metavar="<name of archive>.pyz"
)
parser.add_option(
"-O", "--obfuscate",
action="store_true",
dest="obfuscate",
default=False,
help=(
"Obfuscate all function/method names, variables, and classes. "
"Default is to NOT obfuscate."
)
)
parser.add_option(
"--obfuscate-classes",
action="store_true",
dest="obf_classes",
default=False,
help="Obfuscate class names."
)
parser.add_option(
"--obfuscate-functions",
action="store_true",
dest="obf_functions",
default=False,
help="Obfuscate function and method names."
)
parser.add_option(
"--obfuscate-variables",
action="store_true",
dest="obf_variables",
default=False,
help="Obfuscate variable names."
)
parser.add_option(
"--obfuscate-import-methods",
action="store_true",
dest="obf_import_methods",
default=False,
help="Obfuscate globally-imported mouled methods (e.g. 'Ag=re.compile')."
)
parser.add_option(
"--obfuscate-builtins",
action="store_true",
dest="obf_builtins",
default=False,
help="Obfuscate built-ins (i.e. True, False, object, Exception, etc)."
)
parser.add_option(
"--replacement-length",
dest="replacement_length",
default=1,
help=(
"The length of the random names that will be used when obfuscating "
"identifiers."
),
metavar="1"
)
parser.add_option(
"--nonlatin",
action="store_true",
dest="use_nonlatin",
default=False,
help=(
"Use non-latin (unicode) characters in obfuscation (Python 3 only)."
" WARNING: This results in some SERIOUSLY hard-to-read code."
)
)
parser.add_option(
"--prepend",
dest="prepend",
default=None,
help=(
"Prepend the text in this file to the top of our output. "
"e.g. A copyright notice."
),
metavar="<file path>"
)
options, files = parser.parse_args()
if not files:
parser.print_help()
sys.exit(2)
pyminify(options, files) | Sets up our command line options, prints the usage/help (if warranted), and
runs :py:func:`pyminifier.pyminify` with the given command line options. | Below is the the instruction that describes the task:
### Input:
Sets up our command line options, prints the usage/help (if warranted), and
runs :py:func:`pyminifier.pyminify` with the given command line options.
### Response:
def main():
"""
Sets up our command line options, prints the usage/help (if warranted), and
runs :py:func:`pyminifier.pyminify` with the given command line options.
"""
usage = '%prog [options] "<input file>"'
if '__main__.py' in sys.argv[0]: # python -m pyminifier
usage = 'pyminifier [options] "<input file>"'
parser = OptionParser(usage=usage, version=__version__)
parser.disable_interspersed_args()
parser.add_option(
"-o", "--outfile",
dest="outfile",
default=None,
help="Save output to the given file.",
metavar="<file path>"
)
parser.add_option(
"-d", "--destdir",
dest="destdir",
default="./minified",
help=("Save output to the given directory. "
"This option is required when handling multiple files. "
"Defaults to './minified' and will be created if not present. "),
metavar="<file path>"
)
parser.add_option(
"--nominify",
action="store_true",
dest="nominify",
default=False,
help="Don't bother minifying (only used with --pyz).",
)
parser.add_option(
"--use-tabs",
action="store_true",
dest="tabs",
default=False,
help="Use tabs for indentation instead of spaces.",
)
parser.add_option(
"--bzip2",
action="store_true",
dest="bzip2",
default=False,
help=("bzip2-compress the result into a self-executing python script. "
"Only works on stand-alone scripts without implicit imports.")
)
parser.add_option(
"--gzip",
action="store_true",
dest="gzip",
default=False,
help=("gzip-compress the result into a self-executing python script. "
"Only works on stand-alone scripts without implicit imports.")
)
if lzma:
parser.add_option(
"--lzma",
action="store_true",
dest="lzma",
default=False,
help=("lzma-compress the result into a self-executing python script. "
"Only works on stand-alone scripts without implicit imports.")
)
parser.add_option(
"--pyz",
dest="pyz",
default=None,
help=("zip-compress the result into a self-executing python script. "
"This will create a new file that includes any necessary implicit"
" (local to the script) modules. Will include/process all files "
"given as arguments to pyminifier.py on the command line."),
metavar="<name of archive>.pyz"
)
parser.add_option(
"-O", "--obfuscate",
action="store_true",
dest="obfuscate",
default=False,
help=(
"Obfuscate all function/method names, variables, and classes. "
"Default is to NOT obfuscate."
)
)
parser.add_option(
"--obfuscate-classes",
action="store_true",
dest="obf_classes",
default=False,
help="Obfuscate class names."
)
parser.add_option(
"--obfuscate-functions",
action="store_true",
dest="obf_functions",
default=False,
help="Obfuscate function and method names."
)
parser.add_option(
"--obfuscate-variables",
action="store_true",
dest="obf_variables",
default=False,
help="Obfuscate variable names."
)
parser.add_option(
"--obfuscate-import-methods",
action="store_true",
dest="obf_import_methods",
default=False,
help="Obfuscate globally-imported mouled methods (e.g. 'Ag=re.compile')."
)
parser.add_option(
"--obfuscate-builtins",
action="store_true",
dest="obf_builtins",
default=False,
help="Obfuscate built-ins (i.e. True, False, object, Exception, etc)."
)
parser.add_option(
"--replacement-length",
dest="replacement_length",
default=1,
help=(
"The length of the random names that will be used when obfuscating "
"identifiers."
),
metavar="1"
)
parser.add_option(
"--nonlatin",
action="store_true",
dest="use_nonlatin",
default=False,
help=(
"Use non-latin (unicode) characters in obfuscation (Python 3 only)."
" WARNING: This results in some SERIOUSLY hard-to-read code."
)
)
parser.add_option(
"--prepend",
dest="prepend",
default=None,
help=(
"Prepend the text in this file to the top of our output. "
"e.g. A copyright notice."
),
metavar="<file path>"
)
options, files = parser.parse_args()
if not files:
parser.print_help()
sys.exit(2)
pyminify(options, files) |
def get_default_lab_path(self, config):
"""Generate a default laboratory path based on user environment."""
# Default path settings
# Append project name if present (NCI-specific)
default_project = os.environ.get('PROJECT', '')
default_short_path = os.path.join('/short', default_project)
default_user = pwd.getpwuid(os.getuid()).pw_name
short_path = config.get('shortpath', default_short_path)
lab_name = config.get('laboratory', self.model_type)
if os.path.isabs(lab_name):
lab_path = lab_name
else:
user_name = config.get('user', default_user)
lab_path = os.path.join(short_path, user_name, lab_name)
return lab_path | Generate a default laboratory path based on user environment. | Below is the the instruction that describes the task:
### Input:
Generate a default laboratory path based on user environment.
### Response:
def get_default_lab_path(self, config):
"""Generate a default laboratory path based on user environment."""
# Default path settings
# Append project name if present (NCI-specific)
default_project = os.environ.get('PROJECT', '')
default_short_path = os.path.join('/short', default_project)
default_user = pwd.getpwuid(os.getuid()).pw_name
short_path = config.get('shortpath', default_short_path)
lab_name = config.get('laboratory', self.model_type)
if os.path.isabs(lab_name):
lab_path = lab_name
else:
user_name = config.get('user', default_user)
lab_path = os.path.join(short_path, user_name, lab_name)
return lab_path |
def add_formatter(self, sqla_col_type, formatter, key_specific=None):
"""
Add a formatter to the registry
if key_specific is provided, this formatter will only be used for some
specific exports
"""
self.add_item(sqla_col_type, formatter, key_specific) | Add a formatter to the registry
if key_specific is provided, this formatter will only be used for some
specific exports | Below is the the instruction that describes the task:
### Input:
Add a formatter to the registry
if key_specific is provided, this formatter will only be used for some
specific exports
### Response:
def add_formatter(self, sqla_col_type, formatter, key_specific=None):
"""
Add a formatter to the registry
if key_specific is provided, this formatter will only be used for some
specific exports
"""
self.add_item(sqla_col_type, formatter, key_specific) |
def __levenshteinDistance(s, t):
'''
Find the Levenshtein distance between two Strings.
Python version of Levenshtein distance method implemented in Java at
U{http://www.java2s.com/Code/Java/Data-Type/FindtheLevenshteindistancebetweentwoStrings.htm}.
This is the number of changes needed to change one String into
another, where each change is a single character modification (deletion,
insertion or substitution).
The previous implementation of the Levenshtein distance algorithm
was from U{http://www.merriampark.com/ld.htm}
Chas Emerick has written an implementation in Java, which avoids an OutOfMemoryError
which can occur when my Java implementation is used with very large strings.
This implementation of the Levenshtein distance algorithm
is from U{http://www.merriampark.com/ldjava.htm}::
StringUtils.getLevenshteinDistance(null, *) = IllegalArgumentException
StringUtils.getLevenshteinDistance(*, null) = IllegalArgumentException
StringUtils.getLevenshteinDistance("","") = 0
StringUtils.getLevenshteinDistance("","a") = 1
StringUtils.getLevenshteinDistance("aaapppp", "") = 7
StringUtils.getLevenshteinDistance("frog", "fog") = 1
StringUtils.getLevenshteinDistance("fly", "ant") = 3
StringUtils.getLevenshteinDistance("elephant", "hippo") = 7
StringUtils.getLevenshteinDistance("hippo", "elephant") = 7
StringUtils.getLevenshteinDistance("hippo", "zzzzzzzz") = 8
StringUtils.getLevenshteinDistance("hello", "hallo") = 1
@param s: the first String, must not be null
@param t: the second String, must not be null
@return: result distance
@raise ValueError: if either String input C{null}
'''
if s is None or t is None:
raise ValueError("Strings must not be null")
n = len(s)
m = len(t)
if n == 0:
return m
elif m == 0:
return n
if n > m:
tmp = s
s = t
t = tmp
n = m;
m = len(t)
p = [None]*(n+1)
d = [None]*(n+1)
for i in range(0, n+1):
p[i] = i
for j in range(1, m+1):
if DEBUG_DISTANCE:
if j % 100 == 0:
print >>sys.stderr, "DEBUG:", int(j/(m+1.0)*100),"%\r",
t_j = t[j-1]
d[0] = j
for i in range(1, n+1):
cost = 0 if s[i-1] == t_j else 1
# minimum of cell to the left+1, to the top+1, diagonally left and up +cost
d[i] = min(min(d[i-1]+1, p[i]+1), p[i-1]+cost)
_d = p
p = d
d = _d
if DEBUG_DISTANCE:
print >> sys.stderr, "\n"
return p[n] | Find the Levenshtein distance between two Strings.
Python version of Levenshtein distance method implemented in Java at
U{http://www.java2s.com/Code/Java/Data-Type/FindtheLevenshteindistancebetweentwoStrings.htm}.
This is the number of changes needed to change one String into
another, where each change is a single character modification (deletion,
insertion or substitution).
The previous implementation of the Levenshtein distance algorithm
was from U{http://www.merriampark.com/ld.htm}
Chas Emerick has written an implementation in Java, which avoids an OutOfMemoryError
which can occur when my Java implementation is used with very large strings.
This implementation of the Levenshtein distance algorithm
is from U{http://www.merriampark.com/ldjava.htm}::
StringUtils.getLevenshteinDistance(null, *) = IllegalArgumentException
StringUtils.getLevenshteinDistance(*, null) = IllegalArgumentException
StringUtils.getLevenshteinDistance("","") = 0
StringUtils.getLevenshteinDistance("","a") = 1
StringUtils.getLevenshteinDistance("aaapppp", "") = 7
StringUtils.getLevenshteinDistance("frog", "fog") = 1
StringUtils.getLevenshteinDistance("fly", "ant") = 3
StringUtils.getLevenshteinDistance("elephant", "hippo") = 7
StringUtils.getLevenshteinDistance("hippo", "elephant") = 7
StringUtils.getLevenshteinDistance("hippo", "zzzzzzzz") = 8
StringUtils.getLevenshteinDistance("hello", "hallo") = 1
@param s: the first String, must not be null
@param t: the second String, must not be null
@return: result distance
@raise ValueError: if either String input C{null} | Below is the the instruction that describes the task:
### Input:
Find the Levenshtein distance between two Strings.
Python version of Levenshtein distance method implemented in Java at
U{http://www.java2s.com/Code/Java/Data-Type/FindtheLevenshteindistancebetweentwoStrings.htm}.
This is the number of changes needed to change one String into
another, where each change is a single character modification (deletion,
insertion or substitution).
The previous implementation of the Levenshtein distance algorithm
was from U{http://www.merriampark.com/ld.htm}
Chas Emerick has written an implementation in Java, which avoids an OutOfMemoryError
which can occur when my Java implementation is used with very large strings.
This implementation of the Levenshtein distance algorithm
is from U{http://www.merriampark.com/ldjava.htm}::
StringUtils.getLevenshteinDistance(null, *) = IllegalArgumentException
StringUtils.getLevenshteinDistance(*, null) = IllegalArgumentException
StringUtils.getLevenshteinDistance("","") = 0
StringUtils.getLevenshteinDistance("","a") = 1
StringUtils.getLevenshteinDistance("aaapppp", "") = 7
StringUtils.getLevenshteinDistance("frog", "fog") = 1
StringUtils.getLevenshteinDistance("fly", "ant") = 3
StringUtils.getLevenshteinDistance("elephant", "hippo") = 7
StringUtils.getLevenshteinDistance("hippo", "elephant") = 7
StringUtils.getLevenshteinDistance("hippo", "zzzzzzzz") = 8
StringUtils.getLevenshteinDistance("hello", "hallo") = 1
@param s: the first String, must not be null
@param t: the second String, must not be null
@return: result distance
@raise ValueError: if either String input C{null}
### Response:
def __levenshteinDistance(s, t):
'''
Find the Levenshtein distance between two Strings.
Python version of Levenshtein distance method implemented in Java at
U{http://www.java2s.com/Code/Java/Data-Type/FindtheLevenshteindistancebetweentwoStrings.htm}.
This is the number of changes needed to change one String into
another, where each change is a single character modification (deletion,
insertion or substitution).
The previous implementation of the Levenshtein distance algorithm
was from U{http://www.merriampark.com/ld.htm}
Chas Emerick has written an implementation in Java, which avoids an OutOfMemoryError
which can occur when my Java implementation is used with very large strings.
This implementation of the Levenshtein distance algorithm
is from U{http://www.merriampark.com/ldjava.htm}::
StringUtils.getLevenshteinDistance(null, *) = IllegalArgumentException
StringUtils.getLevenshteinDistance(*, null) = IllegalArgumentException
StringUtils.getLevenshteinDistance("","") = 0
StringUtils.getLevenshteinDistance("","a") = 1
StringUtils.getLevenshteinDistance("aaapppp", "") = 7
StringUtils.getLevenshteinDistance("frog", "fog") = 1
StringUtils.getLevenshteinDistance("fly", "ant") = 3
StringUtils.getLevenshteinDistance("elephant", "hippo") = 7
StringUtils.getLevenshteinDistance("hippo", "elephant") = 7
StringUtils.getLevenshteinDistance("hippo", "zzzzzzzz") = 8
StringUtils.getLevenshteinDistance("hello", "hallo") = 1
@param s: the first String, must not be null
@param t: the second String, must not be null
@return: result distance
@raise ValueError: if either String input C{null}
'''
if s is None or t is None:
raise ValueError("Strings must not be null")
n = len(s)
m = len(t)
if n == 0:
return m
elif m == 0:
return n
if n > m:
tmp = s
s = t
t = tmp
n = m;
m = len(t)
p = [None]*(n+1)
d = [None]*(n+1)
for i in range(0, n+1):
p[i] = i
for j in range(1, m+1):
if DEBUG_DISTANCE:
if j % 100 == 0:
print >>sys.stderr, "DEBUG:", int(j/(m+1.0)*100),"%\r",
t_j = t[j-1]
d[0] = j
for i in range(1, n+1):
cost = 0 if s[i-1] == t_j else 1
# minimum of cell to the left+1, to the top+1, diagonally left and up +cost
d[i] = min(min(d[i-1]+1, p[i]+1), p[i-1]+cost)
_d = p
p = d
d = _d
if DEBUG_DISTANCE:
print >> sys.stderr, "\n"
return p[n] |
def from_parts(cls, parts):
"""
Return content types XML mapping each part in *parts* to the
appropriate content type and suitable for storage as
``[Content_Types].xml`` in an OPC package.
"""
cti = cls()
cti._defaults['rels'] = CT.OPC_RELATIONSHIPS
cti._defaults['xml'] = CT.XML
for part in parts:
cti._add_content_type(part.partname, part.content_type)
return cti | Return content types XML mapping each part in *parts* to the
appropriate content type and suitable for storage as
``[Content_Types].xml`` in an OPC package. | Below is the the instruction that describes the task:
### Input:
Return content types XML mapping each part in *parts* to the
appropriate content type and suitable for storage as
``[Content_Types].xml`` in an OPC package.
### Response:
def from_parts(cls, parts):
"""
Return content types XML mapping each part in *parts* to the
appropriate content type and suitable for storage as
``[Content_Types].xml`` in an OPC package.
"""
cti = cls()
cti._defaults['rels'] = CT.OPC_RELATIONSHIPS
cti._defaults['xml'] = CT.XML
for part in parts:
cti._add_content_type(part.partname, part.content_type)
return cti |
def list_themes(cls, path=THEMES):
"""
Compile all of the themes configuration files in the search path.
"""
themes, errors = [], OrderedDict()
def load_themes(path, source):
"""
Load all themes in the given path.
"""
if os.path.isdir(path):
for filename in sorted(os.listdir(path)):
if not filename.endswith('.cfg'):
continue
filepath = os.path.join(path, filename)
name = filename[:-4]
try:
# Make sure the theme is valid
theme = cls.from_file(filepath, source)
except Exception as e:
errors[(source, name)] = e
else:
themes.append(theme)
themes.extend([Theme(use_color=True), Theme(use_color=False)])
load_themes(DEFAULT_THEMES, 'preset')
load_themes(path, 'installed')
return themes, errors | Compile all of the themes configuration files in the search path. | Below is the the instruction that describes the task:
### Input:
Compile all of the themes configuration files in the search path.
### Response:
def list_themes(cls, path=THEMES):
"""
Compile all of the themes configuration files in the search path.
"""
themes, errors = [], OrderedDict()
def load_themes(path, source):
"""
Load all themes in the given path.
"""
if os.path.isdir(path):
for filename in sorted(os.listdir(path)):
if not filename.endswith('.cfg'):
continue
filepath = os.path.join(path, filename)
name = filename[:-4]
try:
# Make sure the theme is valid
theme = cls.from_file(filepath, source)
except Exception as e:
errors[(source, name)] = e
else:
themes.append(theme)
themes.extend([Theme(use_color=True), Theme(use_color=False)])
load_themes(DEFAULT_THEMES, 'preset')
load_themes(path, 'installed')
return themes, errors |
def get_date_less_query(days, date_field):
"""
Query for if date_field is within number of "days" from now.
"""
query = None
days = get_integer(days)
if days:
future = get_days_from_now(days)
query = Q(**{"%s__lte" % date_field: future.isoformat()})
return query | Query for if date_field is within number of "days" from now. | Below is the the instruction that describes the task:
### Input:
Query for if date_field is within number of "days" from now.
### Response:
def get_date_less_query(days, date_field):
"""
Query for if date_field is within number of "days" from now.
"""
query = None
days = get_integer(days)
if days:
future = get_days_from_now(days)
query = Q(**{"%s__lte" % date_field: future.isoformat()})
return query |
def _load_form_data(self):
"""Method used internally to retrieve submitted data. After calling
this sets `form` and `files` on the request object to multi dicts
filled with the incoming form data. As a matter of fact the input
stream will be empty afterwards. You can also call this method to
force the parsing of the form data.
.. versionadded:: 0.8
"""
# abort early if we have already consumed the stream
if "form" in self.__dict__:
return
_assert_not_shallow(self)
if self.want_form_data_parsed:
content_type = self.environ.get("CONTENT_TYPE", "")
content_length = get_content_length(self.environ)
mimetype, options = parse_options_header(content_type)
parser = self.make_form_data_parser()
data = parser.parse(
self._get_stream_for_parsing(), mimetype, content_length, options
)
else:
data = (
self.stream,
self.parameter_storage_class(),
self.parameter_storage_class(),
)
# inject the values into the instance dict so that we bypass
# our cached_property non-data descriptor.
d = self.__dict__
d["stream"], d["form"], d["files"] = data | Method used internally to retrieve submitted data. After calling
this sets `form` and `files` on the request object to multi dicts
filled with the incoming form data. As a matter of fact the input
stream will be empty afterwards. You can also call this method to
force the parsing of the form data.
.. versionadded:: 0.8 | Below is the the instruction that describes the task:
### Input:
Method used internally to retrieve submitted data. After calling
this sets `form` and `files` on the request object to multi dicts
filled with the incoming form data. As a matter of fact the input
stream will be empty afterwards. You can also call this method to
force the parsing of the form data.
.. versionadded:: 0.8
### Response:
def _load_form_data(self):
"""Method used internally to retrieve submitted data. After calling
this sets `form` and `files` on the request object to multi dicts
filled with the incoming form data. As a matter of fact the input
stream will be empty afterwards. You can also call this method to
force the parsing of the form data.
.. versionadded:: 0.8
"""
# abort early if we have already consumed the stream
if "form" in self.__dict__:
return
_assert_not_shallow(self)
if self.want_form_data_parsed:
content_type = self.environ.get("CONTENT_TYPE", "")
content_length = get_content_length(self.environ)
mimetype, options = parse_options_header(content_type)
parser = self.make_form_data_parser()
data = parser.parse(
self._get_stream_for_parsing(), mimetype, content_length, options
)
else:
data = (
self.stream,
self.parameter_storage_class(),
self.parameter_storage_class(),
)
# inject the values into the instance dict so that we bypass
# our cached_property non-data descriptor.
d = self.__dict__
d["stream"], d["form"], d["files"] = data |
def on_import1(self, event):
"""
initialize window to import an arbitrary file into the working directory
"""
pmag_menu_dialogs.MoveFileIntoWD(self.parent, self.parent.WD) | initialize window to import an arbitrary file into the working directory | Below is the the instruction that describes the task:
### Input:
initialize window to import an arbitrary file into the working directory
### Response:
def on_import1(self, event):
"""
initialize window to import an arbitrary file into the working directory
"""
pmag_menu_dialogs.MoveFileIntoWD(self.parent, self.parent.WD) |
def acos(x, context=None):
"""
Return the inverse cosine of ``x``.
The mathematically exact result lies in the range [0, π]. However, note
that as a result of rounding to the current context, it's possible for the
actual value returned to be fractionally larger than π::
>>> from bigfloat import precision
>>> with precision(12):
... x = acos(-1)
...
>>> print(x)
3.1416
>>> x > const_pi()
True
"""
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_acos,
(BigFloat._implicit_convert(x),),
context,
) | Return the inverse cosine of ``x``.
The mathematically exact result lies in the range [0, π]. However, note
that as a result of rounding to the current context, it's possible for the
actual value returned to be fractionally larger than π::
>>> from bigfloat import precision
>>> with precision(12):
... x = acos(-1)
...
>>> print(x)
3.1416
>>> x > const_pi()
True | Below is the the instruction that describes the task:
### Input:
Return the inverse cosine of ``x``.
The mathematically exact result lies in the range [0, π]. However, note
that as a result of rounding to the current context, it's possible for the
actual value returned to be fractionally larger than π::
>>> from bigfloat import precision
>>> with precision(12):
... x = acos(-1)
...
>>> print(x)
3.1416
>>> x > const_pi()
True
### Response:
def acos(x, context=None):
"""
Return the inverse cosine of ``x``.
The mathematically exact result lies in the range [0, π]. However, note
that as a result of rounding to the current context, it's possible for the
actual value returned to be fractionally larger than π::
>>> from bigfloat import precision
>>> with precision(12):
... x = acos(-1)
...
>>> print(x)
3.1416
>>> x > const_pi()
True
"""
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_acos,
(BigFloat._implicit_convert(x),),
context,
) |
def mount(self, identifier):
"""
Mounts a container or image referred to by identifier to
the host filesystem.
"""
driver = self.client.info()['Driver']
driver_mount_fn = getattr(self, "_mount_" + driver,
self._unsupported_backend)
cid = driver_mount_fn(identifier)
# Return mount path so it can be later unmounted by path
return self.mountpoint, cid | Mounts a container or image referred to by identifier to
the host filesystem. | Below is the the instruction that describes the task:
### Input:
Mounts a container or image referred to by identifier to
the host filesystem.
### Response:
def mount(self, identifier):
"""
Mounts a container or image referred to by identifier to
the host filesystem.
"""
driver = self.client.info()['Driver']
driver_mount_fn = getattr(self, "_mount_" + driver,
self._unsupported_backend)
cid = driver_mount_fn(identifier)
# Return mount path so it can be later unmounted by path
return self.mountpoint, cid |
def put(index_name, doc_type, identifier, body, force, verbose):
"""Index input data."""
result = current_search_client.index(
index=index_name,
doc_type=doc_type or index_name,
id=identifier,
body=json.load(body),
op_type='index' if force or identifier is None else 'create',
)
if verbose:
click.echo(json.dumps(result)) | Index input data. | Below is the the instruction that describes the task:
### Input:
Index input data.
### Response:
def put(index_name, doc_type, identifier, body, force, verbose):
"""Index input data."""
result = current_search_client.index(
index=index_name,
doc_type=doc_type or index_name,
id=identifier,
body=json.load(body),
op_type='index' if force or identifier is None else 'create',
)
if verbose:
click.echo(json.dumps(result)) |
def convert_tstamp(response):
"""
Convert a Stripe API timestamp response (unix epoch) to a native datetime.
:rtype: datetime
"""
if response is None:
# Allow passing None to convert_tstamp()
return response
# Overrides the set timezone to UTC - I think...
tz = timezone.utc if settings.USE_TZ else None
return datetime.datetime.fromtimestamp(response, tz) | Convert a Stripe API timestamp response (unix epoch) to a native datetime.
:rtype: datetime | Below is the the instruction that describes the task:
### Input:
Convert a Stripe API timestamp response (unix epoch) to a native datetime.
:rtype: datetime
### Response:
def convert_tstamp(response):
"""
Convert a Stripe API timestamp response (unix epoch) to a native datetime.
:rtype: datetime
"""
if response is None:
# Allow passing None to convert_tstamp()
return response
# Overrides the set timezone to UTC - I think...
tz = timezone.utc if settings.USE_TZ else None
return datetime.datetime.fromtimestamp(response, tz) |
def distance(x0, x1, y0, y1):
"""
Function that calculates the square of the distance between two points.
Parameters
-----
x0: x - coordinate of point 0
x1: x - coordinate of point 1
y0: y - coordinate of point 0
y1: y - coordinate of point 1
Returns
------
distance : float
square of distance
"""
# Calculate square of the distance between two points (Pythagoras)
distance = (x1.values- x0.values)*(x1.values- x0.values)\
+ (y1.values- y0.values)*(y1.values- y0.values)
return distance | Function that calculates the square of the distance between two points.
Parameters
-----
x0: x - coordinate of point 0
x1: x - coordinate of point 1
y0: y - coordinate of point 0
y1: y - coordinate of point 1
Returns
------
distance : float
square of distance | Below is the the instruction that describes the task:
### Input:
Function that calculates the square of the distance between two points.
Parameters
-----
x0: x - coordinate of point 0
x1: x - coordinate of point 1
y0: y - coordinate of point 0
y1: y - coordinate of point 1
Returns
------
distance : float
square of distance
### Response:
def distance(x0, x1, y0, y1):
"""
Function that calculates the square of the distance between two points.
Parameters
-----
x0: x - coordinate of point 0
x1: x - coordinate of point 1
y0: y - coordinate of point 0
y1: y - coordinate of point 1
Returns
------
distance : float
square of distance
"""
# Calculate square of the distance between two points (Pythagoras)
distance = (x1.values- x0.values)*(x1.values- x0.values)\
+ (y1.values- y0.values)*(y1.values- y0.values)
return distance |
def find_file(path, filename, max_depth=5):
"""Returns full filepath if the file is in path or a subdirectory."""
for root, dirs, files in os.walk(path):
if filename in files:
return os.path.join(root, filename)
# Don't search past max_depth
depth = root[len(path) + 1:].count(os.sep)
if depth > max_depth:
del dirs[:] # Clear dirs
return None | Returns full filepath if the file is in path or a subdirectory. | Below is the the instruction that describes the task:
### Input:
Returns full filepath if the file is in path or a subdirectory.
### Response:
def find_file(path, filename, max_depth=5):
"""Returns full filepath if the file is in path or a subdirectory."""
for root, dirs, files in os.walk(path):
if filename in files:
return os.path.join(root, filename)
# Don't search past max_depth
depth = root[len(path) + 1:].count(os.sep)
if depth > max_depth:
del dirs[:] # Clear dirs
return None |
def get_removes(self, profile=None):
"""Get filtered list of Remove objects in this Feature
:param str profile: Return Remove objects with this profile or None
to return all Remove objects.
:return: list of Remove objects
"""
out = []
for rem in self.removes:
# Filter Remove by profile
if ((rem.profile and not profile) or
(rem.profile and profile and rem.profile != profile)):
continue
out.append(rem)
return out | Get filtered list of Remove objects in this Feature
:param str profile: Return Remove objects with this profile or None
to return all Remove objects.
:return: list of Remove objects | Below is the the instruction that describes the task:
### Input:
Get filtered list of Remove objects in this Feature
:param str profile: Return Remove objects with this profile or None
to return all Remove objects.
:return: list of Remove objects
### Response:
def get_removes(self, profile=None):
"""Get filtered list of Remove objects in this Feature
:param str profile: Return Remove objects with this profile or None
to return all Remove objects.
:return: list of Remove objects
"""
out = []
for rem in self.removes:
# Filter Remove by profile
if ((rem.profile and not profile) or
(rem.profile and profile and rem.profile != profile)):
continue
out.append(rem)
return out |
def add_runnable(self, runnable):
"""
Adds a runnable component to the list of runnable components in
this simulation.
@param runnable: A runnable component
@type runnable: lems.sim.runnable.Runnable
"""
if runnable.id in self.runnables:
raise SimError('Duplicate runnable component {0}'.format(runnable.id))
self.runnables[runnable.id] = runnable | Adds a runnable component to the list of runnable components in
this simulation.
@param runnable: A runnable component
@type runnable: lems.sim.runnable.Runnable | Below is the the instruction that describes the task:
### Input:
Adds a runnable component to the list of runnable components in
this simulation.
@param runnable: A runnable component
@type runnable: lems.sim.runnable.Runnable
### Response:
def add_runnable(self, runnable):
"""
Adds a runnable component to the list of runnable components in
this simulation.
@param runnable: A runnable component
@type runnable: lems.sim.runnable.Runnable
"""
if runnable.id in self.runnables:
raise SimError('Duplicate runnable component {0}'.format(runnable.id))
self.runnables[runnable.id] = runnable |
def get_params_from_list(params_list):
"""Transform params list to dictionary.
"""
params = {}
for i in range(0, len(params_list)):
if '=' not in params_list[i]:
try:
if not isinstance(params[key], list): params[key] = [params[key]]
params[key] += [params_list[i]]
except KeyError:
raise ValueError('Pass parameters like `key1=a key2=b c d key3=...`.')
else:
key_val = params_list[i].split('=')
key, val = key_val
params[key] = convert_string(val)
return params | Transform params list to dictionary. | Below is the the instruction that describes the task:
### Input:
Transform params list to dictionary.
### Response:
def get_params_from_list(params_list):
"""Transform params list to dictionary.
"""
params = {}
for i in range(0, len(params_list)):
if '=' not in params_list[i]:
try:
if not isinstance(params[key], list): params[key] = [params[key]]
params[key] += [params_list[i]]
except KeyError:
raise ValueError('Pass parameters like `key1=a key2=b c d key3=...`.')
else:
key_val = params_list[i].split('=')
key, val = key_val
params[key] = convert_string(val)
return params |
def _get_banks_to_remove(redis_server, bank, path=''):
'''
A simple tree tarversal algorithm that builds the list of banks to remove,
starting from an arbitrary node in the tree.
'''
current_path = bank if not path else '{path}/{bank}'.format(path=path, bank=bank)
bank_paths_to_remove = [current_path]
# as you got here, you'll be removed
bank_key = _get_bank_redis_key(current_path)
child_banks = redis_server.smembers(bank_key)
if not child_banks:
return bank_paths_to_remove # this bank does not have any child banks so we stop here
for child_bank in child_banks:
bank_paths_to_remove.extend(_get_banks_to_remove(redis_server, child_bank, path=current_path))
# go one more level deeper
# and also remove the children of this child bank (if any)
return bank_paths_to_remove | A simple tree tarversal algorithm that builds the list of banks to remove,
starting from an arbitrary node in the tree. | Below is the the instruction that describes the task:
### Input:
A simple tree tarversal algorithm that builds the list of banks to remove,
starting from an arbitrary node in the tree.
### Response:
def _get_banks_to_remove(redis_server, bank, path=''):
'''
A simple tree tarversal algorithm that builds the list of banks to remove,
starting from an arbitrary node in the tree.
'''
current_path = bank if not path else '{path}/{bank}'.format(path=path, bank=bank)
bank_paths_to_remove = [current_path]
# as you got here, you'll be removed
bank_key = _get_bank_redis_key(current_path)
child_banks = redis_server.smembers(bank_key)
if not child_banks:
return bank_paths_to_remove # this bank does not have any child banks so we stop here
for child_bank in child_banks:
bank_paths_to_remove.extend(_get_banks_to_remove(redis_server, child_bank, path=current_path))
# go one more level deeper
# and also remove the children of this child bank (if any)
return bank_paths_to_remove |
def cancel(self, consumer_tag):
"""Cancel a channel by consumer tag."""
if not self.channel.conn:
return
self.channel.basic_cancel(consumer_tag) | Cancel a channel by consumer tag. | Below is the the instruction that describes the task:
### Input:
Cancel a channel by consumer tag.
### Response:
def cancel(self, consumer_tag):
"""Cancel a channel by consumer tag."""
if not self.channel.conn:
return
self.channel.basic_cancel(consumer_tag) |
def update(*args, **kwargs):
'''
Update installed plugin package(s).
Each plugin package must have a directory (**NOT** a link) containing a
``properties.yml`` file with a ``package_name`` value in the following
directory:
<conda prefix>/share/microdrop/plugins/available/
Parameters
----------
*args
Extra arguments to pass to Conda ``install`` command.
See :func:`install`.
package_name : str or list, optional
Name(s) of MicroDrop plugin Conda package(s) to update.
By default, all installed packages are updated.
**kwargs
See :func:`install`.
Returns
-------
dict
Conda installation log object (from JSON ``conda install`` output).
Notes
-----
Only actual plugin directories are considered when updating (i.e., **NOT**
directory links).
This permits, for example, linking of a plugin into the ``available``
plugins directory during development without risking overwriting during an
update.
Raises
------
RuntimeError
If one or more installed plugin packages cannot be updated.
This can happen, for example, if the plugin package is not available in
any of the specified Conda channels.
See also
--------
:func:`installed_plugins`
'''
package_name = kwargs.pop('package_name', None)
# Only consider **installed** plugins (see `installed_plugins()` docstring).
installed_plugins_ = installed_plugins(only_conda=True)
if installed_plugins_:
plugin_packages = [plugin_i['package_name']
for plugin_i in installed_plugins_]
if package_name is None:
package_name = plugin_packages
elif isinstance(package_name, types.StringTypes):
package_name = [package_name]
logger.info('Installing any available updates for plugins: %s',
','.join('`{}`'.format(package_name_i)
for package_name_i in package_name))
# Attempt to install plugin packages.
try:
install_log = install(package_name, *args, **kwargs)
except RuntimeError, exception:
if 'CondaHTTPError' in str(exception):
raise IOError('Error accessing update server.')
else:
raise
if 'actions' in install_log:
logger.debug('Updated plugin(s): ```%s```', install_log['actions'])
return install_log
else:
return {} | Update installed plugin package(s).
Each plugin package must have a directory (**NOT** a link) containing a
``properties.yml`` file with a ``package_name`` value in the following
directory:
<conda prefix>/share/microdrop/plugins/available/
Parameters
----------
*args
Extra arguments to pass to Conda ``install`` command.
See :func:`install`.
package_name : str or list, optional
Name(s) of MicroDrop plugin Conda package(s) to update.
By default, all installed packages are updated.
**kwargs
See :func:`install`.
Returns
-------
dict
Conda installation log object (from JSON ``conda install`` output).
Notes
-----
Only actual plugin directories are considered when updating (i.e., **NOT**
directory links).
This permits, for example, linking of a plugin into the ``available``
plugins directory during development without risking overwriting during an
update.
Raises
------
RuntimeError
If one or more installed plugin packages cannot be updated.
This can happen, for example, if the plugin package is not available in
any of the specified Conda channels.
See also
--------
:func:`installed_plugins` | Below is the the instruction that describes the task:
### Input:
Update installed plugin package(s).
Each plugin package must have a directory (**NOT** a link) containing a
``properties.yml`` file with a ``package_name`` value in the following
directory:
<conda prefix>/share/microdrop/plugins/available/
Parameters
----------
*args
Extra arguments to pass to Conda ``install`` command.
See :func:`install`.
package_name : str or list, optional
Name(s) of MicroDrop plugin Conda package(s) to update.
By default, all installed packages are updated.
**kwargs
See :func:`install`.
Returns
-------
dict
Conda installation log object (from JSON ``conda install`` output).
Notes
-----
Only actual plugin directories are considered when updating (i.e., **NOT**
directory links).
This permits, for example, linking of a plugin into the ``available``
plugins directory during development without risking overwriting during an
update.
Raises
------
RuntimeError
If one or more installed plugin packages cannot be updated.
This can happen, for example, if the plugin package is not available in
any of the specified Conda channels.
See also
--------
:func:`installed_plugins`
### Response:
def update(*args, **kwargs):
'''
Update installed plugin package(s).
Each plugin package must have a directory (**NOT** a link) containing a
``properties.yml`` file with a ``package_name`` value in the following
directory:
<conda prefix>/share/microdrop/plugins/available/
Parameters
----------
*args
Extra arguments to pass to Conda ``install`` command.
See :func:`install`.
package_name : str or list, optional
Name(s) of MicroDrop plugin Conda package(s) to update.
By default, all installed packages are updated.
**kwargs
See :func:`install`.
Returns
-------
dict
Conda installation log object (from JSON ``conda install`` output).
Notes
-----
Only actual plugin directories are considered when updating (i.e., **NOT**
directory links).
This permits, for example, linking of a plugin into the ``available``
plugins directory during development without risking overwriting during an
update.
Raises
------
RuntimeError
If one or more installed plugin packages cannot be updated.
This can happen, for example, if the plugin package is not available in
any of the specified Conda channels.
See also
--------
:func:`installed_plugins`
'''
package_name = kwargs.pop('package_name', None)
# Only consider **installed** plugins (see `installed_plugins()` docstring).
installed_plugins_ = installed_plugins(only_conda=True)
if installed_plugins_:
plugin_packages = [plugin_i['package_name']
for plugin_i in installed_plugins_]
if package_name is None:
package_name = plugin_packages
elif isinstance(package_name, types.StringTypes):
package_name = [package_name]
logger.info('Installing any available updates for plugins: %s',
','.join('`{}`'.format(package_name_i)
for package_name_i in package_name))
# Attempt to install plugin packages.
try:
install_log = install(package_name, *args, **kwargs)
except RuntimeError, exception:
if 'CondaHTTPError' in str(exception):
raise IOError('Error accessing update server.')
else:
raise
if 'actions' in install_log:
logger.debug('Updated plugin(s): ```%s```', install_log['actions'])
return install_log
else:
return {} |
def supports_proxies(*proxy_types):
'''
Decorator to specify which proxy types are supported by a function
proxy_types:
Arbitrary list of strings with the supported types of proxies
'''
def _supports_proxies(fn):
@wraps(fn)
def __supports_proxies(*args, **kwargs):
proxy_type = get_proxy_type()
if proxy_type not in proxy_types:
raise CommandExecutionError(
'\'{0}\' proxy is not supported by function {1}'
''.format(proxy_type, fn.__name__))
return fn(*args, **salt.utils.args.clean_kwargs(**kwargs))
return __supports_proxies
return _supports_proxies | Decorator to specify which proxy types are supported by a function
proxy_types:
Arbitrary list of strings with the supported types of proxies | Below is the the instruction that describes the task:
### Input:
Decorator to specify which proxy types are supported by a function
proxy_types:
Arbitrary list of strings with the supported types of proxies
### Response:
def supports_proxies(*proxy_types):
'''
Decorator to specify which proxy types are supported by a function
proxy_types:
Arbitrary list of strings with the supported types of proxies
'''
def _supports_proxies(fn):
@wraps(fn)
def __supports_proxies(*args, **kwargs):
proxy_type = get_proxy_type()
if proxy_type not in proxy_types:
raise CommandExecutionError(
'\'{0}\' proxy is not supported by function {1}'
''.format(proxy_type, fn.__name__))
return fn(*args, **salt.utils.args.clean_kwargs(**kwargs))
return __supports_proxies
return _supports_proxies |
def serialize(data, measurement=None, tag_columns=None, **extra_tags):
"""Converts input data into line protocol format"""
if isinstance(data, bytes):
return data
elif isinstance(data, str):
return data.encode('utf-8')
elif hasattr(data, 'to_lineprotocol'):
return data.to_lineprotocol()
elif pd is not None and isinstance(data, pd.DataFrame):
return dataframe.serialize(data, measurement, tag_columns, **extra_tags)
elif isinstance(data, dict):
return mapping.serialize(data, measurement, **extra_tags)
elif hasattr(data, '__iter__'):
return b'\n'.join([serialize(i, measurement, tag_columns, **extra_tags) for i in data])
else:
raise ValueError('Invalid input', data) | Converts input data into line protocol format | Below is the the instruction that describes the task:
### Input:
Converts input data into line protocol format
### Response:
def serialize(data, measurement=None, tag_columns=None, **extra_tags):
"""Converts input data into line protocol format"""
if isinstance(data, bytes):
return data
elif isinstance(data, str):
return data.encode('utf-8')
elif hasattr(data, 'to_lineprotocol'):
return data.to_lineprotocol()
elif pd is not None and isinstance(data, pd.DataFrame):
return dataframe.serialize(data, measurement, tag_columns, **extra_tags)
elif isinstance(data, dict):
return mapping.serialize(data, measurement, **extra_tags)
elif hasattr(data, '__iter__'):
return b'\n'.join([serialize(i, measurement, tag_columns, **extra_tags) for i in data])
else:
raise ValueError('Invalid input', data) |
def apply_color_scheme(self, color_scheme):
"""
Apply a pygments color scheme to the console.
As there is not a 1 to 1 mapping between color scheme formats and
console formats, we decided to make the following mapping (it usually
looks good for most of the available pygments styles):
- stdout_color = normal color
- stderr_color = red (lighter if background is dark)
- stdin_color = numbers color
- app_msg_color = string color
- bacgorund_color = background
:param color_scheme: pyqode.core.api.ColorScheme to apply
"""
self.stdout_color = color_scheme.formats['normal'].foreground().color()
self.stdin_color = color_scheme.formats['number'].foreground().color()
self.app_msg_color = color_scheme.formats[
'string'].foreground().color()
self.background_color = color_scheme.background
if self.background_color.lightness() < 128:
self.stderr_color = QColor('#FF8080')
else:
self.stderr_color = QColor('red') | Apply a pygments color scheme to the console.
As there is not a 1 to 1 mapping between color scheme formats and
console formats, we decided to make the following mapping (it usually
looks good for most of the available pygments styles):
- stdout_color = normal color
- stderr_color = red (lighter if background is dark)
- stdin_color = numbers color
- app_msg_color = string color
- bacgorund_color = background
:param color_scheme: pyqode.core.api.ColorScheme to apply | Below is the the instruction that describes the task:
### Input:
Apply a pygments color scheme to the console.
As there is not a 1 to 1 mapping between color scheme formats and
console formats, we decided to make the following mapping (it usually
looks good for most of the available pygments styles):
- stdout_color = normal color
- stderr_color = red (lighter if background is dark)
- stdin_color = numbers color
- app_msg_color = string color
- bacgorund_color = background
:param color_scheme: pyqode.core.api.ColorScheme to apply
### Response:
def apply_color_scheme(self, color_scheme):
"""
Apply a pygments color scheme to the console.
As there is not a 1 to 1 mapping between color scheme formats and
console formats, we decided to make the following mapping (it usually
looks good for most of the available pygments styles):
- stdout_color = normal color
- stderr_color = red (lighter if background is dark)
- stdin_color = numbers color
- app_msg_color = string color
- bacgorund_color = background
:param color_scheme: pyqode.core.api.ColorScheme to apply
"""
self.stdout_color = color_scheme.formats['normal'].foreground().color()
self.stdin_color = color_scheme.formats['number'].foreground().color()
self.app_msg_color = color_scheme.formats[
'string'].foreground().color()
self.background_color = color_scheme.background
if self.background_color.lightness() < 128:
self.stderr_color = QColor('#FF8080')
else:
self.stderr_color = QColor('red') |
def default_output_format(content_type='application/json', apply_globally=False, api=None, cli=False, http=True):
"""A decorator that allows you to override the default output format for an API"""
def decorator(formatter):
formatter = hug.output_format.content_type(content_type)(formatter)
if apply_globally:
if http:
hug.defaults.output_format = formatter
if cli:
hug.defaults.cli_output_format = formatter
else:
apply_to_api = hug.API(api) if api else hug.api.from_object(formatter)
if http:
apply_to_api.http.output_format = formatter
if cli:
apply_to_api.cli.output_format = formatter
return formatter
return decorator | A decorator that allows you to override the default output format for an API | Below is the the instruction that describes the task:
### Input:
A decorator that allows you to override the default output format for an API
### Response:
def default_output_format(content_type='application/json', apply_globally=False, api=None, cli=False, http=True):
"""A decorator that allows you to override the default output format for an API"""
def decorator(formatter):
formatter = hug.output_format.content_type(content_type)(formatter)
if apply_globally:
if http:
hug.defaults.output_format = formatter
if cli:
hug.defaults.cli_output_format = formatter
else:
apply_to_api = hug.API(api) if api else hug.api.from_object(formatter)
if http:
apply_to_api.http.output_format = formatter
if cli:
apply_to_api.cli.output_format = formatter
return formatter
return decorator |
def restore_image_options(cli, image, options):
""" Restores CMD and ENTRYPOINT values of the image
This is needed because we force the overwrite of ENTRYPOINT and CMD in the
`run_code_in_container` function, to be able to run the code in the
container, through /bin/bash.
"""
dockerfile = io.StringIO()
dockerfile.write(u'FROM {image}\nCMD {cmd}'.format(
image=image, cmd=json.dumps(options['cmd'])))
if options['entrypoint']:
dockerfile.write(
'\nENTRYPOINT {}'.format(json.dumps(options['entrypoint'])))
cli.build(tag=image, fileobj=dockerfile) | Restores CMD and ENTRYPOINT values of the image
This is needed because we force the overwrite of ENTRYPOINT and CMD in the
`run_code_in_container` function, to be able to run the code in the
container, through /bin/bash. | Below is the the instruction that describes the task:
### Input:
Restores CMD and ENTRYPOINT values of the image
This is needed because we force the overwrite of ENTRYPOINT and CMD in the
`run_code_in_container` function, to be able to run the code in the
container, through /bin/bash.
### Response:
def restore_image_options(cli, image, options):
""" Restores CMD and ENTRYPOINT values of the image
This is needed because we force the overwrite of ENTRYPOINT and CMD in the
`run_code_in_container` function, to be able to run the code in the
container, through /bin/bash.
"""
dockerfile = io.StringIO()
dockerfile.write(u'FROM {image}\nCMD {cmd}'.format(
image=image, cmd=json.dumps(options['cmd'])))
if options['entrypoint']:
dockerfile.write(
'\nENTRYPOINT {}'.format(json.dumps(options['entrypoint'])))
cli.build(tag=image, fileobj=dockerfile) |
def _enforce_width(text, width, unicode_aware=True):
"""
Enforce a displayed piece of text to be a certain number of cells wide. This takes into
account double-width characters used in CJK languages.
:param text: The text to be truncated
:param width: The screen cell width to enforce
:return: The resulting truncated text
"""
# Double-width strings cannot be more than twice the string length, so no need to try
# expensive truncation if this upper bound isn't an issue.
if 2 * len(text) < width:
return text
# Can still optimize performance if we are not handling unicode characters.
if unicode_aware:
size = 0
for i, c in enumerate(text):
w = wcwidth(c) if ord(c) >= 256 else 1
if size + w > width:
return text[0:i]
size += w
elif len(text) + 1 > width:
return text[0:width]
return text | Enforce a displayed piece of text to be a certain number of cells wide. This takes into
account double-width characters used in CJK languages.
:param text: The text to be truncated
:param width: The screen cell width to enforce
:return: The resulting truncated text | Below is the the instruction that describes the task:
### Input:
Enforce a displayed piece of text to be a certain number of cells wide. This takes into
account double-width characters used in CJK languages.
:param text: The text to be truncated
:param width: The screen cell width to enforce
:return: The resulting truncated text
### Response:
def _enforce_width(text, width, unicode_aware=True):
"""
Enforce a displayed piece of text to be a certain number of cells wide. This takes into
account double-width characters used in CJK languages.
:param text: The text to be truncated
:param width: The screen cell width to enforce
:return: The resulting truncated text
"""
# Double-width strings cannot be more than twice the string length, so no need to try
# expensive truncation if this upper bound isn't an issue.
if 2 * len(text) < width:
return text
# Can still optimize performance if we are not handling unicode characters.
if unicode_aware:
size = 0
for i, c in enumerate(text):
w = wcwidth(c) if ord(c) >= 256 else 1
if size + w > width:
return text[0:i]
size += w
elif len(text) + 1 > width:
return text[0:width]
return text |
def create(host, port):
"""
Prepare server to execute
:return: Modules to execute, cmd line function
:rtype: list[WrapperServer], callable | None
"""
wrapper = WrapperServer({
'server': None
})
d = {
'listen_port': port,
'changer': wrapper
}
if host:
d['listen_bind_ip'] = host
ses = MeasureServer(d)
wrapper.server = ses
return [wrapper], cmd_line | Prepare server to execute
:return: Modules to execute, cmd line function
:rtype: list[WrapperServer], callable | None | Below is the the instruction that describes the task:
### Input:
Prepare server to execute
:return: Modules to execute, cmd line function
:rtype: list[WrapperServer], callable | None
### Response:
def create(host, port):
"""
Prepare server to execute
:return: Modules to execute, cmd line function
:rtype: list[WrapperServer], callable | None
"""
wrapper = WrapperServer({
'server': None
})
d = {
'listen_port': port,
'changer': wrapper
}
if host:
d['listen_bind_ip'] = host
ses = MeasureServer(d)
wrapper.server = ses
return [wrapper], cmd_line |
def gauss(x,m_y,sigma):
'''returns the gaussian with mean m_y and std. dev. sigma,
calculated at the points of x.'''
e_y = [np.exp((1.0/(2*float(sigma)**2)*-(n-m_y)**2)) for n in np.array(x)]
y = [1.0/(float(sigma) * np.sqrt(2 * np.pi)) * e for e in e_y]
return np.array(y) | returns the gaussian with mean m_y and std. dev. sigma,
calculated at the points of x. | Below is the the instruction that describes the task:
### Input:
returns the gaussian with mean m_y and std. dev. sigma,
calculated at the points of x.
### Response:
def gauss(x,m_y,sigma):
'''returns the gaussian with mean m_y and std. dev. sigma,
calculated at the points of x.'''
e_y = [np.exp((1.0/(2*float(sigma)**2)*-(n-m_y)**2)) for n in np.array(x)]
y = [1.0/(float(sigma) * np.sqrt(2 * np.pi)) * e for e in e_y]
return np.array(y) |
def update(self, data):
""" Update meta of one document."""
self.debug(data)
self._check(data)
wg_uuid = data.get('workGroup')
self.log.debug("wg_uuid : %s ", wg_uuid)
uuid = data.get('uuid')
url = "%(base)s/%(wg_uuid)s/nodes/%(uuid)s" % {
'base': self.local_base_url,
'wg_uuid': wg_uuid,
'uuid': uuid
}
return self.core.update(url, data) | Update meta of one document. | Below is the the instruction that describes the task:
### Input:
Update meta of one document.
### Response:
def update(self, data):
""" Update meta of one document."""
self.debug(data)
self._check(data)
wg_uuid = data.get('workGroup')
self.log.debug("wg_uuid : %s ", wg_uuid)
uuid = data.get('uuid')
url = "%(base)s/%(wg_uuid)s/nodes/%(uuid)s" % {
'base': self.local_base_url,
'wg_uuid': wg_uuid,
'uuid': uuid
}
return self.core.update(url, data) |
def evaluator(evaluate):
"""Return an inspyred evaluator function based on the given function.
This function generator takes a function that evaluates only one
candidate. The generator handles the iteration over each candidate
to be evaluated.
The given function ``evaluate`` must have the following signature::
fitness = evaluate(candidate, args)
This function is most commonly used as a function decorator with
the following usage::
@evaluator
def evaluate(candidate, args):
# Implementation of evaluation
pass
The generated function also contains an attribute named
``single_evaluation`` which holds the original evaluation function.
In this way, the original single-candidate function can be
retrieved if necessary.
"""
@functools.wraps(evaluate)
def inspyred_evaluator(candidates, args):
fitness = []
for candidate in candidates:
fitness.append(evaluate(candidate, args))
return fitness
inspyred_evaluator.single_evaluation = evaluate
return inspyred_evaluator | Return an inspyred evaluator function based on the given function.
This function generator takes a function that evaluates only one
candidate. The generator handles the iteration over each candidate
to be evaluated.
The given function ``evaluate`` must have the following signature::
fitness = evaluate(candidate, args)
This function is most commonly used as a function decorator with
the following usage::
@evaluator
def evaluate(candidate, args):
# Implementation of evaluation
pass
The generated function also contains an attribute named
``single_evaluation`` which holds the original evaluation function.
In this way, the original single-candidate function can be
retrieved if necessary. | Below is the the instruction that describes the task:
### Input:
Return an inspyred evaluator function based on the given function.
This function generator takes a function that evaluates only one
candidate. The generator handles the iteration over each candidate
to be evaluated.
The given function ``evaluate`` must have the following signature::
fitness = evaluate(candidate, args)
This function is most commonly used as a function decorator with
the following usage::
@evaluator
def evaluate(candidate, args):
# Implementation of evaluation
pass
The generated function also contains an attribute named
``single_evaluation`` which holds the original evaluation function.
In this way, the original single-candidate function can be
retrieved if necessary.
### Response:
def evaluator(evaluate):
"""Return an inspyred evaluator function based on the given function.
This function generator takes a function that evaluates only one
candidate. The generator handles the iteration over each candidate
to be evaluated.
The given function ``evaluate`` must have the following signature::
fitness = evaluate(candidate, args)
This function is most commonly used as a function decorator with
the following usage::
@evaluator
def evaluate(candidate, args):
# Implementation of evaluation
pass
The generated function also contains an attribute named
``single_evaluation`` which holds the original evaluation function.
In this way, the original single-candidate function can be
retrieved if necessary.
"""
@functools.wraps(evaluate)
def inspyred_evaluator(candidates, args):
fitness = []
for candidate in candidates:
fitness.append(evaluate(candidate, args))
return fitness
inspyred_evaluator.single_evaluation = evaluate
return inspyred_evaluator |
def get_column_keys_and_names(table):
"""
Return a generator of tuples k, c such that k is the name of the python attribute for
the column and c is the name of the column in the sql table.
"""
ins = inspect(table)
return ((k, c.name) for k, c in ins.mapper.c.items()) | Return a generator of tuples k, c such that k is the name of the python attribute for
the column and c is the name of the column in the sql table. | Below is the the instruction that describes the task:
### Input:
Return a generator of tuples k, c such that k is the name of the python attribute for
the column and c is the name of the column in the sql table.
### Response:
def get_column_keys_and_names(table):
"""
Return a generator of tuples k, c such that k is the name of the python attribute for
the column and c is the name of the column in the sql table.
"""
ins = inspect(table)
return ((k, c.name) for k, c in ins.mapper.c.items()) |
def get_ratetimestamp(self, base, code):
"""Return rate timestamp as a datetime/date or None"""
self.get_latestcurrencyrates(base)
try:
return datetime.fromtimestamp(self.rates["timestamp"])
except KeyError:
return None | Return rate timestamp as a datetime/date or None | Below is the the instruction that describes the task:
### Input:
Return rate timestamp as a datetime/date or None
### Response:
def get_ratetimestamp(self, base, code):
"""Return rate timestamp as a datetime/date or None"""
self.get_latestcurrencyrates(base)
try:
return datetime.fromtimestamp(self.rates["timestamp"])
except KeyError:
return None |
def list_pages_ajax(request, invalid_move=False):
"""Render pages table for ajax function."""
language = get_language_from_request(request)
pages = Page.objects.root()
context = {
'can_publish': request.user.has_perm('pages.can_publish'),
'invalid_move': invalid_move,
'language': language,
'pages': pages,
}
return render(
request, "admin/pages/page/change_list_table.html",
context) | Render pages table for ajax function. | Below is the the instruction that describes the task:
### Input:
Render pages table for ajax function.
### Response:
def list_pages_ajax(request, invalid_move=False):
"""Render pages table for ajax function."""
language = get_language_from_request(request)
pages = Page.objects.root()
context = {
'can_publish': request.user.has_perm('pages.can_publish'),
'invalid_move': invalid_move,
'language': language,
'pages': pages,
}
return render(
request, "admin/pages/page/change_list_table.html",
context) |
def toc(tt, return_msg=False, write_msg=True, verbose=None):
"""
similar to matlab toc
SeeAlso:
ut.tic
"""
if verbose is not None:
write_msg = verbose
(msg, start_time) = tt
ellapsed = (default_timer() - start_time)
if (not return_msg) and write_msg and msg is not None:
sys.stdout.write('...toc(%.4fs, ' % ellapsed + '"' + str(msg) + '"' + ')\n')
if return_msg:
return msg
else:
return ellapsed | similar to matlab toc
SeeAlso:
ut.tic | Below is the the instruction that describes the task:
### Input:
similar to matlab toc
SeeAlso:
ut.tic
### Response:
def toc(tt, return_msg=False, write_msg=True, verbose=None):
"""
similar to matlab toc
SeeAlso:
ut.tic
"""
if verbose is not None:
write_msg = verbose
(msg, start_time) = tt
ellapsed = (default_timer() - start_time)
if (not return_msg) and write_msg and msg is not None:
sys.stdout.write('...toc(%.4fs, ' % ellapsed + '"' + str(msg) + '"' + ')\n')
if return_msg:
return msg
else:
return ellapsed |
def add_to_bar_plot(ax, x, number, name = '', color = '0.'):
''' This function takes an axes and adds one bar to it '''
plt.sca(ax)
plt.setp(ax,xticks=np.append(ax.get_xticks(),np.array([x]))\
,xticklabels=[item.get_text() for item in ax.get_xticklabels()] +[name])
plt.bar([x],number , color = color, width = 1.)
return ax | This function takes an axes and adds one bar to it | Below is the the instruction that describes the task:
### Input:
This function takes an axes and adds one bar to it
### Response:
def add_to_bar_plot(ax, x, number, name = '', color = '0.'):
''' This function takes an axes and adds one bar to it '''
plt.sca(ax)
plt.setp(ax,xticks=np.append(ax.get_xticks(),np.array([x]))\
,xticklabels=[item.get_text() for item in ax.get_xticklabels()] +[name])
plt.bar([x],number , color = color, width = 1.)
return ax |
def get_sections(self, gradebook_id='', simple=False):
"""Get the sections for a gradebook.
Return a dictionary of types of sections containing a list of that
type for a given gradebook. Specified by a gradebookid.
If simple=True, a list of dictionaries is provided for each
section regardless of type. The dictionary only contains one
key ``SectionName``.
Args:
gradebook_id (str): unique identifier for gradebook, i.e. ``2314``
simple (bool): return a list of section names only
Raises:
requests.RequestException: Exception connection error
ValueError: Unable to decode response content
Returns:
dict: Dictionary of section types where each type has a
list of sections
An example return value is:
.. code-block:: python
{
u'recitation':
[
{
u'editable': False,
u'groupId': 1293925,
u'groupingScheme': u'Recitation',
u'members': None,
u'name': u'Unassigned',
u'shortName': u'DefaultGroupNoCollisionPlease1234',
u'staffs': None
},
{
u'editable': True,
u'groupId': 1327565,
u'groupingScheme': u'Recitation',
u'members': None,
u'name': u'r01',
u'shortName': u'r01',
u'staffs': None},
{u'editable': True,
u'groupId': 1327555,
u'groupingScheme': u'Recitation',
u'members': None,
u'name': u'r02',
u'shortName': u'r02',
u'staffs': None
}
]
}
"""
params = dict(includeMembers='false')
section_data = self.get(
'sections/{gradebookId}'.format(
gradebookId=gradebook_id or self.gradebook_id
),
params=params
)
if simple:
sections = self.unravel_sections(section_data['data'])
return [{'SectionName': x['name']} for x in sections]
return section_data['data'] | Get the sections for a gradebook.
Return a dictionary of types of sections containing a list of that
type for a given gradebook. Specified by a gradebookid.
If simple=True, a list of dictionaries is provided for each
section regardless of type. The dictionary only contains one
key ``SectionName``.
Args:
gradebook_id (str): unique identifier for gradebook, i.e. ``2314``
simple (bool): return a list of section names only
Raises:
requests.RequestException: Exception connection error
ValueError: Unable to decode response content
Returns:
dict: Dictionary of section types where each type has a
list of sections
An example return value is:
.. code-block:: python
{
u'recitation':
[
{
u'editable': False,
u'groupId': 1293925,
u'groupingScheme': u'Recitation',
u'members': None,
u'name': u'Unassigned',
u'shortName': u'DefaultGroupNoCollisionPlease1234',
u'staffs': None
},
{
u'editable': True,
u'groupId': 1327565,
u'groupingScheme': u'Recitation',
u'members': None,
u'name': u'r01',
u'shortName': u'r01',
u'staffs': None},
{u'editable': True,
u'groupId': 1327555,
u'groupingScheme': u'Recitation',
u'members': None,
u'name': u'r02',
u'shortName': u'r02',
u'staffs': None
}
]
} | Below is the the instruction that describes the task:
### Input:
Get the sections for a gradebook.
Return a dictionary of types of sections containing a list of that
type for a given gradebook. Specified by a gradebookid.
If simple=True, a list of dictionaries is provided for each
section regardless of type. The dictionary only contains one
key ``SectionName``.
Args:
gradebook_id (str): unique identifier for gradebook, i.e. ``2314``
simple (bool): return a list of section names only
Raises:
requests.RequestException: Exception connection error
ValueError: Unable to decode response content
Returns:
dict: Dictionary of section types where each type has a
list of sections
An example return value is:
.. code-block:: python
{
u'recitation':
[
{
u'editable': False,
u'groupId': 1293925,
u'groupingScheme': u'Recitation',
u'members': None,
u'name': u'Unassigned',
u'shortName': u'DefaultGroupNoCollisionPlease1234',
u'staffs': None
},
{
u'editable': True,
u'groupId': 1327565,
u'groupingScheme': u'Recitation',
u'members': None,
u'name': u'r01',
u'shortName': u'r01',
u'staffs': None},
{u'editable': True,
u'groupId': 1327555,
u'groupingScheme': u'Recitation',
u'members': None,
u'name': u'r02',
u'shortName': u'r02',
u'staffs': None
}
]
}
### Response:
def get_sections(self, gradebook_id='', simple=False):
"""Get the sections for a gradebook.
Return a dictionary of types of sections containing a list of that
type for a given gradebook. Specified by a gradebookid.
If simple=True, a list of dictionaries is provided for each
section regardless of type. The dictionary only contains one
key ``SectionName``.
Args:
gradebook_id (str): unique identifier for gradebook, i.e. ``2314``
simple (bool): return a list of section names only
Raises:
requests.RequestException: Exception connection error
ValueError: Unable to decode response content
Returns:
dict: Dictionary of section types where each type has a
list of sections
An example return value is:
.. code-block:: python
{
u'recitation':
[
{
u'editable': False,
u'groupId': 1293925,
u'groupingScheme': u'Recitation',
u'members': None,
u'name': u'Unassigned',
u'shortName': u'DefaultGroupNoCollisionPlease1234',
u'staffs': None
},
{
u'editable': True,
u'groupId': 1327565,
u'groupingScheme': u'Recitation',
u'members': None,
u'name': u'r01',
u'shortName': u'r01',
u'staffs': None},
{u'editable': True,
u'groupId': 1327555,
u'groupingScheme': u'Recitation',
u'members': None,
u'name': u'r02',
u'shortName': u'r02',
u'staffs': None
}
]
}
"""
params = dict(includeMembers='false')
section_data = self.get(
'sections/{gradebookId}'.format(
gradebookId=gradebook_id or self.gradebook_id
),
params=params
)
if simple:
sections = self.unravel_sections(section_data['data'])
return [{'SectionName': x['name']} for x in sections]
return section_data['data'] |
def percent_covered(self, src_path):
"""
Return a float percent of lines covered for the source
in `src_path`.
If we have no coverage information for `src_path`, returns None
"""
diff_violations = self._diff_violations().get(src_path)
if diff_violations is None:
return None
# Protect against a divide by zero
num_measured = len(diff_violations.measured_lines)
if num_measured > 0:
num_uncovered = len(diff_violations.lines)
return 100 - float(num_uncovered) / num_measured * 100
else:
return None | Return a float percent of lines covered for the source
in `src_path`.
If we have no coverage information for `src_path`, returns None | Below is the the instruction that describes the task:
### Input:
Return a float percent of lines covered for the source
in `src_path`.
If we have no coverage information for `src_path`, returns None
### Response:
def percent_covered(self, src_path):
"""
Return a float percent of lines covered for the source
in `src_path`.
If we have no coverage information for `src_path`, returns None
"""
diff_violations = self._diff_violations().get(src_path)
if diff_violations is None:
return None
# Protect against a divide by zero
num_measured = len(diff_violations.measured_lines)
if num_measured > 0:
num_uncovered = len(diff_violations.lines)
return 100 - float(num_uncovered) / num_measured * 100
else:
return None |
def _export_single_project(self):
""" A single project export """
expanded_dic = self.workspace.copy()
self._fix_paths(expanded_dic)
# generic tool template specified or project
if expanded_dic['template']:
template_ewp = False
template_ewd = False
# process each template file
for template in expanded_dic['template']:
template = join(getcwd(), template)
# we support .ewp or .ewp.tmpl templates
if os.path.splitext(template)[1] == '.ewp' or re.match('.*\.ewp.tmpl$', template):
try:
ewp_dic = xmltodict.parse(open(template), dict_constructor=dict)
template_ewp = True
except IOError:
logger.info("Template file %s not found" % template)
ewp_dic = xmltodict.parse(open(self.ewp_file).read())
if os.path.splitext(template)[1] == '.ewd' or re.match('.*\.ewd.tmpl$', template):
try:
ewd_dic = xmltodict.parse(open(template), dict_constructor=dict)
template_ewd = True
except IOError:
logger.info("Template file %s not found" % template)
ewd_dic = xmltodict.parse(open(self.ewd_file).read())
# handle non valid template files or not specified
if not template_ewp and template_ewd:
ewp_dic, _ = self._get_default_templates()
elif not template_ewd and template_ewp:
_, ewd_dic = self._get_default_templates()
else:
ewp_dic, ewd_dic = self._get_default_templates()
elif 'iar' in self.env_settings.templates.keys():
template_ewp = False
template_ewd = False
# template overrides what is set in the yaml files
for template in self.env_settings.templates['iar']:
template = join(getcwd(), template)
if os.path.splitext(template)[1] == '.ewp' or re.match('.*\.ewp.tmpl$', template):
try:
ewp_dic = xmltodict.parse(open(template), dict_constructor=dict)
template_ewp = True
except IOError:
logger.info("Template file %s not found" % template)
ewp_dic = xmltodict.parse(open(self.ewp_file).read())
if os.path.splitext(template)[1] == '.ewd' or re.match('.*\.ewd.tmpl$', template):
# get ewd template
try:
ewd_dic = xmltodict.parse(open(template), dict_constructor=dict)
template_ewd = True
except IOError:
logger.info("Template file %s not found" % template)
ewd_dic = xmltodict.parse(open(self.ewd_file).read())
# handle non valid template files or not specified
if not template_ewp and template_ewd:
ewp_dic, _ = self._get_default_templates()
elif not template_ewd and template_ewp:
_, ewd_dic = self._get_default_templates()
else:
ewp_dic, ewd_dic = self._get_default_templates()
else:
ewp_dic, ewd_dic = self._get_default_templates()
eww = None
if self.workspace['singular']:
# TODO 0xc0170: if we use here self.definitions.eww, travis fails. I cant reproduce it and dont see
# eww used anywhere prior to exporting this.
eww_dic = {u'workspace': {u'project': {u'path': u''}, u'batchBuild': None}}
# set eww
self._eww_set_path_single_project(eww_dic, expanded_dic['name'])
eww_xml = xmltodict.unparse(eww_dic, pretty=True)
project_path, eww = self.gen_file_raw(eww_xml, '%s.eww' % expanded_dic['name'], expanded_dic['output_dir']['path'])
try:
ewp_configuration = ewp_dic['project']['configuration'][0]
logging.debug("Provided .ewp file has multiple configuration, we use only the first one")
ewp_dic['project']['configuration'] = ewp_dic['project']['configuration'][0]
except KeyError:
ewp_configuration = ewp_dic['project']['configuration']
try:
ewp_configuration = ewp_dic['project']['configuration'][0]
logging.debug("Provided .ewp file has multiple configuration, we use only the first one")
ewp_dic['project']['configuration'] = ewp_dic['project']['configuration'][0]
except KeyError:
ewp_configuration = ewp_dic['project']['configuration']
# replace all None with empty strings ''
self._clean_xmldict_ewp(ewp_configuration)
#self._clean_xmldict_ewd(ewd_dic)
try:
self._ewp_set_name(ewp_configuration, expanded_dic['name'])
except KeyError:
raise RuntimeError("The IAR template is not valid .ewp file")
# set ARM toolchain and project name\
self._ewp_set_toolchain(ewp_configuration, 'ARM')
# set common things we have for IAR
self._ewp_general_set(ewp_configuration['settings'], expanded_dic)
self._ewp_iccarm_set(ewp_configuration['settings'], expanded_dic)
self._ewp_aarm_set(ewp_configuration['settings'], expanded_dic)
self._ewp_ilink_set(ewp_configuration['settings'], expanded_dic)
self._ewp_files_set(ewp_dic, expanded_dic)
# set target only if defined, otherwise use from template/default one
if expanded_dic['target']:
# get target definition (target + mcu)
proj_def = ProGenDef('iar')
if not proj_def.is_supported(expanded_dic['target'].lower()):
raise RuntimeError("Target %s is not supported." % expanded_dic['target'].lower())
mcu_def_dic = proj_def.get_tool_definition(expanded_dic['target'].lower())
if not mcu_def_dic:
raise RuntimeError(
"Mcu definitions were not found for %s. Please add them to https://github.com/project-generator/project_generator_definitions" % expanded_dic['target'].lower())
self._normalize_mcu_def(mcu_def_dic)
logger.debug("Mcu definitions: %s" % mcu_def_dic)
self._ewp_set_target(ewp_configuration['settings'], mcu_def_dic)
try:
debugger = proj_def.get_debugger(expanded_dic['target'])
self._ewd_set_debugger(ewd_dic['project']['configuration']['settings'], debugger)
except KeyError as err:
# TODO: worth reporting?
pass
# overwrite debugger only if defined in the project file, otherwise use either default or from template
if expanded_dic['debugger']:
try:
self._ewd_set_debugger(ewd_dic['project']['configuration']['settings'], expanded_dic['debugger'])
except KeyError:
raise RuntimeError("Debugger %s is not supported" % expanded_dic['debugger'])
self._ewd_set_name(ewd_dic['project']['configuration'], expanded_dic['name'])
# IAR uses ident 2 spaces, encoding iso-8859-1
ewp_xml = xmltodict.unparse(ewp_dic, encoding='iso-8859-1', pretty=True, indent=' ')
project_path, ewp = self.gen_file_raw(ewp_xml, '%s.ewp' % expanded_dic['name'], expanded_dic['output_dir']['path'])
ewd_xml = xmltodict.unparse(ewd_dic, encoding='iso-8859-1', pretty=True, indent=' ')
project_path, ewd = self.gen_file_raw(ewd_xml, '%s.ewd' % expanded_dic['name'], expanded_dic['output_dir']['path'])
return project_path, [ewp, eww, ewd] | A single project export | Below is the the instruction that describes the task:
### Input:
A single project export
### Response:
def _export_single_project(self):
""" A single project export """
expanded_dic = self.workspace.copy()
self._fix_paths(expanded_dic)
# generic tool template specified or project
if expanded_dic['template']:
template_ewp = False
template_ewd = False
# process each template file
for template in expanded_dic['template']:
template = join(getcwd(), template)
# we support .ewp or .ewp.tmpl templates
if os.path.splitext(template)[1] == '.ewp' or re.match('.*\.ewp.tmpl$', template):
try:
ewp_dic = xmltodict.parse(open(template), dict_constructor=dict)
template_ewp = True
except IOError:
logger.info("Template file %s not found" % template)
ewp_dic = xmltodict.parse(open(self.ewp_file).read())
if os.path.splitext(template)[1] == '.ewd' or re.match('.*\.ewd.tmpl$', template):
try:
ewd_dic = xmltodict.parse(open(template), dict_constructor=dict)
template_ewd = True
except IOError:
logger.info("Template file %s not found" % template)
ewd_dic = xmltodict.parse(open(self.ewd_file).read())
# handle non valid template files or not specified
if not template_ewp and template_ewd:
ewp_dic, _ = self._get_default_templates()
elif not template_ewd and template_ewp:
_, ewd_dic = self._get_default_templates()
else:
ewp_dic, ewd_dic = self._get_default_templates()
elif 'iar' in self.env_settings.templates.keys():
template_ewp = False
template_ewd = False
# template overrides what is set in the yaml files
for template in self.env_settings.templates['iar']:
template = join(getcwd(), template)
if os.path.splitext(template)[1] == '.ewp' or re.match('.*\.ewp.tmpl$', template):
try:
ewp_dic = xmltodict.parse(open(template), dict_constructor=dict)
template_ewp = True
except IOError:
logger.info("Template file %s not found" % template)
ewp_dic = xmltodict.parse(open(self.ewp_file).read())
if os.path.splitext(template)[1] == '.ewd' or re.match('.*\.ewd.tmpl$', template):
# get ewd template
try:
ewd_dic = xmltodict.parse(open(template), dict_constructor=dict)
template_ewd = True
except IOError:
logger.info("Template file %s not found" % template)
ewd_dic = xmltodict.parse(open(self.ewd_file).read())
# handle non valid template files or not specified
if not template_ewp and template_ewd:
ewp_dic, _ = self._get_default_templates()
elif not template_ewd and template_ewp:
_, ewd_dic = self._get_default_templates()
else:
ewp_dic, ewd_dic = self._get_default_templates()
else:
ewp_dic, ewd_dic = self._get_default_templates()
eww = None
if self.workspace['singular']:
# TODO 0xc0170: if we use here self.definitions.eww, travis fails. I cant reproduce it and dont see
# eww used anywhere prior to exporting this.
eww_dic = {u'workspace': {u'project': {u'path': u''}, u'batchBuild': None}}
# set eww
self._eww_set_path_single_project(eww_dic, expanded_dic['name'])
eww_xml = xmltodict.unparse(eww_dic, pretty=True)
project_path, eww = self.gen_file_raw(eww_xml, '%s.eww' % expanded_dic['name'], expanded_dic['output_dir']['path'])
try:
ewp_configuration = ewp_dic['project']['configuration'][0]
logging.debug("Provided .ewp file has multiple configuration, we use only the first one")
ewp_dic['project']['configuration'] = ewp_dic['project']['configuration'][0]
except KeyError:
ewp_configuration = ewp_dic['project']['configuration']
try:
ewp_configuration = ewp_dic['project']['configuration'][0]
logging.debug("Provided .ewp file has multiple configuration, we use only the first one")
ewp_dic['project']['configuration'] = ewp_dic['project']['configuration'][0]
except KeyError:
ewp_configuration = ewp_dic['project']['configuration']
# replace all None with empty strings ''
self._clean_xmldict_ewp(ewp_configuration)
#self._clean_xmldict_ewd(ewd_dic)
try:
self._ewp_set_name(ewp_configuration, expanded_dic['name'])
except KeyError:
raise RuntimeError("The IAR template is not valid .ewp file")
# set ARM toolchain and project name\
self._ewp_set_toolchain(ewp_configuration, 'ARM')
# set common things we have for IAR
self._ewp_general_set(ewp_configuration['settings'], expanded_dic)
self._ewp_iccarm_set(ewp_configuration['settings'], expanded_dic)
self._ewp_aarm_set(ewp_configuration['settings'], expanded_dic)
self._ewp_ilink_set(ewp_configuration['settings'], expanded_dic)
self._ewp_files_set(ewp_dic, expanded_dic)
# set target only if defined, otherwise use from template/default one
if expanded_dic['target']:
# get target definition (target + mcu)
proj_def = ProGenDef('iar')
if not proj_def.is_supported(expanded_dic['target'].lower()):
raise RuntimeError("Target %s is not supported." % expanded_dic['target'].lower())
mcu_def_dic = proj_def.get_tool_definition(expanded_dic['target'].lower())
if not mcu_def_dic:
raise RuntimeError(
"Mcu definitions were not found for %s. Please add them to https://github.com/project-generator/project_generator_definitions" % expanded_dic['target'].lower())
self._normalize_mcu_def(mcu_def_dic)
logger.debug("Mcu definitions: %s" % mcu_def_dic)
self._ewp_set_target(ewp_configuration['settings'], mcu_def_dic)
try:
debugger = proj_def.get_debugger(expanded_dic['target'])
self._ewd_set_debugger(ewd_dic['project']['configuration']['settings'], debugger)
except KeyError as err:
# TODO: worth reporting?
pass
# overwrite debugger only if defined in the project file, otherwise use either default or from template
if expanded_dic['debugger']:
try:
self._ewd_set_debugger(ewd_dic['project']['configuration']['settings'], expanded_dic['debugger'])
except KeyError:
raise RuntimeError("Debugger %s is not supported" % expanded_dic['debugger'])
self._ewd_set_name(ewd_dic['project']['configuration'], expanded_dic['name'])
# IAR uses ident 2 spaces, encoding iso-8859-1
ewp_xml = xmltodict.unparse(ewp_dic, encoding='iso-8859-1', pretty=True, indent=' ')
project_path, ewp = self.gen_file_raw(ewp_xml, '%s.ewp' % expanded_dic['name'], expanded_dic['output_dir']['path'])
ewd_xml = xmltodict.unparse(ewd_dic, encoding='iso-8859-1', pretty=True, indent=' ')
project_path, ewd = self.gen_file_raw(ewd_xml, '%s.ewd' % expanded_dic['name'], expanded_dic['output_dir']['path'])
return project_path, [ewp, eww, ewd] |
def outstanding(self):
"""Returns whether or not this barrier has pending work."""
# Allow the same WorkItem to be yielded multiple times but not
# count towards blocking the barrier.
done_count = 0
for item in self:
if not self.wait_any and item.fire_and_forget:
# Only count fire_and_forget items as done if this is
# *not* a WaitAny barrier. We only want to return control
# to the caller when at least one of the blocking items
# has completed.
done_count += 1
elif item.done:
done_count += 1
if self.wait_any and done_count > 0:
return False
if done_count == len(self):
return False
return True | Returns whether or not this barrier has pending work. | Below is the the instruction that describes the task:
### Input:
Returns whether or not this barrier has pending work.
### Response:
def outstanding(self):
"""Returns whether or not this barrier has pending work."""
# Allow the same WorkItem to be yielded multiple times but not
# count towards blocking the barrier.
done_count = 0
for item in self:
if not self.wait_any and item.fire_and_forget:
# Only count fire_and_forget items as done if this is
# *not* a WaitAny barrier. We only want to return control
# to the caller when at least one of the blocking items
# has completed.
done_count += 1
elif item.done:
done_count += 1
if self.wait_any and done_count > 0:
return False
if done_count == len(self):
return False
return True |
def bcrop(v, dsz, dimN=2):
"""Crop specified number of initial spatial dimensions of dictionary
array to specified size. Parameter `dsz` must be a tuple having one
of the following forms (the examples assume two spatial/temporal
dimensions). If all filters are of the same size, then
::
(flt_rows, filt_cols, num_filt)
may be used when the dictionary has a single channel, and
::
(flt_rows, filt_cols, num_chan, num_filt)
should be used for a multi-channel dictionary. If the filters are
not all of the same size, then
::
(
(flt_rows1, filt_cols1, num_filt1),
(flt_rows2, filt_cols2, num_filt2),
...
)
may be used for a single-channel dictionary. A multi-channel
dictionary may be specified in the form
::
(
(flt_rows1, filt_cols1, num_chan, num_filt1),
(flt_rows2, filt_cols2, num_chan, num_filt2),
...
)
or
::
(
(
(flt_rows11, filt_cols11, num_chan11, num_filt1),
(flt_rows21, filt_cols21, num_chan21, num_filt1),
...
)
(
(flt_rows12, filt_cols12, num_chan12, num_filt2),
(flt_rows22, filt_cols22, num_chan22, num_filt2),
...
)
...
)
depending on whether the filters for each channel are of the same
size or not. The total number of dictionary filters, is either
num_filt in the first two forms, or the sum of num_filt1,
num_filt2, etc. in the other form. If the filters are not
two-dimensional, then the dimensions above vary accordingly, i.e.,
there may be fewer or more filter spatial dimensions than
flt_rows, filt_cols, e.g.
::
(flt_rows, num_filt)
for one-dimensional signals, or
::
(flt_rows, filt_cols, filt_planes, num_filt)
for three-dimensional signals.
Parameters
----------
v : array_like
Dictionary array to be cropped
dsz : tuple
Filter support size(s)
dimN : int, optional (default 2)
Number of spatial dimensions
Returns
-------
vc : ndarray
Cropped dictionary array
"""
if isinstance(dsz[0], tuple):
# Multi-scale dictionary specification
maxsz = np.zeros((dimN,), dtype=int) # Max. support size
# Iterate over dsz to determine max. support size
for mb in range(0, len(dsz)):
if isinstance(dsz[mb][0], tuple):
for cb in range(0, len(dsz[mb])):
maxsz = np.maximum(maxsz, np.asarray(dsz[mb][cb][0:dimN]))
else:
maxsz = np.maximum(maxsz, np.asarray(dsz[mb][0:dimN]))
# Init. cropped array
vc = np.zeros(maxsz.tolist() + list(v.shape[dimN:]), dtype=v.dtype)
m0 = 0 # Initial index of current block of equi-sized filters
# Iterate over distinct filter sizes
for mb in range(0, len(dsz)):
# Determine end index of current block of filters
if isinstance(dsz[mb][0], tuple):
m1 = m0 + dsz[mb][0][-1]
c0 = 0 # Init. idx. of current chnl-block of equi-sized flt.
for cb in range(0, len(dsz[mb])):
c1 = c0 + dsz[mb][cb][-2]
# Construct slice corresponding to cropped part of
# current block of filters in output array and set from
# input array
cbslc = tuple([slice(0, x) for x in dsz[mb][cb][0:dimN]]
) + (slice(c0, c1),) + (Ellipsis,) + \
(slice(m0, m1),)
vc[cbslc] = v[cbslc]
c0 = c1 # Update initial index for start of next block
else:
m1 = m0 + dsz[mb][-1]
# Construct slice corresponding to cropped part of
# current block of filters in output array and set from
# input array
mbslc = tuple([slice(0, x) for x in dsz[mb][0:-1]]
) + (Ellipsis,) + (slice(m0, m1),)
vc[mbslc] = v[mbslc]
m0 = m1 # Update initial index for start of next block
return vc
else:
# Single scale dictionary specification
axnslc = tuple([slice(0, x) for x in dsz[0:dimN]])
return v[axnslc] | Crop specified number of initial spatial dimensions of dictionary
array to specified size. Parameter `dsz` must be a tuple having one
of the following forms (the examples assume two spatial/temporal
dimensions). If all filters are of the same size, then
::
(flt_rows, filt_cols, num_filt)
may be used when the dictionary has a single channel, and
::
(flt_rows, filt_cols, num_chan, num_filt)
should be used for a multi-channel dictionary. If the filters are
not all of the same size, then
::
(
(flt_rows1, filt_cols1, num_filt1),
(flt_rows2, filt_cols2, num_filt2),
...
)
may be used for a single-channel dictionary. A multi-channel
dictionary may be specified in the form
::
(
(flt_rows1, filt_cols1, num_chan, num_filt1),
(flt_rows2, filt_cols2, num_chan, num_filt2),
...
)
or
::
(
(
(flt_rows11, filt_cols11, num_chan11, num_filt1),
(flt_rows21, filt_cols21, num_chan21, num_filt1),
...
)
(
(flt_rows12, filt_cols12, num_chan12, num_filt2),
(flt_rows22, filt_cols22, num_chan22, num_filt2),
...
)
...
)
depending on whether the filters for each channel are of the same
size or not. The total number of dictionary filters, is either
num_filt in the first two forms, or the sum of num_filt1,
num_filt2, etc. in the other form. If the filters are not
two-dimensional, then the dimensions above vary accordingly, i.e.,
there may be fewer or more filter spatial dimensions than
flt_rows, filt_cols, e.g.
::
(flt_rows, num_filt)
for one-dimensional signals, or
::
(flt_rows, filt_cols, filt_planes, num_filt)
for three-dimensional signals.
Parameters
----------
v : array_like
Dictionary array to be cropped
dsz : tuple
Filter support size(s)
dimN : int, optional (default 2)
Number of spatial dimensions
Returns
-------
vc : ndarray
Cropped dictionary array | Below is the the instruction that describes the task:
### Input:
Crop specified number of initial spatial dimensions of dictionary
array to specified size. Parameter `dsz` must be a tuple having one
of the following forms (the examples assume two spatial/temporal
dimensions). If all filters are of the same size, then
::
(flt_rows, filt_cols, num_filt)
may be used when the dictionary has a single channel, and
::
(flt_rows, filt_cols, num_chan, num_filt)
should be used for a multi-channel dictionary. If the filters are
not all of the same size, then
::
(
(flt_rows1, filt_cols1, num_filt1),
(flt_rows2, filt_cols2, num_filt2),
...
)
may be used for a single-channel dictionary. A multi-channel
dictionary may be specified in the form
::
(
(flt_rows1, filt_cols1, num_chan, num_filt1),
(flt_rows2, filt_cols2, num_chan, num_filt2),
...
)
or
::
(
(
(flt_rows11, filt_cols11, num_chan11, num_filt1),
(flt_rows21, filt_cols21, num_chan21, num_filt1),
...
)
(
(flt_rows12, filt_cols12, num_chan12, num_filt2),
(flt_rows22, filt_cols22, num_chan22, num_filt2),
...
)
...
)
depending on whether the filters for each channel are of the same
size or not. The total number of dictionary filters, is either
num_filt in the first two forms, or the sum of num_filt1,
num_filt2, etc. in the other form. If the filters are not
two-dimensional, then the dimensions above vary accordingly, i.e.,
there may be fewer or more filter spatial dimensions than
flt_rows, filt_cols, e.g.
::
(flt_rows, num_filt)
for one-dimensional signals, or
::
(flt_rows, filt_cols, filt_planes, num_filt)
for three-dimensional signals.
Parameters
----------
v : array_like
Dictionary array to be cropped
dsz : tuple
Filter support size(s)
dimN : int, optional (default 2)
Number of spatial dimensions
Returns
-------
vc : ndarray
Cropped dictionary array
### Response:
def bcrop(v, dsz, dimN=2):
"""Crop specified number of initial spatial dimensions of dictionary
array to specified size. Parameter `dsz` must be a tuple having one
of the following forms (the examples assume two spatial/temporal
dimensions). If all filters are of the same size, then
::
(flt_rows, filt_cols, num_filt)
may be used when the dictionary has a single channel, and
::
(flt_rows, filt_cols, num_chan, num_filt)
should be used for a multi-channel dictionary. If the filters are
not all of the same size, then
::
(
(flt_rows1, filt_cols1, num_filt1),
(flt_rows2, filt_cols2, num_filt2),
...
)
may be used for a single-channel dictionary. A multi-channel
dictionary may be specified in the form
::
(
(flt_rows1, filt_cols1, num_chan, num_filt1),
(flt_rows2, filt_cols2, num_chan, num_filt2),
...
)
or
::
(
(
(flt_rows11, filt_cols11, num_chan11, num_filt1),
(flt_rows21, filt_cols21, num_chan21, num_filt1),
...
)
(
(flt_rows12, filt_cols12, num_chan12, num_filt2),
(flt_rows22, filt_cols22, num_chan22, num_filt2),
...
)
...
)
depending on whether the filters for each channel are of the same
size or not. The total number of dictionary filters, is either
num_filt in the first two forms, or the sum of num_filt1,
num_filt2, etc. in the other form. If the filters are not
two-dimensional, then the dimensions above vary accordingly, i.e.,
there may be fewer or more filter spatial dimensions than
flt_rows, filt_cols, e.g.
::
(flt_rows, num_filt)
for one-dimensional signals, or
::
(flt_rows, filt_cols, filt_planes, num_filt)
for three-dimensional signals.
Parameters
----------
v : array_like
Dictionary array to be cropped
dsz : tuple
Filter support size(s)
dimN : int, optional (default 2)
Number of spatial dimensions
Returns
-------
vc : ndarray
Cropped dictionary array
"""
if isinstance(dsz[0], tuple):
# Multi-scale dictionary specification
maxsz = np.zeros((dimN,), dtype=int) # Max. support size
# Iterate over dsz to determine max. support size
for mb in range(0, len(dsz)):
if isinstance(dsz[mb][0], tuple):
for cb in range(0, len(dsz[mb])):
maxsz = np.maximum(maxsz, np.asarray(dsz[mb][cb][0:dimN]))
else:
maxsz = np.maximum(maxsz, np.asarray(dsz[mb][0:dimN]))
# Init. cropped array
vc = np.zeros(maxsz.tolist() + list(v.shape[dimN:]), dtype=v.dtype)
m0 = 0 # Initial index of current block of equi-sized filters
# Iterate over distinct filter sizes
for mb in range(0, len(dsz)):
# Determine end index of current block of filters
if isinstance(dsz[mb][0], tuple):
m1 = m0 + dsz[mb][0][-1]
c0 = 0 # Init. idx. of current chnl-block of equi-sized flt.
for cb in range(0, len(dsz[mb])):
c1 = c0 + dsz[mb][cb][-2]
# Construct slice corresponding to cropped part of
# current block of filters in output array and set from
# input array
cbslc = tuple([slice(0, x) for x in dsz[mb][cb][0:dimN]]
) + (slice(c0, c1),) + (Ellipsis,) + \
(slice(m0, m1),)
vc[cbslc] = v[cbslc]
c0 = c1 # Update initial index for start of next block
else:
m1 = m0 + dsz[mb][-1]
# Construct slice corresponding to cropped part of
# current block of filters in output array and set from
# input array
mbslc = tuple([slice(0, x) for x in dsz[mb][0:-1]]
) + (Ellipsis,) + (slice(m0, m1),)
vc[mbslc] = v[mbslc]
m0 = m1 # Update initial index for start of next block
return vc
else:
# Single scale dictionary specification
axnslc = tuple([slice(0, x) for x in dsz[0:dimN]])
return v[axnslc] |
def geometries(self):
"""Return an iterator of (shapely) geometries for this feature."""
# Ensure that the associated files are in the cache
fname = '{}_{}'.format(self.name, self.scale)
for extension in ['.dbf', '.shx']:
get_test_data(fname + extension)
path = get_test_data(fname + '.shp', as_file_obj=False)
return iter(tuple(shpreader.Reader(path).geometries())) | Return an iterator of (shapely) geometries for this feature. | Below is the the instruction that describes the task:
### Input:
Return an iterator of (shapely) geometries for this feature.
### Response:
def geometries(self):
"""Return an iterator of (shapely) geometries for this feature."""
# Ensure that the associated files are in the cache
fname = '{}_{}'.format(self.name, self.scale)
for extension in ['.dbf', '.shx']:
get_test_data(fname + extension)
path = get_test_data(fname + '.shp', as_file_obj=False)
return iter(tuple(shpreader.Reader(path).geometries())) |
def gtd7d(Input, flags, output): # pragma: no cover
'''A separate subroutine (GTD7D) computes the ‘‘effec-
tive’’ mass density by summing the thermospheric mass
density and the mass density of the anomalous oxygen
component. Below 500 km, the effective mass density is
equivalent to the thermospheric mass density, and we drop
the distinction.
'''
gtd7(Input, flags, output)
output.d[5] = 1.66E-24 * (4.0 * output.d[0] + 16.0 * output.d[1] + 28.0 * output.d[2] + 32.0 * output.d[3] + 40.0 * output.d[4] + output.d[6] + 14.0 * output.d[7] + 16.0 * output.d[8]);
if (flags.sw[0]):
output.d[5]=output.d[5]/1000;
return | A separate subroutine (GTD7D) computes the ‘‘effec-
tive’’ mass density by summing the thermospheric mass
density and the mass density of the anomalous oxygen
component. Below 500 km, the effective mass density is
equivalent to the thermospheric mass density, and we drop
the distinction. | Below is the the instruction that describes the task:
### Input:
A separate subroutine (GTD7D) computes the ‘‘effec-
tive’’ mass density by summing the thermospheric mass
density and the mass density of the anomalous oxygen
component. Below 500 km, the effective mass density is
equivalent to the thermospheric mass density, and we drop
the distinction.
### Response:
def gtd7d(Input, flags, output): # pragma: no cover
'''A separate subroutine (GTD7D) computes the ‘‘effec-
tive’’ mass density by summing the thermospheric mass
density and the mass density of the anomalous oxygen
component. Below 500 km, the effective mass density is
equivalent to the thermospheric mass density, and we drop
the distinction.
'''
gtd7(Input, flags, output)
output.d[5] = 1.66E-24 * (4.0 * output.d[0] + 16.0 * output.d[1] + 28.0 * output.d[2] + 32.0 * output.d[3] + 40.0 * output.d[4] + output.d[6] + 14.0 * output.d[7] + 16.0 * output.d[8]);
if (flags.sw[0]):
output.d[5]=output.d[5]/1000;
return |
def DiffArrayObjects(self, oldObj, newObj, isElementLinks=False):
"""Method which deligates the diffing of arrays based on the type"""
if oldObj == newObj:
return True
if not oldObj or not newObj:
return False
if len(oldObj) != len(newObj):
__Log__.debug('DiffArrayObjects: Array lengths do not match %d != %d'
% (len(oldObj), len(newObj)))
return False
firstObj = oldObj[0]
if IsPrimitiveType(firstObj):
return self.DiffPrimitiveArrays(oldObj, newObj)
elif isinstance(firstObj, types.ManagedObject):
return self.DiffAnyArrays(oldObj, newObj, isElementLinks)
elif isinstance(firstObj, types.DataObject):
return self.DiffDoArrays(oldObj, newObj, isElementLinks)
else:
raise TypeError("Unknown type: %s" % oldObj.__class__) | Method which deligates the diffing of arrays based on the type | Below is the the instruction that describes the task:
### Input:
Method which deligates the diffing of arrays based on the type
### Response:
def DiffArrayObjects(self, oldObj, newObj, isElementLinks=False):
"""Method which deligates the diffing of arrays based on the type"""
if oldObj == newObj:
return True
if not oldObj or not newObj:
return False
if len(oldObj) != len(newObj):
__Log__.debug('DiffArrayObjects: Array lengths do not match %d != %d'
% (len(oldObj), len(newObj)))
return False
firstObj = oldObj[0]
if IsPrimitiveType(firstObj):
return self.DiffPrimitiveArrays(oldObj, newObj)
elif isinstance(firstObj, types.ManagedObject):
return self.DiffAnyArrays(oldObj, newObj, isElementLinks)
elif isinstance(firstObj, types.DataObject):
return self.DiffDoArrays(oldObj, newObj, isElementLinks)
else:
raise TypeError("Unknown type: %s" % oldObj.__class__) |
def clean_map(obj: Mapping[Any, Any]) -> Mapping[Any, Any]:
"""
Return a new copied dictionary without the keys with ``None`` values from
the given Mapping object.
"""
return {k: v for k, v in obj.items() if v is not None} | Return a new copied dictionary without the keys with ``None`` values from
the given Mapping object. | Below is the the instruction that describes the task:
### Input:
Return a new copied dictionary without the keys with ``None`` values from
the given Mapping object.
### Response:
def clean_map(obj: Mapping[Any, Any]) -> Mapping[Any, Any]:
"""
Return a new copied dictionary without the keys with ``None`` values from
the given Mapping object.
"""
return {k: v for k, v in obj.items() if v is not None} |
def minmax(self, constraints, x, iters=10000):
"""Returns the min and max possible values for x within given constraints"""
if issymbolic(x):
m = self.min(constraints, x, iters)
M = self.max(constraints, x, iters)
return m, M
else:
return x, x | Returns the min and max possible values for x within given constraints | Below is the the instruction that describes the task:
### Input:
Returns the min and max possible values for x within given constraints
### Response:
def minmax(self, constraints, x, iters=10000):
"""Returns the min and max possible values for x within given constraints"""
if issymbolic(x):
m = self.min(constraints, x, iters)
M = self.max(constraints, x, iters)
return m, M
else:
return x, x |
def generate_dims_coords(shape, var_name, dims=None, coords=None, default_dims=None):
"""Generate default dimensions and coordinates for a variable.
Parameters
----------
shape : tuple[int]
Shape of the variable
var_name : str
Name of the variable. Used in the default name, if necessary
dims : list
List of dimensions for the variable
coords : dict[str] -> list[str]
Map of dimensions to coordinates
default_dims : list[str]
Dimensions that do not apply to the variable's shape
Returns
-------
list[str]
Default dims
dict[str] -> list[str]
Default coords
"""
if default_dims is None:
default_dims = []
if dims is None:
dims = []
if len([dim for dim in dims if dim not in default_dims]) > len(shape):
warnings.warn(
"More dims ({dims_len}) given than exists ({shape_len}). "
"Passed array should have shape (chains, draws, *shape)".format(
dims_len=len(dims), shape_len=len(shape)
),
SyntaxWarning,
)
if coords is None:
coords = {}
coords = deepcopy(coords)
dims = deepcopy(dims)
for idx, dim_len in enumerate(shape):
if (len(dims) < idx + 1) or (dims[idx] is None):
dim_name = "{var_name}_dim_{idx}".format(var_name=var_name, idx=idx)
if len(dims) < idx + 1:
dims.append(dim_name)
else:
dims[idx] = dim_name
dim_name = dims[idx]
if dim_name not in coords:
coords[dim_name] = np.arange(dim_len)
coords = {key: coord for key, coord in coords.items() if any(key == dim for dim in dims)}
return dims, coords | Generate default dimensions and coordinates for a variable.
Parameters
----------
shape : tuple[int]
Shape of the variable
var_name : str
Name of the variable. Used in the default name, if necessary
dims : list
List of dimensions for the variable
coords : dict[str] -> list[str]
Map of dimensions to coordinates
default_dims : list[str]
Dimensions that do not apply to the variable's shape
Returns
-------
list[str]
Default dims
dict[str] -> list[str]
Default coords | Below is the the instruction that describes the task:
### Input:
Generate default dimensions and coordinates for a variable.
Parameters
----------
shape : tuple[int]
Shape of the variable
var_name : str
Name of the variable. Used in the default name, if necessary
dims : list
List of dimensions for the variable
coords : dict[str] -> list[str]
Map of dimensions to coordinates
default_dims : list[str]
Dimensions that do not apply to the variable's shape
Returns
-------
list[str]
Default dims
dict[str] -> list[str]
Default coords
### Response:
def generate_dims_coords(shape, var_name, dims=None, coords=None, default_dims=None):
"""Generate default dimensions and coordinates for a variable.
Parameters
----------
shape : tuple[int]
Shape of the variable
var_name : str
Name of the variable. Used in the default name, if necessary
dims : list
List of dimensions for the variable
coords : dict[str] -> list[str]
Map of dimensions to coordinates
default_dims : list[str]
Dimensions that do not apply to the variable's shape
Returns
-------
list[str]
Default dims
dict[str] -> list[str]
Default coords
"""
if default_dims is None:
default_dims = []
if dims is None:
dims = []
if len([dim for dim in dims if dim not in default_dims]) > len(shape):
warnings.warn(
"More dims ({dims_len}) given than exists ({shape_len}). "
"Passed array should have shape (chains, draws, *shape)".format(
dims_len=len(dims), shape_len=len(shape)
),
SyntaxWarning,
)
if coords is None:
coords = {}
coords = deepcopy(coords)
dims = deepcopy(dims)
for idx, dim_len in enumerate(shape):
if (len(dims) < idx + 1) or (dims[idx] is None):
dim_name = "{var_name}_dim_{idx}".format(var_name=var_name, idx=idx)
if len(dims) < idx + 1:
dims.append(dim_name)
else:
dims[idx] = dim_name
dim_name = dims[idx]
if dim_name not in coords:
coords[dim_name] = np.arange(dim_len)
coords = {key: coord for key, coord in coords.items() if any(key == dim for dim in dims)}
return dims, coords |
def predictionExtent(inputs, resets, outputs, minOverlapPct=100.0):
"""
Computes the predictive ability of a temporal memory (TM). This routine returns
a value which is the average number of time steps of prediction provided
by the TM. It accepts as input the inputs, outputs, and resets provided to
the TM as well as a 'minOverlapPct' used to evalulate whether or not a
prediction is a good enough match to the actual input.
The 'outputs' are the pooling outputs of the TM. This routine treats each output
as a "manifold" that includes the active columns that should be present in the
next N inputs. It then looks at each successive input and sees if it's active
columns are within the manifold. For each output sample, it computes how
many time steps it can go forward on the input before the input overlap with
the manifold is less then 'minOverlapPct'. It returns the average number of
time steps calculated for each output.
Parameters:
-----------------------------------------------
inputs: The inputs to the TM. Row 0 contains the inputs from time
step 0, row 1 from time step 1, etc.
resets: The reset input to the TM. Element 0 contains the reset from
time step 0, element 1 from time step 1, etc.
outputs: The pooling outputs from the TM. Row 0 contains the outputs
from time step 0, row 1 from time step 1, etc.
minOverlapPct: How much each input's columns must overlap with the pooling
output's columns to be considered a valid prediction.
retval: (Average number of time steps of prediction over all output
samples,
Average number of time steps of prediction when we aren't
cut short by the end of the sequence,
List containing frequency counts of each encountered
prediction time)
"""
# List of how many times we encountered each prediction amount. Element 0
# is how many times we successfully predicted 0 steps in advance, element 1
# is how many times we predicted 1 step in advance, etc.
predCounts = None
# Total steps of prediction over all samples
predTotal = 0
# Total number of samples
nSamples = len(outputs)
# Total steps of prediction for samples at the start of the sequence, or
# for samples whose prediction runs aren't cut short by the end of the
# sequence.
predTotalNotLimited = 0
nSamplesNotLimited = 0
# Compute how many cells/column we have
nCols = len(inputs[0])
nCellsPerCol = len(outputs[0]) // nCols
# Evalulate prediction for each output sample
for idx in xrange(nSamples):
# What are the active columns for this output?
activeCols = outputs[idx].reshape(nCols, nCellsPerCol).max(axis=1)
# How many steps of prediction do we have?
steps = 0
while (idx+steps+1 < nSamples) and (resets[idx+steps+1] == 0):
overlap = numpy.logical_and(inputs[idx+steps+1], activeCols)
overlapPct = 100.0 * float(overlap.sum()) / inputs[idx+steps+1].sum()
if overlapPct >= minOverlapPct:
steps += 1
else:
break
# print "idx:", idx, "steps:", steps
# Accumulate into our total
predCounts = _accumulateFrequencyCounts([steps], predCounts)
predTotal += steps
# If this sample was not cut short by the end of the sequence, include
# it into the "NotLimited" runs
if resets[idx] or \
((idx+steps+1 < nSamples) and (not resets[idx+steps+1])):
predTotalNotLimited += steps
nSamplesNotLimited += 1
# Return results
return (float(predTotal) / nSamples,
float(predTotalNotLimited) / nSamplesNotLimited,
predCounts) | Computes the predictive ability of a temporal memory (TM). This routine returns
a value which is the average number of time steps of prediction provided
by the TM. It accepts as input the inputs, outputs, and resets provided to
the TM as well as a 'minOverlapPct' used to evalulate whether or not a
prediction is a good enough match to the actual input.
The 'outputs' are the pooling outputs of the TM. This routine treats each output
as a "manifold" that includes the active columns that should be present in the
next N inputs. It then looks at each successive input and sees if it's active
columns are within the manifold. For each output sample, it computes how
many time steps it can go forward on the input before the input overlap with
the manifold is less then 'minOverlapPct'. It returns the average number of
time steps calculated for each output.
Parameters:
-----------------------------------------------
inputs: The inputs to the TM. Row 0 contains the inputs from time
step 0, row 1 from time step 1, etc.
resets: The reset input to the TM. Element 0 contains the reset from
time step 0, element 1 from time step 1, etc.
outputs: The pooling outputs from the TM. Row 0 contains the outputs
from time step 0, row 1 from time step 1, etc.
minOverlapPct: How much each input's columns must overlap with the pooling
output's columns to be considered a valid prediction.
retval: (Average number of time steps of prediction over all output
samples,
Average number of time steps of prediction when we aren't
cut short by the end of the sequence,
List containing frequency counts of each encountered
prediction time) | Below is the the instruction that describes the task:
### Input:
Computes the predictive ability of a temporal memory (TM). This routine returns
a value which is the average number of time steps of prediction provided
by the TM. It accepts as input the inputs, outputs, and resets provided to
the TM as well as a 'minOverlapPct' used to evalulate whether or not a
prediction is a good enough match to the actual input.
The 'outputs' are the pooling outputs of the TM. This routine treats each output
as a "manifold" that includes the active columns that should be present in the
next N inputs. It then looks at each successive input and sees if it's active
columns are within the manifold. For each output sample, it computes how
many time steps it can go forward on the input before the input overlap with
the manifold is less then 'minOverlapPct'. It returns the average number of
time steps calculated for each output.
Parameters:
-----------------------------------------------
inputs: The inputs to the TM. Row 0 contains the inputs from time
step 0, row 1 from time step 1, etc.
resets: The reset input to the TM. Element 0 contains the reset from
time step 0, element 1 from time step 1, etc.
outputs: The pooling outputs from the TM. Row 0 contains the outputs
from time step 0, row 1 from time step 1, etc.
minOverlapPct: How much each input's columns must overlap with the pooling
output's columns to be considered a valid prediction.
retval: (Average number of time steps of prediction over all output
samples,
Average number of time steps of prediction when we aren't
cut short by the end of the sequence,
List containing frequency counts of each encountered
prediction time)
### Response:
def predictionExtent(inputs, resets, outputs, minOverlapPct=100.0):
"""
Computes the predictive ability of a temporal memory (TM). This routine returns
a value which is the average number of time steps of prediction provided
by the TM. It accepts as input the inputs, outputs, and resets provided to
the TM as well as a 'minOverlapPct' used to evalulate whether or not a
prediction is a good enough match to the actual input.
The 'outputs' are the pooling outputs of the TM. This routine treats each output
as a "manifold" that includes the active columns that should be present in the
next N inputs. It then looks at each successive input and sees if it's active
columns are within the manifold. For each output sample, it computes how
many time steps it can go forward on the input before the input overlap with
the manifold is less then 'minOverlapPct'. It returns the average number of
time steps calculated for each output.
Parameters:
-----------------------------------------------
inputs: The inputs to the TM. Row 0 contains the inputs from time
step 0, row 1 from time step 1, etc.
resets: The reset input to the TM. Element 0 contains the reset from
time step 0, element 1 from time step 1, etc.
outputs: The pooling outputs from the TM. Row 0 contains the outputs
from time step 0, row 1 from time step 1, etc.
minOverlapPct: How much each input's columns must overlap with the pooling
output's columns to be considered a valid prediction.
retval: (Average number of time steps of prediction over all output
samples,
Average number of time steps of prediction when we aren't
cut short by the end of the sequence,
List containing frequency counts of each encountered
prediction time)
"""
# List of how many times we encountered each prediction amount. Element 0
# is how many times we successfully predicted 0 steps in advance, element 1
# is how many times we predicted 1 step in advance, etc.
predCounts = None
# Total steps of prediction over all samples
predTotal = 0
# Total number of samples
nSamples = len(outputs)
# Total steps of prediction for samples at the start of the sequence, or
# for samples whose prediction runs aren't cut short by the end of the
# sequence.
predTotalNotLimited = 0
nSamplesNotLimited = 0
# Compute how many cells/column we have
nCols = len(inputs[0])
nCellsPerCol = len(outputs[0]) // nCols
# Evalulate prediction for each output sample
for idx in xrange(nSamples):
# What are the active columns for this output?
activeCols = outputs[idx].reshape(nCols, nCellsPerCol).max(axis=1)
# How many steps of prediction do we have?
steps = 0
while (idx+steps+1 < nSamples) and (resets[idx+steps+1] == 0):
overlap = numpy.logical_and(inputs[idx+steps+1], activeCols)
overlapPct = 100.0 * float(overlap.sum()) / inputs[idx+steps+1].sum()
if overlapPct >= minOverlapPct:
steps += 1
else:
break
# print "idx:", idx, "steps:", steps
# Accumulate into our total
predCounts = _accumulateFrequencyCounts([steps], predCounts)
predTotal += steps
# If this sample was not cut short by the end of the sequence, include
# it into the "NotLimited" runs
if resets[idx] or \
((idx+steps+1 < nSamples) and (not resets[idx+steps+1])):
predTotalNotLimited += steps
nSamplesNotLimited += 1
# Return results
return (float(predTotal) / nSamples,
float(predTotalNotLimited) / nSamplesNotLimited,
predCounts) |
def resume_transfer_operation(self, operation_name):
"""
Resumes an transfer operation in Google Storage Transfer Service.
:param operation_name: (Required) Name of the transfer operation.
:type operation_name: str
:rtype: None
"""
self.get_conn().transferOperations().resume(name=operation_name).execute(num_retries=self.num_retries) | Resumes an transfer operation in Google Storage Transfer Service.
:param operation_name: (Required) Name of the transfer operation.
:type operation_name: str
:rtype: None | Below is the the instruction that describes the task:
### Input:
Resumes an transfer operation in Google Storage Transfer Service.
:param operation_name: (Required) Name of the transfer operation.
:type operation_name: str
:rtype: None
### Response:
def resume_transfer_operation(self, operation_name):
"""
Resumes an transfer operation in Google Storage Transfer Service.
:param operation_name: (Required) Name of the transfer operation.
:type operation_name: str
:rtype: None
"""
self.get_conn().transferOperations().resume(name=operation_name).execute(num_retries=self.num_retries) |
def create_comment(self, comment_form):
"""Creates a new ``Comment``.
arg: comment_form (osid.commenting.CommentForm): the form for
this ``Comment``
return: (osid.commenting.Comment) - the new ``Comment``
raise: IllegalState - ``comment_form`` already used in a create
transaction
raise: InvalidArgument - one or more of the form elements is
invalid
raise: NullArgument - ``comment_form`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
raise: Unsupported - ``comment_form`` did not originate from
``get_comment_form_for_create()``
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceAdminSession.create_resource_template
collection = JSONClientValidated('commenting',
collection='Comment',
runtime=self._runtime)
if not isinstance(comment_form, ABCCommentForm):
raise errors.InvalidArgument('argument type is not an CommentForm')
if comment_form.is_for_update():
raise errors.InvalidArgument('the CommentForm is for update only, not create')
try:
if self._forms[comment_form.get_id().get_identifier()] == CREATED:
raise errors.IllegalState('comment_form already used in a create transaction')
except KeyError:
raise errors.Unsupported('comment_form did not originate from this session')
if not comment_form.is_valid():
raise errors.InvalidArgument('one or more of the form elements is invalid')
insert_result = collection.insert_one(comment_form._my_map)
self._forms[comment_form.get_id().get_identifier()] = CREATED
result = objects.Comment(
osid_object_map=collection.find_one({'_id': insert_result.inserted_id}),
runtime=self._runtime,
proxy=self._proxy)
return result | Creates a new ``Comment``.
arg: comment_form (osid.commenting.CommentForm): the form for
this ``Comment``
return: (osid.commenting.Comment) - the new ``Comment``
raise: IllegalState - ``comment_form`` already used in a create
transaction
raise: InvalidArgument - one or more of the form elements is
invalid
raise: NullArgument - ``comment_form`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
raise: Unsupported - ``comment_form`` did not originate from
``get_comment_form_for_create()``
*compliance: mandatory -- This method must be implemented.* | Below is the the instruction that describes the task:
### Input:
Creates a new ``Comment``.
arg: comment_form (osid.commenting.CommentForm): the form for
this ``Comment``
return: (osid.commenting.Comment) - the new ``Comment``
raise: IllegalState - ``comment_form`` already used in a create
transaction
raise: InvalidArgument - one or more of the form elements is
invalid
raise: NullArgument - ``comment_form`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
raise: Unsupported - ``comment_form`` did not originate from
``get_comment_form_for_create()``
*compliance: mandatory -- This method must be implemented.*
### Response:
def create_comment(self, comment_form):
"""Creates a new ``Comment``.
arg: comment_form (osid.commenting.CommentForm): the form for
this ``Comment``
return: (osid.commenting.Comment) - the new ``Comment``
raise: IllegalState - ``comment_form`` already used in a create
transaction
raise: InvalidArgument - one or more of the form elements is
invalid
raise: NullArgument - ``comment_form`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
raise: Unsupported - ``comment_form`` did not originate from
``get_comment_form_for_create()``
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceAdminSession.create_resource_template
collection = JSONClientValidated('commenting',
collection='Comment',
runtime=self._runtime)
if not isinstance(comment_form, ABCCommentForm):
raise errors.InvalidArgument('argument type is not an CommentForm')
if comment_form.is_for_update():
raise errors.InvalidArgument('the CommentForm is for update only, not create')
try:
if self._forms[comment_form.get_id().get_identifier()] == CREATED:
raise errors.IllegalState('comment_form already used in a create transaction')
except KeyError:
raise errors.Unsupported('comment_form did not originate from this session')
if not comment_form.is_valid():
raise errors.InvalidArgument('one or more of the form elements is invalid')
insert_result = collection.insert_one(comment_form._my_map)
self._forms[comment_form.get_id().get_identifier()] = CREATED
result = objects.Comment(
osid_object_map=collection.find_one({'_id': insert_result.inserted_id}),
runtime=self._runtime,
proxy=self._proxy)
return result |
def show(self, n=10, headers=(), tablefmt="simple", floatfmt="g", numalign="decimal",
stralign="left", missingval=""):
"""
Pretty print first n rows of sequence as a table. See
https://bitbucket.org/astanin/python-tabulate for details on tabulate parameters
:param n: Number of rows to show
:param headers: Passed to tabulate
:param tablefmt: Passed to tabulate
:param floatfmt: Passed to tabulate
:param numalign: Passed to tabulate
:param stralign: Passed to tabulate
:param missingval: Passed to tabulate
"""
formatted_seq = self.tabulate(n=n, headers=headers, tablefmt=tablefmt,
floatfmt=floatfmt, numalign=numalign, stralign=stralign,
missingval=missingval)
print(formatted_seq) | Pretty print first n rows of sequence as a table. See
https://bitbucket.org/astanin/python-tabulate for details on tabulate parameters
:param n: Number of rows to show
:param headers: Passed to tabulate
:param tablefmt: Passed to tabulate
:param floatfmt: Passed to tabulate
:param numalign: Passed to tabulate
:param stralign: Passed to tabulate
:param missingval: Passed to tabulate | Below is the the instruction that describes the task:
### Input:
Pretty print first n rows of sequence as a table. See
https://bitbucket.org/astanin/python-tabulate for details on tabulate parameters
:param n: Number of rows to show
:param headers: Passed to tabulate
:param tablefmt: Passed to tabulate
:param floatfmt: Passed to tabulate
:param numalign: Passed to tabulate
:param stralign: Passed to tabulate
:param missingval: Passed to tabulate
### Response:
def show(self, n=10, headers=(), tablefmt="simple", floatfmt="g", numalign="decimal",
stralign="left", missingval=""):
"""
Pretty print first n rows of sequence as a table. See
https://bitbucket.org/astanin/python-tabulate for details on tabulate parameters
:param n: Number of rows to show
:param headers: Passed to tabulate
:param tablefmt: Passed to tabulate
:param floatfmt: Passed to tabulate
:param numalign: Passed to tabulate
:param stralign: Passed to tabulate
:param missingval: Passed to tabulate
"""
formatted_seq = self.tabulate(n=n, headers=headers, tablefmt=tablefmt,
floatfmt=floatfmt, numalign=numalign, stralign=stralign,
missingval=missingval)
print(formatted_seq) |
def get_parent_book_nodes(self):
"""Gets the parents of this book.
return: (osid.commenting.BookNodeList) - the parents of this
book
*compliance: mandatory -- This method must be implemented.*
"""
parent_book_nodes = []
for node in self._my_map['parentNodes']:
parent_book_nodes.append(BookNode(
node._my_map,
runtime=self._runtime,
proxy=self._proxy,
lookup_session=self._lookup_session))
return BookNodeList(parent_book_nodes) | Gets the parents of this book.
return: (osid.commenting.BookNodeList) - the parents of this
book
*compliance: mandatory -- This method must be implemented.* | Below is the the instruction that describes the task:
### Input:
Gets the parents of this book.
return: (osid.commenting.BookNodeList) - the parents of this
book
*compliance: mandatory -- This method must be implemented.*
### Response:
def get_parent_book_nodes(self):
"""Gets the parents of this book.
return: (osid.commenting.BookNodeList) - the parents of this
book
*compliance: mandatory -- This method must be implemented.*
"""
parent_book_nodes = []
for node in self._my_map['parentNodes']:
parent_book_nodes.append(BookNode(
node._my_map,
runtime=self._runtime,
proxy=self._proxy,
lookup_session=self._lookup_session))
return BookNodeList(parent_book_nodes) |
def register_language(self, language):
"""
Registers given language in the :obj:`LanguagesModel.languages` class property.
:param language: Language to register.
:type language: Language
:return: Method success.
:rtype: bool
"""
if self.get_language(language):
raise foundations.exceptions.ProgrammingError("{0} | '{1}' language is already registered!".format(
self.__class__.__name__, language.name))
LOGGER.debug("> Registering '{0}' language.".format(language.name))
self.__languages.append(language)
self.sort_languages()
return True | Registers given language in the :obj:`LanguagesModel.languages` class property.
:param language: Language to register.
:type language: Language
:return: Method success.
:rtype: bool | Below is the the instruction that describes the task:
### Input:
Registers given language in the :obj:`LanguagesModel.languages` class property.
:param language: Language to register.
:type language: Language
:return: Method success.
:rtype: bool
### Response:
def register_language(self, language):
"""
Registers given language in the :obj:`LanguagesModel.languages` class property.
:param language: Language to register.
:type language: Language
:return: Method success.
:rtype: bool
"""
if self.get_language(language):
raise foundations.exceptions.ProgrammingError("{0} | '{1}' language is already registered!".format(
self.__class__.__name__, language.name))
LOGGER.debug("> Registering '{0}' language.".format(language.name))
self.__languages.append(language)
self.sort_languages()
return True |
def list(cls, rc_file='~/.odoorpcrc'):
"""Return a list of all stored sessions available in the
`rc_file` file:
.. doctest::
:options: +SKIP
>>> import odoorpc
>>> odoorpc.ODOO.list()
['foo', 'bar']
Use the :func:`save <odoorpc.ODOO.save>` and
:func:`load <odoorpc.ODOO.load>` methods to manage such sessions.
*Python 2:*
:raise: `IOError`
*Python 3:*
:raise: `PermissionError`
:raise: `FileNotFoundError`
"""
sessions = session.get_all(rc_file)
return [name for name in sessions
if sessions[name].get('type') == cls.__name__] | Return a list of all stored sessions available in the
`rc_file` file:
.. doctest::
:options: +SKIP
>>> import odoorpc
>>> odoorpc.ODOO.list()
['foo', 'bar']
Use the :func:`save <odoorpc.ODOO.save>` and
:func:`load <odoorpc.ODOO.load>` methods to manage such sessions.
*Python 2:*
:raise: `IOError`
*Python 3:*
:raise: `PermissionError`
:raise: `FileNotFoundError` | Below is the the instruction that describes the task:
### Input:
Return a list of all stored sessions available in the
`rc_file` file:
.. doctest::
:options: +SKIP
>>> import odoorpc
>>> odoorpc.ODOO.list()
['foo', 'bar']
Use the :func:`save <odoorpc.ODOO.save>` and
:func:`load <odoorpc.ODOO.load>` methods to manage such sessions.
*Python 2:*
:raise: `IOError`
*Python 3:*
:raise: `PermissionError`
:raise: `FileNotFoundError`
### Response:
def list(cls, rc_file='~/.odoorpcrc'):
"""Return a list of all stored sessions available in the
`rc_file` file:
.. doctest::
:options: +SKIP
>>> import odoorpc
>>> odoorpc.ODOO.list()
['foo', 'bar']
Use the :func:`save <odoorpc.ODOO.save>` and
:func:`load <odoorpc.ODOO.load>` methods to manage such sessions.
*Python 2:*
:raise: `IOError`
*Python 3:*
:raise: `PermissionError`
:raise: `FileNotFoundError`
"""
sessions = session.get_all(rc_file)
return [name for name in sessions
if sessions[name].get('type') == cls.__name__] |
def setChargingStationStop(self, vehID, stopID, duration=2**31 - 1, until=-1, flags=tc.STOP_DEFAULT):
"""setChargingStationStop(string, string, integer, integer, integer) -> None
Adds or modifies a stop at a chargingStation with the given parameters. The duration and the until attribute are
in milliseconds.
"""
self.setStop(vehID, stopID, duration=duration, until=until,
flags=flags | tc.STOP_CHARGING_STATION) | setChargingStationStop(string, string, integer, integer, integer) -> None
Adds or modifies a stop at a chargingStation with the given parameters. The duration and the until attribute are
in milliseconds. | Below is the the instruction that describes the task:
### Input:
setChargingStationStop(string, string, integer, integer, integer) -> None
Adds or modifies a stop at a chargingStation with the given parameters. The duration and the until attribute are
in milliseconds.
### Response:
def setChargingStationStop(self, vehID, stopID, duration=2**31 - 1, until=-1, flags=tc.STOP_DEFAULT):
"""setChargingStationStop(string, string, integer, integer, integer) -> None
Adds or modifies a stop at a chargingStation with the given parameters. The duration and the until attribute are
in milliseconds.
"""
self.setStop(vehID, stopID, duration=duration, until=until,
flags=flags | tc.STOP_CHARGING_STATION) |
def init(self, switch_configuration, terminal_controller, logger, piping_processor, *args):
"""
:type switch_configuration: fake_switches.switch_configuration.SwitchConfiguration
:type terminal_controller: fake_switches.terminal.TerminalController
:type logger: logging.Logger
:type piping_processor: fake_switches.command_processing.piping_processor_base.PipingProcessorBase
"""
self.switch_configuration = switch_configuration
self.terminal_controller = terminal_controller
self.logger = logger
self.piping_processor = piping_processor
self.sub_processor = None
self.continuing_to = None
self.is_done = False
self.replace_input = False
self.awaiting_keystroke = False | :type switch_configuration: fake_switches.switch_configuration.SwitchConfiguration
:type terminal_controller: fake_switches.terminal.TerminalController
:type logger: logging.Logger
:type piping_processor: fake_switches.command_processing.piping_processor_base.PipingProcessorBase | Below is the the instruction that describes the task:
### Input:
:type switch_configuration: fake_switches.switch_configuration.SwitchConfiguration
:type terminal_controller: fake_switches.terminal.TerminalController
:type logger: logging.Logger
:type piping_processor: fake_switches.command_processing.piping_processor_base.PipingProcessorBase
### Response:
def init(self, switch_configuration, terminal_controller, logger, piping_processor, *args):
"""
:type switch_configuration: fake_switches.switch_configuration.SwitchConfiguration
:type terminal_controller: fake_switches.terminal.TerminalController
:type logger: logging.Logger
:type piping_processor: fake_switches.command_processing.piping_processor_base.PipingProcessorBase
"""
self.switch_configuration = switch_configuration
self.terminal_controller = terminal_controller
self.logger = logger
self.piping_processor = piping_processor
self.sub_processor = None
self.continuing_to = None
self.is_done = False
self.replace_input = False
self.awaiting_keystroke = False |
def rotate_y(self, angle):
"""
Rotates mesh about the y-axis.
Parameters
----------
angle : float
Angle in degrees to rotate about the y-axis.
"""
axis_rotation(self.points, angle, inplace=True, axis='y') | Rotates mesh about the y-axis.
Parameters
----------
angle : float
Angle in degrees to rotate about the y-axis. | Below is the the instruction that describes the task:
### Input:
Rotates mesh about the y-axis.
Parameters
----------
angle : float
Angle in degrees to rotate about the y-axis.
### Response:
def rotate_y(self, angle):
"""
Rotates mesh about the y-axis.
Parameters
----------
angle : float
Angle in degrees to rotate about the y-axis.
"""
axis_rotation(self.points, angle, inplace=True, axis='y') |
def deduplication_backup(self, process_bar):
"""
Backup the current file and compare the content.
:param process_bar: tqdm process bar
"""
self.fast_backup = False # Was a fast backup used?
src_path = self.dir_path.resolved_path
log.debug("*** deduplication backup: '%s'", src_path)
log.debug("abs_src_filepath: '%s'", self.path_helper.abs_src_filepath)
log.debug("abs_dst_filepath: '%s'", self.path_helper.abs_dst_filepath)
log.debug("abs_dst_hash_filepath: '%s'", self.path_helper.abs_dst_hash_filepath)
log.debug("abs_dst_dir: '%s'", self.path_helper.abs_dst_path)
if not self.path_helper.abs_dst_path.is_dir():
try:
self.path_helper.abs_dst_path.makedirs(mode=phlb_config.default_new_path_mode)
except OSError as err:
raise BackupFileError("Error creating out path: %s" % err)
else:
assert not self.path_helper.abs_dst_filepath.is_file(), (
"Out file already exists: %r" % self.path_helper.abs_src_filepath
)
try:
try:
with self.path_helper.abs_src_filepath.open("rb") as in_file:
with self.path_helper.abs_dst_hash_filepath.open("w") as hash_file:
with self.path_helper.abs_dst_filepath.open("wb") as out_file:
hash = self._deduplication_backup(self.dir_path, in_file, out_file, process_bar)
hash_hexdigest = hash.hexdigest()
hash_file.write(hash_hexdigest)
except OSError as err:
# FIXME: Better error message
raise BackupFileError("Skip file %s error: %s" % (self.path_helper.abs_src_filepath, err))
except KeyboardInterrupt:
# Try to remove created files
try:
self.path_helper.abs_dst_filepath.unlink()
except OSError:
pass
try:
self.path_helper.abs_dst_hash_filepath.unlink()
except OSError:
pass
raise KeyboardInterrupt
old_backup_entry = deduplicate(self.path_helper.abs_dst_filepath, hash_hexdigest)
if old_backup_entry is None:
log.debug("File is unique.")
self.file_linked = False # Was a hardlink used?
else:
log.debug("File was deduplicated via hardlink to: %s" % old_backup_entry)
self.file_linked = True # Was a hardlink used?
# set origin access/modified times to the new created backup file
atime_ns = self.dir_path.stat.st_atime_ns
mtime_ns = self.dir_path.stat.st_mtime_ns
self.path_helper.abs_dst_filepath.utime(ns=(atime_ns, mtime_ns)) # call os.utime()
log.debug("Set mtime to: %s" % mtime_ns)
BackupEntry.objects.create(
backup_run=self.backup_run,
backup_entry_path=self.path_helper.abs_dst_filepath,
hash_hexdigest=hash_hexdigest,
)
self.fast_backup = False | Backup the current file and compare the content.
:param process_bar: tqdm process bar | Below is the the instruction that describes the task:
### Input:
Backup the current file and compare the content.
:param process_bar: tqdm process bar
### Response:
def deduplication_backup(self, process_bar):
"""
Backup the current file and compare the content.
:param process_bar: tqdm process bar
"""
self.fast_backup = False # Was a fast backup used?
src_path = self.dir_path.resolved_path
log.debug("*** deduplication backup: '%s'", src_path)
log.debug("abs_src_filepath: '%s'", self.path_helper.abs_src_filepath)
log.debug("abs_dst_filepath: '%s'", self.path_helper.abs_dst_filepath)
log.debug("abs_dst_hash_filepath: '%s'", self.path_helper.abs_dst_hash_filepath)
log.debug("abs_dst_dir: '%s'", self.path_helper.abs_dst_path)
if not self.path_helper.abs_dst_path.is_dir():
try:
self.path_helper.abs_dst_path.makedirs(mode=phlb_config.default_new_path_mode)
except OSError as err:
raise BackupFileError("Error creating out path: %s" % err)
else:
assert not self.path_helper.abs_dst_filepath.is_file(), (
"Out file already exists: %r" % self.path_helper.abs_src_filepath
)
try:
try:
with self.path_helper.abs_src_filepath.open("rb") as in_file:
with self.path_helper.abs_dst_hash_filepath.open("w") as hash_file:
with self.path_helper.abs_dst_filepath.open("wb") as out_file:
hash = self._deduplication_backup(self.dir_path, in_file, out_file, process_bar)
hash_hexdigest = hash.hexdigest()
hash_file.write(hash_hexdigest)
except OSError as err:
# FIXME: Better error message
raise BackupFileError("Skip file %s error: %s" % (self.path_helper.abs_src_filepath, err))
except KeyboardInterrupt:
# Try to remove created files
try:
self.path_helper.abs_dst_filepath.unlink()
except OSError:
pass
try:
self.path_helper.abs_dst_hash_filepath.unlink()
except OSError:
pass
raise KeyboardInterrupt
old_backup_entry = deduplicate(self.path_helper.abs_dst_filepath, hash_hexdigest)
if old_backup_entry is None:
log.debug("File is unique.")
self.file_linked = False # Was a hardlink used?
else:
log.debug("File was deduplicated via hardlink to: %s" % old_backup_entry)
self.file_linked = True # Was a hardlink used?
# set origin access/modified times to the new created backup file
atime_ns = self.dir_path.stat.st_atime_ns
mtime_ns = self.dir_path.stat.st_mtime_ns
self.path_helper.abs_dst_filepath.utime(ns=(atime_ns, mtime_ns)) # call os.utime()
log.debug("Set mtime to: %s" % mtime_ns)
BackupEntry.objects.create(
backup_run=self.backup_run,
backup_entry_path=self.path_helper.abs_dst_filepath,
hash_hexdigest=hash_hexdigest,
)
self.fast_backup = False |
def run_kernel(self, func, c_args, threads, grid):
"""runs the kernel once, returns whatever the kernel returns
:param func: A C function compiled for this specific configuration
:type func: ctypes._FuncPtr
:param c_args: A list of arguments to the function, order should match the
order in the code. The list should be prepared using
ready_argument_list().
:type c_args: list(Argument)
:param threads: Ignored, but left as argument for now to have the same
interface as CudaFunctions and OpenCLFunctions.
:type threads: any
:param grid: Ignored, but left as argument for now to have the same
interface as CudaFunctions and OpenCLFunctions.
:type grid: any
:returns: A robust average of values returned by the C function.
:rtype: float
"""
logging.debug("run_kernel")
logging.debug("arguments=" + str([str(arg.ctypes) for arg in c_args]))
time = func(*[arg.ctypes for arg in c_args])
return time | runs the kernel once, returns whatever the kernel returns
:param func: A C function compiled for this specific configuration
:type func: ctypes._FuncPtr
:param c_args: A list of arguments to the function, order should match the
order in the code. The list should be prepared using
ready_argument_list().
:type c_args: list(Argument)
:param threads: Ignored, but left as argument for now to have the same
interface as CudaFunctions and OpenCLFunctions.
:type threads: any
:param grid: Ignored, but left as argument for now to have the same
interface as CudaFunctions and OpenCLFunctions.
:type grid: any
:returns: A robust average of values returned by the C function.
:rtype: float | Below is the the instruction that describes the task:
### Input:
runs the kernel once, returns whatever the kernel returns
:param func: A C function compiled for this specific configuration
:type func: ctypes._FuncPtr
:param c_args: A list of arguments to the function, order should match the
order in the code. The list should be prepared using
ready_argument_list().
:type c_args: list(Argument)
:param threads: Ignored, but left as argument for now to have the same
interface as CudaFunctions and OpenCLFunctions.
:type threads: any
:param grid: Ignored, but left as argument for now to have the same
interface as CudaFunctions and OpenCLFunctions.
:type grid: any
:returns: A robust average of values returned by the C function.
:rtype: float
### Response:
def run_kernel(self, func, c_args, threads, grid):
"""runs the kernel once, returns whatever the kernel returns
:param func: A C function compiled for this specific configuration
:type func: ctypes._FuncPtr
:param c_args: A list of arguments to the function, order should match the
order in the code. The list should be prepared using
ready_argument_list().
:type c_args: list(Argument)
:param threads: Ignored, but left as argument for now to have the same
interface as CudaFunctions and OpenCLFunctions.
:type threads: any
:param grid: Ignored, but left as argument for now to have the same
interface as CudaFunctions and OpenCLFunctions.
:type grid: any
:returns: A robust average of values returned by the C function.
:rtype: float
"""
logging.debug("run_kernel")
logging.debug("arguments=" + str([str(arg.ctypes) for arg in c_args]))
time = func(*[arg.ctypes for arg in c_args])
return time |
def _clear_block_deco(self):
"""Clear the folded block decorations."""
for deco in self._block_decos:
self.editor.decorations.remove(deco)
self._block_decos[:] = [] | Clear the folded block decorations. | Below is the the instruction that describes the task:
### Input:
Clear the folded block decorations.
### Response:
def _clear_block_deco(self):
"""Clear the folded block decorations."""
for deco in self._block_decos:
self.editor.decorations.remove(deco)
self._block_decos[:] = [] |
def set_published(self, value=None):
"""stub"""
if value is None:
raise NullArgument()
if self.get_published_metadata().is_read_only():
raise NoAccess()
if not self.my_osid_object_form._is_valid_boolean(value):
raise InvalidArgument()
self.my_osid_object_form._my_map['published'] = value | stub | Below is the the instruction that describes the task:
### Input:
stub
### Response:
def set_published(self, value=None):
"""stub"""
if value is None:
raise NullArgument()
if self.get_published_metadata().is_read_only():
raise NoAccess()
if not self.my_osid_object_form._is_valid_boolean(value):
raise InvalidArgument()
self.my_osid_object_form._my_map['published'] = value |
def event(from_states=None, to_state=None):
""" a decorator for transitioning from certain states to a target state. must be used on bound methods of a class
instance, only. """
from_states_tuple = (from_states, ) if isinstance(from_states, State) else tuple(from_states or [])
if not len(from_states_tuple) >= 1:
raise ValueError()
if not all(isinstance(state, State) for state in from_states_tuple):
raise TypeError()
if not isinstance(to_state, State):
raise TypeError()
def wrapper(wrapped):
@functools.wraps(wrapped)
def transition(instance, *a, **kw):
if instance.current_state not in from_states_tuple:
raise InvalidStateTransition()
try:
result = wrapped(instance, *a, **kw)
except Exception as error:
error_handlers = getattr(instance, '___pystatemachine_transition_failure_handlers', [])
for error_handler in error_handlers:
error_handler(instance, wrapped, instance.current_state, to_state, error)
if not error_handlers:
raise error
else:
StateInfo.set_current_state(instance, to_state)
return result
return transition
return wrapper | a decorator for transitioning from certain states to a target state. must be used on bound methods of a class
instance, only. | Below is the the instruction that describes the task:
### Input:
a decorator for transitioning from certain states to a target state. must be used on bound methods of a class
instance, only.
### Response:
def event(from_states=None, to_state=None):
""" a decorator for transitioning from certain states to a target state. must be used on bound methods of a class
instance, only. """
from_states_tuple = (from_states, ) if isinstance(from_states, State) else tuple(from_states or [])
if not len(from_states_tuple) >= 1:
raise ValueError()
if not all(isinstance(state, State) for state in from_states_tuple):
raise TypeError()
if not isinstance(to_state, State):
raise TypeError()
def wrapper(wrapped):
@functools.wraps(wrapped)
def transition(instance, *a, **kw):
if instance.current_state not in from_states_tuple:
raise InvalidStateTransition()
try:
result = wrapped(instance, *a, **kw)
except Exception as error:
error_handlers = getattr(instance, '___pystatemachine_transition_failure_handlers', [])
for error_handler in error_handlers:
error_handler(instance, wrapped, instance.current_state, to_state, error)
if not error_handlers:
raise error
else:
StateInfo.set_current_state(instance, to_state)
return result
return transition
return wrapper |
def _derive_log_path(self):
"""Guess logfile path produced by Mothur
This method checks the working directory for log files
generated by Mothur. It will raise an ApplicationError if no
log file can be found.
Mothur generates log files named in a nondeterministic way,
using the current time. We return the log file with the most
recent time, although this may lead to incorrect log file
detection if you are running many instances of mothur
simultaneously.
"""
filenames = listdir(self.WorkingDir)
lognames = [
x for x in filenames if re.match(
"^mothur\.\d+\.logfile$",
x)]
if not lognames:
raise ApplicationError(
'No log file detected in directory %s. Contents: \n\t%s' % (
input_dir, '\n\t'.join(possible_logfiles)))
most_recent_logname = sorted(lognames, reverse=True)[0]
return path.join(self.WorkingDir, most_recent_logname) | Guess logfile path produced by Mothur
This method checks the working directory for log files
generated by Mothur. It will raise an ApplicationError if no
log file can be found.
Mothur generates log files named in a nondeterministic way,
using the current time. We return the log file with the most
recent time, although this may lead to incorrect log file
detection if you are running many instances of mothur
simultaneously. | Below is the the instruction that describes the task:
### Input:
Guess logfile path produced by Mothur
This method checks the working directory for log files
generated by Mothur. It will raise an ApplicationError if no
log file can be found.
Mothur generates log files named in a nondeterministic way,
using the current time. We return the log file with the most
recent time, although this may lead to incorrect log file
detection if you are running many instances of mothur
simultaneously.
### Response:
def _derive_log_path(self):
"""Guess logfile path produced by Mothur
This method checks the working directory for log files
generated by Mothur. It will raise an ApplicationError if no
log file can be found.
Mothur generates log files named in a nondeterministic way,
using the current time. We return the log file with the most
recent time, although this may lead to incorrect log file
detection if you are running many instances of mothur
simultaneously.
"""
filenames = listdir(self.WorkingDir)
lognames = [
x for x in filenames if re.match(
"^mothur\.\d+\.logfile$",
x)]
if not lognames:
raise ApplicationError(
'No log file detected in directory %s. Contents: \n\t%s' % (
input_dir, '\n\t'.join(possible_logfiles)))
most_recent_logname = sorted(lognames, reverse=True)[0]
return path.join(self.WorkingDir, most_recent_logname) |
def pkcs7_unpad(buf):
# type: (bytes) -> bytes
"""Removes PKCS7 padding a decrypted object
:param bytes buf: buffer to remove padding
:rtype: bytes
:return: buffer without PKCS7_PADDING
"""
unpadder = cryptography.hazmat.primitives.padding.PKCS7(
cryptography.hazmat.primitives.ciphers.
algorithms.AES.block_size).unpadder()
return unpadder.update(buf) + unpadder.finalize() | Removes PKCS7 padding a decrypted object
:param bytes buf: buffer to remove padding
:rtype: bytes
:return: buffer without PKCS7_PADDING | Below is the the instruction that describes the task:
### Input:
Removes PKCS7 padding a decrypted object
:param bytes buf: buffer to remove padding
:rtype: bytes
:return: buffer without PKCS7_PADDING
### Response:
def pkcs7_unpad(buf):
# type: (bytes) -> bytes
"""Removes PKCS7 padding a decrypted object
:param bytes buf: buffer to remove padding
:rtype: bytes
:return: buffer without PKCS7_PADDING
"""
unpadder = cryptography.hazmat.primitives.padding.PKCS7(
cryptography.hazmat.primitives.ciphers.
algorithms.AES.block_size).unpadder()
return unpadder.update(buf) + unpadder.finalize() |
def group_objects_by(self, list, attr, valueLabel="value", childrenLabel="children"):
"""
Generates a group object based on the attribute value on of the given attr value that is passed in.
:param list list: A list of dictionary objects
:param str attr: The attribute that the dictionaries should be sorted upon
:param str valueLabel: What to call the key of the field we're sorting upon
:param str childrenLabel: What to call the list of child objects on the group object
:returns: list of grouped objects by a given attribute
:rtype: list
"""
groups = []
for obj in list:
val = obj.get(attr)
if not val:
pass
newGroup = {"attribute": attr, valueLabel: val, childrenLabel: [obj]}
found = False
for i in range(0,len(groups)):
if val == groups[i].get(valueLabel):
found = True
groups[i][childrenLabel].append(obj)
pass
if not found:
groups.append(newGroup)
return groups | Generates a group object based on the attribute value on of the given attr value that is passed in.
:param list list: A list of dictionary objects
:param str attr: The attribute that the dictionaries should be sorted upon
:param str valueLabel: What to call the key of the field we're sorting upon
:param str childrenLabel: What to call the list of child objects on the group object
:returns: list of grouped objects by a given attribute
:rtype: list | Below is the the instruction that describes the task:
### Input:
Generates a group object based on the attribute value on of the given attr value that is passed in.
:param list list: A list of dictionary objects
:param str attr: The attribute that the dictionaries should be sorted upon
:param str valueLabel: What to call the key of the field we're sorting upon
:param str childrenLabel: What to call the list of child objects on the group object
:returns: list of grouped objects by a given attribute
:rtype: list
### Response:
def group_objects_by(self, list, attr, valueLabel="value", childrenLabel="children"):
"""
Generates a group object based on the attribute value on of the given attr value that is passed in.
:param list list: A list of dictionary objects
:param str attr: The attribute that the dictionaries should be sorted upon
:param str valueLabel: What to call the key of the field we're sorting upon
:param str childrenLabel: What to call the list of child objects on the group object
:returns: list of grouped objects by a given attribute
:rtype: list
"""
groups = []
for obj in list:
val = obj.get(attr)
if not val:
pass
newGroup = {"attribute": attr, valueLabel: val, childrenLabel: [obj]}
found = False
for i in range(0,len(groups)):
if val == groups[i].get(valueLabel):
found = True
groups[i][childrenLabel].append(obj)
pass
if not found:
groups.append(newGroup)
return groups |
def load(self):
"""
Loads the state of a previously saved CallStack to this instance.
"""
s = load_stack(self)
if s:
self.hooks = s.hooks
self.calls = s.calls | Loads the state of a previously saved CallStack to this instance. | Below is the the instruction that describes the task:
### Input:
Loads the state of a previously saved CallStack to this instance.
### Response:
def load(self):
"""
Loads the state of a previously saved CallStack to this instance.
"""
s = load_stack(self)
if s:
self.hooks = s.hooks
self.calls = s.calls |
def _tag_and_field_maker(self, event):
'''
>>> idbf = InfluxDBForwarder('no_host', '8086', 'deadpool',
... 'chimichanga', 'logs', 'collection')
>>> log = {u'data': {u'_': {u'file': u'log.py',
... u'fn': u'start',
... u'ln': 8,
... u'name': u'__main__'},
... u'a': 1,
... u'b': 2,
... u'__ignore_this': 'some_string',
... u'msg': u'this is a dummy log'},
... u'error': False,
... u'error_tb': u'',
... u'event': u'some_log',
... u'file': u'/var/log/sample.log',
... u'formatter': u'logagg.formatters.basescript',
... u'host': u'deepcompute',
... u'id': u'20180409T095924_aec36d313bdc11e89da654e1ad04f45e',
... u'level': u'info',
... u'raw': u'{...}',
... u'timestamp': u'2018-04-09T09:59:24.733945Z',
... u'type': u'metric'}
>>> tags, fields = idbf._tag_and_field_maker(log)
>>> from pprint import pprint
>>> pprint(tags)
{u'data.msg': u'this is a dummy log',
u'error_tb': u'',
u'file': u'/var/log/sample.log',
u'formatter': u'logagg.formatters.basescript',
u'host': u'deepcompute',
u'level': u'info'}
>>> pprint(fields)
{u'data._': "{u'ln': 8, u'fn': u'start', u'file': u'log.py', u'name': u'__main__'}",
u'data.a': 1,
u'data.b': 2}
'''
data = event.pop('data')
data = flatten_dict({'data': data})
t = dict((k, event[k]) for k in event if k not in self.EXCLUDE_TAGS)
f = dict()
for k in data:
v = data[k]
if is_number(v) or isinstance(v, MarkValue):
f[k] = v
else:
#if v.startswith('_'): f[k] = eval(v.split('_', 1)[1])
t[k] = v
return t, f | >>> idbf = InfluxDBForwarder('no_host', '8086', 'deadpool',
... 'chimichanga', 'logs', 'collection')
>>> log = {u'data': {u'_': {u'file': u'log.py',
... u'fn': u'start',
... u'ln': 8,
... u'name': u'__main__'},
... u'a': 1,
... u'b': 2,
... u'__ignore_this': 'some_string',
... u'msg': u'this is a dummy log'},
... u'error': False,
... u'error_tb': u'',
... u'event': u'some_log',
... u'file': u'/var/log/sample.log',
... u'formatter': u'logagg.formatters.basescript',
... u'host': u'deepcompute',
... u'id': u'20180409T095924_aec36d313bdc11e89da654e1ad04f45e',
... u'level': u'info',
... u'raw': u'{...}',
... u'timestamp': u'2018-04-09T09:59:24.733945Z',
... u'type': u'metric'}
>>> tags, fields = idbf._tag_and_field_maker(log)
>>> from pprint import pprint
>>> pprint(tags)
{u'data.msg': u'this is a dummy log',
u'error_tb': u'',
u'file': u'/var/log/sample.log',
u'formatter': u'logagg.formatters.basescript',
u'host': u'deepcompute',
u'level': u'info'}
>>> pprint(fields)
{u'data._': "{u'ln': 8, u'fn': u'start', u'file': u'log.py', u'name': u'__main__'}",
u'data.a': 1,
u'data.b': 2} | Below is the the instruction that describes the task:
### Input:
>>> idbf = InfluxDBForwarder('no_host', '8086', 'deadpool',
... 'chimichanga', 'logs', 'collection')
>>> log = {u'data': {u'_': {u'file': u'log.py',
... u'fn': u'start',
... u'ln': 8,
... u'name': u'__main__'},
... u'a': 1,
... u'b': 2,
... u'__ignore_this': 'some_string',
... u'msg': u'this is a dummy log'},
... u'error': False,
... u'error_tb': u'',
... u'event': u'some_log',
... u'file': u'/var/log/sample.log',
... u'formatter': u'logagg.formatters.basescript',
... u'host': u'deepcompute',
... u'id': u'20180409T095924_aec36d313bdc11e89da654e1ad04f45e',
... u'level': u'info',
... u'raw': u'{...}',
... u'timestamp': u'2018-04-09T09:59:24.733945Z',
... u'type': u'metric'}
>>> tags, fields = idbf._tag_and_field_maker(log)
>>> from pprint import pprint
>>> pprint(tags)
{u'data.msg': u'this is a dummy log',
u'error_tb': u'',
u'file': u'/var/log/sample.log',
u'formatter': u'logagg.formatters.basescript',
u'host': u'deepcompute',
u'level': u'info'}
>>> pprint(fields)
{u'data._': "{u'ln': 8, u'fn': u'start', u'file': u'log.py', u'name': u'__main__'}",
u'data.a': 1,
u'data.b': 2}
### Response:
def _tag_and_field_maker(self, event):
'''
>>> idbf = InfluxDBForwarder('no_host', '8086', 'deadpool',
... 'chimichanga', 'logs', 'collection')
>>> log = {u'data': {u'_': {u'file': u'log.py',
... u'fn': u'start',
... u'ln': 8,
... u'name': u'__main__'},
... u'a': 1,
... u'b': 2,
... u'__ignore_this': 'some_string',
... u'msg': u'this is a dummy log'},
... u'error': False,
... u'error_tb': u'',
... u'event': u'some_log',
... u'file': u'/var/log/sample.log',
... u'formatter': u'logagg.formatters.basescript',
... u'host': u'deepcompute',
... u'id': u'20180409T095924_aec36d313bdc11e89da654e1ad04f45e',
... u'level': u'info',
... u'raw': u'{...}',
... u'timestamp': u'2018-04-09T09:59:24.733945Z',
... u'type': u'metric'}
>>> tags, fields = idbf._tag_and_field_maker(log)
>>> from pprint import pprint
>>> pprint(tags)
{u'data.msg': u'this is a dummy log',
u'error_tb': u'',
u'file': u'/var/log/sample.log',
u'formatter': u'logagg.formatters.basescript',
u'host': u'deepcompute',
u'level': u'info'}
>>> pprint(fields)
{u'data._': "{u'ln': 8, u'fn': u'start', u'file': u'log.py', u'name': u'__main__'}",
u'data.a': 1,
u'data.b': 2}
'''
data = event.pop('data')
data = flatten_dict({'data': data})
t = dict((k, event[k]) for k in event if k not in self.EXCLUDE_TAGS)
f = dict()
for k in data:
v = data[k]
if is_number(v) or isinstance(v, MarkValue):
f[k] = v
else:
#if v.startswith('_'): f[k] = eval(v.split('_', 1)[1])
t[k] = v
return t, f |
def qos_queue_scheduler_strict_priority_dwrr_traffic_class4(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
qos = ET.SubElement(config, "qos", xmlns="urn:brocade.com:mgmt:brocade-qos")
queue = ET.SubElement(qos, "queue")
scheduler = ET.SubElement(queue, "scheduler")
strict_priority = ET.SubElement(scheduler, "strict-priority")
dwrr_traffic_class4 = ET.SubElement(strict_priority, "dwrr-traffic-class4")
dwrr_traffic_class4.text = kwargs.pop('dwrr_traffic_class4')
callback = kwargs.pop('callback', self._callback)
return callback(config) | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def qos_queue_scheduler_strict_priority_dwrr_traffic_class4(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
qos = ET.SubElement(config, "qos", xmlns="urn:brocade.com:mgmt:brocade-qos")
queue = ET.SubElement(qos, "queue")
scheduler = ET.SubElement(queue, "scheduler")
strict_priority = ET.SubElement(scheduler, "strict-priority")
dwrr_traffic_class4 = ET.SubElement(strict_priority, "dwrr-traffic-class4")
dwrr_traffic_class4.text = kwargs.pop('dwrr_traffic_class4')
callback = kwargs.pop('callback', self._callback)
return callback(config) |
def unassign_log_entry_from_log(self, log_entry_id, log_id):
"""Removes a ``LogEntry`` from a ``Log``.
arg: log_entry_id (osid.id.Id): the ``Id`` of the
``LogEntry``
arg: log_id (osid.id.Id): the ``Id`` of the ``Log``
raise: NotFound - ``log_entry_id`` or ``log_id`` not found or
``log_entry_id`` not assigned to ``log_id``
raise: NullArgument - ``log_entry_id`` or ``log_id`` is
``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceBinAssignmentSession.unassign_resource_from_bin
mgr = self._get_provider_manager('LOGGING', local=True)
lookup_session = mgr.get_log_lookup_session(proxy=self._proxy)
lookup_session.get_log(log_id) # to raise NotFound
self._unassign_object_from_catalog(log_entry_id, log_id) | Removes a ``LogEntry`` from a ``Log``.
arg: log_entry_id (osid.id.Id): the ``Id`` of the
``LogEntry``
arg: log_id (osid.id.Id): the ``Id`` of the ``Log``
raise: NotFound - ``log_entry_id`` or ``log_id`` not found or
``log_entry_id`` not assigned to ``log_id``
raise: NullArgument - ``log_entry_id`` or ``log_id`` is
``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.* | Below is the the instruction that describes the task:
### Input:
Removes a ``LogEntry`` from a ``Log``.
arg: log_entry_id (osid.id.Id): the ``Id`` of the
``LogEntry``
arg: log_id (osid.id.Id): the ``Id`` of the ``Log``
raise: NotFound - ``log_entry_id`` or ``log_id`` not found or
``log_entry_id`` not assigned to ``log_id``
raise: NullArgument - ``log_entry_id`` or ``log_id`` is
``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
### Response:
def unassign_log_entry_from_log(self, log_entry_id, log_id):
"""Removes a ``LogEntry`` from a ``Log``.
arg: log_entry_id (osid.id.Id): the ``Id`` of the
``LogEntry``
arg: log_id (osid.id.Id): the ``Id`` of the ``Log``
raise: NotFound - ``log_entry_id`` or ``log_id`` not found or
``log_entry_id`` not assigned to ``log_id``
raise: NullArgument - ``log_entry_id`` or ``log_id`` is
``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceBinAssignmentSession.unassign_resource_from_bin
mgr = self._get_provider_manager('LOGGING', local=True)
lookup_session = mgr.get_log_lookup_session(proxy=self._proxy)
lookup_session.get_log(log_id) # to raise NotFound
self._unassign_object_from_catalog(log_entry_id, log_id) |
def p_scalar__doublequote(self, p):
"""
scalar : DOUBLEQUOTE_START SCALAR DOUBLEQUOTE_END
"""
scalar = re.sub('\n\s+', ' ', str(p[2]))
p[0] = Str(scalar.replace('\\"', '"')) | scalar : DOUBLEQUOTE_START SCALAR DOUBLEQUOTE_END | Below is the the instruction that describes the task:
### Input:
scalar : DOUBLEQUOTE_START SCALAR DOUBLEQUOTE_END
### Response:
def p_scalar__doublequote(self, p):
"""
scalar : DOUBLEQUOTE_START SCALAR DOUBLEQUOTE_END
"""
scalar = re.sub('\n\s+', ' ', str(p[2]))
p[0] = Str(scalar.replace('\\"', '"')) |
def suggest(self, index=None, body=None, params=None):
"""
The suggest feature suggests similar looking terms based on a provided
text by using a suggester.
`<http://elasticsearch.org/guide/reference/api/search/suggest/>`_
:arg index: A comma-separated list of index names to restrict the
operation; use `_all` or empty string to perform the operation on
all indices
:arg body: The request definition
:arg ignore_indices: When performed on multiple indices, allows to
ignore `missing` ones (default: none)
:arg preference: Specify the node or shard the operation should be
performed on (default: random)
:arg routing: Specific routing value
:arg source: The URL-encoded request definition (instead of using
request body)
"""
_, data = yield self.transport.perform_request('POST',
_make_path(index,
'_suggest'),
params=params, body=body)
raise gen.Return(data) | The suggest feature suggests similar looking terms based on a provided
text by using a suggester.
`<http://elasticsearch.org/guide/reference/api/search/suggest/>`_
:arg index: A comma-separated list of index names to restrict the
operation; use `_all` or empty string to perform the operation on
all indices
:arg body: The request definition
:arg ignore_indices: When performed on multiple indices, allows to
ignore `missing` ones (default: none)
:arg preference: Specify the node or shard the operation should be
performed on (default: random)
:arg routing: Specific routing value
:arg source: The URL-encoded request definition (instead of using
request body) | Below is the the instruction that describes the task:
### Input:
The suggest feature suggests similar looking terms based on a provided
text by using a suggester.
`<http://elasticsearch.org/guide/reference/api/search/suggest/>`_
:arg index: A comma-separated list of index names to restrict the
operation; use `_all` or empty string to perform the operation on
all indices
:arg body: The request definition
:arg ignore_indices: When performed on multiple indices, allows to
ignore `missing` ones (default: none)
:arg preference: Specify the node or shard the operation should be
performed on (default: random)
:arg routing: Specific routing value
:arg source: The URL-encoded request definition (instead of using
request body)
### Response:
def suggest(self, index=None, body=None, params=None):
"""
The suggest feature suggests similar looking terms based on a provided
text by using a suggester.
`<http://elasticsearch.org/guide/reference/api/search/suggest/>`_
:arg index: A comma-separated list of index names to restrict the
operation; use `_all` or empty string to perform the operation on
all indices
:arg body: The request definition
:arg ignore_indices: When performed on multiple indices, allows to
ignore `missing` ones (default: none)
:arg preference: Specify the node or shard the operation should be
performed on (default: random)
:arg routing: Specific routing value
:arg source: The URL-encoded request definition (instead of using
request body)
"""
_, data = yield self.transport.perform_request('POST',
_make_path(index,
'_suggest'),
params=params, body=body)
raise gen.Return(data) |
def run(self, timeout=-1):
"""
Run the subprocess.
Arguments:
timeout (optional) If a positive real value, then timout after
the given number of seconds.
Raises:
SubprocessError If subprocess has not completed after "timeout"
seconds.
"""
def target():
self.process = subprocess.Popen(self.cmd,
stdout=self.stdout_dest,
stderr=self.stderr_dest,
shell=self.shell)
stdout, stderr = self.process.communicate()
# Decode output if the user wants, and if there is any.
if self.decode_out:
if stdout:
self.stdout = stdout.decode("utf-8")
if stderr:
self.stderr = stderr.decode("utf-8")
thread = threading.Thread(target=target)
thread.start()
if timeout > 0:
thread.join(timeout)
if thread.is_alive():
self.process.terminate()
thread.join()
raise SubprocessError(("Reached timeout after {t} seconds"
.format(t=timeout)))
else:
thread.join()
return self.process.returncode, self.stdout, self.stderr | Run the subprocess.
Arguments:
timeout (optional) If a positive real value, then timout after
the given number of seconds.
Raises:
SubprocessError If subprocess has not completed after "timeout"
seconds. | Below is the the instruction that describes the task:
### Input:
Run the subprocess.
Arguments:
timeout (optional) If a positive real value, then timout after
the given number of seconds.
Raises:
SubprocessError If subprocess has not completed after "timeout"
seconds.
### Response:
def run(self, timeout=-1):
"""
Run the subprocess.
Arguments:
timeout (optional) If a positive real value, then timout after
the given number of seconds.
Raises:
SubprocessError If subprocess has not completed after "timeout"
seconds.
"""
def target():
self.process = subprocess.Popen(self.cmd,
stdout=self.stdout_dest,
stderr=self.stderr_dest,
shell=self.shell)
stdout, stderr = self.process.communicate()
# Decode output if the user wants, and if there is any.
if self.decode_out:
if stdout:
self.stdout = stdout.decode("utf-8")
if stderr:
self.stderr = stderr.decode("utf-8")
thread = threading.Thread(target=target)
thread.start()
if timeout > 0:
thread.join(timeout)
if thread.is_alive():
self.process.terminate()
thread.join()
raise SubprocessError(("Reached timeout after {t} seconds"
.format(t=timeout)))
else:
thread.join()
return self.process.returncode, self.stdout, self.stderr |
def route(app_or_blueprint, context=default_context, **kwargs):
""" attach a transmute route. """
def decorator(fn):
fn = describe(**kwargs)(fn)
transmute_func = TransmuteFunction(fn)
routes, handler = create_routes_and_handler(transmute_func, context)
for r in routes:
# push swagger info.
if not hasattr(app_or_blueprint, SWAGGER_ATTR_NAME):
setattr(app_or_blueprint, SWAGGER_ATTR_NAME, SwaggerSpec())
swagger_obj = getattr(app_or_blueprint, SWAGGER_ATTR_NAME)
swagger_obj.add_func(transmute_func, context)
app_or_blueprint.route(r, methods=transmute_func.methods)(handler)
return handler
return decorator | attach a transmute route. | Below is the the instruction that describes the task:
### Input:
attach a transmute route.
### Response:
def route(app_or_blueprint, context=default_context, **kwargs):
""" attach a transmute route. """
def decorator(fn):
fn = describe(**kwargs)(fn)
transmute_func = TransmuteFunction(fn)
routes, handler = create_routes_and_handler(transmute_func, context)
for r in routes:
# push swagger info.
if not hasattr(app_or_blueprint, SWAGGER_ATTR_NAME):
setattr(app_or_blueprint, SWAGGER_ATTR_NAME, SwaggerSpec())
swagger_obj = getattr(app_or_blueprint, SWAGGER_ATTR_NAME)
swagger_obj.add_func(transmute_func, context)
app_or_blueprint.route(r, methods=transmute_func.methods)(handler)
return handler
return decorator |
def __crawler_start(self):
"""Spawn the first X queued request, where X is the max threads option.
Note:
The main thread will sleep until the crawler is finished. This enables
quiting the application using sigints (see http://stackoverflow.com/a/11816038/2491049).
Note:
`__crawler_stop()` and `__spawn_new_requests()` are called here on the main thread to
prevent thread recursion and deadlocks.
"""
try:
self.__options.callbacks.crawler_before_start()
except Exception as e:
print(e)
print(traceback.format_exc())
self.__spawn_new_requests()
while not self.__stopped:
if self.__should_stop:
self.__crawler_stop()
if self.__should_spawn_new_requests:
self.__spawn_new_requests()
time.sleep(0.1) | Spawn the first X queued request, where X is the max threads option.
Note:
The main thread will sleep until the crawler is finished. This enables
quiting the application using sigints (see http://stackoverflow.com/a/11816038/2491049).
Note:
`__crawler_stop()` and `__spawn_new_requests()` are called here on the main thread to
prevent thread recursion and deadlocks. | Below is the the instruction that describes the task:
### Input:
Spawn the first X queued request, where X is the max threads option.
Note:
The main thread will sleep until the crawler is finished. This enables
quiting the application using sigints (see http://stackoverflow.com/a/11816038/2491049).
Note:
`__crawler_stop()` and `__spawn_new_requests()` are called here on the main thread to
prevent thread recursion and deadlocks.
### Response:
def __crawler_start(self):
"""Spawn the first X queued request, where X is the max threads option.
Note:
The main thread will sleep until the crawler is finished. This enables
quiting the application using sigints (see http://stackoverflow.com/a/11816038/2491049).
Note:
`__crawler_stop()` and `__spawn_new_requests()` are called here on the main thread to
prevent thread recursion and deadlocks.
"""
try:
self.__options.callbacks.crawler_before_start()
except Exception as e:
print(e)
print(traceback.format_exc())
self.__spawn_new_requests()
while not self.__stopped:
if self.__should_stop:
self.__crawler_stop()
if self.__should_spawn_new_requests:
self.__spawn_new_requests()
time.sleep(0.1) |
def soviet_checksum(code):
"""Courtesy of Sir Vlad Lavrov."""
def sum_digits(code, offset=1):
total = 0
for digit, index in zip(code[:7], count(offset)):
total += int(digit) * index
summed = (total / 11 * 11)
return total - summed
check = sum_digits(code, 1)
if check == 10:
check = sum_digits(code, 3)
if check == 10:
return code + '0'
return code + str(check) | Courtesy of Sir Vlad Lavrov. | Below is the the instruction that describes the task:
### Input:
Courtesy of Sir Vlad Lavrov.
### Response:
def soviet_checksum(code):
"""Courtesy of Sir Vlad Lavrov."""
def sum_digits(code, offset=1):
total = 0
for digit, index in zip(code[:7], count(offset)):
total += int(digit) * index
summed = (total / 11 * 11)
return total - summed
check = sum_digits(code, 1)
if check == 10:
check = sum_digits(code, 3)
if check == 10:
return code + '0'
return code + str(check) |
def get_unique_fields(cls):
"""
Return a list of fields with "unique" attribute, which needs to
be augmented by the language.
"""
unique_fields = []
for fname, field in cls.__dict__.items():
if isinstance(field, models.fields.Field):
if getattr(field,'unique',False):
try:
field.unique = False
except AttributeError:
# newer Django defines unique as a property
# that uses _unique to store data. We're
# jumping over the fence by setting _unique,
# so this sucks, but this happens early enough
# to be safe.
field._unique = False
unique_fields.append(fname)
return unique_fields | Return a list of fields with "unique" attribute, which needs to
be augmented by the language. | Below is the the instruction that describes the task:
### Input:
Return a list of fields with "unique" attribute, which needs to
be augmented by the language.
### Response:
def get_unique_fields(cls):
"""
Return a list of fields with "unique" attribute, which needs to
be augmented by the language.
"""
unique_fields = []
for fname, field in cls.__dict__.items():
if isinstance(field, models.fields.Field):
if getattr(field,'unique',False):
try:
field.unique = False
except AttributeError:
# newer Django defines unique as a property
# that uses _unique to store data. We're
# jumping over the fence by setting _unique,
# so this sucks, but this happens early enough
# to be safe.
field._unique = False
unique_fields.append(fname)
return unique_fields |
def _split(self, rect):
"""
Split all max_rects intersecting the rectangle rect into up to
4 new max_rects.
Arguments:
rect (Rectangle): Rectangle
Returns:
split (Rectangle list): List of rectangles resulting from the split
"""
max_rects = collections.deque()
for r in self._max_rects:
if r.intersects(rect):
max_rects.extend(self._generate_splits(r, rect))
else:
max_rects.append(r)
# Add newly generated max_rects
self._max_rects = list(max_rects) | Split all max_rects intersecting the rectangle rect into up to
4 new max_rects.
Arguments:
rect (Rectangle): Rectangle
Returns:
split (Rectangle list): List of rectangles resulting from the split | Below is the the instruction that describes the task:
### Input:
Split all max_rects intersecting the rectangle rect into up to
4 new max_rects.
Arguments:
rect (Rectangle): Rectangle
Returns:
split (Rectangle list): List of rectangles resulting from the split
### Response:
def _split(self, rect):
"""
Split all max_rects intersecting the rectangle rect into up to
4 new max_rects.
Arguments:
rect (Rectangle): Rectangle
Returns:
split (Rectangle list): List of rectangles resulting from the split
"""
max_rects = collections.deque()
for r in self._max_rects:
if r.intersects(rect):
max_rects.extend(self._generate_splits(r, rect))
else:
max_rects.append(r)
# Add newly generated max_rects
self._max_rects = list(max_rects) |
def init_with_context(self, context):
"""
Please refer to
:meth:`~admin_tools.menu.items.MenuItem.init_with_context`
documentation from :class:`~admin_tools.menu.items.MenuItem` class.
"""
from admin_tools.menu.models import Bookmark
for b in Bookmark.objects.filter(user=context['request'].user):
self.children.append(MenuItem(mark_safe(b.title), b.url))
if not len(self.children):
self.enabled = False | Please refer to
:meth:`~admin_tools.menu.items.MenuItem.init_with_context`
documentation from :class:`~admin_tools.menu.items.MenuItem` class. | Below is the the instruction that describes the task:
### Input:
Please refer to
:meth:`~admin_tools.menu.items.MenuItem.init_with_context`
documentation from :class:`~admin_tools.menu.items.MenuItem` class.
### Response:
def init_with_context(self, context):
"""
Please refer to
:meth:`~admin_tools.menu.items.MenuItem.init_with_context`
documentation from :class:`~admin_tools.menu.items.MenuItem` class.
"""
from admin_tools.menu.models import Bookmark
for b in Bookmark.objects.filter(user=context['request'].user):
self.children.append(MenuItem(mark_safe(b.title), b.url))
if not len(self.children):
self.enabled = False |
def get_word_from_data(self, data, offset):
"""Convert two bytes of data to a word (little endian)
'offset' is assumed to index into a word array. So setting it to
N will return a dword out of the data starting at offset N*2.
Returns None if the data can't be turned into a word.
"""
if (offset+1)*2 > len(data):
return None
return struct.unpack('<H', data[offset*2:(offset+1)*2])[0] | Convert two bytes of data to a word (little endian)
'offset' is assumed to index into a word array. So setting it to
N will return a dword out of the data starting at offset N*2.
Returns None if the data can't be turned into a word. | Below is the the instruction that describes the task:
### Input:
Convert two bytes of data to a word (little endian)
'offset' is assumed to index into a word array. So setting it to
N will return a dword out of the data starting at offset N*2.
Returns None if the data can't be turned into a word.
### Response:
def get_word_from_data(self, data, offset):
"""Convert two bytes of data to a word (little endian)
'offset' is assumed to index into a word array. So setting it to
N will return a dword out of the data starting at offset N*2.
Returns None if the data can't be turned into a word.
"""
if (offset+1)*2 > len(data):
return None
return struct.unpack('<H', data[offset*2:(offset+1)*2])[0] |
def split_frame(self, ratios=None, destination_frames=None, seed=None):
"""
Split a frame into distinct subsets of size determined by the given ratios.
The number of subsets is always 1 more than the number of ratios given. Note that
this does not give an exact split. H2O is designed to be efficient on big data
using a probabilistic splitting method rather than an exact split. For example
when specifying a split of 0.75/0.25, H2O will produce a test/train split with
an expected value of 0.75/0.25 rather than exactly 0.75/0.25. On small datasets,
the sizes of the resulting splits will deviate from the expected value more than
on big data, where they will be very close to exact.
:param List[float] ratios: The fractions of rows for each split.
:param List[str] destination_frames: The names of the split frames.
:param int seed: seed for the random number generator
:returns: A list of H2OFrames
"""
assert_is_type(ratios, [numeric], None)
assert_is_type(destination_frames, [str], None)
assert_is_type(seed, int, None)
if ratios is None:
ratios = [0.75]
if not ratios:
raise ValueError("Ratios array may not be empty")
if destination_frames is not None:
if len(ratios) + 1 != len(destination_frames):
raise ValueError("The number of provided destination_frames must be one more "
"than the number of provided ratios")
num_slices = len(ratios) + 1
boundaries = []
last_boundary = 0
i = 0
while i < num_slices - 1:
ratio = ratios[i]
if ratio < 0:
raise ValueError("Ratio must be greater than 0")
boundary = last_boundary + ratio
if boundary >= 1.0:
raise ValueError("Ratios must add up to less than 1.0")
boundaries.append(boundary)
last_boundary = boundary
i += 1
splits = []
tmp_runif = self.runif(seed)
tmp_runif.frame_id = "%s_splitter" % _py_tmp_key(h2o.connection().session_id)
i = 0
while i < num_slices:
if i == 0:
# lower_boundary is 0.0
upper_boundary = boundaries[i]
tmp_slice = self[(tmp_runif <= upper_boundary), :]
elif i == num_slices - 1:
lower_boundary = boundaries[i - 1]
# upper_boundary is 1.0
tmp_slice = self[(tmp_runif > lower_boundary), :]
else:
lower_boundary = boundaries[i - 1]
upper_boundary = boundaries[i]
tmp_slice = self[((tmp_runif > lower_boundary) & (tmp_runif <= upper_boundary)), :]
if destination_frames is None:
splits.append(tmp_slice)
else:
destination_frame_id = destination_frames[i]
tmp_slice.frame_id = destination_frame_id
splits.append(tmp_slice)
i += 1
del tmp_runif
return splits | Split a frame into distinct subsets of size determined by the given ratios.
The number of subsets is always 1 more than the number of ratios given. Note that
this does not give an exact split. H2O is designed to be efficient on big data
using a probabilistic splitting method rather than an exact split. For example
when specifying a split of 0.75/0.25, H2O will produce a test/train split with
an expected value of 0.75/0.25 rather than exactly 0.75/0.25. On small datasets,
the sizes of the resulting splits will deviate from the expected value more than
on big data, where they will be very close to exact.
:param List[float] ratios: The fractions of rows for each split.
:param List[str] destination_frames: The names of the split frames.
:param int seed: seed for the random number generator
:returns: A list of H2OFrames | Below is the the instruction that describes the task:
### Input:
Split a frame into distinct subsets of size determined by the given ratios.
The number of subsets is always 1 more than the number of ratios given. Note that
this does not give an exact split. H2O is designed to be efficient on big data
using a probabilistic splitting method rather than an exact split. For example
when specifying a split of 0.75/0.25, H2O will produce a test/train split with
an expected value of 0.75/0.25 rather than exactly 0.75/0.25. On small datasets,
the sizes of the resulting splits will deviate from the expected value more than
on big data, where they will be very close to exact.
:param List[float] ratios: The fractions of rows for each split.
:param List[str] destination_frames: The names of the split frames.
:param int seed: seed for the random number generator
:returns: A list of H2OFrames
### Response:
def split_frame(self, ratios=None, destination_frames=None, seed=None):
"""
Split a frame into distinct subsets of size determined by the given ratios.
The number of subsets is always 1 more than the number of ratios given. Note that
this does not give an exact split. H2O is designed to be efficient on big data
using a probabilistic splitting method rather than an exact split. For example
when specifying a split of 0.75/0.25, H2O will produce a test/train split with
an expected value of 0.75/0.25 rather than exactly 0.75/0.25. On small datasets,
the sizes of the resulting splits will deviate from the expected value more than
on big data, where they will be very close to exact.
:param List[float] ratios: The fractions of rows for each split.
:param List[str] destination_frames: The names of the split frames.
:param int seed: seed for the random number generator
:returns: A list of H2OFrames
"""
assert_is_type(ratios, [numeric], None)
assert_is_type(destination_frames, [str], None)
assert_is_type(seed, int, None)
if ratios is None:
ratios = [0.75]
if not ratios:
raise ValueError("Ratios array may not be empty")
if destination_frames is not None:
if len(ratios) + 1 != len(destination_frames):
raise ValueError("The number of provided destination_frames must be one more "
"than the number of provided ratios")
num_slices = len(ratios) + 1
boundaries = []
last_boundary = 0
i = 0
while i < num_slices - 1:
ratio = ratios[i]
if ratio < 0:
raise ValueError("Ratio must be greater than 0")
boundary = last_boundary + ratio
if boundary >= 1.0:
raise ValueError("Ratios must add up to less than 1.0")
boundaries.append(boundary)
last_boundary = boundary
i += 1
splits = []
tmp_runif = self.runif(seed)
tmp_runif.frame_id = "%s_splitter" % _py_tmp_key(h2o.connection().session_id)
i = 0
while i < num_slices:
if i == 0:
# lower_boundary is 0.0
upper_boundary = boundaries[i]
tmp_slice = self[(tmp_runif <= upper_boundary), :]
elif i == num_slices - 1:
lower_boundary = boundaries[i - 1]
# upper_boundary is 1.0
tmp_slice = self[(tmp_runif > lower_boundary), :]
else:
lower_boundary = boundaries[i - 1]
upper_boundary = boundaries[i]
tmp_slice = self[((tmp_runif > lower_boundary) & (tmp_runif <= upper_boundary)), :]
if destination_frames is None:
splits.append(tmp_slice)
else:
destination_frame_id = destination_frames[i]
tmp_slice.frame_id = destination_frame_id
splits.append(tmp_slice)
i += 1
del tmp_runif
return splits |
def calculate_eclipses(M1s, M2s, R1s, R2s, mag1s, mag2s,
u11s=0.394, u21s=0.296, u12s=0.394, u22s=0.296,
Ps=None, period=None, logperkde=RAGHAVAN_LOGPERKDE,
incs=None, eccs=None,
mininc=None, calc_mininc=True,
maxecc=0.97, ecc_fn=draw_eccs,
band='Kepler',
return_probability_only=False, return_indices=True,
MAfn=None):
"""Returns random eclipse parameters for provided inputs
:param M1s, M2s, R1s, R2s, mag1s, mag2s: (array-like)
Primary and secondary properties (mass, radius, magnitude)
:param u11s, u21s, u12s, u22s: (optional)
Limb darkening parameters (u11 = u1 for star 1, u21 = u2 for star 1, etc.)
:param Ps: (array-like, optional)
Orbital periods; same size as ``M1s``, etc.
If only a single period is desired, use ``period``.
:param period: (optional)
Orbital period; use this keyword if only a single period is desired.
:param logperkde: (optional)
If neither ``Ps`` nor ``period`` is provided, then periods will be
randomly generated according to this log-period distribution.
Default is taken from the Raghavan (2010) period distribution.
:param incs, eccs: (optional)
Inclinations and eccentricities. If not passed, they will be generated.
Eccentricities will be generated according to ``ecc_fn``; inclinations
will be randomly generated out to ``mininc``.
:param mininc: (optional)
Minimum inclination to generate. Useful if you want to enhance
efficiency by only generating mostly eclipsing, instead of mostly
non-eclipsing systems. If not provided and ``calc_mininc`` is
``True``, then this will be calculated based on inputs.
:param calc_mininc: (optional)
Whether to calculate ``mininc`` based on inputs. If truly isotropic
inclinations are desired, set this to ``False``.
:param maxecc: (optional)
Maximum eccentricity to generate.
:param ecc_fn: (callable, optional)
Orbital eccentricity generating function. Must return ``n`` orbital
eccentricities generated according to provided period(s)::
eccs = ecc_fn(n,Ps)
Defaults to :func:`stars.utils.draw_eccs`.
:param band: (optional)
Photometric bandpass in which eclipse is observed.
:param return_probability_only: (optional)
If ``True``, then will return only the average eclipse probability
of population.
:param return_indices: (optional)
If ``True``, returns the indices of the original input arrays
that the output ``DataFrame`` corresponds to. **This behavior
will/should be changed to just return a ``DataFrame`` of the same
length as inputs...**
:param MAfn: (optional)
:class:`transit_basic.MAInterpolationFunction` object.
If not passed, then one with default parameters will
be created.
:return:
* [``wany``: indices describing which of the original input
arrays the output ``DataFrame`` corresponds to.
* ``df``: ``DataFrame`` with the following columns:
``[{band}_mag_tot, P, ecc, inc, w, dpri, dsec,
T14_pri, T23_pri, T14_sec, T23_sec, b_pri,
b_sec, {band}_mag_1, {band}_mag_2, fluxfrac_1,
fluxfrac_2, switched, u1_1, u2_1, u1_2, u2_2]``.
**N.B. that this will be shorter than your input arrays,
because not everything will eclipse; this behavior
will likely be changed in the future because it's confusing.**
* ``(prob, dprob)`` Eclipse probability with Poisson uncertainty
"""
if MAfn is None:
logging.warning('MAInterpolationFunction not passed, so generating one...')
MAfn = MAInterpolationFunction(nzs=200,nps=400,pmin=0.007,pmax=1/0.007)
M1s = np.atleast_1d(M1s)
M2s = np.atleast_1d(M2s)
R1s = np.atleast_1d(R1s)
R2s = np.atleast_1d(R2s)
nbad = (np.isnan(M1s) | np.isnan(M2s) | np.isnan(R1s) | np.isnan(R2s)).sum()
if nbad > 0:
logging.warning('{} M1s are nan'.format(np.isnan(M1s).sum()))
logging.warning('{} M2s are nan'.format(np.isnan(M2s).sum()))
logging.warning('{} R1s are nan'.format(np.isnan(R1s).sum()))
logging.warning('{} R2s are nan'.format(np.isnan(R2s).sum()))
mag1s = mag1s * np.ones_like(M1s)
mag2s = mag2s * np.ones_like(M1s)
u11s = u11s * np.ones_like(M1s)
u21s = u21s * np.ones_like(M1s)
u12s = u12s * np.ones_like(M1s)
u22s = u22s * np.ones_like(M1s)
n = np.size(M1s)
#a bit clunky here, but works.
simPs = False
if period:
Ps = np.ones(n)*period
else:
if Ps is None:
Ps = 10**(logperkde.rvs(n))
simPs = True
simeccs = False
if eccs is None:
if not simPs and period is not None:
eccs = ecc_fn(n,period,maxecc=maxecc)
else:
eccs = ecc_fn(n,Ps,maxecc=maxecc)
simeccs = True
bad_Ps = np.isnan(Ps)
if bad_Ps.sum()>0:
logging.warning('{} nan periods. why?'.format(bad_Ps.sum()))
bad_eccs = np.isnan(eccs)
if bad_eccs.sum()>0:
logging.warning('{} nan eccentricities. why?'.format(bad_eccs.sum()))
semimajors = semimajor(Ps, M1s+M2s)*AU #in AU
#check to see if there are simulated instances that are
# too close; i.e. periastron sends secondary within roche
# lobe of primary
tooclose = withinroche(semimajors*(1-eccs)/AU,M1s,R1s,M2s,R2s)
ntooclose = tooclose.sum()
tries = 0
maxtries=5
if simPs:
while ntooclose > 0:
lastntooclose=ntooclose
Ps[tooclose] = 10**(logperkde.rvs(ntooclose))
if simeccs:
eccs[tooclose] = draw_eccs(ntooclose,Ps[tooclose])
semimajors[tooclose] = semimajor(Ps[tooclose],M1s[tooclose]+M2s[tooclose])*AU
tooclose = withinroche(semimajors*(1-eccs)/AU,M1s,R1s,M2s,R2s)
ntooclose = tooclose.sum()
if ntooclose==lastntooclose: #prevent infinite loop
tries += 1
if tries > maxtries:
logging.info('{} binaries are "too close"; gave up trying to fix.'.format(ntooclose))
break
else:
while ntooclose > 0:
lastntooclose=ntooclose
if simeccs:
eccs[tooclose] = draw_eccs(ntooclose,Ps[tooclose])
semimajors[tooclose] = semimajor(Ps[tooclose],M1s[tooclose]+M2s[tooclose])*AU
#wtooclose = where(semimajors*(1-eccs) < 2*(R1s+R2s)*RSUN)
tooclose = withinroche(semimajors*(1-eccs)/AU,M1s,R1s,M2s,R2s)
ntooclose = tooclose.sum()
if ntooclose==lastntooclose: #prevent infinite loop
tries += 1
if tries > maxtries:
logging.info('{} binaries are "too close"; gave up trying to fix.'.format(ntooclose))
break
#randomize inclinations, either full range, or within restricted range
if mininc is None and calc_mininc:
mininc = minimum_inclination(Ps, M1s, M2s, R1s, R2s)
if incs is None:
if mininc is None:
incs = np.arccos(np.random.random(n)) #random inclinations in radians
else:
incs = np.arccos(np.random.random(n)*np.cos(mininc*np.pi/180))
if mininc:
prob = np.cos(mininc*np.pi/180)
else:
prob = 1
logging.debug('initial probability given mininc starting at {}'.format(prob))
ws = np.random.random(n)*2*np.pi
switched = (R2s > R1s)
R_large = switched*R2s + ~switched*R1s
R_small = switched*R1s + ~switched*R2s
b_tras = semimajors*np.cos(incs)/(R_large*RSUN) * (1-eccs**2)/(1 + eccs*np.sin(ws))
b_occs = semimajors*np.cos(incs)/(R_large*RSUN) * (1-eccs**2)/(1 - eccs*np.sin(ws))
b_tras[tooclose] = np.inf
b_occs[tooclose] = np.inf
ks = R_small/R_large
Rtots = (R_small + R_large)/R_large
tra = (b_tras < Rtots)
occ = (b_occs < Rtots)
nany = (tra | occ).sum()
peb = nany/float(n)
prob *= peb
if return_probability_only:
return prob,prob*np.sqrt(nany)/n
i = (tra | occ)
wany = np.where(i)
P,M1,M2,R1,R2,mag1,mag2,inc,ecc,w = Ps[i],M1s[i],M2s[i],R1s[i],R2s[i],\
mag1s[i],mag2s[i],incs[i]*180/np.pi,eccs[i],ws[i]*180/np.pi
a = semimajors[i] #in cm already
b_tra = b_tras[i]
b_occ = b_occs[i]
u11 = u11s[i]
u21 = u21s[i]
u12 = u12s[i]
u22 = u22s[i]
switched = (R2 > R1)
R_large = switched*R2 + ~switched*R1
R_small = switched*R1 + ~switched*R2
k = R_small/R_large
#calculate durations
T14_tra = P/np.pi*np.arcsin(R_large*RSUN/a * np.sqrt((1+k)**2 - b_tra**2)/np.sin(inc*np.pi/180)) *\
np.sqrt(1-ecc**2)/(1+ecc*np.sin(w*np.pi/180)) #*24*60
T23_tra = P/np.pi*np.arcsin(R_large*RSUN/a * np.sqrt((1-k)**2 - b_tra**2)/np.sin(inc*np.pi/180)) *\
np.sqrt(1-ecc**2)/(1+ecc*np.sin(w*np.pi/180)) #*24*60
T14_occ = P/np.pi*np.arcsin(R_large*RSUN/a * np.sqrt((1+k)**2 - b_occ**2)/np.sin(inc*np.pi/180)) *\
np.sqrt(1-ecc**2)/(1-ecc*np.sin(w*np.pi/180)) #*24*60
T23_occ = P/np.pi*np.arcsin(R_large*RSUN/a * np.sqrt((1-k)**2 - b_occ**2)/np.sin(inc*np.pi/180)) *\
np.sqrt(1-ecc**2)/(1-ecc*np.sin(w*np.pi/180)) #*24*60
bad = (np.isnan(T14_tra) & np.isnan(T14_occ))
if bad.sum() > 0:
logging.error('Something snuck through with no eclipses!')
logging.error('k: {}'.format(k[bad]))
logging.error('b_tra: {}'.format(b_tra[bad]))
logging.error('b_occ: {}'.format(b_occ[bad]))
logging.error('T14_tra: {}'.format(T14_tra[bad]))
logging.error('T14_occ: {}'.format(T14_occ[bad]))
logging.error('under sqrt (tra): {}'.format((1+k[bad])**2 - b_tra[bad]**2))
logging.error('under sqrt (occ): {}'.format((1+k[bad])**2 - b_occ[bad]**2))
logging.error('eccsq: {}'.format(ecc[bad]**2))
logging.error('a in Rsun: {}'.format(a[bad]/RSUN))
logging.error('R_large: {}'.format(R_large[bad]))
logging.error('R_small: {}'.format(R_small[bad]))
logging.error('P: {}'.format(P[bad]))
logging.error('total M: {}'.format(M1[bad]+M2[bad]))
T14_tra[(np.isnan(T14_tra))] = 0
T23_tra[(np.isnan(T23_tra))] = 0
T14_occ[(np.isnan(T14_occ))] = 0
T23_occ[(np.isnan(T23_occ))] = 0
#calling mandel-agol
ftra = MAfn(k,b_tra,u11,u21)
focc = MAfn(1/k,b_occ/k,u12,u22)
#fix those with k or 1/k out of range of MAFN....or do it in MAfn eventually?
wtrabad = np.where((k < MAfn.pmin) | (k > MAfn.pmax))
woccbad = np.where((1/k < MAfn.pmin) | (1/k > MAfn.pmax))
for ind in wtrabad[0]:
ftra[ind] = occultquad(b_tra[ind],u11[ind],u21[ind],k[ind])
for ind in woccbad[0]:
focc[ind] = occultquad(b_occ[ind]/k[ind],u12[ind],u22[ind],1/k[ind])
F1 = 10**(-0.4*mag1) + switched*10**(-0.4*mag2)
F2 = 10**(-0.4*mag2) + switched*10**(-0.4*mag1)
dtra = 1-(F2 + F1*ftra)/(F1+F2)
docc = 1-(F1 + F2*focc)/(F1+F2)
totmag = -2.5*np.log10(F1+F2)
#wswitched = where(switched)
dtra[switched],docc[switched] = (docc[switched],dtra[switched])
T14_tra[switched],T14_occ[switched] = (T14_occ[switched],T14_tra[switched])
T23_tra[switched],T23_occ[switched] = (T23_occ[switched],T23_tra[switched])
b_tra[switched],b_occ[switched] = (b_occ[switched],b_tra[switched])
#mag1[wswitched],mag2[wswitched] = (mag2[wswitched],mag1[wswitched])
F1[switched],F2[switched] = (F2[switched],F1[switched])
u11[switched],u12[switched] = (u12[switched],u11[switched])
u21[switched],u22[switched] = (u22[switched],u21[switched])
dtra[(np.isnan(dtra))] = 0
docc[(np.isnan(docc))] = 0
if np.any(np.isnan(ecc)):
logging.warning('{} nans in eccentricity. why?'.format(np.isnan(ecc).sum()))
df = pd.DataFrame({'{}_mag_tot'.format(band) : totmag,
'P':P, 'ecc':ecc, 'inc':inc, 'w':w,
'dpri':dtra, 'dsec':docc,
'T14_pri':T14_tra, 'T23_pri':T23_tra,
'T14_sec':T14_occ, 'T23_sec':T23_occ,
'b_pri':b_tra, 'b_sec':b_occ,
'{}_mag_1'.format(band) : mag1,
'{}_mag_2'.format(band) : mag2,
'fluxfrac_1':F1/(F1+F2),
'fluxfrac_2':F2/(F1+F2),
'switched':switched,
'u1_1':u11, 'u2_1':u21, 'u1_2':u12, 'u2_2':u22})
df.reset_index(inplace=True)
logging.debug('final prob: {}'.format(prob))
if return_indices:
return wany, df, (prob, prob*np.sqrt(nany)/n)
else:
return df, (prob, prob*np.sqrt(nany)/n) | Returns random eclipse parameters for provided inputs
:param M1s, M2s, R1s, R2s, mag1s, mag2s: (array-like)
Primary and secondary properties (mass, radius, magnitude)
:param u11s, u21s, u12s, u22s: (optional)
Limb darkening parameters (u11 = u1 for star 1, u21 = u2 for star 1, etc.)
:param Ps: (array-like, optional)
Orbital periods; same size as ``M1s``, etc.
If only a single period is desired, use ``period``.
:param period: (optional)
Orbital period; use this keyword if only a single period is desired.
:param logperkde: (optional)
If neither ``Ps`` nor ``period`` is provided, then periods will be
randomly generated according to this log-period distribution.
Default is taken from the Raghavan (2010) period distribution.
:param incs, eccs: (optional)
Inclinations and eccentricities. If not passed, they will be generated.
Eccentricities will be generated according to ``ecc_fn``; inclinations
will be randomly generated out to ``mininc``.
:param mininc: (optional)
Minimum inclination to generate. Useful if you want to enhance
efficiency by only generating mostly eclipsing, instead of mostly
non-eclipsing systems. If not provided and ``calc_mininc`` is
``True``, then this will be calculated based on inputs.
:param calc_mininc: (optional)
Whether to calculate ``mininc`` based on inputs. If truly isotropic
inclinations are desired, set this to ``False``.
:param maxecc: (optional)
Maximum eccentricity to generate.
:param ecc_fn: (callable, optional)
Orbital eccentricity generating function. Must return ``n`` orbital
eccentricities generated according to provided period(s)::
eccs = ecc_fn(n,Ps)
Defaults to :func:`stars.utils.draw_eccs`.
:param band: (optional)
Photometric bandpass in which eclipse is observed.
:param return_probability_only: (optional)
If ``True``, then will return only the average eclipse probability
of population.
:param return_indices: (optional)
If ``True``, returns the indices of the original input arrays
that the output ``DataFrame`` corresponds to. **This behavior
will/should be changed to just return a ``DataFrame`` of the same
length as inputs...**
:param MAfn: (optional)
:class:`transit_basic.MAInterpolationFunction` object.
If not passed, then one with default parameters will
be created.
:return:
* [``wany``: indices describing which of the original input
arrays the output ``DataFrame`` corresponds to.
* ``df``: ``DataFrame`` with the following columns:
``[{band}_mag_tot, P, ecc, inc, w, dpri, dsec,
T14_pri, T23_pri, T14_sec, T23_sec, b_pri,
b_sec, {band}_mag_1, {band}_mag_2, fluxfrac_1,
fluxfrac_2, switched, u1_1, u2_1, u1_2, u2_2]``.
**N.B. that this will be shorter than your input arrays,
because not everything will eclipse; this behavior
will likely be changed in the future because it's confusing.**
* ``(prob, dprob)`` Eclipse probability with Poisson uncertainty | Below is the the instruction that describes the task:
### Input:
Returns random eclipse parameters for provided inputs
:param M1s, M2s, R1s, R2s, mag1s, mag2s: (array-like)
Primary and secondary properties (mass, radius, magnitude)
:param u11s, u21s, u12s, u22s: (optional)
Limb darkening parameters (u11 = u1 for star 1, u21 = u2 for star 1, etc.)
:param Ps: (array-like, optional)
Orbital periods; same size as ``M1s``, etc.
If only a single period is desired, use ``period``.
:param period: (optional)
Orbital period; use this keyword if only a single period is desired.
:param logperkde: (optional)
If neither ``Ps`` nor ``period`` is provided, then periods will be
randomly generated according to this log-period distribution.
Default is taken from the Raghavan (2010) period distribution.
:param incs, eccs: (optional)
Inclinations and eccentricities. If not passed, they will be generated.
Eccentricities will be generated according to ``ecc_fn``; inclinations
will be randomly generated out to ``mininc``.
:param mininc: (optional)
Minimum inclination to generate. Useful if you want to enhance
efficiency by only generating mostly eclipsing, instead of mostly
non-eclipsing systems. If not provided and ``calc_mininc`` is
``True``, then this will be calculated based on inputs.
:param calc_mininc: (optional)
Whether to calculate ``mininc`` based on inputs. If truly isotropic
inclinations are desired, set this to ``False``.
:param maxecc: (optional)
Maximum eccentricity to generate.
:param ecc_fn: (callable, optional)
Orbital eccentricity generating function. Must return ``n`` orbital
eccentricities generated according to provided period(s)::
eccs = ecc_fn(n,Ps)
Defaults to :func:`stars.utils.draw_eccs`.
:param band: (optional)
Photometric bandpass in which eclipse is observed.
:param return_probability_only: (optional)
If ``True``, then will return only the average eclipse probability
of population.
:param return_indices: (optional)
If ``True``, returns the indices of the original input arrays
that the output ``DataFrame`` corresponds to. **This behavior
will/should be changed to just return a ``DataFrame`` of the same
length as inputs...**
:param MAfn: (optional)
:class:`transit_basic.MAInterpolationFunction` object.
If not passed, then one with default parameters will
be created.
:return:
* [``wany``: indices describing which of the original input
arrays the output ``DataFrame`` corresponds to.
* ``df``: ``DataFrame`` with the following columns:
``[{band}_mag_tot, P, ecc, inc, w, dpri, dsec,
T14_pri, T23_pri, T14_sec, T23_sec, b_pri,
b_sec, {band}_mag_1, {band}_mag_2, fluxfrac_1,
fluxfrac_2, switched, u1_1, u2_1, u1_2, u2_2]``.
**N.B. that this will be shorter than your input arrays,
because not everything will eclipse; this behavior
will likely be changed in the future because it's confusing.**
* ``(prob, dprob)`` Eclipse probability with Poisson uncertainty
### Response:
def calculate_eclipses(M1s, M2s, R1s, R2s, mag1s, mag2s,
u11s=0.394, u21s=0.296, u12s=0.394, u22s=0.296,
Ps=None, period=None, logperkde=RAGHAVAN_LOGPERKDE,
incs=None, eccs=None,
mininc=None, calc_mininc=True,
maxecc=0.97, ecc_fn=draw_eccs,
band='Kepler',
return_probability_only=False, return_indices=True,
MAfn=None):
"""Returns random eclipse parameters for provided inputs
:param M1s, M2s, R1s, R2s, mag1s, mag2s: (array-like)
Primary and secondary properties (mass, radius, magnitude)
:param u11s, u21s, u12s, u22s: (optional)
Limb darkening parameters (u11 = u1 for star 1, u21 = u2 for star 1, etc.)
:param Ps: (array-like, optional)
Orbital periods; same size as ``M1s``, etc.
If only a single period is desired, use ``period``.
:param period: (optional)
Orbital period; use this keyword if only a single period is desired.
:param logperkde: (optional)
If neither ``Ps`` nor ``period`` is provided, then periods will be
randomly generated according to this log-period distribution.
Default is taken from the Raghavan (2010) period distribution.
:param incs, eccs: (optional)
Inclinations and eccentricities. If not passed, they will be generated.
Eccentricities will be generated according to ``ecc_fn``; inclinations
will be randomly generated out to ``mininc``.
:param mininc: (optional)
Minimum inclination to generate. Useful if you want to enhance
efficiency by only generating mostly eclipsing, instead of mostly
non-eclipsing systems. If not provided and ``calc_mininc`` is
``True``, then this will be calculated based on inputs.
:param calc_mininc: (optional)
Whether to calculate ``mininc`` based on inputs. If truly isotropic
inclinations are desired, set this to ``False``.
:param maxecc: (optional)
Maximum eccentricity to generate.
:param ecc_fn: (callable, optional)
Orbital eccentricity generating function. Must return ``n`` orbital
eccentricities generated according to provided period(s)::
eccs = ecc_fn(n,Ps)
Defaults to :func:`stars.utils.draw_eccs`.
:param band: (optional)
Photometric bandpass in which eclipse is observed.
:param return_probability_only: (optional)
If ``True``, then will return only the average eclipse probability
of population.
:param return_indices: (optional)
If ``True``, returns the indices of the original input arrays
that the output ``DataFrame`` corresponds to. **This behavior
will/should be changed to just return a ``DataFrame`` of the same
length as inputs...**
:param MAfn: (optional)
:class:`transit_basic.MAInterpolationFunction` object.
If not passed, then one with default parameters will
be created.
:return:
* [``wany``: indices describing which of the original input
arrays the output ``DataFrame`` corresponds to.
* ``df``: ``DataFrame`` with the following columns:
``[{band}_mag_tot, P, ecc, inc, w, dpri, dsec,
T14_pri, T23_pri, T14_sec, T23_sec, b_pri,
b_sec, {band}_mag_1, {band}_mag_2, fluxfrac_1,
fluxfrac_2, switched, u1_1, u2_1, u1_2, u2_2]``.
**N.B. that this will be shorter than your input arrays,
because not everything will eclipse; this behavior
will likely be changed in the future because it's confusing.**
* ``(prob, dprob)`` Eclipse probability with Poisson uncertainty
"""
if MAfn is None:
logging.warning('MAInterpolationFunction not passed, so generating one...')
MAfn = MAInterpolationFunction(nzs=200,nps=400,pmin=0.007,pmax=1/0.007)
M1s = np.atleast_1d(M1s)
M2s = np.atleast_1d(M2s)
R1s = np.atleast_1d(R1s)
R2s = np.atleast_1d(R2s)
nbad = (np.isnan(M1s) | np.isnan(M2s) | np.isnan(R1s) | np.isnan(R2s)).sum()
if nbad > 0:
logging.warning('{} M1s are nan'.format(np.isnan(M1s).sum()))
logging.warning('{} M2s are nan'.format(np.isnan(M2s).sum()))
logging.warning('{} R1s are nan'.format(np.isnan(R1s).sum()))
logging.warning('{} R2s are nan'.format(np.isnan(R2s).sum()))
mag1s = mag1s * np.ones_like(M1s)
mag2s = mag2s * np.ones_like(M1s)
u11s = u11s * np.ones_like(M1s)
u21s = u21s * np.ones_like(M1s)
u12s = u12s * np.ones_like(M1s)
u22s = u22s * np.ones_like(M1s)
n = np.size(M1s)
#a bit clunky here, but works.
simPs = False
if period:
Ps = np.ones(n)*period
else:
if Ps is None:
Ps = 10**(logperkde.rvs(n))
simPs = True
simeccs = False
if eccs is None:
if not simPs and period is not None:
eccs = ecc_fn(n,period,maxecc=maxecc)
else:
eccs = ecc_fn(n,Ps,maxecc=maxecc)
simeccs = True
bad_Ps = np.isnan(Ps)
if bad_Ps.sum()>0:
logging.warning('{} nan periods. why?'.format(bad_Ps.sum()))
bad_eccs = np.isnan(eccs)
if bad_eccs.sum()>0:
logging.warning('{} nan eccentricities. why?'.format(bad_eccs.sum()))
semimajors = semimajor(Ps, M1s+M2s)*AU #in AU
#check to see if there are simulated instances that are
# too close; i.e. periastron sends secondary within roche
# lobe of primary
tooclose = withinroche(semimajors*(1-eccs)/AU,M1s,R1s,M2s,R2s)
ntooclose = tooclose.sum()
tries = 0
maxtries=5
if simPs:
while ntooclose > 0:
lastntooclose=ntooclose
Ps[tooclose] = 10**(logperkde.rvs(ntooclose))
if simeccs:
eccs[tooclose] = draw_eccs(ntooclose,Ps[tooclose])
semimajors[tooclose] = semimajor(Ps[tooclose],M1s[tooclose]+M2s[tooclose])*AU
tooclose = withinroche(semimajors*(1-eccs)/AU,M1s,R1s,M2s,R2s)
ntooclose = tooclose.sum()
if ntooclose==lastntooclose: #prevent infinite loop
tries += 1
if tries > maxtries:
logging.info('{} binaries are "too close"; gave up trying to fix.'.format(ntooclose))
break
else:
while ntooclose > 0:
lastntooclose=ntooclose
if simeccs:
eccs[tooclose] = draw_eccs(ntooclose,Ps[tooclose])
semimajors[tooclose] = semimajor(Ps[tooclose],M1s[tooclose]+M2s[tooclose])*AU
#wtooclose = where(semimajors*(1-eccs) < 2*(R1s+R2s)*RSUN)
tooclose = withinroche(semimajors*(1-eccs)/AU,M1s,R1s,M2s,R2s)
ntooclose = tooclose.sum()
if ntooclose==lastntooclose: #prevent infinite loop
tries += 1
if tries > maxtries:
logging.info('{} binaries are "too close"; gave up trying to fix.'.format(ntooclose))
break
#randomize inclinations, either full range, or within restricted range
if mininc is None and calc_mininc:
mininc = minimum_inclination(Ps, M1s, M2s, R1s, R2s)
if incs is None:
if mininc is None:
incs = np.arccos(np.random.random(n)) #random inclinations in radians
else:
incs = np.arccos(np.random.random(n)*np.cos(mininc*np.pi/180))
if mininc:
prob = np.cos(mininc*np.pi/180)
else:
prob = 1
logging.debug('initial probability given mininc starting at {}'.format(prob))
ws = np.random.random(n)*2*np.pi
switched = (R2s > R1s)
R_large = switched*R2s + ~switched*R1s
R_small = switched*R1s + ~switched*R2s
b_tras = semimajors*np.cos(incs)/(R_large*RSUN) * (1-eccs**2)/(1 + eccs*np.sin(ws))
b_occs = semimajors*np.cos(incs)/(R_large*RSUN) * (1-eccs**2)/(1 - eccs*np.sin(ws))
b_tras[tooclose] = np.inf
b_occs[tooclose] = np.inf
ks = R_small/R_large
Rtots = (R_small + R_large)/R_large
tra = (b_tras < Rtots)
occ = (b_occs < Rtots)
nany = (tra | occ).sum()
peb = nany/float(n)
prob *= peb
if return_probability_only:
return prob,prob*np.sqrt(nany)/n
i = (tra | occ)
wany = np.where(i)
P,M1,M2,R1,R2,mag1,mag2,inc,ecc,w = Ps[i],M1s[i],M2s[i],R1s[i],R2s[i],\
mag1s[i],mag2s[i],incs[i]*180/np.pi,eccs[i],ws[i]*180/np.pi
a = semimajors[i] #in cm already
b_tra = b_tras[i]
b_occ = b_occs[i]
u11 = u11s[i]
u21 = u21s[i]
u12 = u12s[i]
u22 = u22s[i]
switched = (R2 > R1)
R_large = switched*R2 + ~switched*R1
R_small = switched*R1 + ~switched*R2
k = R_small/R_large
#calculate durations
T14_tra = P/np.pi*np.arcsin(R_large*RSUN/a * np.sqrt((1+k)**2 - b_tra**2)/np.sin(inc*np.pi/180)) *\
np.sqrt(1-ecc**2)/(1+ecc*np.sin(w*np.pi/180)) #*24*60
T23_tra = P/np.pi*np.arcsin(R_large*RSUN/a * np.sqrt((1-k)**2 - b_tra**2)/np.sin(inc*np.pi/180)) *\
np.sqrt(1-ecc**2)/(1+ecc*np.sin(w*np.pi/180)) #*24*60
T14_occ = P/np.pi*np.arcsin(R_large*RSUN/a * np.sqrt((1+k)**2 - b_occ**2)/np.sin(inc*np.pi/180)) *\
np.sqrt(1-ecc**2)/(1-ecc*np.sin(w*np.pi/180)) #*24*60
T23_occ = P/np.pi*np.arcsin(R_large*RSUN/a * np.sqrt((1-k)**2 - b_occ**2)/np.sin(inc*np.pi/180)) *\
np.sqrt(1-ecc**2)/(1-ecc*np.sin(w*np.pi/180)) #*24*60
bad = (np.isnan(T14_tra) & np.isnan(T14_occ))
if bad.sum() > 0:
logging.error('Something snuck through with no eclipses!')
logging.error('k: {}'.format(k[bad]))
logging.error('b_tra: {}'.format(b_tra[bad]))
logging.error('b_occ: {}'.format(b_occ[bad]))
logging.error('T14_tra: {}'.format(T14_tra[bad]))
logging.error('T14_occ: {}'.format(T14_occ[bad]))
logging.error('under sqrt (tra): {}'.format((1+k[bad])**2 - b_tra[bad]**2))
logging.error('under sqrt (occ): {}'.format((1+k[bad])**2 - b_occ[bad]**2))
logging.error('eccsq: {}'.format(ecc[bad]**2))
logging.error('a in Rsun: {}'.format(a[bad]/RSUN))
logging.error('R_large: {}'.format(R_large[bad]))
logging.error('R_small: {}'.format(R_small[bad]))
logging.error('P: {}'.format(P[bad]))
logging.error('total M: {}'.format(M1[bad]+M2[bad]))
T14_tra[(np.isnan(T14_tra))] = 0
T23_tra[(np.isnan(T23_tra))] = 0
T14_occ[(np.isnan(T14_occ))] = 0
T23_occ[(np.isnan(T23_occ))] = 0
#calling mandel-agol
ftra = MAfn(k,b_tra,u11,u21)
focc = MAfn(1/k,b_occ/k,u12,u22)
#fix those with k or 1/k out of range of MAFN....or do it in MAfn eventually?
wtrabad = np.where((k < MAfn.pmin) | (k > MAfn.pmax))
woccbad = np.where((1/k < MAfn.pmin) | (1/k > MAfn.pmax))
for ind in wtrabad[0]:
ftra[ind] = occultquad(b_tra[ind],u11[ind],u21[ind],k[ind])
for ind in woccbad[0]:
focc[ind] = occultquad(b_occ[ind]/k[ind],u12[ind],u22[ind],1/k[ind])
F1 = 10**(-0.4*mag1) + switched*10**(-0.4*mag2)
F2 = 10**(-0.4*mag2) + switched*10**(-0.4*mag1)
dtra = 1-(F2 + F1*ftra)/(F1+F2)
docc = 1-(F1 + F2*focc)/(F1+F2)
totmag = -2.5*np.log10(F1+F2)
#wswitched = where(switched)
dtra[switched],docc[switched] = (docc[switched],dtra[switched])
T14_tra[switched],T14_occ[switched] = (T14_occ[switched],T14_tra[switched])
T23_tra[switched],T23_occ[switched] = (T23_occ[switched],T23_tra[switched])
b_tra[switched],b_occ[switched] = (b_occ[switched],b_tra[switched])
#mag1[wswitched],mag2[wswitched] = (mag2[wswitched],mag1[wswitched])
F1[switched],F2[switched] = (F2[switched],F1[switched])
u11[switched],u12[switched] = (u12[switched],u11[switched])
u21[switched],u22[switched] = (u22[switched],u21[switched])
dtra[(np.isnan(dtra))] = 0
docc[(np.isnan(docc))] = 0
if np.any(np.isnan(ecc)):
logging.warning('{} nans in eccentricity. why?'.format(np.isnan(ecc).sum()))
df = pd.DataFrame({'{}_mag_tot'.format(band) : totmag,
'P':P, 'ecc':ecc, 'inc':inc, 'w':w,
'dpri':dtra, 'dsec':docc,
'T14_pri':T14_tra, 'T23_pri':T23_tra,
'T14_sec':T14_occ, 'T23_sec':T23_occ,
'b_pri':b_tra, 'b_sec':b_occ,
'{}_mag_1'.format(band) : mag1,
'{}_mag_2'.format(band) : mag2,
'fluxfrac_1':F1/(F1+F2),
'fluxfrac_2':F2/(F1+F2),
'switched':switched,
'u1_1':u11, 'u2_1':u21, 'u1_2':u12, 'u2_2':u22})
df.reset_index(inplace=True)
logging.debug('final prob: {}'.format(prob))
if return_indices:
return wany, df, (prob, prob*np.sqrt(nany)/n)
else:
return df, (prob, prob*np.sqrt(nany)/n) |
def pathjoin(*args, **kwargs):
"""
Arguments:
args (list): *args list of paths
if len(args) == 1, args[0] is not a string, and args[0] is iterable,
set args to args[0].
Basically::
joined_path = u'/'.join(
[args[0].rstrip('/')] +
[a.strip('/') for a in args[1:-1]] +
[args[-1].lstrip('/')])
"""
log.debug('pathjoin: %r' % list(args))
def _pathjoin(*args, **kwargs):
len_ = len(args) - 1
if len_ < 0:
raise Exception('no args specified')
elif len_ == 0:
if not isinstance(args, basestring):
if hasattr(args, '__iter__'):
_args = args
_args
args = args[0]
for i, arg in enumerate(args):
if not i:
yield arg.rstrip('/')
elif i == len_:
yield arg.lstrip('/')
else:
yield arg.strip('/')
joined_path = u'/'.join(_pathjoin(*args))
return sanitize_path(joined_path) | Arguments:
args (list): *args list of paths
if len(args) == 1, args[0] is not a string, and args[0] is iterable,
set args to args[0].
Basically::
joined_path = u'/'.join(
[args[0].rstrip('/')] +
[a.strip('/') for a in args[1:-1]] +
[args[-1].lstrip('/')]) | Below is the the instruction that describes the task:
### Input:
Arguments:
args (list): *args list of paths
if len(args) == 1, args[0] is not a string, and args[0] is iterable,
set args to args[0].
Basically::
joined_path = u'/'.join(
[args[0].rstrip('/')] +
[a.strip('/') for a in args[1:-1]] +
[args[-1].lstrip('/')])
### Response:
def pathjoin(*args, **kwargs):
"""
Arguments:
args (list): *args list of paths
if len(args) == 1, args[0] is not a string, and args[0] is iterable,
set args to args[0].
Basically::
joined_path = u'/'.join(
[args[0].rstrip('/')] +
[a.strip('/') for a in args[1:-1]] +
[args[-1].lstrip('/')])
"""
log.debug('pathjoin: %r' % list(args))
def _pathjoin(*args, **kwargs):
len_ = len(args) - 1
if len_ < 0:
raise Exception('no args specified')
elif len_ == 0:
if not isinstance(args, basestring):
if hasattr(args, '__iter__'):
_args = args
_args
args = args[0]
for i, arg in enumerate(args):
if not i:
yield arg.rstrip('/')
elif i == len_:
yield arg.lstrip('/')
else:
yield arg.strip('/')
joined_path = u'/'.join(_pathjoin(*args))
return sanitize_path(joined_path) |
def sketch_fasta(fasta_path, outdir):
"""Create a Mash sketch from an input fasta file
Args:
fasta_path (str): input fasta file path. Genome name in fasta filename
outdir (str): output directory path to write Mash sketch file to
Returns:
str: output Mash sketch file path
"""
genome_name = genome_name_from_fasta_path(fasta_path)
outpath = os.path.join(outdir, genome_name)
args = ['mash', 'sketch', '-o', outpath, fasta_path]
logging.info('Running Mash sketch with command: %s', ' '.join(args))
p = Popen(args)
p.wait()
sketch_path = outpath + '.msh'
assert os.path.exists(sketch_path), 'Mash sketch for genome {} was not created at {}'.format(
genome_name,
sketch_path)
return sketch_path | Create a Mash sketch from an input fasta file
Args:
fasta_path (str): input fasta file path. Genome name in fasta filename
outdir (str): output directory path to write Mash sketch file to
Returns:
str: output Mash sketch file path | Below is the the instruction that describes the task:
### Input:
Create a Mash sketch from an input fasta file
Args:
fasta_path (str): input fasta file path. Genome name in fasta filename
outdir (str): output directory path to write Mash sketch file to
Returns:
str: output Mash sketch file path
### Response:
def sketch_fasta(fasta_path, outdir):
"""Create a Mash sketch from an input fasta file
Args:
fasta_path (str): input fasta file path. Genome name in fasta filename
outdir (str): output directory path to write Mash sketch file to
Returns:
str: output Mash sketch file path
"""
genome_name = genome_name_from_fasta_path(fasta_path)
outpath = os.path.join(outdir, genome_name)
args = ['mash', 'sketch', '-o', outpath, fasta_path]
logging.info('Running Mash sketch with command: %s', ' '.join(args))
p = Popen(args)
p.wait()
sketch_path = outpath + '.msh'
assert os.path.exists(sketch_path), 'Mash sketch for genome {} was not created at {}'.format(
genome_name,
sketch_path)
return sketch_path |
def process_data(self, data, cloud_cover='total_clouds', **kwargs):
"""
Defines the steps needed to convert raw forecast data
into processed forecast data.
Parameters
----------
data: DataFrame
Raw forecast data
cloud_cover: str, default 'total_clouds'
The type of cloud cover used to infer the irradiance.
Returns
-------
data: DataFrame
Processed forecast data.
"""
data = super(GFS, self).process_data(data, **kwargs)
data['temp_air'] = self.kelvin_to_celsius(data['temp_air'])
data['wind_speed'] = self.uv_to_speed(data)
irrads = self.cloud_cover_to_irradiance(data[cloud_cover], **kwargs)
data = data.join(irrads, how='outer')
return data[self.output_variables] | Defines the steps needed to convert raw forecast data
into processed forecast data.
Parameters
----------
data: DataFrame
Raw forecast data
cloud_cover: str, default 'total_clouds'
The type of cloud cover used to infer the irradiance.
Returns
-------
data: DataFrame
Processed forecast data. | Below is the the instruction that describes the task:
### Input:
Defines the steps needed to convert raw forecast data
into processed forecast data.
Parameters
----------
data: DataFrame
Raw forecast data
cloud_cover: str, default 'total_clouds'
The type of cloud cover used to infer the irradiance.
Returns
-------
data: DataFrame
Processed forecast data.
### Response:
def process_data(self, data, cloud_cover='total_clouds', **kwargs):
"""
Defines the steps needed to convert raw forecast data
into processed forecast data.
Parameters
----------
data: DataFrame
Raw forecast data
cloud_cover: str, default 'total_clouds'
The type of cloud cover used to infer the irradiance.
Returns
-------
data: DataFrame
Processed forecast data.
"""
data = super(GFS, self).process_data(data, **kwargs)
data['temp_air'] = self.kelvin_to_celsius(data['temp_air'])
data['wind_speed'] = self.uv_to_speed(data)
irrads = self.cloud_cover_to_irradiance(data[cloud_cover], **kwargs)
data = data.join(irrads, how='outer')
return data[self.output_variables] |
def get_status(dom):
"""
Gets Status from a Response.
:param dom: The Response as XML
:type: Document
:returns: The Status, an array with the code and a message.
:rtype: dict
"""
status = {}
status_entry = OneLogin_Saml2_Utils.query(dom, '/samlp:Response/samlp:Status')
if len(status_entry) != 1:
raise OneLogin_Saml2_ValidationError(
'Missing Status on response',
OneLogin_Saml2_ValidationError.MISSING_STATUS
)
code_entry = OneLogin_Saml2_Utils.query(dom, '/samlp:Response/samlp:Status/samlp:StatusCode', status_entry[0])
if len(code_entry) != 1:
raise OneLogin_Saml2_ValidationError(
'Missing Status Code on response',
OneLogin_Saml2_ValidationError.MISSING_STATUS_CODE
)
code = code_entry[0].values()[0]
status['code'] = code
status['msg'] = ''
message_entry = OneLogin_Saml2_Utils.query(dom, '/samlp:Response/samlp:Status/samlp:StatusMessage', status_entry[0])
if len(message_entry) == 0:
subcode_entry = OneLogin_Saml2_Utils.query(dom, '/samlp:Response/samlp:Status/samlp:StatusCode/samlp:StatusCode', status_entry[0])
if len(subcode_entry) == 1:
status['msg'] = subcode_entry[0].values()[0]
elif len(message_entry) == 1:
status['msg'] = OneLogin_Saml2_Utils.element_text(message_entry[0])
return status | Gets Status from a Response.
:param dom: The Response as XML
:type: Document
:returns: The Status, an array with the code and a message.
:rtype: dict | Below is the the instruction that describes the task:
### Input:
Gets Status from a Response.
:param dom: The Response as XML
:type: Document
:returns: The Status, an array with the code and a message.
:rtype: dict
### Response:
def get_status(dom):
"""
Gets Status from a Response.
:param dom: The Response as XML
:type: Document
:returns: The Status, an array with the code and a message.
:rtype: dict
"""
status = {}
status_entry = OneLogin_Saml2_Utils.query(dom, '/samlp:Response/samlp:Status')
if len(status_entry) != 1:
raise OneLogin_Saml2_ValidationError(
'Missing Status on response',
OneLogin_Saml2_ValidationError.MISSING_STATUS
)
code_entry = OneLogin_Saml2_Utils.query(dom, '/samlp:Response/samlp:Status/samlp:StatusCode', status_entry[0])
if len(code_entry) != 1:
raise OneLogin_Saml2_ValidationError(
'Missing Status Code on response',
OneLogin_Saml2_ValidationError.MISSING_STATUS_CODE
)
code = code_entry[0].values()[0]
status['code'] = code
status['msg'] = ''
message_entry = OneLogin_Saml2_Utils.query(dom, '/samlp:Response/samlp:Status/samlp:StatusMessage', status_entry[0])
if len(message_entry) == 0:
subcode_entry = OneLogin_Saml2_Utils.query(dom, '/samlp:Response/samlp:Status/samlp:StatusCode/samlp:StatusCode', status_entry[0])
if len(subcode_entry) == 1:
status['msg'] = subcode_entry[0].values()[0]
elif len(message_entry) == 1:
status['msg'] = OneLogin_Saml2_Utils.element_text(message_entry[0])
return status |
def _attribute_definition(self, attrid):
""" Returns the attribute definition dict of a given attribute
ID, can be the name or the integer ID """
attrs = self._schema["attributes"]
try:
# Make a new dict to avoid side effects
return dict(attrs[attrid])
except KeyError:
attr_names = self._schema["attribute_names"]
attrdef = attrs.get(attr_names.get(str(attrid).lower()))
if not attrdef:
return None
else:
return dict(attrdef) | Returns the attribute definition dict of a given attribute
ID, can be the name or the integer ID | Below is the the instruction that describes the task:
### Input:
Returns the attribute definition dict of a given attribute
ID, can be the name or the integer ID
### Response:
def _attribute_definition(self, attrid):
""" Returns the attribute definition dict of a given attribute
ID, can be the name or the integer ID """
attrs = self._schema["attributes"]
try:
# Make a new dict to avoid side effects
return dict(attrs[attrid])
except KeyError:
attr_names = self._schema["attribute_names"]
attrdef = attrs.get(attr_names.get(str(attrid).lower()))
if not attrdef:
return None
else:
return dict(attrdef) |
def add_job(cls, identifier, queue_name=None, priority=0, queue_model=None,
prepend=False, delayed_for=None, delayed_until=None,
**fields_if_new):
"""
Add a job to a queue.
If this job already exists, check it's current priority. If its higher
than the new one, don't touch it, else move the job to the wanted queue.
Before setting/moving the job to the queue, check for a `delayed_for`
(int/foat/timedelta) or `delayed_until` (datetime) argument to see if
it must be delayed instead of queued.
If the job is created, fields in fields_if_new will be set for the new
job.
Finally return the job.
"""
# check for delayed_for/delayed_until arguments
delayed_until = compute_delayed_until(delayed_for, delayed_until)
# create the job or get an existing one
job_kwargs = {'identifier': identifier, 'queued': '1'}
retries = 0
while retries < 10:
retries += 1
try:
job, created = cls.get_or_connect(**job_kwargs)
except IndexError:
# Failure during the retrieval https://friendpaste.com/5U63a8aFuV44SEgQckgMP
# => retry
continue
except ValueError:
# more than one already in the queue !
try:
job = cls.collection(**job_kwargs).instances()[0]
except IndexError:
# but no more now ?!
# => retry
continue
else:
created = False
# ok we have our job, stop now
break
try:
# check queue_name
queue_name = cls._get_queue_name(queue_name)
# if the job already exists, and we want a higher priority or move it,
# start by updating it
if not created:
current_priority = int(job.priority.hget() or 0)
# if the job has a higher priority, or don't need to be moved,
# don't move it
if not prepend and current_priority >= priority:
return job
# cancel it temporarily, we'll set it as waiting later
job.status.hset(STATUSES.CANCELED)
# remove it from the current queue, we'll add it to the new one later
if queue_model is None:
queue_model = cls.queue_model
current_queue = queue_model.get_queue(queue_name, current_priority)
current_queue.waiting.lrem(0, job.ident)
else:
job.set_fields(added=str(datetime.utcnow()), **(fields_if_new or {}))
# add the job to the queue
job.enqueue_or_delay(queue_name, priority, delayed_until, prepend, queue_model)
return job
except Exception:
job.queued.delete()
raise | Add a job to a queue.
If this job already exists, check it's current priority. If its higher
than the new one, don't touch it, else move the job to the wanted queue.
Before setting/moving the job to the queue, check for a `delayed_for`
(int/foat/timedelta) or `delayed_until` (datetime) argument to see if
it must be delayed instead of queued.
If the job is created, fields in fields_if_new will be set for the new
job.
Finally return the job. | Below is the the instruction that describes the task:
### Input:
Add a job to a queue.
If this job already exists, check it's current priority. If its higher
than the new one, don't touch it, else move the job to the wanted queue.
Before setting/moving the job to the queue, check for a `delayed_for`
(int/foat/timedelta) or `delayed_until` (datetime) argument to see if
it must be delayed instead of queued.
If the job is created, fields in fields_if_new will be set for the new
job.
Finally return the job.
### Response:
def add_job(cls, identifier, queue_name=None, priority=0, queue_model=None,
prepend=False, delayed_for=None, delayed_until=None,
**fields_if_new):
"""
Add a job to a queue.
If this job already exists, check it's current priority. If its higher
than the new one, don't touch it, else move the job to the wanted queue.
Before setting/moving the job to the queue, check for a `delayed_for`
(int/foat/timedelta) or `delayed_until` (datetime) argument to see if
it must be delayed instead of queued.
If the job is created, fields in fields_if_new will be set for the new
job.
Finally return the job.
"""
# check for delayed_for/delayed_until arguments
delayed_until = compute_delayed_until(delayed_for, delayed_until)
# create the job or get an existing one
job_kwargs = {'identifier': identifier, 'queued': '1'}
retries = 0
while retries < 10:
retries += 1
try:
job, created = cls.get_or_connect(**job_kwargs)
except IndexError:
# Failure during the retrieval https://friendpaste.com/5U63a8aFuV44SEgQckgMP
# => retry
continue
except ValueError:
# more than one already in the queue !
try:
job = cls.collection(**job_kwargs).instances()[0]
except IndexError:
# but no more now ?!
# => retry
continue
else:
created = False
# ok we have our job, stop now
break
try:
# check queue_name
queue_name = cls._get_queue_name(queue_name)
# if the job already exists, and we want a higher priority or move it,
# start by updating it
if not created:
current_priority = int(job.priority.hget() or 0)
# if the job has a higher priority, or don't need to be moved,
# don't move it
if not prepend and current_priority >= priority:
return job
# cancel it temporarily, we'll set it as waiting later
job.status.hset(STATUSES.CANCELED)
# remove it from the current queue, we'll add it to the new one later
if queue_model is None:
queue_model = cls.queue_model
current_queue = queue_model.get_queue(queue_name, current_priority)
current_queue.waiting.lrem(0, job.ident)
else:
job.set_fields(added=str(datetime.utcnow()), **(fields_if_new or {}))
# add the job to the queue
job.enqueue_or_delay(queue_name, priority, delayed_until, prepend, queue_model)
return job
except Exception:
job.queued.delete()
raise |
def evolve(self, profile, t, return_log=False):
"""
Compute the probability of the sequence state of the child
at time t later, given the parent profile.
Parameters
----------
profile : numpy.array
Sequence profile. Shape = (L, a),
where L - sequence length, a - alphabet size.
t : double
Time to propagate
return_log: bool
If True, return log-probability
Returns
-------
res : np.array
Profile of the sequence after time t in the future.
Shape = (L, a), where L - sequence length, a - alphabet size.
"""
Qt = self.expQt(t).T
res = profile.dot(Qt)
return np.log(res) if return_log else res | Compute the probability of the sequence state of the child
at time t later, given the parent profile.
Parameters
----------
profile : numpy.array
Sequence profile. Shape = (L, a),
where L - sequence length, a - alphabet size.
t : double
Time to propagate
return_log: bool
If True, return log-probability
Returns
-------
res : np.array
Profile of the sequence after time t in the future.
Shape = (L, a), where L - sequence length, a - alphabet size. | Below is the the instruction that describes the task:
### Input:
Compute the probability of the sequence state of the child
at time t later, given the parent profile.
Parameters
----------
profile : numpy.array
Sequence profile. Shape = (L, a),
where L - sequence length, a - alphabet size.
t : double
Time to propagate
return_log: bool
If True, return log-probability
Returns
-------
res : np.array
Profile of the sequence after time t in the future.
Shape = (L, a), where L - sequence length, a - alphabet size.
### Response:
def evolve(self, profile, t, return_log=False):
"""
Compute the probability of the sequence state of the child
at time t later, given the parent profile.
Parameters
----------
profile : numpy.array
Sequence profile. Shape = (L, a),
where L - sequence length, a - alphabet size.
t : double
Time to propagate
return_log: bool
If True, return log-probability
Returns
-------
res : np.array
Profile of the sequence after time t in the future.
Shape = (L, a), where L - sequence length, a - alphabet size.
"""
Qt = self.expQt(t).T
res = profile.dot(Qt)
return np.log(res) if return_log else res |
def _persist(self):
"""Persist client data."""
with open(self.file, 'w') as f:
json.dump({
'client': self.client,
'creds': self.creds,
'config': self.config
}, f) | Persist client data. | Below is the the instruction that describes the task:
### Input:
Persist client data.
### Response:
def _persist(self):
"""Persist client data."""
with open(self.file, 'w') as f:
json.dump({
'client': self.client,
'creds': self.creds,
'config': self.config
}, f) |
def get_function_params(self, scope_path, pyfunc):
""":type pyfunc: rope.base.pyobjectsdef.PyFunction"""
pyclass = pyfunc.parent
scope_path = get_attribute_scope_path(pyclass)
glade_file = self.get_glade_file_for_class(scope_path, pyclass)
if glade_file:
self.process_glade(scope_path, glade_file)
return self.get_params_for_handler(scope_path, pyfunc)
else:
return {} | :type pyfunc: rope.base.pyobjectsdef.PyFunction | Below is the the instruction that describes the task:
### Input:
:type pyfunc: rope.base.pyobjectsdef.PyFunction
### Response:
def get_function_params(self, scope_path, pyfunc):
""":type pyfunc: rope.base.pyobjectsdef.PyFunction"""
pyclass = pyfunc.parent
scope_path = get_attribute_scope_path(pyclass)
glade_file = self.get_glade_file_for_class(scope_path, pyclass)
if glade_file:
self.process_glade(scope_path, glade_file)
return self.get_params_for_handler(scope_path, pyfunc)
else:
return {} |
def shp2geom(shp_fn):
"""Extract geometries from input shapefile
Need to handle multi-part geom: http://osgeo-org.1560.x6.nabble.com/Multipart-to-singlepart-td3746767.html
"""
ds = ogr.Open(shp_fn)
lyr = ds.GetLayer()
srs = lyr.GetSpatialRef()
lyr.ResetReading()
geom_list = []
for feat in lyr:
geom = feat.GetGeometryRef()
geom.AssignSpatialReference(srs)
#Duplicate the geometry, or segfault
#See: http://trac.osgeo.org/gdal/wiki/PythonGotchas
#g = ogr.CreateGeometryFromWkt(geom.ExportToWkt())
#g.AssignSpatialReference(srs)
g = geom_dup(geom)
geom_list.append(g)
#geom = ogr.ForceToPolygon(' '.join(geom_list))
#Dissolve should convert multipolygon to single polygon
#return geom_list[0]
ds = None
return geom_list | Extract geometries from input shapefile
Need to handle multi-part geom: http://osgeo-org.1560.x6.nabble.com/Multipart-to-singlepart-td3746767.html | Below is the the instruction that describes the task:
### Input:
Extract geometries from input shapefile
Need to handle multi-part geom: http://osgeo-org.1560.x6.nabble.com/Multipart-to-singlepart-td3746767.html
### Response:
def shp2geom(shp_fn):
"""Extract geometries from input shapefile
Need to handle multi-part geom: http://osgeo-org.1560.x6.nabble.com/Multipart-to-singlepart-td3746767.html
"""
ds = ogr.Open(shp_fn)
lyr = ds.GetLayer()
srs = lyr.GetSpatialRef()
lyr.ResetReading()
geom_list = []
for feat in lyr:
geom = feat.GetGeometryRef()
geom.AssignSpatialReference(srs)
#Duplicate the geometry, or segfault
#See: http://trac.osgeo.org/gdal/wiki/PythonGotchas
#g = ogr.CreateGeometryFromWkt(geom.ExportToWkt())
#g.AssignSpatialReference(srs)
g = geom_dup(geom)
geom_list.append(g)
#geom = ogr.ForceToPolygon(' '.join(geom_list))
#Dissolve should convert multipolygon to single polygon
#return geom_list[0]
ds = None
return geom_list |
def terminate(self):
""" Terminate Qutepart instance.
This method MUST be called before application stop to avoid crashes and
some other interesting effects
Call it on close to free memory and stop background highlighting
"""
self.text = ''
self._completer.terminate()
if self._highlighter is not None:
self._highlighter.terminate()
if self._vim is not None:
self._vim.terminate() | Terminate Qutepart instance.
This method MUST be called before application stop to avoid crashes and
some other interesting effects
Call it on close to free memory and stop background highlighting | Below is the the instruction that describes the task:
### Input:
Terminate Qutepart instance.
This method MUST be called before application stop to avoid crashes and
some other interesting effects
Call it on close to free memory and stop background highlighting
### Response:
def terminate(self):
""" Terminate Qutepart instance.
This method MUST be called before application stop to avoid crashes and
some other interesting effects
Call it on close to free memory and stop background highlighting
"""
self.text = ''
self._completer.terminate()
if self._highlighter is not None:
self._highlighter.terminate()
if self._vim is not None:
self._vim.terminate() |
def list_groups(self, scope_descriptor=None, subject_types=None, continuation_token=None):
"""ListGroups.
[Preview API] Gets a list of all groups in the current scope (usually organization or account).
:param str scope_descriptor: Specify a non-default scope (collection, project) to search for groups.
:param [str] subject_types: A comma separated list of user subject subtypes to reduce the retrieved results, e.g. Microsoft.IdentityModel.Claims.ClaimsIdentity
:param str continuation_token: An opaque data blob that allows the next page of data to resume immediately after where the previous page ended. The only reliable way to know if there is more data left is the presence of a continuation token.
:rtype: :class:`<PagedGraphGroups> <azure.devops.v5_0.graph.models.PagedGraphGroups>`
"""
query_parameters = {}
if scope_descriptor is not None:
query_parameters['scopeDescriptor'] = self._serialize.query('scope_descriptor', scope_descriptor, 'str')
if subject_types is not None:
subject_types = ",".join(subject_types)
query_parameters['subjectTypes'] = self._serialize.query('subject_types', subject_types, 'str')
if continuation_token is not None:
query_parameters['continuationToken'] = self._serialize.query('continuation_token', continuation_token, 'str')
response = self._send(http_method='GET',
location_id='ebbe6af8-0b91-4c13-8cf1-777c14858188',
version='5.0-preview.1',
query_parameters=query_parameters)
response_object = models.PagedGraphGroups()
response_object.graph_groups = self._deserialize('[GraphGroup]', self._unwrap_collection(response))
response_object.continuation_token = response.headers.get('X-MS-ContinuationToken')
return response_object | ListGroups.
[Preview API] Gets a list of all groups in the current scope (usually organization or account).
:param str scope_descriptor: Specify a non-default scope (collection, project) to search for groups.
:param [str] subject_types: A comma separated list of user subject subtypes to reduce the retrieved results, e.g. Microsoft.IdentityModel.Claims.ClaimsIdentity
:param str continuation_token: An opaque data blob that allows the next page of data to resume immediately after where the previous page ended. The only reliable way to know if there is more data left is the presence of a continuation token.
:rtype: :class:`<PagedGraphGroups> <azure.devops.v5_0.graph.models.PagedGraphGroups>` | Below is the the instruction that describes the task:
### Input:
ListGroups.
[Preview API] Gets a list of all groups in the current scope (usually organization or account).
:param str scope_descriptor: Specify a non-default scope (collection, project) to search for groups.
:param [str] subject_types: A comma separated list of user subject subtypes to reduce the retrieved results, e.g. Microsoft.IdentityModel.Claims.ClaimsIdentity
:param str continuation_token: An opaque data blob that allows the next page of data to resume immediately after where the previous page ended. The only reliable way to know if there is more data left is the presence of a continuation token.
:rtype: :class:`<PagedGraphGroups> <azure.devops.v5_0.graph.models.PagedGraphGroups>`
### Response:
def list_groups(self, scope_descriptor=None, subject_types=None, continuation_token=None):
"""ListGroups.
[Preview API] Gets a list of all groups in the current scope (usually organization or account).
:param str scope_descriptor: Specify a non-default scope (collection, project) to search for groups.
:param [str] subject_types: A comma separated list of user subject subtypes to reduce the retrieved results, e.g. Microsoft.IdentityModel.Claims.ClaimsIdentity
:param str continuation_token: An opaque data blob that allows the next page of data to resume immediately after where the previous page ended. The only reliable way to know if there is more data left is the presence of a continuation token.
:rtype: :class:`<PagedGraphGroups> <azure.devops.v5_0.graph.models.PagedGraphGroups>`
"""
query_parameters = {}
if scope_descriptor is not None:
query_parameters['scopeDescriptor'] = self._serialize.query('scope_descriptor', scope_descriptor, 'str')
if subject_types is not None:
subject_types = ",".join(subject_types)
query_parameters['subjectTypes'] = self._serialize.query('subject_types', subject_types, 'str')
if continuation_token is not None:
query_parameters['continuationToken'] = self._serialize.query('continuation_token', continuation_token, 'str')
response = self._send(http_method='GET',
location_id='ebbe6af8-0b91-4c13-8cf1-777c14858188',
version='5.0-preview.1',
query_parameters=query_parameters)
response_object = models.PagedGraphGroups()
response_object.graph_groups = self._deserialize('[GraphGroup]', self._unwrap_collection(response))
response_object.continuation_token = response.headers.get('X-MS-ContinuationToken')
return response_object |
def create_vector_observation_encoder(observation_input, h_size, activation, num_layers, scope,
reuse):
"""
Builds a set of hidden state encoders.
:param reuse: Whether to re-use the weights within the same scope.
:param scope: Graph scope for the encoder ops.
:param observation_input: Input vector.
:param h_size: Hidden layer size.
:param activation: What type of activation function to use for layers.
:param num_layers: number of hidden layers to create.
:return: List of hidden layer tensors.
"""
with tf.variable_scope(scope):
hidden = observation_input
for i in range(num_layers):
hidden = tf.layers.dense(hidden, h_size, activation=activation, reuse=reuse,
name="hidden_{}".format(i),
kernel_initializer=c_layers.variance_scaling_initializer(
1.0))
return hidden | Builds a set of hidden state encoders.
:param reuse: Whether to re-use the weights within the same scope.
:param scope: Graph scope for the encoder ops.
:param observation_input: Input vector.
:param h_size: Hidden layer size.
:param activation: What type of activation function to use for layers.
:param num_layers: number of hidden layers to create.
:return: List of hidden layer tensors. | Below is the the instruction that describes the task:
### Input:
Builds a set of hidden state encoders.
:param reuse: Whether to re-use the weights within the same scope.
:param scope: Graph scope for the encoder ops.
:param observation_input: Input vector.
:param h_size: Hidden layer size.
:param activation: What type of activation function to use for layers.
:param num_layers: number of hidden layers to create.
:return: List of hidden layer tensors.
### Response:
def create_vector_observation_encoder(observation_input, h_size, activation, num_layers, scope,
reuse):
"""
Builds a set of hidden state encoders.
:param reuse: Whether to re-use the weights within the same scope.
:param scope: Graph scope for the encoder ops.
:param observation_input: Input vector.
:param h_size: Hidden layer size.
:param activation: What type of activation function to use for layers.
:param num_layers: number of hidden layers to create.
:return: List of hidden layer tensors.
"""
with tf.variable_scope(scope):
hidden = observation_input
for i in range(num_layers):
hidden = tf.layers.dense(hidden, h_size, activation=activation, reuse=reuse,
name="hidden_{}".format(i),
kernel_initializer=c_layers.variance_scaling_initializer(
1.0))
return hidden |
def import_module(self, name):
"""Import a module into the bridge."""
if name not in self._objects:
module = _import_module(name)
self._objects[name] = module
self._object_references[id(module)] = name
return self._objects[name] | Import a module into the bridge. | Below is the the instruction that describes the task:
### Input:
Import a module into the bridge.
### Response:
def import_module(self, name):
"""Import a module into the bridge."""
if name not in self._objects:
module = _import_module(name)
self._objects[name] = module
self._object_references[id(module)] = name
return self._objects[name] |
def run(self, configurations):
""" Run all tests
Returns:
A dictionnary containing tests results.
"""
result = CourgetteResult()
for configuration in configurations:
runner = CourgetteTestsRunner(url=self.url,
username=self.username,
password=self.password,
enterprise=self.enterprise,
version=self.apiversion,
specification=configuration.specification,
sdk_identifier=self.sdk_identifier,
monolithe_config=self.monolithe_config,
parent_resource=configuration.parent_resource_name,
parent_id=configuration.parent_id,
default_values=configuration.default_values)
result.add_report(configuration.specification.rest_name + ".spec", runner.run())
return result | Run all tests
Returns:
A dictionnary containing tests results. | Below is the the instruction that describes the task:
### Input:
Run all tests
Returns:
A dictionnary containing tests results.
### Response:
def run(self, configurations):
""" Run all tests
Returns:
A dictionnary containing tests results.
"""
result = CourgetteResult()
for configuration in configurations:
runner = CourgetteTestsRunner(url=self.url,
username=self.username,
password=self.password,
enterprise=self.enterprise,
version=self.apiversion,
specification=configuration.specification,
sdk_identifier=self.sdk_identifier,
monolithe_config=self.monolithe_config,
parent_resource=configuration.parent_resource_name,
parent_id=configuration.parent_id,
default_values=configuration.default_values)
result.add_report(configuration.specification.rest_name + ".spec", runner.run())
return result |
def edit(self, name=None, description=None, **kwargs):
# type: (AnyStr, AnyStr, **Any) -> None
"""
Edit the details of a part (model or instance).
For an instance you can edit the Part instance name and the part instance description. To alter the values
of properties use :func:`Part.update()`.
In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as
additional keyword=value argument to this method. This will improve performance of the backend
against a trade-off that someone looking at the frontend won't notice any changes unless the page
is refreshed.
:param name: optional name of the part to edit
:param description: (optional) description of the part
:type description: basestring or None
:param kwargs: (optional) additional kwargs that will be passed in the during the edit/update request
:type kwargs: dict or None
:return: the updated object if successful
:raises IllegalArgumentError: when the type or value of an argument provided is incorrect
:raises APIError: in case an Error occurs
Example
-------
For changing a part:
>>> front_fork = project.part('Front Fork')
>>> front_fork.edit(name='Front Fork - updated')
>>> front_fork.edit(name='Front Fork cruizer', description='With my ragtop down so my hair can blow' )
for changing a model:
>>> front_fork = project.model('Front Fork')
>>> front_fork.edit(name='Front Fork basemodel', description='Some description here')
"""
update_dict = {'id': self.id}
if name:
if not isinstance(name, str):
raise IllegalArgumentError("name should be provided as a string")
update_dict.update({'name': name})
if description:
if not isinstance(description, str):
raise IllegalArgumentError("description should be provided as a string")
update_dict.update({'description': description})
if kwargs: # pragma: no cover
update_dict.update(**kwargs)
r = self._client._request('PUT', self._client._build_url('part', part_id=self.id), json=update_dict)
if r.status_code != requests.codes.ok: # pragma: no cover
raise APIError("Could not update Part ({})".format(r))
if name:
self.name = name | Edit the details of a part (model or instance).
For an instance you can edit the Part instance name and the part instance description. To alter the values
of properties use :func:`Part.update()`.
In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as
additional keyword=value argument to this method. This will improve performance of the backend
against a trade-off that someone looking at the frontend won't notice any changes unless the page
is refreshed.
:param name: optional name of the part to edit
:param description: (optional) description of the part
:type description: basestring or None
:param kwargs: (optional) additional kwargs that will be passed in the during the edit/update request
:type kwargs: dict or None
:return: the updated object if successful
:raises IllegalArgumentError: when the type or value of an argument provided is incorrect
:raises APIError: in case an Error occurs
Example
-------
For changing a part:
>>> front_fork = project.part('Front Fork')
>>> front_fork.edit(name='Front Fork - updated')
>>> front_fork.edit(name='Front Fork cruizer', description='With my ragtop down so my hair can blow' )
for changing a model:
>>> front_fork = project.model('Front Fork')
>>> front_fork.edit(name='Front Fork basemodel', description='Some description here') | Below is the the instruction that describes the task:
### Input:
Edit the details of a part (model or instance).
For an instance you can edit the Part instance name and the part instance description. To alter the values
of properties use :func:`Part.update()`.
In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as
additional keyword=value argument to this method. This will improve performance of the backend
against a trade-off that someone looking at the frontend won't notice any changes unless the page
is refreshed.
:param name: optional name of the part to edit
:param description: (optional) description of the part
:type description: basestring or None
:param kwargs: (optional) additional kwargs that will be passed in the during the edit/update request
:type kwargs: dict or None
:return: the updated object if successful
:raises IllegalArgumentError: when the type or value of an argument provided is incorrect
:raises APIError: in case an Error occurs
Example
-------
For changing a part:
>>> front_fork = project.part('Front Fork')
>>> front_fork.edit(name='Front Fork - updated')
>>> front_fork.edit(name='Front Fork cruizer', description='With my ragtop down so my hair can blow' )
for changing a model:
>>> front_fork = project.model('Front Fork')
>>> front_fork.edit(name='Front Fork basemodel', description='Some description here')
### Response:
def edit(self, name=None, description=None, **kwargs):
# type: (AnyStr, AnyStr, **Any) -> None
"""
Edit the details of a part (model or instance).
For an instance you can edit the Part instance name and the part instance description. To alter the values
of properties use :func:`Part.update()`.
In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as
additional keyword=value argument to this method. This will improve performance of the backend
against a trade-off that someone looking at the frontend won't notice any changes unless the page
is refreshed.
:param name: optional name of the part to edit
:param description: (optional) description of the part
:type description: basestring or None
:param kwargs: (optional) additional kwargs that will be passed in the during the edit/update request
:type kwargs: dict or None
:return: the updated object if successful
:raises IllegalArgumentError: when the type or value of an argument provided is incorrect
:raises APIError: in case an Error occurs
Example
-------
For changing a part:
>>> front_fork = project.part('Front Fork')
>>> front_fork.edit(name='Front Fork - updated')
>>> front_fork.edit(name='Front Fork cruizer', description='With my ragtop down so my hair can blow' )
for changing a model:
>>> front_fork = project.model('Front Fork')
>>> front_fork.edit(name='Front Fork basemodel', description='Some description here')
"""
update_dict = {'id': self.id}
if name:
if not isinstance(name, str):
raise IllegalArgumentError("name should be provided as a string")
update_dict.update({'name': name})
if description:
if not isinstance(description, str):
raise IllegalArgumentError("description should be provided as a string")
update_dict.update({'description': description})
if kwargs: # pragma: no cover
update_dict.update(**kwargs)
r = self._client._request('PUT', self._client._build_url('part', part_id=self.id), json=update_dict)
if r.status_code != requests.codes.ok: # pragma: no cover
raise APIError("Could not update Part ({})".format(r))
if name:
self.name = name |
def velocity_kalman_model():
'''Return a KalmanState set up to model objects with constant velocity
The observation and measurement vectors are i,j.
The state vector is i,j,vi,vj
'''
om = np.array([[1,0,0,0], [0, 1, 0, 0]])
tm = np.array([[1,0,1,0],
[0,1,0,1],
[0,0,1,0],
[0,0,0,1]])
return KalmanState(om, tm) | Return a KalmanState set up to model objects with constant velocity
The observation and measurement vectors are i,j.
The state vector is i,j,vi,vj | Below is the the instruction that describes the task:
### Input:
Return a KalmanState set up to model objects with constant velocity
The observation and measurement vectors are i,j.
The state vector is i,j,vi,vj
### Response:
def velocity_kalman_model():
'''Return a KalmanState set up to model objects with constant velocity
The observation and measurement vectors are i,j.
The state vector is i,j,vi,vj
'''
om = np.array([[1,0,0,0], [0, 1, 0, 0]])
tm = np.array([[1,0,1,0],
[0,1,0,1],
[0,0,1,0],
[0,0,0,1]])
return KalmanState(om, tm) |
def detectGamingHandheld(self):
"""Return detection of a gaming handheld with a modern iPhone-class browser
Detects if the current device is a handheld gaming device with
a touchscreen and modern iPhone-class browser. Includes the Playstation Vita.
"""
return UAgentInfo.devicePlaystation in self.__userAgent \
and UAgentInfo.devicePlaystationVita in self.__userAgent | Return detection of a gaming handheld with a modern iPhone-class browser
Detects if the current device is a handheld gaming device with
a touchscreen and modern iPhone-class browser. Includes the Playstation Vita. | Below is the the instruction that describes the task:
### Input:
Return detection of a gaming handheld with a modern iPhone-class browser
Detects if the current device is a handheld gaming device with
a touchscreen and modern iPhone-class browser. Includes the Playstation Vita.
### Response:
def detectGamingHandheld(self):
"""Return detection of a gaming handheld with a modern iPhone-class browser
Detects if the current device is a handheld gaming device with
a touchscreen and modern iPhone-class browser. Includes the Playstation Vita.
"""
return UAgentInfo.devicePlaystation in self.__userAgent \
and UAgentInfo.devicePlaystationVita in self.__userAgent |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.