repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
inveniosoftware/invenio-previewer | invenio_previewer/extensions/mistune.py | render | def render(file):
"""Render HTML from Markdown file content."""
with file.open() as fp:
encoding = detect_encoding(fp, default='utf-8')
result = mistune.markdown(fp.read().decode(encoding))
return result | python | def render(file):
"""Render HTML from Markdown file content."""
with file.open() as fp:
encoding = detect_encoding(fp, default='utf-8')
result = mistune.markdown(fp.read().decode(encoding))
return result | [
"def",
"render",
"(",
"file",
")",
":",
"with",
"file",
".",
"open",
"(",
")",
"as",
"fp",
":",
"encoding",
"=",
"detect_encoding",
"(",
"fp",
",",
"default",
"=",
"'utf-8'",
")",
"result",
"=",
"mistune",
".",
"markdown",
"(",
"fp",
".",
"read",
"... | Render HTML from Markdown file content. | [
"Render",
"HTML",
"from",
"Markdown",
"file",
"content",
"."
] | train | https://github.com/inveniosoftware/invenio-previewer/blob/558fd22e0f29cc8cd7a6999abd4febcf6b248c49/invenio_previewer/extensions/mistune.py#L21-L26 |
paylogic/halogen | halogen/validators.py | Length.validate | def validate(self, value):
"""Validate the length of a list.
:param value: List of values.
:raises: :class:`halogen.exception.ValidationError` exception when length of the list is less than
minimum or greater than maximum.
"""
try:
length = len(value)
except TypeError:
length = 0
if self.min_length is not None:
min_length = self.min_length() if callable(self.min_length) else self.min_length
if length < min_length:
raise exceptions.ValidationError(self.min_err.format(min_length))
if self.max_length is not None:
max_length = self.max_length() if callable(self.max_length) else self.max_length
if length > max_length:
raise exceptions.ValidationError(self.max_err.format(max_length)) | python | def validate(self, value):
"""Validate the length of a list.
:param value: List of values.
:raises: :class:`halogen.exception.ValidationError` exception when length of the list is less than
minimum or greater than maximum.
"""
try:
length = len(value)
except TypeError:
length = 0
if self.min_length is not None:
min_length = self.min_length() if callable(self.min_length) else self.min_length
if length < min_length:
raise exceptions.ValidationError(self.min_err.format(min_length))
if self.max_length is not None:
max_length = self.max_length() if callable(self.max_length) else self.max_length
if length > max_length:
raise exceptions.ValidationError(self.max_err.format(max_length)) | [
"def",
"validate",
"(",
"self",
",",
"value",
")",
":",
"try",
":",
"length",
"=",
"len",
"(",
"value",
")",
"except",
"TypeError",
":",
"length",
"=",
"0",
"if",
"self",
".",
"min_length",
"is",
"not",
"None",
":",
"min_length",
"=",
"self",
".",
... | Validate the length of a list.
:param value: List of values.
:raises: :class:`halogen.exception.ValidationError` exception when length of the list is less than
minimum or greater than maximum. | [
"Validate",
"the",
"length",
"of",
"a",
"list",
"."
] | train | https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/validators.py#L92-L113 |
paylogic/halogen | halogen/validators.py | Range.validate | def validate(self, value):
"""Validate value.
:param value: Value which should be validated.
:raises: :class:`halogen.exception.ValidationError` exception when either if value less than min in case when
min is not None or if value greater than max in case when max is not None.
"""
if self.min is not None:
min_value = self.min() if callable(self.min) else self.min
if value < min_value:
raise exceptions.ValidationError(self.min_err.format(val=value, min=min_value))
if self.max is not None:
max_value = self.max() if callable(self.max) else self.max
if value > max_value:
raise exceptions.ValidationError(self.max_err.format(val=value, max=max_value)) | python | def validate(self, value):
"""Validate value.
:param value: Value which should be validated.
:raises: :class:`halogen.exception.ValidationError` exception when either if value less than min in case when
min is not None or if value greater than max in case when max is not None.
"""
if self.min is not None:
min_value = self.min() if callable(self.min) else self.min
if value < min_value:
raise exceptions.ValidationError(self.min_err.format(val=value, min=min_value))
if self.max is not None:
max_value = self.max() if callable(self.max) else self.max
if value > max_value:
raise exceptions.ValidationError(self.max_err.format(val=value, max=max_value)) | [
"def",
"validate",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"min",
"is",
"not",
"None",
":",
"min_value",
"=",
"self",
".",
"min",
"(",
")",
"if",
"callable",
"(",
"self",
".",
"min",
")",
"else",
"self",
".",
"min",
"if",
"value",... | Validate value.
:param value: Value which should be validated.
:raises: :class:`halogen.exception.ValidationError` exception when either if value less than min in case when
min is not None or if value greater than max in case when max is not None. | [
"Validate",
"value",
"."
] | train | https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/validators.py#L143-L159 |
dhondta/tinyscript | tinyscript/parser.py | __get_calls_from_parser | def __get_calls_from_parser(proxy_parser, real_parser):
"""
This actually executes the calls registered in the ProxyArgumentParser.
:param proxy_parser: ProxyArgumentParser instance
:param real_parser: ArgumentParser instance
"""
__parsers[proxy_parser] = real_parser
for method, safe, args, kwargs, proxy_subparser in proxy_parser.calls:
args = (__proxy_to_real_parser(v) for v in args)
kwargs = {k: __proxy_to_real_parser(v) for k, v in kwargs.items()}
real_subparser = getattr(real_parser, method)(*args, **kwargs)
if real_subparser is not None:
__get_calls_from_parser(proxy_subparser, real_subparser) | python | def __get_calls_from_parser(proxy_parser, real_parser):
"""
This actually executes the calls registered in the ProxyArgumentParser.
:param proxy_parser: ProxyArgumentParser instance
:param real_parser: ArgumentParser instance
"""
__parsers[proxy_parser] = real_parser
for method, safe, args, kwargs, proxy_subparser in proxy_parser.calls:
args = (__proxy_to_real_parser(v) for v in args)
kwargs = {k: __proxy_to_real_parser(v) for k, v in kwargs.items()}
real_subparser = getattr(real_parser, method)(*args, **kwargs)
if real_subparser is not None:
__get_calls_from_parser(proxy_subparser, real_subparser) | [
"def",
"__get_calls_from_parser",
"(",
"proxy_parser",
",",
"real_parser",
")",
":",
"__parsers",
"[",
"proxy_parser",
"]",
"=",
"real_parser",
"for",
"method",
",",
"safe",
",",
"args",
",",
"kwargs",
",",
"proxy_subparser",
"in",
"proxy_parser",
".",
"calls",
... | This actually executes the calls registered in the ProxyArgumentParser.
:param proxy_parser: ProxyArgumentParser instance
:param real_parser: ArgumentParser instance | [
"This",
"actually",
"executes",
"the",
"calls",
"registered",
"in",
"the",
"ProxyArgumentParser",
"."
] | train | https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/parser.py#L28-L41 |
dhondta/tinyscript | tinyscript/parser.py | __proxy_to_real_parser | def __proxy_to_real_parser(value):
"""
This recursively converts ProxyArgumentParser instances to actual parsers.
Use case: defining subparsers with a parent
>>> [...]
>>> parser.add_argument(...) # argument common to all subparsers
>>> subparsers = parser.add_subparsers()
>>> subparsers.add_parser(..., parents=[parent])
^
this is an instance of ProxyArgumentParser
and must be converted to an actual parser instance
:param value: a value coming from args or kwargs aimed to an actual parser
"""
if isinstance(value, ProxyArgumentParser):
return __parsers[value]
elif any(isinstance(value, t) for t in [list, tuple]):
new_value = []
for subvalue in iter(value):
new_value.append(__proxy_to_real_parser(subvalue))
return new_value
return value | python | def __proxy_to_real_parser(value):
"""
This recursively converts ProxyArgumentParser instances to actual parsers.
Use case: defining subparsers with a parent
>>> [...]
>>> parser.add_argument(...) # argument common to all subparsers
>>> subparsers = parser.add_subparsers()
>>> subparsers.add_parser(..., parents=[parent])
^
this is an instance of ProxyArgumentParser
and must be converted to an actual parser instance
:param value: a value coming from args or kwargs aimed to an actual parser
"""
if isinstance(value, ProxyArgumentParser):
return __parsers[value]
elif any(isinstance(value, t) for t in [list, tuple]):
new_value = []
for subvalue in iter(value):
new_value.append(__proxy_to_real_parser(subvalue))
return new_value
return value | [
"def",
"__proxy_to_real_parser",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"ProxyArgumentParser",
")",
":",
"return",
"__parsers",
"[",
"value",
"]",
"elif",
"any",
"(",
"isinstance",
"(",
"value",
",",
"t",
")",
"for",
"t",
"in",
"[... | This recursively converts ProxyArgumentParser instances to actual parsers.
Use case: defining subparsers with a parent
>>> [...]
>>> parser.add_argument(...) # argument common to all subparsers
>>> subparsers = parser.add_subparsers()
>>> subparsers.add_parser(..., parents=[parent])
^
this is an instance of ProxyArgumentParser
and must be converted to an actual parser instance
:param value: a value coming from args or kwargs aimed to an actual parser | [
"This",
"recursively",
"converts",
"ProxyArgumentParser",
"instances",
"to",
"actual",
"parsers",
"."
] | train | https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/parser.py#L44-L66 |
dhondta/tinyscript | tinyscript/parser.py | initialize | def initialize(glob,
sudo=False,
multi_level_debug=False,
add_config=False,
add_demo=False,
add_interact=False,
add_step=False,
add_time=False,
add_version=False,
add_wizard=False,
ext_logging=False,
noargs_action=None,
report_func=None):
"""
Initialization function ; sets up the arguments for the parser and creates a
logger to be inserted in the input dictionary of global variables from the
calling script.
:param glob: globals() instance from the calling script
:param sudo: if True, require sudo credentials and re-run
script with sudo
:param multi_level_debug: allow to use -v, -vv, -vvv (adjust logging level)
instead of just -v (only debug on/off)
:param relative_time: use relative time for log messages
:param add_config: add an option to input an INI configuration file
:param add_demo: add an option to re-run the process using a random
entry from the __examples__ (only works if this
variable is populated)
:param add_interact: add an interaction option
:param add_step: add an execution stepping option
:param add_time: add an execution timing option
:param add_version: add a version option
:param add_wizard: add an option to run a wizard, asking for each
input argument
:param ext_logging: extended logging options
:param noargs_action: action to be performed when no argument is input
:param report_func: report generation function
"""
global parser, __parsers
add = {'config': add_config, 'demo': add_demo, 'interact': add_interact,
'step': add_step, 'time': add_time, 'version': add_version,
'wizard': add_wizard, 'help': True}
p = ArgumentParser(glob)
# 1) handle action when no input argument is given
add['demo'] = add['demo'] and p.examples
noarg = len(sys.argv) == 1
if noarg and noargs_action:
if noargs_action not in add.keys():
raise ValueError("Bad action when no args (should be one of: {})"
.format('|'.join(add.keys())))
add[noargs_action] = True # ensure this action is enabled, even if it
# is not given the passed arguments
# 2) populate the real parser and add information arguments
__parsers = {}
__get_calls_from_parser(parser, p)
# config handling feature, for reading/writing an INI config file with the
# input arguments, e.g. for future reuse
if add['config']:
c = p.add_argument_group(gt("config arguments"))
opt = c.add_argument("-r", "--read-config", action='config',
help=gt("read args from a config file"),
note=gt("this overrides other arguments"))
c.add_argument("-w", "--write-config", metavar="INI",
help=gt("write args to a config file"))
if noarg and noargs_action == "config":
sys.argv[1:] = [opt, "config.ini"]
i = p.add_argument_group(gt("extra arguments"))
# demonstration feature, for executing an example amongst these defined in
# __examples__, useful for observing what the tool does
if add['demo']:
opt = i.add_argument("--demo", action='demo', prefix="play",
help=gt("demonstrate a random example"))
if noarg and noargs_action == "demo":
sys.argv[1:] = [opt]
# help feature, for displaying classical or extended help about the tool
if add['help']:
if glob.get('__details__'):
opt = i.add_argument("-h", dest="help", default=0, action="count",
help=gt("show extended help message and exit"),
note=gt("-hhh is the highest help detail level"))
else:
opt = i.add_argument("-h", "--help", action='help', prefix="show",
help=gt("show this help message and exit"))
if noarg and noargs_action == "help":
sys.argv[1:] = [opt]
# interaction mode feature, for interacting with the tool during its
# execution, useful for debugging when it is complex
if add['interact']:
j = p.add_argument_group(gt("interaction arguments"))
opt = j.add_argument("--interact", action="store_true",
suffix="mode", help=gt("interaction mode"))
if opt:
j.add_argument("--host", default="127.0.0.1", type=ip_address,
prefix="remote", help=gt("remote interacting host"))
j.add_argument("--port", default=12345, type=port_number,
prefix="remote", help=gt("remote interacting port"))
if noarg and noargs_action == "interact":
sys.argv[1:] = [opt]
# stepping mode feature, for stepping within the tool during its execution,
# especially useful for debugging when it is complex
if add['step']:
opt = i.add_argument("--step", action="store_true", last=True,
suffix="mode", help=gt("stepping mode"))
if noarg and noargs_action == "step":
sys.argv[1:] = [opt]
# timing mode feature, for measuring time along the execution of the tool
if add['time']:
b = p.add_argument_group(gt("timing arguments"))
opt = b.add_argument("--stats", action='store_true', last=True,
prefix="time",
help=gt("display execution time stats at exit"))
b.add_argument("--timings", action='store_true', last=True,
suffix="mode",
help=gt("display time stats during execution"))
if noarg and noargs_action == "time":
sys.argv[1:] = [opt]
# version feature, for displaying the version from __version__
if add['version']:
version = glob['__version__'] if '__version__' in glob else None
if version is not None:
opt = i.add_argument("--version", action='version', prefix="show",
version=version, help=gt("show program's "
"version number and exit"))
if noarg and noargs_action == "version":
sys.argv[1:] = [opt]
# verbosity feature, for displaying debugging messages, with the
# possibility to handle multi-level verbosity
if multi_level_debug:
i.add_argument("-v", dest="verbose", default=0, action="count",
suffix="mode", cancel=True, last=True,
help=gt("verbose level"),
note=gt("-vvv is the highest verbosity level"))
else:
i.add_argument("-v", "--verbose", action="store_true", last=True,
suffix="mode", help=gt("verbose mode"))
# wizard feature, for asking argument values to the user
if add['wizard']:
opt = i.add_argument("-w", "--wizard", action='wizard',
prefix="start", help=gt("start a wizard"))
if noarg and noargs_action == "wizard":
sys.argv[1:] = [opt]
# reporting feature, for making a reporting with the results of the tool
# at the end of its execution
if report_func is not None and PYTHON3:
if not isfunction(report_func):
report_func = None
glob['logger'].error("Bad report generation function")
return
# lazily import report features
# -> reason: they rely on pandas and weasyprint, which take time to be
# imported ; so, when report features are not used in a
# script, report classes won't be loaded
all_list = __import__("tinyscript.report", fromlist=['__all__']).__all__
report = __import__("tinyscript.report", fromlist=all_list)
for f in all_list:
glob[f] = globals()[f] = getattr(report, f)
# now populate the parser with report-related arguments
r = p.add_argument_group(gt("report arguments"))
output_func = list(filter(lambda x: not x[0].startswith('_'),
getmembers(Report, predicate=isfunction)))
choices = list(map(lambda x: x[0], output_func))
if r.add_argument("--output", choices=choices, default="pdf", last=True,
prefix="report", help=gt("report output format")):
r.add_argument("--title", last=True, prefix="report",
help=gt("report title"))
r.add_argument("--css", last=True, prefix="report",
help=gt("report stylesheet file"))
r.add_argument("--theme", default="default", last=True,
prefix="report", help=gt("report stylesheet theme"),
note=gt("--css overrides this setting"))
r.add_argument("--filename", last=True, prefix="report",
help=gt("report filename"))
elif report_func is not None and not PYTHON3:
glob['logger'].warning("Report generation is only for Python 3")
# extended logging features
if ext_logging:
i.add_argument("-f", "--logfile", last=True,
help=gt("destination log file"))
i.add_argument("-r", "--relative", action="store_true", last=True,
suffix="time", help=gt("display relative time"))
if LINUX:
i.add_argument("-s", "--syslog", action="store_true", last=True,
suffix="mode", help=gt("log to /var/log/syslog"))
glob['args'], glob['parser'] = p.parse_args(), p
# 3) if sudo required, restart the script
if sudo:
# if not root, restart the script in another process and jump to this
if os.geteuid() != 0:
python = [] if glob['__file__'].startswith("./") else ["python"]
os.execvp("sudo", ["sudo"] + python + sys.argv)
# 4) configure logging and get the main logger
configure_logger(glob, multi_level_debug,
glob['args']._collisions.get("relative"),
glob['args']._collisions.get("logfile"),
glob['args']._collisions.get("syslog"))
# 5) append modes items
set_interact_items(glob)
set_step_items(glob)
set_time_items(glob)
# 6) finally, bind the global exit handler
def __at_exit():
# first, dump the config if required
if add['config']:
_save_config(glob)
# then handle the state
if _hooks.state == "INTERRUPTED":
glob['at_interrupt']()
elif _hooks.state == "TERMINATED":
glob['at_terminate']()
else:
if report_func is not None and PYTHON3:
# generate the report only when exiting gracefully, just before
# the user-defined function at_graceful_exit
_ = glob['args']
r = Report(*report_func(), title=_.title, filename=_.filename,
logger=glob['logger'], css=_.css)
getattr(r, _.output)(False)
t = glob['time_manager']
if add['time'] and t._stats:
t.stats()
glob['at_graceful_exit']()
glob['at_exit']()
logging.shutdown()
atexit.register(__at_exit) | python | def initialize(glob,
sudo=False,
multi_level_debug=False,
add_config=False,
add_demo=False,
add_interact=False,
add_step=False,
add_time=False,
add_version=False,
add_wizard=False,
ext_logging=False,
noargs_action=None,
report_func=None):
"""
Initialization function ; sets up the arguments for the parser and creates a
logger to be inserted in the input dictionary of global variables from the
calling script.
:param glob: globals() instance from the calling script
:param sudo: if True, require sudo credentials and re-run
script with sudo
:param multi_level_debug: allow to use -v, -vv, -vvv (adjust logging level)
instead of just -v (only debug on/off)
:param relative_time: use relative time for log messages
:param add_config: add an option to input an INI configuration file
:param add_demo: add an option to re-run the process using a random
entry from the __examples__ (only works if this
variable is populated)
:param add_interact: add an interaction option
:param add_step: add an execution stepping option
:param add_time: add an execution timing option
:param add_version: add a version option
:param add_wizard: add an option to run a wizard, asking for each
input argument
:param ext_logging: extended logging options
:param noargs_action: action to be performed when no argument is input
:param report_func: report generation function
"""
global parser, __parsers
add = {'config': add_config, 'demo': add_demo, 'interact': add_interact,
'step': add_step, 'time': add_time, 'version': add_version,
'wizard': add_wizard, 'help': True}
p = ArgumentParser(glob)
# 1) handle action when no input argument is given
add['demo'] = add['demo'] and p.examples
noarg = len(sys.argv) == 1
if noarg and noargs_action:
if noargs_action not in add.keys():
raise ValueError("Bad action when no args (should be one of: {})"
.format('|'.join(add.keys())))
add[noargs_action] = True # ensure this action is enabled, even if it
# is not given the passed arguments
# 2) populate the real parser and add information arguments
__parsers = {}
__get_calls_from_parser(parser, p)
# config handling feature, for reading/writing an INI config file with the
# input arguments, e.g. for future reuse
if add['config']:
c = p.add_argument_group(gt("config arguments"))
opt = c.add_argument("-r", "--read-config", action='config',
help=gt("read args from a config file"),
note=gt("this overrides other arguments"))
c.add_argument("-w", "--write-config", metavar="INI",
help=gt("write args to a config file"))
if noarg and noargs_action == "config":
sys.argv[1:] = [opt, "config.ini"]
i = p.add_argument_group(gt("extra arguments"))
# demonstration feature, for executing an example amongst these defined in
# __examples__, useful for observing what the tool does
if add['demo']:
opt = i.add_argument("--demo", action='demo', prefix="play",
help=gt("demonstrate a random example"))
if noarg and noargs_action == "demo":
sys.argv[1:] = [opt]
# help feature, for displaying classical or extended help about the tool
if add['help']:
if glob.get('__details__'):
opt = i.add_argument("-h", dest="help", default=0, action="count",
help=gt("show extended help message and exit"),
note=gt("-hhh is the highest help detail level"))
else:
opt = i.add_argument("-h", "--help", action='help', prefix="show",
help=gt("show this help message and exit"))
if noarg and noargs_action == "help":
sys.argv[1:] = [opt]
# interaction mode feature, for interacting with the tool during its
# execution, useful for debugging when it is complex
if add['interact']:
j = p.add_argument_group(gt("interaction arguments"))
opt = j.add_argument("--interact", action="store_true",
suffix="mode", help=gt("interaction mode"))
if opt:
j.add_argument("--host", default="127.0.0.1", type=ip_address,
prefix="remote", help=gt("remote interacting host"))
j.add_argument("--port", default=12345, type=port_number,
prefix="remote", help=gt("remote interacting port"))
if noarg and noargs_action == "interact":
sys.argv[1:] = [opt]
# stepping mode feature, for stepping within the tool during its execution,
# especially useful for debugging when it is complex
if add['step']:
opt = i.add_argument("--step", action="store_true", last=True,
suffix="mode", help=gt("stepping mode"))
if noarg and noargs_action == "step":
sys.argv[1:] = [opt]
# timing mode feature, for measuring time along the execution of the tool
if add['time']:
b = p.add_argument_group(gt("timing arguments"))
opt = b.add_argument("--stats", action='store_true', last=True,
prefix="time",
help=gt("display execution time stats at exit"))
b.add_argument("--timings", action='store_true', last=True,
suffix="mode",
help=gt("display time stats during execution"))
if noarg and noargs_action == "time":
sys.argv[1:] = [opt]
# version feature, for displaying the version from __version__
if add['version']:
version = glob['__version__'] if '__version__' in glob else None
if version is not None:
opt = i.add_argument("--version", action='version', prefix="show",
version=version, help=gt("show program's "
"version number and exit"))
if noarg and noargs_action == "version":
sys.argv[1:] = [opt]
# verbosity feature, for displaying debugging messages, with the
# possibility to handle multi-level verbosity
if multi_level_debug:
i.add_argument("-v", dest="verbose", default=0, action="count",
suffix="mode", cancel=True, last=True,
help=gt("verbose level"),
note=gt("-vvv is the highest verbosity level"))
else:
i.add_argument("-v", "--verbose", action="store_true", last=True,
suffix="mode", help=gt("verbose mode"))
# wizard feature, for asking argument values to the user
if add['wizard']:
opt = i.add_argument("-w", "--wizard", action='wizard',
prefix="start", help=gt("start a wizard"))
if noarg and noargs_action == "wizard":
sys.argv[1:] = [opt]
# reporting feature, for making a reporting with the results of the tool
# at the end of its execution
if report_func is not None and PYTHON3:
if not isfunction(report_func):
report_func = None
glob['logger'].error("Bad report generation function")
return
# lazily import report features
# -> reason: they rely on pandas and weasyprint, which take time to be
# imported ; so, when report features are not used in a
# script, report classes won't be loaded
all_list = __import__("tinyscript.report", fromlist=['__all__']).__all__
report = __import__("tinyscript.report", fromlist=all_list)
for f in all_list:
glob[f] = globals()[f] = getattr(report, f)
# now populate the parser with report-related arguments
r = p.add_argument_group(gt("report arguments"))
output_func = list(filter(lambda x: not x[0].startswith('_'),
getmembers(Report, predicate=isfunction)))
choices = list(map(lambda x: x[0], output_func))
if r.add_argument("--output", choices=choices, default="pdf", last=True,
prefix="report", help=gt("report output format")):
r.add_argument("--title", last=True, prefix="report",
help=gt("report title"))
r.add_argument("--css", last=True, prefix="report",
help=gt("report stylesheet file"))
r.add_argument("--theme", default="default", last=True,
prefix="report", help=gt("report stylesheet theme"),
note=gt("--css overrides this setting"))
r.add_argument("--filename", last=True, prefix="report",
help=gt("report filename"))
elif report_func is not None and not PYTHON3:
glob['logger'].warning("Report generation is only for Python 3")
# extended logging features
if ext_logging:
i.add_argument("-f", "--logfile", last=True,
help=gt("destination log file"))
i.add_argument("-r", "--relative", action="store_true", last=True,
suffix="time", help=gt("display relative time"))
if LINUX:
i.add_argument("-s", "--syslog", action="store_true", last=True,
suffix="mode", help=gt("log to /var/log/syslog"))
glob['args'], glob['parser'] = p.parse_args(), p
# 3) if sudo required, restart the script
if sudo:
# if not root, restart the script in another process and jump to this
if os.geteuid() != 0:
python = [] if glob['__file__'].startswith("./") else ["python"]
os.execvp("sudo", ["sudo"] + python + sys.argv)
# 4) configure logging and get the main logger
configure_logger(glob, multi_level_debug,
glob['args']._collisions.get("relative"),
glob['args']._collisions.get("logfile"),
glob['args']._collisions.get("syslog"))
# 5) append modes items
set_interact_items(glob)
set_step_items(glob)
set_time_items(glob)
# 6) finally, bind the global exit handler
def __at_exit():
# first, dump the config if required
if add['config']:
_save_config(glob)
# then handle the state
if _hooks.state == "INTERRUPTED":
glob['at_interrupt']()
elif _hooks.state == "TERMINATED":
glob['at_terminate']()
else:
if report_func is not None and PYTHON3:
# generate the report only when exiting gracefully, just before
# the user-defined function at_graceful_exit
_ = glob['args']
r = Report(*report_func(), title=_.title, filename=_.filename,
logger=glob['logger'], css=_.css)
getattr(r, _.output)(False)
t = glob['time_manager']
if add['time'] and t._stats:
t.stats()
glob['at_graceful_exit']()
glob['at_exit']()
logging.shutdown()
atexit.register(__at_exit) | [
"def",
"initialize",
"(",
"glob",
",",
"sudo",
"=",
"False",
",",
"multi_level_debug",
"=",
"False",
",",
"add_config",
"=",
"False",
",",
"add_demo",
"=",
"False",
",",
"add_interact",
"=",
"False",
",",
"add_step",
"=",
"False",
",",
"add_time",
"=",
"... | Initialization function ; sets up the arguments for the parser and creates a
logger to be inserted in the input dictionary of global variables from the
calling script.
:param glob: globals() instance from the calling script
:param sudo: if True, require sudo credentials and re-run
script with sudo
:param multi_level_debug: allow to use -v, -vv, -vvv (adjust logging level)
instead of just -v (only debug on/off)
:param relative_time: use relative time for log messages
:param add_config: add an option to input an INI configuration file
:param add_demo: add an option to re-run the process using a random
entry from the __examples__ (only works if this
variable is populated)
:param add_interact: add an interaction option
:param add_step: add an execution stepping option
:param add_time: add an execution timing option
:param add_version: add a version option
:param add_wizard: add an option to run a wizard, asking for each
input argument
:param ext_logging: extended logging options
:param noargs_action: action to be performed when no argument is input
:param report_func: report generation function | [
"Initialization",
"function",
";",
"sets",
"up",
"the",
"arguments",
"for",
"the",
"parser",
"and",
"creates",
"a",
"logger",
"to",
"be",
"inserted",
"in",
"the",
"input",
"dictionary",
"of",
"global",
"variables",
"from",
"the",
"calling",
"script",
"."
] | train | https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/parser.py#L78-L302 |
dhondta/tinyscript | tinyscript/parser.py | validate | def validate(glob, *arg_checks):
"""
Function for validating group of arguments ; each argument is represented as
a 4-tuple like follows:
(argument_name, fail_condition, error_message, default)
- argument_name: the name of the argument like entered in add_argument()
- fail_condition: condition in Python code with the argument name
replaced by ' ? ' (e.g. " ? > 0")
- error_message: message describing what failed with the validation ofs
the current argument
- default [optional]: value to be given if the validation fails ; this
implies that the script will not exit after the
validation (if no other blocking argument present)
:param glob: globals() instance from the calling script
:param arg_checks: list of 3/4-tuples
"""
locals().update(glob) # allows to import user-defined objects from glob
# into the local scope
if glob['args'] is None or glob['logger'] is None:
return
exit_app = False
for check in arg_checks:
check = check + (None, ) * (4 - len(check))
param, condition, message, default = check
if re.match(r'^_?[a-zA-Z][a-zA-Z0-9_]*$', param) is None:
raise ValueError("Illegal argument name")
try:
result = eval(condition.replace(" ? ", " glob['args'].{} "
.format(param)))
except Exception as e:
result = True
message = str(e)
if result:
if default is None:
glob['logger'].error(message or "Validation failed")
exit_app = True
else:
glob['logger'].warning(message or "Validation failed")
setattr(glob['args'], param, default)
if exit_app:
sys.exit(2) | python | def validate(glob, *arg_checks):
"""
Function for validating group of arguments ; each argument is represented as
a 4-tuple like follows:
(argument_name, fail_condition, error_message, default)
- argument_name: the name of the argument like entered in add_argument()
- fail_condition: condition in Python code with the argument name
replaced by ' ? ' (e.g. " ? > 0")
- error_message: message describing what failed with the validation ofs
the current argument
- default [optional]: value to be given if the validation fails ; this
implies that the script will not exit after the
validation (if no other blocking argument present)
:param glob: globals() instance from the calling script
:param arg_checks: list of 3/4-tuples
"""
locals().update(glob) # allows to import user-defined objects from glob
# into the local scope
if glob['args'] is None or glob['logger'] is None:
return
exit_app = False
for check in arg_checks:
check = check + (None, ) * (4 - len(check))
param, condition, message, default = check
if re.match(r'^_?[a-zA-Z][a-zA-Z0-9_]*$', param) is None:
raise ValueError("Illegal argument name")
try:
result = eval(condition.replace(" ? ", " glob['args'].{} "
.format(param)))
except Exception as e:
result = True
message = str(e)
if result:
if default is None:
glob['logger'].error(message or "Validation failed")
exit_app = True
else:
glob['logger'].warning(message or "Validation failed")
setattr(glob['args'], param, default)
if exit_app:
sys.exit(2) | [
"def",
"validate",
"(",
"glob",
",",
"*",
"arg_checks",
")",
":",
"locals",
"(",
")",
".",
"update",
"(",
"glob",
")",
"# allows to import user-defined objects from glob",
"# into the local scope",
"if",
"glob",
"[",
"'args'",
"]",
"is",
"None",
"or",
"glob",
... | Function for validating group of arguments ; each argument is represented as
a 4-tuple like follows:
(argument_name, fail_condition, error_message, default)
- argument_name: the name of the argument like entered in add_argument()
- fail_condition: condition in Python code with the argument name
replaced by ' ? ' (e.g. " ? > 0")
- error_message: message describing what failed with the validation ofs
the current argument
- default [optional]: value to be given if the validation fails ; this
implies that the script will not exit after the
validation (if no other blocking argument present)
:param glob: globals() instance from the calling script
:param arg_checks: list of 3/4-tuples | [
"Function",
"for",
"validating",
"group",
"of",
"arguments",
";",
"each",
"argument",
"is",
"represented",
"as",
"a",
"4",
"-",
"tuple",
"like",
"follows",
":"
] | train | https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/parser.py#L305-L348 |
LCAV/pylocus | pylocus/basics.py | mse | def mse(x, xhat):
""" Calcualte mse between vector or matrix x and xhat """
buf_ = x - xhat
np.square(buf_, out=buf_) # square in-place
sum_ = np.sum(buf_)
sum_ /= x.size # divide in-place
return sum_ | python | def mse(x, xhat):
""" Calcualte mse between vector or matrix x and xhat """
buf_ = x - xhat
np.square(buf_, out=buf_) # square in-place
sum_ = np.sum(buf_)
sum_ /= x.size # divide in-place
return sum_ | [
"def",
"mse",
"(",
"x",
",",
"xhat",
")",
":",
"buf_",
"=",
"x",
"-",
"xhat",
"np",
".",
"square",
"(",
"buf_",
",",
"out",
"=",
"buf_",
")",
"# square in-place",
"sum_",
"=",
"np",
".",
"sum",
"(",
"buf_",
")",
"sum_",
"/=",
"x",
".",
"size",
... | Calcualte mse between vector or matrix x and xhat | [
"Calcualte",
"mse",
"between",
"vector",
"or",
"matrix",
"x",
"and",
"xhat"
] | train | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/basics.py#L6-L12 |
LCAV/pylocus | pylocus/basics.py | low_rank_approximation | def low_rank_approximation(A, r):
""" Returns approximation of A of rank r in least-squares sense."""
try:
u, s, v = np.linalg.svd(A, full_matrices=False)
except np.linalg.LinAlgError as e:
print('Matrix:', A)
print('Matrix rank:', np.linalg.matrix_rank(A))
raise
Ar = np.zeros((len(u), len(v)), dtype=u.dtype)
buf_ = np.empty_like(Ar)
sc_vec_ = np.empty((v.shape[1],), dtype=v.dtype)
for i in range(r):
np.multiply(v[i], s[i], out=sc_vec_)
np.outer(u[:, i], sc_vec_, out=buf_)
Ar += buf_
return Ar | python | def low_rank_approximation(A, r):
""" Returns approximation of A of rank r in least-squares sense."""
try:
u, s, v = np.linalg.svd(A, full_matrices=False)
except np.linalg.LinAlgError as e:
print('Matrix:', A)
print('Matrix rank:', np.linalg.matrix_rank(A))
raise
Ar = np.zeros((len(u), len(v)), dtype=u.dtype)
buf_ = np.empty_like(Ar)
sc_vec_ = np.empty((v.shape[1],), dtype=v.dtype)
for i in range(r):
np.multiply(v[i], s[i], out=sc_vec_)
np.outer(u[:, i], sc_vec_, out=buf_)
Ar += buf_
return Ar | [
"def",
"low_rank_approximation",
"(",
"A",
",",
"r",
")",
":",
"try",
":",
"u",
",",
"s",
",",
"v",
"=",
"np",
".",
"linalg",
".",
"svd",
"(",
"A",
",",
"full_matrices",
"=",
"False",
")",
"except",
"np",
".",
"linalg",
".",
"LinAlgError",
"as",
... | Returns approximation of A of rank r in least-squares sense. | [
"Returns",
"approximation",
"of",
"A",
"of",
"rank",
"r",
"in",
"least",
"-",
"squares",
"sense",
"."
] | train | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/basics.py#L28-L44 |
LCAV/pylocus | pylocus/basics.py | eigendecomp | def eigendecomp(G, d):
"""
Computes sorted eigendecomposition of G.
:param G: Matrix
:param d: rank
:return factor: vector of square root d of eigenvalues (biggest to smallest).
:return u: matrix with colums equal to the normalized eigenvectors corresponding to sorted eigenvalues.
"""
N = G.shape[0]
lamda, u = np.linalg.eig(G)
# test decomposition of G.
#G_hat = np.dot(np.dot(u, np.diag(lamda)), u.T)
#assert np.linalg.norm(G_hat - G) < 1e-10, 'decomposition not exact: err {}'.format(np.linalg.norm(G_hat - G))
# sort the eigenvalues in decreasing order
lamda = np.real(lamda)
indices = np.argsort(lamda)[::-1]
lamda_sorted = lamda[indices]
assert (lamda_sorted[
:d] > -1e-10).all(), "{} not all positive!".format(lamda_sorted[:d])
u = u[:, indices]
factor = np.empty((N,), dtype=lamda.dtype)
np.sqrt(lamda_sorted[:d], out=factor[0:d])
factor[d:] = 0.0
return factor, np.real(u) | python | def eigendecomp(G, d):
"""
Computes sorted eigendecomposition of G.
:param G: Matrix
:param d: rank
:return factor: vector of square root d of eigenvalues (biggest to smallest).
:return u: matrix with colums equal to the normalized eigenvectors corresponding to sorted eigenvalues.
"""
N = G.shape[0]
lamda, u = np.linalg.eig(G)
# test decomposition of G.
#G_hat = np.dot(np.dot(u, np.diag(lamda)), u.T)
#assert np.linalg.norm(G_hat - G) < 1e-10, 'decomposition not exact: err {}'.format(np.linalg.norm(G_hat - G))
# sort the eigenvalues in decreasing order
lamda = np.real(lamda)
indices = np.argsort(lamda)[::-1]
lamda_sorted = lamda[indices]
assert (lamda_sorted[
:d] > -1e-10).all(), "{} not all positive!".format(lamda_sorted[:d])
u = u[:, indices]
factor = np.empty((N,), dtype=lamda.dtype)
np.sqrt(lamda_sorted[:d], out=factor[0:d])
factor[d:] = 0.0
return factor, np.real(u) | [
"def",
"eigendecomp",
"(",
"G",
",",
"d",
")",
":",
"N",
"=",
"G",
".",
"shape",
"[",
"0",
"]",
"lamda",
",",
"u",
"=",
"np",
".",
"linalg",
".",
"eig",
"(",
"G",
")",
"# test decomposition of G.",
"#G_hat = np.dot(np.dot(u, np.diag(lamda)), u.T)",
"#asser... | Computes sorted eigendecomposition of G.
:param G: Matrix
:param d: rank
:return factor: vector of square root d of eigenvalues (biggest to smallest).
:return u: matrix with colums equal to the normalized eigenvectors corresponding to sorted eigenvalues. | [
"Computes",
"sorted",
"eigendecomposition",
"of",
"G",
"."
] | train | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/basics.py#L62-L89 |
LCAV/pylocus | pylocus/basics.py | projection | def projection(x, A, b):
""" Returns the vector xhat closest to x in 2-norm, satisfying A.xhat =b.
:param x: vector
:param A, b: matrix and array characterizing the constraints on x (A.x = b)
:return x_hat: optimum angle vector, minimizing cost.
:return cost: least square error of xhat, x
:return constraints_error: mse of constraint.
:rtype: (numpy.ndarray, float, float)
"""
A_pseudoinv = pseudo_inverse(A)
tmp_ = A.dot(x)
tmp_ -= b
x_hat = A_pseudoinv.dot(tmp_)
np.subtract(x, x_hat, out=x_hat)
cost = mse(x_hat, x)
A.dot(x_hat, out=tmp_)
constraints_error = mse(tmp_, b)
return x_hat, cost, constraints_error | python | def projection(x, A, b):
""" Returns the vector xhat closest to x in 2-norm, satisfying A.xhat =b.
:param x: vector
:param A, b: matrix and array characterizing the constraints on x (A.x = b)
:return x_hat: optimum angle vector, minimizing cost.
:return cost: least square error of xhat, x
:return constraints_error: mse of constraint.
:rtype: (numpy.ndarray, float, float)
"""
A_pseudoinv = pseudo_inverse(A)
tmp_ = A.dot(x)
tmp_ -= b
x_hat = A_pseudoinv.dot(tmp_)
np.subtract(x, x_hat, out=x_hat)
cost = mse(x_hat, x)
A.dot(x_hat, out=tmp_)
constraints_error = mse(tmp_, b)
return x_hat, cost, constraints_error | [
"def",
"projection",
"(",
"x",
",",
"A",
",",
"b",
")",
":",
"A_pseudoinv",
"=",
"pseudo_inverse",
"(",
"A",
")",
"tmp_",
"=",
"A",
".",
"dot",
"(",
"x",
")",
"tmp_",
"-=",
"b",
"x_hat",
"=",
"A_pseudoinv",
".",
"dot",
"(",
"tmp_",
")",
"np",
"... | Returns the vector xhat closest to x in 2-norm, satisfying A.xhat =b.
:param x: vector
:param A, b: matrix and array characterizing the constraints on x (A.x = b)
:return x_hat: optimum angle vector, minimizing cost.
:return cost: least square error of xhat, x
:return constraints_error: mse of constraint.
:rtype: (numpy.ndarray, float, float) | [
"Returns",
"the",
"vector",
"xhat",
"closest",
"to",
"x",
"in",
"2",
"-",
"norm",
"satisfying",
"A",
".",
"xhat",
"=",
"b",
"."
] | train | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/basics.py#L143-L163 |
agoragames/chai | chai/comparators.py | build_comparators | def build_comparators(*values_or_types):
'''
All of the comparators that can be used for arguments.
'''
comparators = []
for item in values_or_types:
if isinstance(item, Comparator):
comparators.append(item)
elif isinstance(item, type):
# If you are passing around a type you will have to build a Equals
# comparator
comparators.append(Any(IsA(item), Is(item)))
else:
comparators.append(Equals(item))
return comparators | python | def build_comparators(*values_or_types):
'''
All of the comparators that can be used for arguments.
'''
comparators = []
for item in values_or_types:
if isinstance(item, Comparator):
comparators.append(item)
elif isinstance(item, type):
# If you are passing around a type you will have to build a Equals
# comparator
comparators.append(Any(IsA(item), Is(item)))
else:
comparators.append(Equals(item))
return comparators | [
"def",
"build_comparators",
"(",
"*",
"values_or_types",
")",
":",
"comparators",
"=",
"[",
"]",
"for",
"item",
"in",
"values_or_types",
":",
"if",
"isinstance",
"(",
"item",
",",
"Comparator",
")",
":",
"comparators",
".",
"append",
"(",
"item",
")",
"eli... | All of the comparators that can be used for arguments. | [
"All",
"of",
"the",
"comparators",
"that",
"can",
"be",
"used",
"for",
"arguments",
"."
] | train | https://github.com/agoragames/chai/blob/8148d7b7754226b0d1cabfc2af10cd912612abdc/chai/comparators.py#L9-L23 |
toumorokoshi/transmute-core | ubuild.py | changelog | def changelog(build):
""" create a changelog """
build.packages.install("gitchangelog")
changelog_text = subprocess.check_output(["gitchangelog", "HEAD...v0.2.9"])
with open(os.path.join(build.root, "CHANGELOG"), "wb+") as fh:
fh.write(changelog_text) | python | def changelog(build):
""" create a changelog """
build.packages.install("gitchangelog")
changelog_text = subprocess.check_output(["gitchangelog", "HEAD...v0.2.9"])
with open(os.path.join(build.root, "CHANGELOG"), "wb+") as fh:
fh.write(changelog_text) | [
"def",
"changelog",
"(",
"build",
")",
":",
"build",
".",
"packages",
".",
"install",
"(",
"\"gitchangelog\"",
")",
"changelog_text",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"\"gitchangelog\"",
",",
"\"HEAD...v0.2.9\"",
"]",
")",
"with",
"open",
"(",... | create a changelog | [
"create",
"a",
"changelog"
] | train | https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/ubuild.py#L50-L55 |
agoragames/chai | chai/expectation.py | Expectation.args | def args(self, *args, **kwargs):
"""
Creates a ArgumentsExpectationRule and adds it to the expectation
"""
self._any_args = False
self._arguments_rule.set_args(*args, **kwargs)
return self | python | def args(self, *args, **kwargs):
"""
Creates a ArgumentsExpectationRule and adds it to the expectation
"""
self._any_args = False
self._arguments_rule.set_args(*args, **kwargs)
return self | [
"def",
"args",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_any_args",
"=",
"False",
"self",
".",
"_arguments_rule",
".",
"set_args",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"self"
] | Creates a ArgumentsExpectationRule and adds it to the expectation | [
"Creates",
"a",
"ArgumentsExpectationRule",
"and",
"adds",
"it",
"to",
"the",
"expectation"
] | train | https://github.com/agoragames/chai/blob/8148d7b7754226b0d1cabfc2af10cd912612abdc/chai/expectation.py#L139-L145 |
agoragames/chai | chai/expectation.py | Expectation.return_value | def return_value(self):
"""
Returns the value for this expectation or raises the proper exception.
"""
if self._raises:
# Handle exceptions
if inspect.isclass(self._raises):
raise self._raises()
else:
raise self._raises
else:
if isinstance(self._returns, tuple):
return tuple([x.value if isinstance(x, Variable)
else x for x in self._returns])
return self._returns.value if isinstance(self._returns, Variable) \
else self._returns | python | def return_value(self):
"""
Returns the value for this expectation or raises the proper exception.
"""
if self._raises:
# Handle exceptions
if inspect.isclass(self._raises):
raise self._raises()
else:
raise self._raises
else:
if isinstance(self._returns, tuple):
return tuple([x.value if isinstance(x, Variable)
else x for x in self._returns])
return self._returns.value if isinstance(self._returns, Variable) \
else self._returns | [
"def",
"return_value",
"(",
"self",
")",
":",
"if",
"self",
".",
"_raises",
":",
"# Handle exceptions",
"if",
"inspect",
".",
"isclass",
"(",
"self",
".",
"_raises",
")",
":",
"raise",
"self",
".",
"_raises",
"(",
")",
"else",
":",
"raise",
"self",
"."... | Returns the value for this expectation or raises the proper exception. | [
"Returns",
"the",
"value",
"for",
"this",
"expectation",
"or",
"raises",
"the",
"proper",
"exception",
"."
] | train | https://github.com/agoragames/chai/blob/8148d7b7754226b0d1cabfc2af10cd912612abdc/chai/expectation.py#L226-L241 |
agoragames/chai | chai/expectation.py | Expectation.match | def match(self, *args, **kwargs):
"""
Check the if these args match this expectation.
"""
return self._any_args or \
self._arguments_rule.validate(*args, **kwargs) | python | def match(self, *args, **kwargs):
"""
Check the if these args match this expectation.
"""
return self._any_args or \
self._arguments_rule.validate(*args, **kwargs) | [
"def",
"match",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_any_args",
"or",
"self",
".",
"_arguments_rule",
".",
"validate",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Check the if these args match this expectation. | [
"Check",
"the",
"if",
"these",
"args",
"match",
"this",
"expectation",
"."
] | train | https://github.com/agoragames/chai/blob/8148d7b7754226b0d1cabfc2af10cd912612abdc/chai/expectation.py#L265-L270 |
inveniosoftware/invenio-previewer | invenio_previewer/ext.py | _InvenioPreviewerState.record_file_factory | def record_file_factory(self):
"""Load default record file factory."""
try:
get_distribution('invenio-records-files')
from invenio_records_files.utils import record_file_factory
default = record_file_factory
except DistributionNotFound:
def default(pid, record, filename):
return None
return load_or_import_from_config(
'PREVIEWER_RECORD_FILE_FACOTRY',
app=self.app,
default=default,
) | python | def record_file_factory(self):
"""Load default record file factory."""
try:
get_distribution('invenio-records-files')
from invenio_records_files.utils import record_file_factory
default = record_file_factory
except DistributionNotFound:
def default(pid, record, filename):
return None
return load_or_import_from_config(
'PREVIEWER_RECORD_FILE_FACOTRY',
app=self.app,
default=default,
) | [
"def",
"record_file_factory",
"(",
"self",
")",
":",
"try",
":",
"get_distribution",
"(",
"'invenio-records-files'",
")",
"from",
"invenio_records_files",
".",
"utils",
"import",
"record_file_factory",
"default",
"=",
"record_file_factory",
"except",
"DistributionNotFound... | Load default record file factory. | [
"Load",
"default",
"record",
"file",
"factory",
"."
] | train | https://github.com/inveniosoftware/invenio-previewer/blob/558fd22e0f29cc8cd7a6999abd4febcf6b248c49/invenio_previewer/ext.py#L57-L71 |
inveniosoftware/invenio-previewer | invenio_previewer/ext.py | _InvenioPreviewerState.register_previewer | def register_previewer(self, name, previewer):
"""Register a previewer in the system."""
if name in self.previewers:
assert name not in self.previewers, \
"Previewer with same name already registered"
self.previewers[name] = previewer
if hasattr(previewer, 'previewable_extensions'):
self._previewable_extensions |= set(
previewer.previewable_extensions) | python | def register_previewer(self, name, previewer):
"""Register a previewer in the system."""
if name in self.previewers:
assert name not in self.previewers, \
"Previewer with same name already registered"
self.previewers[name] = previewer
if hasattr(previewer, 'previewable_extensions'):
self._previewable_extensions |= set(
previewer.previewable_extensions) | [
"def",
"register_previewer",
"(",
"self",
",",
"name",
",",
"previewer",
")",
":",
"if",
"name",
"in",
"self",
".",
"previewers",
":",
"assert",
"name",
"not",
"in",
"self",
".",
"previewers",
",",
"\"Previewer with same name already registered\"",
"self",
".",
... | Register a previewer in the system. | [
"Register",
"a",
"previewer",
"in",
"the",
"system",
"."
] | train | https://github.com/inveniosoftware/invenio-previewer/blob/558fd22e0f29cc8cd7a6999abd4febcf6b248c49/invenio_previewer/ext.py#L81-L89 |
inveniosoftware/invenio-previewer | invenio_previewer/ext.py | _InvenioPreviewerState.iter_previewers | def iter_previewers(self, previewers=None):
"""Get previewers ordered by PREVIEWER_PREVIEWERS_ORDER."""
if self.entry_point_group is not None:
self.load_entry_point_group(self.entry_point_group)
self.entry_point_group = None
previewers = previewers or \
self.app.config.get('PREVIEWER_PREFERENCE', [])
for item in previewers:
if item in self.previewers:
yield self.previewers[item] | python | def iter_previewers(self, previewers=None):
"""Get previewers ordered by PREVIEWER_PREVIEWERS_ORDER."""
if self.entry_point_group is not None:
self.load_entry_point_group(self.entry_point_group)
self.entry_point_group = None
previewers = previewers or \
self.app.config.get('PREVIEWER_PREFERENCE', [])
for item in previewers:
if item in self.previewers:
yield self.previewers[item] | [
"def",
"iter_previewers",
"(",
"self",
",",
"previewers",
"=",
"None",
")",
":",
"if",
"self",
".",
"entry_point_group",
"is",
"not",
"None",
":",
"self",
".",
"load_entry_point_group",
"(",
"self",
".",
"entry_point_group",
")",
"self",
".",
"entry_point_grou... | Get previewers ordered by PREVIEWER_PREVIEWERS_ORDER. | [
"Get",
"previewers",
"ordered",
"by",
"PREVIEWER_PREVIEWERS_ORDER",
"."
] | train | https://github.com/inveniosoftware/invenio-previewer/blob/558fd22e0f29cc8cd7a6999abd4febcf6b248c49/invenio_previewer/ext.py#L96-L107 |
inveniosoftware/invenio-previewer | invenio_previewer/ext.py | InvenioPreviewer.init_app | def init_app(self, app, entry_point_group='invenio_previewer.previewers'):
"""Flask application initialization."""
self.init_config(app)
app.register_blueprint(blueprint)
state = _InvenioPreviewerState(
app,
entry_point_group=entry_point_group)
app.extensions['invenio-previewer'] = state
return state | python | def init_app(self, app, entry_point_group='invenio_previewer.previewers'):
"""Flask application initialization."""
self.init_config(app)
app.register_blueprint(blueprint)
state = _InvenioPreviewerState(
app,
entry_point_group=entry_point_group)
app.extensions['invenio-previewer'] = state
return state | [
"def",
"init_app",
"(",
"self",
",",
"app",
",",
"entry_point_group",
"=",
"'invenio_previewer.previewers'",
")",
":",
"self",
".",
"init_config",
"(",
"app",
")",
"app",
".",
"register_blueprint",
"(",
"blueprint",
")",
"state",
"=",
"_InvenioPreviewerState",
"... | Flask application initialization. | [
"Flask",
"application",
"initialization",
"."
] | train | https://github.com/inveniosoftware/invenio-previewer/blob/558fd22e0f29cc8cd7a6999abd4febcf6b248c49/invenio_previewer/ext.py#L118-L126 |
d0ugal/python-rfxcom | rfxcom/protocol/humidity.py | Humidity.parse | def parse(self, data):
"""Parse a 9 bytes packet in the Humidity format and return a
dictionary containing the data extracted. An example of a return value
would be:
.. code-block:: python
{
'id': "0x2EB2",
'packet_length': 8,
'packet_type': 81,
'packet_type_name': 'Humidity sensors',
'sequence_number': 0,
'packet_subtype': 1,
'packet_subtype_name': "LaCrosse TX3",
'humidity': 91,
'humidity_status': "Wet"
'signal_level': 9,
'battery_level': 6,
}
:param data: bytearray to be parsed
:type data: bytearray
:return: Data dictionary containing the parsed values
:rtype: dict
"""
self.validate_packet(data)
id_ = self.dump_hex(data[4:6])
# channel = data[5] TBC
humidity = data[6]
humidity_status = self._extract_humidity_status(data[7])
sensor_specific = {
'id': id_,
# 'channel': channel, TBC
'humidity': humidity,
'humidity_status': humidity_status
}
results = self.parse_header_part(data)
results.update(RfxPacketUtils.parse_signal_and_battery(data[8]))
results.update(sensor_specific)
return results | python | def parse(self, data):
"""Parse a 9 bytes packet in the Humidity format and return a
dictionary containing the data extracted. An example of a return value
would be:
.. code-block:: python
{
'id': "0x2EB2",
'packet_length': 8,
'packet_type': 81,
'packet_type_name': 'Humidity sensors',
'sequence_number': 0,
'packet_subtype': 1,
'packet_subtype_name': "LaCrosse TX3",
'humidity': 91,
'humidity_status': "Wet"
'signal_level': 9,
'battery_level': 6,
}
:param data: bytearray to be parsed
:type data: bytearray
:return: Data dictionary containing the parsed values
:rtype: dict
"""
self.validate_packet(data)
id_ = self.dump_hex(data[4:6])
# channel = data[5] TBC
humidity = data[6]
humidity_status = self._extract_humidity_status(data[7])
sensor_specific = {
'id': id_,
# 'channel': channel, TBC
'humidity': humidity,
'humidity_status': humidity_status
}
results = self.parse_header_part(data)
results.update(RfxPacketUtils.parse_signal_and_battery(data[8]))
results.update(sensor_specific)
return results | [
"def",
"parse",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"validate_packet",
"(",
"data",
")",
"id_",
"=",
"self",
".",
"dump_hex",
"(",
"data",
"[",
"4",
":",
"6",
"]",
")",
"# channel = data[5] TBC",
"humidity",
"=",
"data",
"[",
"6",
"]",
... | Parse a 9 bytes packet in the Humidity format and return a
dictionary containing the data extracted. An example of a return value
would be:
.. code-block:: python
{
'id': "0x2EB2",
'packet_length': 8,
'packet_type': 81,
'packet_type_name': 'Humidity sensors',
'sequence_number': 0,
'packet_subtype': 1,
'packet_subtype_name': "LaCrosse TX3",
'humidity': 91,
'humidity_status': "Wet"
'signal_level': 9,
'battery_level': 6,
}
:param data: bytearray to be parsed
:type data: bytearray
:return: Data dictionary containing the parsed values
:rtype: dict | [
"Parse",
"a",
"9",
"bytes",
"packet",
"in",
"the",
"Humidity",
"format",
"and",
"return",
"a",
"dictionary",
"containing",
"the",
"data",
"extracted",
".",
"An",
"example",
"of",
"a",
"return",
"value",
"would",
"be",
":"
] | train | https://github.com/d0ugal/python-rfxcom/blob/2eb87f85e5f5a04d00f32f25e0f010edfefbde0d/rfxcom/protocol/humidity.py#L41-L88 |
howl-anderson/MicroTokenizer | MicroTokenizer/tokenizer_loader.py | TokenizerLoader.create_tokenizer | def create_tokenizer(self, name, config=dict()):
"""Create a pipeline component from a factory.
name (unicode): Factory name to look up in `Language.factories`.
config (dict): Configuration parameters to initialise component.
RETURNS (callable): Pipeline component.
"""
if name not in self.factories:
raise KeyError(Errors.E002.format(name=name))
factory = self.factories[name]
return factory(self, **config) | python | def create_tokenizer(self, name, config=dict()):
"""Create a pipeline component from a factory.
name (unicode): Factory name to look up in `Language.factories`.
config (dict): Configuration parameters to initialise component.
RETURNS (callable): Pipeline component.
"""
if name not in self.factories:
raise KeyError(Errors.E002.format(name=name))
factory = self.factories[name]
return factory(self, **config) | [
"def",
"create_tokenizer",
"(",
"self",
",",
"name",
",",
"config",
"=",
"dict",
"(",
")",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"factories",
":",
"raise",
"KeyError",
"(",
"Errors",
".",
"E002",
".",
"format",
"(",
"name",
"=",
"name",
... | Create a pipeline component from a factory.
name (unicode): Factory name to look up in `Language.factories`.
config (dict): Configuration parameters to initialise component.
RETURNS (callable): Pipeline component. | [
"Create",
"a",
"pipeline",
"component",
"from",
"a",
"factory",
"."
] | train | https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/tokenizer_loader.py#L44-L54 |
howl-anderson/MicroTokenizer | MicroTokenizer/errors.py | add_codes | def add_codes(err_cls):
"""Add error codes to string messages via class attribute names."""
class ErrorsWithCodes(object):
def __getattribute__(self, code):
msg = getattr(err_cls, code)
return '[{code}] {msg}'.format(code=code, msg=msg)
return ErrorsWithCodes() | python | def add_codes(err_cls):
"""Add error codes to string messages via class attribute names."""
class ErrorsWithCodes(object):
def __getattribute__(self, code):
msg = getattr(err_cls, code)
return '[{code}] {msg}'.format(code=code, msg=msg)
return ErrorsWithCodes() | [
"def",
"add_codes",
"(",
"err_cls",
")",
":",
"class",
"ErrorsWithCodes",
"(",
"object",
")",
":",
"def",
"__getattribute__",
"(",
"self",
",",
"code",
")",
":",
"msg",
"=",
"getattr",
"(",
"err_cls",
",",
"code",
")",
"return",
"'[{code}] {msg}'",
".",
... | Add error codes to string messages via class attribute names. | [
"Add",
"error",
"codes",
"to",
"string",
"messages",
"via",
"class",
"attribute",
"names",
"."
] | train | https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/errors.py#L9-L15 |
howl-anderson/MicroTokenizer | MicroTokenizer/errors.py | _warn | def _warn(message, warn_type='user'):
"""
message (unicode): The message to display.
category (Warning): The Warning to show.
"""
w_id = message.split('[', 1)[1].split(']', 1)[0] # get ID from string
if warn_type in SPACY_WARNING_TYPES and w_id not in SPACY_WARNING_IGNORE:
category = WARNINGS[warn_type]
stack = inspect.stack()[-1]
with warnings.catch_warnings():
if SPACY_WARNING_FILTER:
warnings.simplefilter(SPACY_WARNING_FILTER, category)
warnings.warn_explicit(message, category, stack[1], stack[2]) | python | def _warn(message, warn_type='user'):
"""
message (unicode): The message to display.
category (Warning): The Warning to show.
"""
w_id = message.split('[', 1)[1].split(']', 1)[0] # get ID from string
if warn_type in SPACY_WARNING_TYPES and w_id not in SPACY_WARNING_IGNORE:
category = WARNINGS[warn_type]
stack = inspect.stack()[-1]
with warnings.catch_warnings():
if SPACY_WARNING_FILTER:
warnings.simplefilter(SPACY_WARNING_FILTER, category)
warnings.warn_explicit(message, category, stack[1], stack[2]) | [
"def",
"_warn",
"(",
"message",
",",
"warn_type",
"=",
"'user'",
")",
":",
"w_id",
"=",
"message",
".",
"split",
"(",
"'['",
",",
"1",
")",
"[",
"1",
"]",
".",
"split",
"(",
"']'",
",",
"1",
")",
"[",
"0",
"]",
"# get ID from string",
"if",
"warn... | message (unicode): The message to display.
category (Warning): The Warning to show. | [
"message",
"(",
"unicode",
")",
":",
"The",
"message",
"to",
"display",
".",
"category",
"(",
"Warning",
")",
":",
"The",
"Warning",
"to",
"show",
"."
] | train | https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/errors.py#L314-L326 |
howl-anderson/MicroTokenizer | MicroTokenizer/cli_command/download.py | download | def download(model=None, direct=False, *pip_args):
"""
Download compatible model from default download path using pip. Model
can be shortcut, model name or, if --direct flag is set, full model name
with version.
"""
if model is None:
model = about.__default_corpus__
if direct:
dl = download_model('{m}/{m}.tar.gz#egg={m}'.format(m=model), pip_args)
else:
shortcuts = get_json(about.__shortcuts__, "available shortcuts")
model_name = shortcuts.get(model, model)
compatibility = get_compatibility()
version = get_version(model_name, compatibility)
dl = download_model('{m}-{v}/{m}-{v}.tar.gz#egg={m}=={v}'
.format(m=model_name, v=version), pip_args)
if dl != 0: # if download subprocess doesn't return 0, exit
sys.exit(dl)
try:
# Get package path here because link uses
# pip.get_installed_distributions() to check if model is a
# package, which fails if model was just installed via
# subprocess
package_path = get_package_path(model_name)
link(model_name, model, force=True, model_path=package_path)
except:
# Dirty, but since spacy.download and the auto-linking is
# mostly a convenience wrapper, it's best to show a success
# message and loading instructions, even if linking fails.
prints(Messages.M001.format(name=model_name), title=Messages.M002) | python | def download(model=None, direct=False, *pip_args):
"""
Download compatible model from default download path using pip. Model
can be shortcut, model name or, if --direct flag is set, full model name
with version.
"""
if model is None:
model = about.__default_corpus__
if direct:
dl = download_model('{m}/{m}.tar.gz#egg={m}'.format(m=model), pip_args)
else:
shortcuts = get_json(about.__shortcuts__, "available shortcuts")
model_name = shortcuts.get(model, model)
compatibility = get_compatibility()
version = get_version(model_name, compatibility)
dl = download_model('{m}-{v}/{m}-{v}.tar.gz#egg={m}=={v}'
.format(m=model_name, v=version), pip_args)
if dl != 0: # if download subprocess doesn't return 0, exit
sys.exit(dl)
try:
# Get package path here because link uses
# pip.get_installed_distributions() to check if model is a
# package, which fails if model was just installed via
# subprocess
package_path = get_package_path(model_name)
link(model_name, model, force=True, model_path=package_path)
except:
# Dirty, but since spacy.download and the auto-linking is
# mostly a convenience wrapper, it's best to show a success
# message and loading instructions, even if linking fails.
prints(Messages.M001.format(name=model_name), title=Messages.M002) | [
"def",
"download",
"(",
"model",
"=",
"None",
",",
"direct",
"=",
"False",
",",
"*",
"pip_args",
")",
":",
"if",
"model",
"is",
"None",
":",
"model",
"=",
"about",
".",
"__default_corpus__",
"if",
"direct",
":",
"dl",
"=",
"download_model",
"(",
"'{m}/... | Download compatible model from default download path using pip. Model
can be shortcut, model name or, if --direct flag is set, full model name
with version. | [
"Download",
"compatible",
"model",
"from",
"default",
"download",
"path",
"using",
"pip",
".",
"Model",
"can",
"be",
"shortcut",
"model",
"name",
"or",
"if",
"--",
"direct",
"flag",
"is",
"set",
"full",
"model",
"name",
"with",
"version",
"."
] | train | https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/cli_command/download.py#L22-L53 |
howl-anderson/MicroTokenizer | MicroTokenizer/cli_command/link.py | link | def link(origin, link_name, force=False, model_path=None):
"""
Create a symlink for models within the spacy/data directory. Accepts
either the name of a pip package, or the local path to the model data
directory. Linking models allows loading them via spacy.load(link_name).
"""
if util.is_package(origin):
model_path = util.get_package_path(origin)
else:
model_path = Path(origin) if model_path is None else Path(model_path)
if not model_path.exists():
prints(Messages.M009.format(path=path2str(model_path)),
title=Messages.M008, exits=1)
data_path = util.get_data_path()
if not data_path or not data_path.exists():
spacy_loc = Path(__file__).parent.parent
prints(Messages.M011, spacy_loc, title=Messages.M010, exits=1)
link_path = util.get_data_path() / link_name
if link_path.is_symlink() and not force:
prints(Messages.M013, title=Messages.M012.format(name=link_name),
exits=1)
elif link_path.is_symlink(): # does a symlink exist?
# NB: It's important to check for is_symlink here and not for exists,
# because invalid/outdated symlinks would return False otherwise.
link_path.unlink()
elif link_path.exists(): # does it exist otherwise?
# NB: Check this last because valid symlinks also "exist".
prints(Messages.M015, link_path,
title=Messages.M014.format(name=link_name), exits=1)
msg = "%s --> %s" % (path2str(model_path), path2str(link_path))
try:
symlink_to(link_path, model_path)
except:
# This is quite dirty, but just making sure other errors are caught.
prints(Messages.M017, msg, title=Messages.M016.format(name=link_name))
raise
prints(msg, Messages.M019.format(name=link_name), title=Messages.M018) | python | def link(origin, link_name, force=False, model_path=None):
"""
Create a symlink for models within the spacy/data directory. Accepts
either the name of a pip package, or the local path to the model data
directory. Linking models allows loading them via spacy.load(link_name).
"""
if util.is_package(origin):
model_path = util.get_package_path(origin)
else:
model_path = Path(origin) if model_path is None else Path(model_path)
if not model_path.exists():
prints(Messages.M009.format(path=path2str(model_path)),
title=Messages.M008, exits=1)
data_path = util.get_data_path()
if not data_path or not data_path.exists():
spacy_loc = Path(__file__).parent.parent
prints(Messages.M011, spacy_loc, title=Messages.M010, exits=1)
link_path = util.get_data_path() / link_name
if link_path.is_symlink() and not force:
prints(Messages.M013, title=Messages.M012.format(name=link_name),
exits=1)
elif link_path.is_symlink(): # does a symlink exist?
# NB: It's important to check for is_symlink here and not for exists,
# because invalid/outdated symlinks would return False otherwise.
link_path.unlink()
elif link_path.exists(): # does it exist otherwise?
# NB: Check this last because valid symlinks also "exist".
prints(Messages.M015, link_path,
title=Messages.M014.format(name=link_name), exits=1)
msg = "%s --> %s" % (path2str(model_path), path2str(link_path))
try:
symlink_to(link_path, model_path)
except:
# This is quite dirty, but just making sure other errors are caught.
prints(Messages.M017, msg, title=Messages.M016.format(name=link_name))
raise
prints(msg, Messages.M019.format(name=link_name), title=Messages.M018) | [
"def",
"link",
"(",
"origin",
",",
"link_name",
",",
"force",
"=",
"False",
",",
"model_path",
"=",
"None",
")",
":",
"if",
"util",
".",
"is_package",
"(",
"origin",
")",
":",
"model_path",
"=",
"util",
".",
"get_package_path",
"(",
"origin",
")",
"els... | Create a symlink for models within the spacy/data directory. Accepts
either the name of a pip package, or the local path to the model data
directory. Linking models allows loading them via spacy.load(link_name). | [
"Create",
"a",
"symlink",
"for",
"models",
"within",
"the",
"spacy",
"/",
"data",
"directory",
".",
"Accepts",
"either",
"the",
"name",
"of",
"a",
"pip",
"package",
"or",
"the",
"local",
"path",
"to",
"the",
"model",
"data",
"directory",
".",
"Linking",
... | train | https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/cli_command/link.py#L17-L53 |
howl-anderson/MicroTokenizer | MicroTokenizer/util.py | load_model_from_path | def load_model_from_path(model_path, meta=False, **overrides):
"""Load a model from a data directory path. Creates Language class with
pipeline from meta.json and then calls from_disk() with path."""
from .tokenizer_loader import TokenizerLoader
if not meta:
meta = get_model_meta(model_path)
tokenizer_loader = TokenizerLoader(meta=meta, **overrides)
tokenizers = meta.get('tokenizers', [])
disable = overrides.get('disable', [])
if tokenizers is True:
tokenizers = TokenizerLoader.Defaults.tokenizers
elif tokenizers in (False, None):
tokenizers = []
for tokenizer_name in tokenizers:
if tokenizer_name not in disable:
config = meta.get('tokenizer_args', {}).get(tokenizer_name, {})
component = tokenizer_loader.create_tokenizer(tokenizer_name, config=config)
tokenizer_loader.add_tokenizer(component, name=tokenizer_name)
return tokenizer_loader.from_disk(model_path) | python | def load_model_from_path(model_path, meta=False, **overrides):
"""Load a model from a data directory path. Creates Language class with
pipeline from meta.json and then calls from_disk() with path."""
from .tokenizer_loader import TokenizerLoader
if not meta:
meta = get_model_meta(model_path)
tokenizer_loader = TokenizerLoader(meta=meta, **overrides)
tokenizers = meta.get('tokenizers', [])
disable = overrides.get('disable', [])
if tokenizers is True:
tokenizers = TokenizerLoader.Defaults.tokenizers
elif tokenizers in (False, None):
tokenizers = []
for tokenizer_name in tokenizers:
if tokenizer_name not in disable:
config = meta.get('tokenizer_args', {}).get(tokenizer_name, {})
component = tokenizer_loader.create_tokenizer(tokenizer_name, config=config)
tokenizer_loader.add_tokenizer(component, name=tokenizer_name)
return tokenizer_loader.from_disk(model_path) | [
"def",
"load_model_from_path",
"(",
"model_path",
",",
"meta",
"=",
"False",
",",
"*",
"*",
"overrides",
")",
":",
"from",
".",
"tokenizer_loader",
"import",
"TokenizerLoader",
"if",
"not",
"meta",
":",
"meta",
"=",
"get_model_meta",
"(",
"model_path",
")",
... | Load a model from a data directory path. Creates Language class with
pipeline from meta.json and then calls from_disk() with path. | [
"Load",
"a",
"model",
"from",
"a",
"data",
"directory",
"path",
".",
"Creates",
"Language",
"class",
"with",
"pipeline",
"from",
"meta",
".",
"json",
"and",
"then",
"calls",
"from_disk",
"()",
"with",
"path",
"."
] | train | https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/util.py#L101-L120 |
howl-anderson/MicroTokenizer | MicroTokenizer/util.py | is_package | def is_package(name):
"""Check if string maps to a package installed via pip.
name (unicode): Name of package.
RETURNS (bool): True if installed package, False if not.
"""
name = name.lower() # compare package name against lowercase name
packages = pkg_resources.working_set.by_key.keys()
for package in packages:
if package.lower().replace('-', '_') == name:
return True
return False | python | def is_package(name):
"""Check if string maps to a package installed via pip.
name (unicode): Name of package.
RETURNS (bool): True if installed package, False if not.
"""
name = name.lower() # compare package name against lowercase name
packages = pkg_resources.working_set.by_key.keys()
for package in packages:
if package.lower().replace('-', '_') == name:
return True
return False | [
"def",
"is_package",
"(",
"name",
")",
":",
"name",
"=",
"name",
".",
"lower",
"(",
")",
"# compare package name against lowercase name",
"packages",
"=",
"pkg_resources",
".",
"working_set",
".",
"by_key",
".",
"keys",
"(",
")",
"for",
"package",
"in",
"packa... | Check if string maps to a package installed via pip.
name (unicode): Name of package.
RETURNS (bool): True if installed package, False if not. | [
"Check",
"if",
"string",
"maps",
"to",
"a",
"package",
"installed",
"via",
"pip",
"."
] | train | https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/util.py#L159-L170 |
howl-anderson/MicroTokenizer | MicroTokenizer/util.py | decaying | def decaying(start, stop, decay):
"""Yield an infinite series of linearly decaying values."""
def clip(value):
return max(value, stop) if (start > stop) else min(value, stop)
nr_upd = 1.
while True:
yield clip(start * 1./(1. + decay * nr_upd))
nr_upd += 1 | python | def decaying(start, stop, decay):
"""Yield an infinite series of linearly decaying values."""
def clip(value):
return max(value, stop) if (start > stop) else min(value, stop)
nr_upd = 1.
while True:
yield clip(start * 1./(1. + decay * nr_upd))
nr_upd += 1 | [
"def",
"decaying",
"(",
"start",
",",
"stop",
",",
"decay",
")",
":",
"def",
"clip",
"(",
"value",
")",
":",
"return",
"max",
"(",
"value",
",",
"stop",
")",
"if",
"(",
"start",
">",
"stop",
")",
"else",
"min",
"(",
"value",
",",
"stop",
")",
"... | Yield an infinite series of linearly decaying values. | [
"Yield",
"an",
"infinite",
"series",
"of",
"linearly",
"decaying",
"values",
"."
] | train | https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/util.py#L272-L279 |
howl-anderson/MicroTokenizer | MicroTokenizer/util.py | read_json | def read_json(location):
"""Open and load JSON from file.
location (Path): Path to JSON file.
RETURNS (dict): Loaded JSON content.
"""
location = ensure_path(location)
with location.open('r', encoding='utf8') as f:
return ujson.load(f) | python | def read_json(location):
"""Open and load JSON from file.
location (Path): Path to JSON file.
RETURNS (dict): Loaded JSON content.
"""
location = ensure_path(location)
with location.open('r', encoding='utf8') as f:
return ujson.load(f) | [
"def",
"read_json",
"(",
"location",
")",
":",
"location",
"=",
"ensure_path",
"(",
"location",
")",
"with",
"location",
".",
"open",
"(",
"'r'",
",",
"encoding",
"=",
"'utf8'",
")",
"as",
"f",
":",
"return",
"ujson",
".",
"load",
"(",
"f",
")"
] | Open and load JSON from file.
location (Path): Path to JSON file.
RETURNS (dict): Loaded JSON content. | [
"Open",
"and",
"load",
"JSON",
"from",
"file",
"."
] | train | https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/util.py#L311-L319 |
howl-anderson/MicroTokenizer | MicroTokenizer/util.py | get_raw_input | def get_raw_input(description, default=False):
"""Get user input from the command line via raw_input / input.
description (unicode): Text to display before prompt.
default (unicode or False/None): Default value to display with prompt.
RETURNS (unicode): User input.
"""
additional = ' (default: %s)' % default if default else ''
prompt = ' %s%s: ' % (description, additional)
user_input = input_(prompt)
return user_input | python | def get_raw_input(description, default=False):
"""Get user input from the command line via raw_input / input.
description (unicode): Text to display before prompt.
default (unicode or False/None): Default value to display with prompt.
RETURNS (unicode): User input.
"""
additional = ' (default: %s)' % default if default else ''
prompt = ' %s%s: ' % (description, additional)
user_input = input_(prompt)
return user_input | [
"def",
"get_raw_input",
"(",
"description",
",",
"default",
"=",
"False",
")",
":",
"additional",
"=",
"' (default: %s)'",
"%",
"default",
"if",
"default",
"else",
"''",
"prompt",
"=",
"' %s%s: '",
"%",
"(",
"description",
",",
"additional",
")",
"user_inpu... | Get user input from the command line via raw_input / input.
description (unicode): Text to display before prompt.
default (unicode or False/None): Default value to display with prompt.
RETURNS (unicode): User input. | [
"Get",
"user",
"input",
"from",
"the",
"command",
"line",
"via",
"raw_input",
"/",
"input",
"."
] | train | https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/util.py#L322-L332 |
howl-anderson/MicroTokenizer | MicroTokenizer/util.py | print_table | def print_table(data, title=None):
"""Print data in table format.
data (dict or list of tuples): Label/value pairs.
title (unicode or None): Title, will be printed above.
"""
if isinstance(data, dict):
data = list(data.items())
tpl_row = ' {:<15}' * len(data[0])
table = '\n'.join([tpl_row.format(l, unicode_(v)) for l, v in data])
if title:
print('\n \033[93m{}\033[0m'.format(title))
print('\n{}\n'.format(table)) | python | def print_table(data, title=None):
"""Print data in table format.
data (dict or list of tuples): Label/value pairs.
title (unicode or None): Title, will be printed above.
"""
if isinstance(data, dict):
data = list(data.items())
tpl_row = ' {:<15}' * len(data[0])
table = '\n'.join([tpl_row.format(l, unicode_(v)) for l, v in data])
if title:
print('\n \033[93m{}\033[0m'.format(title))
print('\n{}\n'.format(table)) | [
"def",
"print_table",
"(",
"data",
",",
"title",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"data",
"=",
"list",
"(",
"data",
".",
"items",
"(",
")",
")",
"tpl_row",
"=",
"' {:<15}'",
"*",
"len",
"(",
"data",
... | Print data in table format.
data (dict or list of tuples): Label/value pairs.
title (unicode or None): Title, will be printed above. | [
"Print",
"data",
"in",
"table",
"format",
"."
] | train | https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/util.py#L355-L367 |
howl-anderson/MicroTokenizer | MicroTokenizer/util.py | print_markdown | def print_markdown(data, title=None):
"""Print data in GitHub-flavoured Markdown format for issues etc.
data (dict or list of tuples): Label/value pairs.
title (unicode or None): Title, will be rendered as headline 2.
"""
def excl_value(value):
# contains path, i.e. personal info
return isinstance(value, basestring_) and Path(value).exists()
if isinstance(data, dict):
data = list(data.items())
markdown = ["* **{}:** {}".format(l, unicode_(v))
for l, v in data if not excl_value(v)]
if title:
print("\n## {}".format(title))
print('\n{}\n'.format('\n'.join(markdown))) | python | def print_markdown(data, title=None):
"""Print data in GitHub-flavoured Markdown format for issues etc.
data (dict or list of tuples): Label/value pairs.
title (unicode or None): Title, will be rendered as headline 2.
"""
def excl_value(value):
# contains path, i.e. personal info
return isinstance(value, basestring_) and Path(value).exists()
if isinstance(data, dict):
data = list(data.items())
markdown = ["* **{}:** {}".format(l, unicode_(v))
for l, v in data if not excl_value(v)]
if title:
print("\n## {}".format(title))
print('\n{}\n'.format('\n'.join(markdown))) | [
"def",
"print_markdown",
"(",
"data",
",",
"title",
"=",
"None",
")",
":",
"def",
"excl_value",
"(",
"value",
")",
":",
"# contains path, i.e. personal info",
"return",
"isinstance",
"(",
"value",
",",
"basestring_",
")",
"and",
"Path",
"(",
"value",
")",
".... | Print data in GitHub-flavoured Markdown format for issues etc.
data (dict or list of tuples): Label/value pairs.
title (unicode or None): Title, will be rendered as headline 2. | [
"Print",
"data",
"in",
"GitHub",
"-",
"flavoured",
"Markdown",
"format",
"for",
"issues",
"etc",
"."
] | train | https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/util.py#L370-L386 |
howl-anderson/MicroTokenizer | MicroTokenizer/util.py | prints | def prints(*texts, **kwargs):
"""Print formatted message (manual ANSI escape sequences to avoid
dependency)
*texts (unicode): Texts to print. Each argument is rendered as paragraph.
**kwargs: 'title' becomes coloured headline. exits=True performs sys exit.
"""
exits = kwargs.get('exits', None)
title = kwargs.get('title', None)
title = '\033[93m{}\033[0m\n'.format(_wrap(title)) if title else ''
message = '\n\n'.join([_wrap(text) for text in texts])
print('\n{}{}\n'.format(title, message))
if exits is not None:
sys.exit(exits) | python | def prints(*texts, **kwargs):
"""Print formatted message (manual ANSI escape sequences to avoid
dependency)
*texts (unicode): Texts to print. Each argument is rendered as paragraph.
**kwargs: 'title' becomes coloured headline. exits=True performs sys exit.
"""
exits = kwargs.get('exits', None)
title = kwargs.get('title', None)
title = '\033[93m{}\033[0m\n'.format(_wrap(title)) if title else ''
message = '\n\n'.join([_wrap(text) for text in texts])
print('\n{}{}\n'.format(title, message))
if exits is not None:
sys.exit(exits) | [
"def",
"prints",
"(",
"*",
"texts",
",",
"*",
"*",
"kwargs",
")",
":",
"exits",
"=",
"kwargs",
".",
"get",
"(",
"'exits'",
",",
"None",
")",
"title",
"=",
"kwargs",
".",
"get",
"(",
"'title'",
",",
"None",
")",
"title",
"=",
"'\\033[93m{}\\033[0m\\n'... | Print formatted message (manual ANSI escape sequences to avoid
dependency)
*texts (unicode): Texts to print. Each argument is rendered as paragraph.
**kwargs: 'title' becomes coloured headline. exits=True performs sys exit. | [
"Print",
"formatted",
"message",
"(",
"manual",
"ANSI",
"escape",
"sequences",
"to",
"avoid",
"dependency",
")"
] | train | https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/util.py#L389-L402 |
howl-anderson/MicroTokenizer | MicroTokenizer/util.py | _wrap | def _wrap(text, wrap_max=80, indent=4):
"""Wrap text at given width using textwrap module.
text (unicode): Text to wrap. If it's a Path, it's converted to string.
wrap_max (int): Maximum line length (indent is deducted).
indent (int): Number of spaces for indentation.
RETURNS (unicode): Wrapped text.
"""
indent = indent * ' '
wrap_width = wrap_max - len(indent)
if isinstance(text, Path):
text = path2str(text)
return textwrap.fill(text, width=wrap_width, initial_indent=indent,
subsequent_indent=indent, break_long_words=False,
break_on_hyphens=False) | python | def _wrap(text, wrap_max=80, indent=4):
"""Wrap text at given width using textwrap module.
text (unicode): Text to wrap. If it's a Path, it's converted to string.
wrap_max (int): Maximum line length (indent is deducted).
indent (int): Number of spaces for indentation.
RETURNS (unicode): Wrapped text.
"""
indent = indent * ' '
wrap_width = wrap_max - len(indent)
if isinstance(text, Path):
text = path2str(text)
return textwrap.fill(text, width=wrap_width, initial_indent=indent,
subsequent_indent=indent, break_long_words=False,
break_on_hyphens=False) | [
"def",
"_wrap",
"(",
"text",
",",
"wrap_max",
"=",
"80",
",",
"indent",
"=",
"4",
")",
":",
"indent",
"=",
"indent",
"*",
"' '",
"wrap_width",
"=",
"wrap_max",
"-",
"len",
"(",
"indent",
")",
"if",
"isinstance",
"(",
"text",
",",
"Path",
")",
":",
... | Wrap text at given width using textwrap module.
text (unicode): Text to wrap. If it's a Path, it's converted to string.
wrap_max (int): Maximum line length (indent is deducted).
indent (int): Number of spaces for indentation.
RETURNS (unicode): Wrapped text. | [
"Wrap",
"text",
"at",
"given",
"width",
"using",
"textwrap",
"module",
"."
] | train | https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/util.py#L405-L419 |
howl-anderson/MicroTokenizer | MicroTokenizer/util.py | escape_html | def escape_html(text):
"""Replace <, >, &, " with their HTML encoded representation. Intended to
prevent HTML errors in rendered displaCy markup.
text (unicode): The original text.
RETURNS (unicode): Equivalent text to be safely used within HTML.
"""
text = text.replace('&', '&')
text = text.replace('<', '<')
text = text.replace('>', '>')
text = text.replace('"', '"')
return text | python | def escape_html(text):
"""Replace <, >, &, " with their HTML encoded representation. Intended to
prevent HTML errors in rendered displaCy markup.
text (unicode): The original text.
RETURNS (unicode): Equivalent text to be safely used within HTML.
"""
text = text.replace('&', '&')
text = text.replace('<', '<')
text = text.replace('>', '>')
text = text.replace('"', '"')
return text | [
"def",
"escape_html",
"(",
"text",
")",
":",
"text",
"=",
"text",
".",
"replace",
"(",
"'&'",
",",
"'&'",
")",
"text",
"=",
"text",
".",
"replace",
"(",
"'<'",
",",
"'<'",
")",
"text",
"=",
"text",
".",
"replace",
"(",
"'>'",
",",
"'>'",
... | Replace <, >, &, " with their HTML encoded representation. Intended to
prevent HTML errors in rendered displaCy markup.
text (unicode): The original text.
RETURNS (unicode): Equivalent text to be safely used within HTML. | [
"Replace",
"<",
">",
"&",
"with",
"their",
"HTML",
"encoded",
"representation",
".",
"Intended",
"to",
"prevent",
"HTML",
"errors",
"in",
"rendered",
"displaCy",
"markup",
"."
] | train | https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/util.py#L433-L444 |
howl-anderson/MicroTokenizer | MicroTokenizer/compat.py | normalize_string_keys | def normalize_string_keys(old):
"""Given a dictionary, make sure keys are unicode strings, not bytes."""
new = {}
for key, value in old.items():
if isinstance(key, bytes_):
new[key.decode('utf8')] = value
else:
new[key] = value
return new | python | def normalize_string_keys(old):
"""Given a dictionary, make sure keys are unicode strings, not bytes."""
new = {}
for key, value in old.items():
if isinstance(key, bytes_):
new[key.decode('utf8')] = value
else:
new[key] = value
return new | [
"def",
"normalize_string_keys",
"(",
"old",
")",
":",
"new",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"old",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"key",
",",
"bytes_",
")",
":",
"new",
"[",
"key",
".",
"decode",
"(",
"'ut... | Given a dictionary, make sure keys are unicode strings, not bytes. | [
"Given",
"a",
"dictionary",
"make",
"sure",
"keys",
"are",
"unicode",
"strings",
"not",
"bytes",
"."
] | train | https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/compat.py#L78-L86 |
howl-anderson/MicroTokenizer | MicroTokenizer/compat.py | locale_escape | def locale_escape(string, errors='replace'):
'''
Mangle non-supported characters, for savages with ascii terminals.
'''
encoding = locale.getpreferredencoding()
string = string.encode(encoding, errors).decode('utf8')
return string | python | def locale_escape(string, errors='replace'):
'''
Mangle non-supported characters, for savages with ascii terminals.
'''
encoding = locale.getpreferredencoding()
string = string.encode(encoding, errors).decode('utf8')
return string | [
"def",
"locale_escape",
"(",
"string",
",",
"errors",
"=",
"'replace'",
")",
":",
"encoding",
"=",
"locale",
".",
"getpreferredencoding",
"(",
")",
"string",
"=",
"string",
".",
"encode",
"(",
"encoding",
",",
"errors",
")",
".",
"decode",
"(",
"'utf8'",
... | Mangle non-supported characters, for savages with ascii terminals. | [
"Mangle",
"non",
"-",
"supported",
"characters",
"for",
"savages",
"with",
"ascii",
"terminals",
"."
] | train | https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/compat.py#L102-L108 |
aparrish/pronouncingpy | pronouncing/__init__.py | parse_cmu | def parse_cmu(cmufh):
"""Parses an incoming file handle as a CMU pronouncing dictionary file.
(Most end-users of this module won't need to call this function explicitly,
as it's called internally by the :func:`init_cmu` function.)
:param cmufh: a filehandle with CMUdict-formatted data
:returns: a list of 2-tuples pairing a word with its phones (as a string)
"""
pronunciations = list()
for line in cmufh:
line = line.strip().decode('utf-8')
if line.startswith(';'):
continue
word, phones = line.split(" ", 1)
pronunciations.append((word.split('(', 1)[0].lower(), phones))
return pronunciations | python | def parse_cmu(cmufh):
"""Parses an incoming file handle as a CMU pronouncing dictionary file.
(Most end-users of this module won't need to call this function explicitly,
as it's called internally by the :func:`init_cmu` function.)
:param cmufh: a filehandle with CMUdict-formatted data
:returns: a list of 2-tuples pairing a word with its phones (as a string)
"""
pronunciations = list()
for line in cmufh:
line = line.strip().decode('utf-8')
if line.startswith(';'):
continue
word, phones = line.split(" ", 1)
pronunciations.append((word.split('(', 1)[0].lower(), phones))
return pronunciations | [
"def",
"parse_cmu",
"(",
"cmufh",
")",
":",
"pronunciations",
"=",
"list",
"(",
")",
"for",
"line",
"in",
"cmufh",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"if",
"line",
".",
"startswith",
"(",
"';'",
")... | Parses an incoming file handle as a CMU pronouncing dictionary file.
(Most end-users of this module won't need to call this function explicitly,
as it's called internally by the :func:`init_cmu` function.)
:param cmufh: a filehandle with CMUdict-formatted data
:returns: a list of 2-tuples pairing a word with its phones (as a string) | [
"Parses",
"an",
"incoming",
"file",
"handle",
"as",
"a",
"CMU",
"pronouncing",
"dictionary",
"file",
"."
] | train | https://github.com/aparrish/pronouncingpy/blob/09467fa9407d7d87cb0998ee3cb09db4dcc9571a/pronouncing/__init__.py#L17-L33 |
aparrish/pronouncingpy | pronouncing/__init__.py | init_cmu | def init_cmu(filehandle=None):
"""Initialize the module's pronunciation data.
This function is called automatically the first time you attempt to use
another function in the library that requires loading the pronunciation
data from disk. You can call this function manually to control when and
how the pronunciation data is loaded (e.g., you're using this module in
a web application and want to load the data asynchronously).
:param filehandle: a filehandle with CMUdict-formatted data
:returns: None
"""
global pronunciations, lookup, rhyme_lookup
if pronunciations is None:
if filehandle is None:
filehandle = cmudict.dict_stream()
pronunciations = parse_cmu(filehandle)
filehandle.close()
lookup = collections.defaultdict(list)
for word, phones in pronunciations:
lookup[word].append(phones)
rhyme_lookup = collections.defaultdict(list)
for word, phones in pronunciations:
rp = rhyming_part(phones)
if rp is not None:
rhyme_lookup[rp].append(word) | python | def init_cmu(filehandle=None):
"""Initialize the module's pronunciation data.
This function is called automatically the first time you attempt to use
another function in the library that requires loading the pronunciation
data from disk. You can call this function manually to control when and
how the pronunciation data is loaded (e.g., you're using this module in
a web application and want to load the data asynchronously).
:param filehandle: a filehandle with CMUdict-formatted data
:returns: None
"""
global pronunciations, lookup, rhyme_lookup
if pronunciations is None:
if filehandle is None:
filehandle = cmudict.dict_stream()
pronunciations = parse_cmu(filehandle)
filehandle.close()
lookup = collections.defaultdict(list)
for word, phones in pronunciations:
lookup[word].append(phones)
rhyme_lookup = collections.defaultdict(list)
for word, phones in pronunciations:
rp = rhyming_part(phones)
if rp is not None:
rhyme_lookup[rp].append(word) | [
"def",
"init_cmu",
"(",
"filehandle",
"=",
"None",
")",
":",
"global",
"pronunciations",
",",
"lookup",
",",
"rhyme_lookup",
"if",
"pronunciations",
"is",
"None",
":",
"if",
"filehandle",
"is",
"None",
":",
"filehandle",
"=",
"cmudict",
".",
"dict_stream",
"... | Initialize the module's pronunciation data.
This function is called automatically the first time you attempt to use
another function in the library that requires loading the pronunciation
data from disk. You can call this function manually to control when and
how the pronunciation data is loaded (e.g., you're using this module in
a web application and want to load the data asynchronously).
:param filehandle: a filehandle with CMUdict-formatted data
:returns: None | [
"Initialize",
"the",
"module",
"s",
"pronunciation",
"data",
"."
] | train | https://github.com/aparrish/pronouncingpy/blob/09467fa9407d7d87cb0998ee3cb09db4dcc9571a/pronouncing/__init__.py#L36-L61 |
aparrish/pronouncingpy | pronouncing/__init__.py | rhyming_part | def rhyming_part(phones):
"""Get the "rhyming part" of a string with CMUdict phones.
"Rhyming part" here means everything from the vowel in the stressed
syllable nearest the end of the word up to the end of the word.
.. doctest::
>>> import pronouncing
>>> phones = pronouncing.phones_for_word("purple")
>>> pronouncing.rhyming_part(phones[0])
'ER1 P AH0 L'
:param phones: a string containing space-separated CMUdict phones
:returns: a string with just the "rhyming part" of those phones
"""
phones_list = phones.split()
for i in range(len(phones_list) - 1, 0, -1):
if phones_list[i][-1] in '12':
return ' '.join(phones_list[i:])
return phones | python | def rhyming_part(phones):
"""Get the "rhyming part" of a string with CMUdict phones.
"Rhyming part" here means everything from the vowel in the stressed
syllable nearest the end of the word up to the end of the word.
.. doctest::
>>> import pronouncing
>>> phones = pronouncing.phones_for_word("purple")
>>> pronouncing.rhyming_part(phones[0])
'ER1 P AH0 L'
:param phones: a string containing space-separated CMUdict phones
:returns: a string with just the "rhyming part" of those phones
"""
phones_list = phones.split()
for i in range(len(phones_list) - 1, 0, -1):
if phones_list[i][-1] in '12':
return ' '.join(phones_list[i:])
return phones | [
"def",
"rhyming_part",
"(",
"phones",
")",
":",
"phones_list",
"=",
"phones",
".",
"split",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"phones_list",
")",
"-",
"1",
",",
"0",
",",
"-",
"1",
")",
":",
"if",
"phones_list",
"[",
"i",
"]",... | Get the "rhyming part" of a string with CMUdict phones.
"Rhyming part" here means everything from the vowel in the stressed
syllable nearest the end of the word up to the end of the word.
.. doctest::
>>> import pronouncing
>>> phones = pronouncing.phones_for_word("purple")
>>> pronouncing.rhyming_part(phones[0])
'ER1 P AH0 L'
:param phones: a string containing space-separated CMUdict phones
:returns: a string with just the "rhyming part" of those phones | [
"Get",
"the",
"rhyming",
"part",
"of",
"a",
"string",
"with",
"CMUdict",
"phones",
"."
] | train | https://github.com/aparrish/pronouncingpy/blob/09467fa9407d7d87cb0998ee3cb09db4dcc9571a/pronouncing/__init__.py#L135-L155 |
aparrish/pronouncingpy | pronouncing/__init__.py | search | def search(pattern):
"""Get words whose pronunciation matches a regular expression.
This function Searches the CMU dictionary for pronunciations matching a
given regular expression. (Word boundary anchors are automatically added
before and after the pattern.)
.. doctest::
>>> import pronouncing
>>> 'interpolate' in pronouncing.search('ER1 P AH0')
True
:param pattern: a string containing a regular expression
:returns: a list of matching words
"""
init_cmu()
regexp = re.compile(r"\b" + pattern + r"\b")
return [word
for word, phones in pronunciations
if regexp.search(phones)] | python | def search(pattern):
"""Get words whose pronunciation matches a regular expression.
This function Searches the CMU dictionary for pronunciations matching a
given regular expression. (Word boundary anchors are automatically added
before and after the pattern.)
.. doctest::
>>> import pronouncing
>>> 'interpolate' in pronouncing.search('ER1 P AH0')
True
:param pattern: a string containing a regular expression
:returns: a list of matching words
"""
init_cmu()
regexp = re.compile(r"\b" + pattern + r"\b")
return [word
for word, phones in pronunciations
if regexp.search(phones)] | [
"def",
"search",
"(",
"pattern",
")",
":",
"init_cmu",
"(",
")",
"regexp",
"=",
"re",
".",
"compile",
"(",
"r\"\\b\"",
"+",
"pattern",
"+",
"r\"\\b\"",
")",
"return",
"[",
"word",
"for",
"word",
",",
"phones",
"in",
"pronunciations",
"if",
"regexp",
".... | Get words whose pronunciation matches a regular expression.
This function Searches the CMU dictionary for pronunciations matching a
given regular expression. (Word boundary anchors are automatically added
before and after the pattern.)
.. doctest::
>>> import pronouncing
>>> 'interpolate' in pronouncing.search('ER1 P AH0')
True
:param pattern: a string containing a regular expression
:returns: a list of matching words | [
"Get",
"words",
"whose",
"pronunciation",
"matches",
"a",
"regular",
"expression",
"."
] | train | https://github.com/aparrish/pronouncingpy/blob/09467fa9407d7d87cb0998ee3cb09db4dcc9571a/pronouncing/__init__.py#L158-L178 |
aparrish/pronouncingpy | pronouncing/__init__.py | search_stresses | def search_stresses(pattern):
"""Get words whose stress pattern matches a regular expression.
This function is a special case of :func:`search` that searches only the
stress patterns of each pronunciation in the dictionary. You can get
stress patterns for a word using the :func:`stresses_for_word` function.
.. doctest::
>>> import pronouncing
>>> pronouncing.search_stresses('020120')
['gubernatorial']
:param pattern: a string containing a regular expression
:returns: a list of matching words
"""
init_cmu()
regexp = re.compile(pattern)
return [word
for word, phones in pronunciations
if regexp.search(stresses(phones))] | python | def search_stresses(pattern):
"""Get words whose stress pattern matches a regular expression.
This function is a special case of :func:`search` that searches only the
stress patterns of each pronunciation in the dictionary. You can get
stress patterns for a word using the :func:`stresses_for_word` function.
.. doctest::
>>> import pronouncing
>>> pronouncing.search_stresses('020120')
['gubernatorial']
:param pattern: a string containing a regular expression
:returns: a list of matching words
"""
init_cmu()
regexp = re.compile(pattern)
return [word
for word, phones in pronunciations
if regexp.search(stresses(phones))] | [
"def",
"search_stresses",
"(",
"pattern",
")",
":",
"init_cmu",
"(",
")",
"regexp",
"=",
"re",
".",
"compile",
"(",
"pattern",
")",
"return",
"[",
"word",
"for",
"word",
",",
"phones",
"in",
"pronunciations",
"if",
"regexp",
".",
"search",
"(",
"stresses... | Get words whose stress pattern matches a regular expression.
This function is a special case of :func:`search` that searches only the
stress patterns of each pronunciation in the dictionary. You can get
stress patterns for a word using the :func:`stresses_for_word` function.
.. doctest::
>>> import pronouncing
>>> pronouncing.search_stresses('020120')
['gubernatorial']
:param pattern: a string containing a regular expression
:returns: a list of matching words | [
"Get",
"words",
"whose",
"stress",
"pattern",
"matches",
"a",
"regular",
"expression",
"."
] | train | https://github.com/aparrish/pronouncingpy/blob/09467fa9407d7d87cb0998ee3cb09db4dcc9571a/pronouncing/__init__.py#L181-L201 |
aparrish/pronouncingpy | pronouncing/__init__.py | rhymes | def rhymes(word):
"""Get words rhyming with a given word.
This function may return an empty list if no rhyming words are found in
the dictionary, or if the word you pass to the function is itself not
found in the dictionary.
.. doctest::
>>> import pronouncing
>>> pronouncing.rhymes("conditioner")
['commissioner', 'parishioner', 'petitioner', 'practitioner']
:param word: a word
:returns: a list of rhyming words
"""
phones = phones_for_word(word)
combined_rhymes = []
if phones:
for element in phones:
combined_rhymes.append([w for w in rhyme_lookup.get(rhyming_part(
element), []) if w != word])
combined_rhymes = list(chain.from_iterable(combined_rhymes))
unique_combined_rhymes = sorted(set(combined_rhymes))
return unique_combined_rhymes
else:
return [] | python | def rhymes(word):
"""Get words rhyming with a given word.
This function may return an empty list if no rhyming words are found in
the dictionary, or if the word you pass to the function is itself not
found in the dictionary.
.. doctest::
>>> import pronouncing
>>> pronouncing.rhymes("conditioner")
['commissioner', 'parishioner', 'petitioner', 'practitioner']
:param word: a word
:returns: a list of rhyming words
"""
phones = phones_for_word(word)
combined_rhymes = []
if phones:
for element in phones:
combined_rhymes.append([w for w in rhyme_lookup.get(rhyming_part(
element), []) if w != word])
combined_rhymes = list(chain.from_iterable(combined_rhymes))
unique_combined_rhymes = sorted(set(combined_rhymes))
return unique_combined_rhymes
else:
return [] | [
"def",
"rhymes",
"(",
"word",
")",
":",
"phones",
"=",
"phones_for_word",
"(",
"word",
")",
"combined_rhymes",
"=",
"[",
"]",
"if",
"phones",
":",
"for",
"element",
"in",
"phones",
":",
"combined_rhymes",
".",
"append",
"(",
"[",
"w",
"for",
"w",
"in",... | Get words rhyming with a given word.
This function may return an empty list if no rhyming words are found in
the dictionary, or if the word you pass to the function is itself not
found in the dictionary.
.. doctest::
>>> import pronouncing
>>> pronouncing.rhymes("conditioner")
['commissioner', 'parishioner', 'petitioner', 'practitioner']
:param word: a word
:returns: a list of rhyming words | [
"Get",
"words",
"rhyming",
"with",
"a",
"given",
"word",
"."
] | train | https://github.com/aparrish/pronouncingpy/blob/09467fa9407d7d87cb0998ee3cb09db4dcc9571a/pronouncing/__init__.py#L204-L230 |
OSSOS/MOP | src/ossos/core/ossos/gui/views/imageview.py | ImageViewManager.set_ds9 | def set_ds9(self, level="PREF"):
"""
Set the default values on the ds9 display.
"""
self.set_zoom()
ds9_settings = config.read("DS9."+level)
for key in ds9_settings.keys():
value = ds9_settings[key]
cmd = key.replace("_", " ")
self.ds9.set("{} {}".format(cmd, value)) | python | def set_ds9(self, level="PREF"):
"""
Set the default values on the ds9 display.
"""
self.set_zoom()
ds9_settings = config.read("DS9."+level)
for key in ds9_settings.keys():
value = ds9_settings[key]
cmd = key.replace("_", " ")
self.ds9.set("{} {}".format(cmd, value)) | [
"def",
"set_ds9",
"(",
"self",
",",
"level",
"=",
"\"PREF\"",
")",
":",
"self",
".",
"set_zoom",
"(",
")",
"ds9_settings",
"=",
"config",
".",
"read",
"(",
"\"DS9.\"",
"+",
"level",
")",
"for",
"key",
"in",
"ds9_settings",
".",
"keys",
"(",
")",
":",... | Set the default values on the ds9 display. | [
"Set",
"the",
"default",
"values",
"on",
"the",
"ds9",
"display",
"."
] | train | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/gui/views/imageview.py#L29-L38 |
OSSOS/MOP | src/ossos/core/ossos/cadc.py | cfht_megacam_tap_query | def cfht_megacam_tap_query(ra_deg=180.0, dec_deg=0.0, width=1, height=1, date=None):
"""Do a query of the CADC Megacam table.
Get all observations inside the box (right now it turns width/height into a radius, should not do this).
@rtype : Table
@param ra_deg: center of search region, in degrees
@param dec_deg: center of search region in degrees
@param width: width of search region in degrees
@param height: height of search region in degrees
@param date: ISO format date string. Query will be +/- 0.5 days from date given.
"""
radius = min(90, max(width, height) / 2.0)
query = ("SELECT "
"COORD1(CENTROID(Plane.position_bounds)) AS RAJ2000,"
"COORD2(CENTROID(Plane.position_bounds)) AS DEJ2000,"
"target_name "
"FROM "
"caom2.Observation as o "
"JOIN caom2.Plane as Plane on o.obsID=Plane.obsID "
"WHERE o.collection = 'CFHT' "
"AND o.instrument_name = 'MegaPrime' "
"AND INTERSECTS( CIRCLE('ICRS', %f, %f, %f), Plane.position_bounds ) = 1")
query = query % (ra_deg, dec_deg, radius)
if date is not None:
mjd = Time(date, scale='utc').mjd
query += " AND Plane.time_bounds_lower <= {} AND {} <= Plane.time_bounds_upper ".format(mjd+0.5, mjd-0.5)
data = {"QUERY": query,
"REQUEST": "doQuery",
"LANG": "ADQL",
"FORMAT": "votable"}
url = "http://www.cadc.hia.nrc.gc.ca/tap/sync"
warnings.simplefilter('ignore')
ff = StringIO(requests.get(url, params=data).content)
ff.seek(0)
table = votable.parse(ff).get_first_table().to_table()
assert isinstance(table, Table)
return table | python | def cfht_megacam_tap_query(ra_deg=180.0, dec_deg=0.0, width=1, height=1, date=None):
"""Do a query of the CADC Megacam table.
Get all observations inside the box (right now it turns width/height into a radius, should not do this).
@rtype : Table
@param ra_deg: center of search region, in degrees
@param dec_deg: center of search region in degrees
@param width: width of search region in degrees
@param height: height of search region in degrees
@param date: ISO format date string. Query will be +/- 0.5 days from date given.
"""
radius = min(90, max(width, height) / 2.0)
query = ("SELECT "
"COORD1(CENTROID(Plane.position_bounds)) AS RAJ2000,"
"COORD2(CENTROID(Plane.position_bounds)) AS DEJ2000,"
"target_name "
"FROM "
"caom2.Observation as o "
"JOIN caom2.Plane as Plane on o.obsID=Plane.obsID "
"WHERE o.collection = 'CFHT' "
"AND o.instrument_name = 'MegaPrime' "
"AND INTERSECTS( CIRCLE('ICRS', %f, %f, %f), Plane.position_bounds ) = 1")
query = query % (ra_deg, dec_deg, radius)
if date is not None:
mjd = Time(date, scale='utc').mjd
query += " AND Plane.time_bounds_lower <= {} AND {} <= Plane.time_bounds_upper ".format(mjd+0.5, mjd-0.5)
data = {"QUERY": query,
"REQUEST": "doQuery",
"LANG": "ADQL",
"FORMAT": "votable"}
url = "http://www.cadc.hia.nrc.gc.ca/tap/sync"
warnings.simplefilter('ignore')
ff = StringIO(requests.get(url, params=data).content)
ff.seek(0)
table = votable.parse(ff).get_first_table().to_table()
assert isinstance(table, Table)
return table | [
"def",
"cfht_megacam_tap_query",
"(",
"ra_deg",
"=",
"180.0",
",",
"dec_deg",
"=",
"0.0",
",",
"width",
"=",
"1",
",",
"height",
"=",
"1",
",",
"date",
"=",
"None",
")",
":",
"radius",
"=",
"min",
"(",
"90",
",",
"max",
"(",
"width",
",",
"height",... | Do a query of the CADC Megacam table.
Get all observations inside the box (right now it turns width/height into a radius, should not do this).
@rtype : Table
@param ra_deg: center of search region, in degrees
@param dec_deg: center of search region in degrees
@param width: width of search region in degrees
@param height: height of search region in degrees
@param date: ISO format date string. Query will be +/- 0.5 days from date given. | [
"Do",
"a",
"query",
"of",
"the",
"CADC",
"Megacam",
"table",
"."
] | train | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/cadc.py#L11-L55 |
JohnVinyard/zounds | zounds/spectral/tfrepresentation.py | FrequencyDimension.validate | def validate(self, size):
"""
Ensure that the size of the dimension matches the number of bands in the
scale
Raises:
ValueError: when the dimension size and number of bands don't match
"""
msg = 'scale and array size must match, ' \
'but were scale: {self.scale.n_bands}, array size: {size}'
if size != len(self.scale):
raise ValueError(msg.format(**locals())) | python | def validate(self, size):
"""
Ensure that the size of the dimension matches the number of bands in the
scale
Raises:
ValueError: when the dimension size and number of bands don't match
"""
msg = 'scale and array size must match, ' \
'but were scale: {self.scale.n_bands}, array size: {size}'
if size != len(self.scale):
raise ValueError(msg.format(**locals())) | [
"def",
"validate",
"(",
"self",
",",
"size",
")",
":",
"msg",
"=",
"'scale and array size must match, '",
"'but were scale: {self.scale.n_bands}, array size: {size}'",
"if",
"size",
"!=",
"len",
"(",
"self",
".",
"scale",
")",
":",
"raise",
"ValueError",
"(",
"msg"... | Ensure that the size of the dimension matches the number of bands in the
scale
Raises:
ValueError: when the dimension size and number of bands don't match | [
"Ensure",
"that",
"the",
"size",
"of",
"the",
"dimension",
"matches",
"the",
"number",
"of",
"bands",
"in",
"the",
"scale"
] | train | https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/spectral/tfrepresentation.py#L57-L69 |
JohnVinyard/zounds | zounds/basic/audiograph.py | resampled | def resampled(
chunksize_bytes=DEFAULT_CHUNK_SIZE,
resample_to=SR44100(),
store_resampled=False):
"""
Create a basic processing pipeline that can resample all incoming audio
to a normalized sampling rate for downstream processing, and store a
convenient, compressed version for playback
:param chunksize_bytes: The number of bytes from the raw stream to process
at once
:param resample_to: The new, normalized sampling rate
:return: A simple processing pipeline
"""
class Resampled(BaseModel):
meta = JSONFeature(
MetaData,
store=True,
encoder=AudioMetaDataEncoder)
raw = ByteStreamFeature(
ByteStream,
chunksize=chunksize_bytes,
needs=meta,
store=False)
ogg = OggVorbisFeature(
OggVorbis,
needs=raw,
store=True)
pcm = AudioSamplesFeature(
AudioStream,
needs=raw,
store=False)
resampled = AudioSamplesFeature(
Resampler,
needs=pcm,
samplerate=resample_to,
store=store_resampled)
return Resampled | python | def resampled(
chunksize_bytes=DEFAULT_CHUNK_SIZE,
resample_to=SR44100(),
store_resampled=False):
"""
Create a basic processing pipeline that can resample all incoming audio
to a normalized sampling rate for downstream processing, and store a
convenient, compressed version for playback
:param chunksize_bytes: The number of bytes from the raw stream to process
at once
:param resample_to: The new, normalized sampling rate
:return: A simple processing pipeline
"""
class Resampled(BaseModel):
meta = JSONFeature(
MetaData,
store=True,
encoder=AudioMetaDataEncoder)
raw = ByteStreamFeature(
ByteStream,
chunksize=chunksize_bytes,
needs=meta,
store=False)
ogg = OggVorbisFeature(
OggVorbis,
needs=raw,
store=True)
pcm = AudioSamplesFeature(
AudioStream,
needs=raw,
store=False)
resampled = AudioSamplesFeature(
Resampler,
needs=pcm,
samplerate=resample_to,
store=store_resampled)
return Resampled | [
"def",
"resampled",
"(",
"chunksize_bytes",
"=",
"DEFAULT_CHUNK_SIZE",
",",
"resample_to",
"=",
"SR44100",
"(",
")",
",",
"store_resampled",
"=",
"False",
")",
":",
"class",
"Resampled",
"(",
"BaseModel",
")",
":",
"meta",
"=",
"JSONFeature",
"(",
"MetaData",
... | Create a basic processing pipeline that can resample all incoming audio
to a normalized sampling rate for downstream processing, and store a
convenient, compressed version for playback
:param chunksize_bytes: The number of bytes from the raw stream to process
at once
:param resample_to: The new, normalized sampling rate
:return: A simple processing pipeline | [
"Create",
"a",
"basic",
"processing",
"pipeline",
"that",
"can",
"resample",
"all",
"incoming",
"audio",
"to",
"a",
"normalized",
"sampling",
"rate",
"for",
"downstream",
"processing",
"and",
"store",
"a",
"convenient",
"compressed",
"version",
"for",
"playback"
] | train | https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/basic/audiograph.py#L22-L65 |
JohnVinyard/zounds | zounds/basic/audiograph.py | audio_graph | def audio_graph(
chunksize_bytes=DEFAULT_CHUNK_SIZE,
resample_to=SR44100(),
store_fft=False):
"""
Produce a base class suitable as a starting point for many audio processing
pipelines. This class resamples all audio to a common sampling rate, and
produces a bark band spectrogram from overlapping short-time fourier
transform frames. It also compresses the audio into ogg vorbis format for
compact storage.
"""
band = FrequencyBand(20, resample_to.nyquist)
class AudioGraph(BaseModel):
meta = JSONFeature(
MetaData,
store=True,
encoder=AudioMetaDataEncoder)
raw = ByteStreamFeature(
ByteStream,
chunksize=chunksize_bytes,
needs=meta,
store=False)
ogg = OggVorbisFeature(
OggVorbis,
needs=raw,
store=True)
pcm = AudioSamplesFeature(
AudioStream,
needs=raw,
store=False)
resampled = AudioSamplesFeature(
Resampler,
needs=pcm,
samplerate=resample_to,
store=False)
windowed = ArrayWithUnitsFeature(
SlidingWindow,
needs=resampled,
wscheme=HalfLapped(),
wfunc=OggVorbisWindowingFunc(),
store=False)
dct = ArrayWithUnitsFeature(
DCT,
needs=windowed,
store=True)
fft = ArrayWithUnitsFeature(
FFT,
needs=windowed,
store=store_fft)
bark = ArrayWithUnitsFeature(
BarkBands,
needs=fft,
frequency_band=band,
store=True)
centroid = ArrayWithUnitsFeature(
SpectralCentroid,
needs=bark,
store=True)
chroma = ArrayWithUnitsFeature(
Chroma,
needs=fft,
frequency_band=band,
store=True)
bfcc = ArrayWithUnitsFeature(
BFCC,
needs=fft,
store=True)
return AudioGraph | python | def audio_graph(
chunksize_bytes=DEFAULT_CHUNK_SIZE,
resample_to=SR44100(),
store_fft=False):
"""
Produce a base class suitable as a starting point for many audio processing
pipelines. This class resamples all audio to a common sampling rate, and
produces a bark band spectrogram from overlapping short-time fourier
transform frames. It also compresses the audio into ogg vorbis format for
compact storage.
"""
band = FrequencyBand(20, resample_to.nyquist)
class AudioGraph(BaseModel):
meta = JSONFeature(
MetaData,
store=True,
encoder=AudioMetaDataEncoder)
raw = ByteStreamFeature(
ByteStream,
chunksize=chunksize_bytes,
needs=meta,
store=False)
ogg = OggVorbisFeature(
OggVorbis,
needs=raw,
store=True)
pcm = AudioSamplesFeature(
AudioStream,
needs=raw,
store=False)
resampled = AudioSamplesFeature(
Resampler,
needs=pcm,
samplerate=resample_to,
store=False)
windowed = ArrayWithUnitsFeature(
SlidingWindow,
needs=resampled,
wscheme=HalfLapped(),
wfunc=OggVorbisWindowingFunc(),
store=False)
dct = ArrayWithUnitsFeature(
DCT,
needs=windowed,
store=True)
fft = ArrayWithUnitsFeature(
FFT,
needs=windowed,
store=store_fft)
bark = ArrayWithUnitsFeature(
BarkBands,
needs=fft,
frequency_band=band,
store=True)
centroid = ArrayWithUnitsFeature(
SpectralCentroid,
needs=bark,
store=True)
chroma = ArrayWithUnitsFeature(
Chroma,
needs=fft,
frequency_band=band,
store=True)
bfcc = ArrayWithUnitsFeature(
BFCC,
needs=fft,
store=True)
return AudioGraph | [
"def",
"audio_graph",
"(",
"chunksize_bytes",
"=",
"DEFAULT_CHUNK_SIZE",
",",
"resample_to",
"=",
"SR44100",
"(",
")",
",",
"store_fft",
"=",
"False",
")",
":",
"band",
"=",
"FrequencyBand",
"(",
"20",
",",
"resample_to",
".",
"nyquist",
")",
"class",
"Audio... | Produce a base class suitable as a starting point for many audio processing
pipelines. This class resamples all audio to a common sampling rate, and
produces a bark band spectrogram from overlapping short-time fourier
transform frames. It also compresses the audio into ogg vorbis format for
compact storage. | [
"Produce",
"a",
"base",
"class",
"suitable",
"as",
"a",
"starting",
"point",
"for",
"many",
"audio",
"processing",
"pipelines",
".",
"This",
"class",
"resamples",
"all",
"audio",
"to",
"a",
"common",
"sampling",
"rate",
"and",
"produces",
"a",
"bark",
"band"... | train | https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/basic/audiograph.py#L179-L260 |
JohnVinyard/zounds | zounds/basic/audiograph.py | with_onsets | def with_onsets(fft_feature):
"""
Produce a mixin class that extracts onsets
:param fft_feature: The short-time fourier transform feature
:return: A mixin class that extracts onsets
"""
class Onsets(BaseModel):
onset_prep = ArrayWithUnitsFeature(
SlidingWindow,
needs=fft_feature,
wscheme=HalfLapped() * Stride(frequency=1, duration=3),
store=False)
complex_domain = ArrayWithUnitsFeature(
ComplexDomain,
needs=onset_prep,
store=False)
sliding_detection = ArrayWithUnitsFeature(
SlidingWindow,
needs=complex_domain,
wscheme=HalfLapped() * Stride(frequency=1, duration=11),
padwith=5,
store=False)
slices = TimeSliceFeature(
MovingAveragePeakPicker,
needs=sliding_detection,
aggregate=np.median,
store=True)
return Onsets | python | def with_onsets(fft_feature):
"""
Produce a mixin class that extracts onsets
:param fft_feature: The short-time fourier transform feature
:return: A mixin class that extracts onsets
"""
class Onsets(BaseModel):
onset_prep = ArrayWithUnitsFeature(
SlidingWindow,
needs=fft_feature,
wscheme=HalfLapped() * Stride(frequency=1, duration=3),
store=False)
complex_domain = ArrayWithUnitsFeature(
ComplexDomain,
needs=onset_prep,
store=False)
sliding_detection = ArrayWithUnitsFeature(
SlidingWindow,
needs=complex_domain,
wscheme=HalfLapped() * Stride(frequency=1, duration=11),
padwith=5,
store=False)
slices = TimeSliceFeature(
MovingAveragePeakPicker,
needs=sliding_detection,
aggregate=np.median,
store=True)
return Onsets | [
"def",
"with_onsets",
"(",
"fft_feature",
")",
":",
"class",
"Onsets",
"(",
"BaseModel",
")",
":",
"onset_prep",
"=",
"ArrayWithUnitsFeature",
"(",
"SlidingWindow",
",",
"needs",
"=",
"fft_feature",
",",
"wscheme",
"=",
"HalfLapped",
"(",
")",
"*",
"Stride",
... | Produce a mixin class that extracts onsets
:param fft_feature: The short-time fourier transform feature
:return: A mixin class that extracts onsets | [
"Produce",
"a",
"mixin",
"class",
"that",
"extracts",
"onsets",
":",
"param",
"fft_feature",
":",
"The",
"short",
"-",
"time",
"fourier",
"transform",
"feature",
":",
"return",
":",
"A",
"mixin",
"class",
"that",
"extracts",
"onsets"
] | train | https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/basic/audiograph.py#L263-L295 |
OSSOS/MOP | src/ossos/plotting/scripts/sky_location_plots.py | keplerian_sheared_field_locations | def keplerian_sheared_field_locations(ax, kbos, date, ras, decs, names, elongation=False, plot=False):
"""
Shift fields from the discovery set to the requested date by the average motion of L7 kbos in the discovery field.
:param ras:
:param decs:
:param plot:
:param ax:
:param kbos: precomputed at the discovery date for that block. e.g. Oct new moon for 13B
:param date:
:param names:
:param elongation:
"""
seps = {'dra': 0., 'ddec': 0.}
for kbo in kbos:
ra = kbo.ra
dec = kbo.dec
kbo.compute(date)
seps['dra'] += kbo.ra - ra
seps['ddec'] += kbo.dec - dec
seps['dra'] /= float(len(kbos))
seps['ddec'] /= float(len(kbos))
print date, seps, len(kbos)
for idx in range(len(ras)):
name = names[idx]
ra = ras[idx] + seps['dra']
dec = decs[idx] + seps['ddec']
if plot:
ax.add_artist(Rectangle(xy=(math.degrees(ra) - camera_dimen / 2.0, math.degrees(dec) - camera_dimen / 2.0),
height=camera_dimen,
width=camera_dimen,
edgecolor='b',
facecolor='b',
lw=0.5, fill=True, alpha=0.2))
if elongation:
# For each field centre, plot the elongation onto the field at that date.
elong = field_elongation(ephem.degrees(ra), ephem.degrees(dec), date)
ax.annotate(name, (math.degrees(ra) + camera_dimen / 2., math.degrees(dec)), size=3)
ax.annotate("%0.1f" % elong, (math.degrees(ra) + camera_dimen / 4., math.degrees(dec) - camera_dimen / 4.),
size=5)
return ax | python | def keplerian_sheared_field_locations(ax, kbos, date, ras, decs, names, elongation=False, plot=False):
"""
Shift fields from the discovery set to the requested date by the average motion of L7 kbos in the discovery field.
:param ras:
:param decs:
:param plot:
:param ax:
:param kbos: precomputed at the discovery date for that block. e.g. Oct new moon for 13B
:param date:
:param names:
:param elongation:
"""
seps = {'dra': 0., 'ddec': 0.}
for kbo in kbos:
ra = kbo.ra
dec = kbo.dec
kbo.compute(date)
seps['dra'] += kbo.ra - ra
seps['ddec'] += kbo.dec - dec
seps['dra'] /= float(len(kbos))
seps['ddec'] /= float(len(kbos))
print date, seps, len(kbos)
for idx in range(len(ras)):
name = names[idx]
ra = ras[idx] + seps['dra']
dec = decs[idx] + seps['ddec']
if plot:
ax.add_artist(Rectangle(xy=(math.degrees(ra) - camera_dimen / 2.0, math.degrees(dec) - camera_dimen / 2.0),
height=camera_dimen,
width=camera_dimen,
edgecolor='b',
facecolor='b',
lw=0.5, fill=True, alpha=0.2))
if elongation:
# For each field centre, plot the elongation onto the field at that date.
elong = field_elongation(ephem.degrees(ra), ephem.degrees(dec), date)
ax.annotate(name, (math.degrees(ra) + camera_dimen / 2., math.degrees(dec)), size=3)
ax.annotate("%0.1f" % elong, (math.degrees(ra) + camera_dimen / 4., math.degrees(dec) - camera_dimen / 4.),
size=5)
return ax | [
"def",
"keplerian_sheared_field_locations",
"(",
"ax",
",",
"kbos",
",",
"date",
",",
"ras",
",",
"decs",
",",
"names",
",",
"elongation",
"=",
"False",
",",
"plot",
"=",
"False",
")",
":",
"seps",
"=",
"{",
"'dra'",
":",
"0.",
",",
"'ddec'",
":",
"0... | Shift fields from the discovery set to the requested date by the average motion of L7 kbos in the discovery field.
:param ras:
:param decs:
:param plot:
:param ax:
:param kbos: precomputed at the discovery date for that block. e.g. Oct new moon for 13B
:param date:
:param names:
:param elongation: | [
"Shift",
"fields",
"from",
"the",
"discovery",
"set",
"to",
"the",
"requested",
"date",
"by",
"the",
"average",
"motion",
"of",
"L7",
"kbos",
"in",
"the",
"discovery",
"field",
".",
":",
"param",
"ras",
":",
":",
"param",
"decs",
":",
":",
"param",
"pl... | train | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/plotting/scripts/sky_location_plots.py#L322-L365 |
OSSOS/MOP | src/ossos/plotting/scripts/sky_location_plots.py | field_elongation | def field_elongation(ra, dec, date):
"""
For a given field, calculate the solar elongation at the given date.
:param ra: field's right ascension. unit="h" format="RAh:RAm:RAs"
:param dec: field's declination. degrees
:param date: date at which to calculate elongation
:return: elongation from the Sun in degrees
"""
sun = ephem.Sun()
sun.compute(date)
sep = ephem.separation((ra, dec), sun)
retval = 180. - math.degrees(sep)
return retval | python | def field_elongation(ra, dec, date):
"""
For a given field, calculate the solar elongation at the given date.
:param ra: field's right ascension. unit="h" format="RAh:RAm:RAs"
:param dec: field's declination. degrees
:param date: date at which to calculate elongation
:return: elongation from the Sun in degrees
"""
sun = ephem.Sun()
sun.compute(date)
sep = ephem.separation((ra, dec), sun)
retval = 180. - math.degrees(sep)
return retval | [
"def",
"field_elongation",
"(",
"ra",
",",
"dec",
",",
"date",
")",
":",
"sun",
"=",
"ephem",
".",
"Sun",
"(",
")",
"sun",
".",
"compute",
"(",
"date",
")",
"sep",
"=",
"ephem",
".",
"separation",
"(",
"(",
"ra",
",",
"dec",
")",
",",
"sun",
")... | For a given field, calculate the solar elongation at the given date.
:param ra: field's right ascension. unit="h" format="RAh:RAm:RAs"
:param dec: field's declination. degrees
:param date: date at which to calculate elongation
:return: elongation from the Sun in degrees | [
"For",
"a",
"given",
"field",
"calculate",
"the",
"solar",
"elongation",
"at",
"the",
"given",
"date",
".",
":",
"param",
"ra",
":",
"field",
"s",
"right",
"ascension",
".",
"unit",
"=",
"h",
"format",
"=",
"RAh",
":",
"RAm",
":",
"RAs",
":",
"param"... | train | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/plotting/scripts/sky_location_plots.py#L368-L381 |
playpauseandstop/rororo | rororo/timedelta.py | str_to_timedelta | def str_to_timedelta(value: str,
fmt: str = None) -> Optional[datetime.timedelta]:
"""
Convert string value to timedelta instance according to the given format.
If format not set function tries to load timedelta using default
``TIMEDELTA_FORMAT`` and then both of magic "full" formats.
You should also specify list of formats and function tries to convert
to timedelta using each of formats in list. First matched format would
return the converted timedelta instance.
If user specified format, but function cannot convert string to
new timedelta instance - ``ValueError`` would be raised. But if user did
not specify the format, function would be fail silently and return ``None``
as result.
:param value: String representation of timedelta.
:param fmt: Format to use for conversion.
"""
def timedelta_kwargs(data: DictStrInt) -> DictStrInt:
"""
Convert day_hours, hour_minutes, minute_seconds, week_days and weeks to
timedelta seconds.
"""
seconds = data.get('seconds', 0)
seconds += data.get('day_hours', 0) * 3600
seconds += data.pop('hour_minutes', 0) * 60
seconds += data.pop('minute_seconds', 0)
seconds += data.pop('week_days', 0) * SECONDS_PER_DAY
seconds += data.pop('weeks', 0) * SECONDS_PER_WEEK
data.update({'seconds': seconds})
return data
if not isinstance(value, str):
raise ValueError(
'Value should be a "str" instance. You use {0}.'
.format(type(value)))
user_fmt = fmt
if isinstance(fmt, (list, tuple)):
formats = list(fmt)
elif fmt is None:
formats = [TIMEDELTA_FORMAT, 'F', 'f']
else:
formats = [fmt]
locale_data = {
'days_label': '({0}|{1})'.format('day', 'days'),
'short_days_label': 'd',
'short_week_days_label': 'd',
'short_weeks_label': 'w',
'week_days_label': '({0}|{1})'.format('day', 'days'),
'weeks_label': '({0}|{1})'.format('week', 'weeks'),
}
regexps = []
for item in formats:
processed = r'^'
for part in item:
if part in TIMEDELTA_FORMATS:
part = TIMEDELTA_FORMATS[part][1] % locale_data
else:
part = re.escape(part)
processed += part
processed += r'$'
regexps.append(processed)
for regexp in regexps:
timedelta_re = re.compile(regexp)
matched = timedelta_re.match(value)
if matched:
data = {
key: to_int(value) or 0
for key, value in matched.groupdict().items()}
return datetime.timedelta(**timedelta_kwargs(data))
if user_fmt:
raise ValueError(
'Cannot convert {0!r} to timedelta instance, using {1!r} format.'
.format(value, user_fmt))
return None | python | def str_to_timedelta(value: str,
fmt: str = None) -> Optional[datetime.timedelta]:
"""
Convert string value to timedelta instance according to the given format.
If format not set function tries to load timedelta using default
``TIMEDELTA_FORMAT`` and then both of magic "full" formats.
You should also specify list of formats and function tries to convert
to timedelta using each of formats in list. First matched format would
return the converted timedelta instance.
If user specified format, but function cannot convert string to
new timedelta instance - ``ValueError`` would be raised. But if user did
not specify the format, function would be fail silently and return ``None``
as result.
:param value: String representation of timedelta.
:param fmt: Format to use for conversion.
"""
def timedelta_kwargs(data: DictStrInt) -> DictStrInt:
"""
Convert day_hours, hour_minutes, minute_seconds, week_days and weeks to
timedelta seconds.
"""
seconds = data.get('seconds', 0)
seconds += data.get('day_hours', 0) * 3600
seconds += data.pop('hour_minutes', 0) * 60
seconds += data.pop('minute_seconds', 0)
seconds += data.pop('week_days', 0) * SECONDS_PER_DAY
seconds += data.pop('weeks', 0) * SECONDS_PER_WEEK
data.update({'seconds': seconds})
return data
if not isinstance(value, str):
raise ValueError(
'Value should be a "str" instance. You use {0}.'
.format(type(value)))
user_fmt = fmt
if isinstance(fmt, (list, tuple)):
formats = list(fmt)
elif fmt is None:
formats = [TIMEDELTA_FORMAT, 'F', 'f']
else:
formats = [fmt]
locale_data = {
'days_label': '({0}|{1})'.format('day', 'days'),
'short_days_label': 'd',
'short_week_days_label': 'd',
'short_weeks_label': 'w',
'week_days_label': '({0}|{1})'.format('day', 'days'),
'weeks_label': '({0}|{1})'.format('week', 'weeks'),
}
regexps = []
for item in formats:
processed = r'^'
for part in item:
if part in TIMEDELTA_FORMATS:
part = TIMEDELTA_FORMATS[part][1] % locale_data
else:
part = re.escape(part)
processed += part
processed += r'$'
regexps.append(processed)
for regexp in regexps:
timedelta_re = re.compile(regexp)
matched = timedelta_re.match(value)
if matched:
data = {
key: to_int(value) or 0
for key, value in matched.groupdict().items()}
return datetime.timedelta(**timedelta_kwargs(data))
if user_fmt:
raise ValueError(
'Cannot convert {0!r} to timedelta instance, using {1!r} format.'
.format(value, user_fmt))
return None | [
"def",
"str_to_timedelta",
"(",
"value",
":",
"str",
",",
"fmt",
":",
"str",
"=",
"None",
")",
"->",
"Optional",
"[",
"datetime",
".",
"timedelta",
"]",
":",
"def",
"timedelta_kwargs",
"(",
"data",
":",
"DictStrInt",
")",
"->",
"DictStrInt",
":",
"\"\"\"... | Convert string value to timedelta instance according to the given format.
If format not set function tries to load timedelta using default
``TIMEDELTA_FORMAT`` and then both of magic "full" formats.
You should also specify list of formats and function tries to convert
to timedelta using each of formats in list. First matched format would
return the converted timedelta instance.
If user specified format, but function cannot convert string to
new timedelta instance - ``ValueError`` would be raised. But if user did
not specify the format, function would be fail silently and return ``None``
as result.
:param value: String representation of timedelta.
:param fmt: Format to use for conversion. | [
"Convert",
"string",
"value",
"to",
"timedelta",
"instance",
"according",
"to",
"the",
"given",
"format",
"."
] | train | https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/timedelta.py#L66-L152 |
playpauseandstop/rororo | rororo/timedelta.py | timedelta_average | def timedelta_average(*values: datetime.timedelta) -> datetime.timedelta:
r"""Compute the arithmetic mean for timedeltas list.
:param \*values: Timedelta instances to process.
"""
if isinstance(values[0], (list, tuple)):
values = values[0]
return sum(values, datetime.timedelta()) // len(values) | python | def timedelta_average(*values: datetime.timedelta) -> datetime.timedelta:
r"""Compute the arithmetic mean for timedeltas list.
:param \*values: Timedelta instances to process.
"""
if isinstance(values[0], (list, tuple)):
values = values[0]
return sum(values, datetime.timedelta()) // len(values) | [
"def",
"timedelta_average",
"(",
"*",
"values",
":",
"datetime",
".",
"timedelta",
")",
"->",
"datetime",
".",
"timedelta",
":",
"if",
"isinstance",
"(",
"values",
"[",
"0",
"]",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"values",
"=",
"values",
... | r"""Compute the arithmetic mean for timedeltas list.
:param \*values: Timedelta instances to process. | [
"r",
"Compute",
"the",
"arithmetic",
"mean",
"for",
"timedeltas",
"list",
"."
] | train | https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/timedelta.py#L155-L162 |
playpauseandstop/rororo | rororo/timedelta.py | timedelta_div | def timedelta_div(first: datetime.timedelta,
second: datetime.timedelta) -> Optional[float]:
"""Implement divison for timedelta instances.
:param first: First timedelta instance.
:param second: Second timedelta instance.
"""
first_seconds = timedelta_seconds(first)
second_seconds = timedelta_seconds(second)
if not second_seconds:
return None
return first_seconds / second_seconds | python | def timedelta_div(first: datetime.timedelta,
second: datetime.timedelta) -> Optional[float]:
"""Implement divison for timedelta instances.
:param first: First timedelta instance.
:param second: Second timedelta instance.
"""
first_seconds = timedelta_seconds(first)
second_seconds = timedelta_seconds(second)
if not second_seconds:
return None
return first_seconds / second_seconds | [
"def",
"timedelta_div",
"(",
"first",
":",
"datetime",
".",
"timedelta",
",",
"second",
":",
"datetime",
".",
"timedelta",
")",
"->",
"Optional",
"[",
"float",
"]",
":",
"first_seconds",
"=",
"timedelta_seconds",
"(",
"first",
")",
"second_seconds",
"=",
"ti... | Implement divison for timedelta instances.
:param first: First timedelta instance.
:param second: Second timedelta instance. | [
"Implement",
"divison",
"for",
"timedelta",
"instances",
"."
] | train | https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/timedelta.py#L165-L178 |
playpauseandstop/rororo | rororo/timedelta.py | timedelta_seconds | def timedelta_seconds(value: datetime.timedelta) -> int:
"""Return full number of seconds from timedelta.
By default, Python returns only one day seconds, not all timedelta seconds.
:param value: Timedelta instance.
"""
return SECONDS_PER_DAY * value.days + value.seconds | python | def timedelta_seconds(value: datetime.timedelta) -> int:
"""Return full number of seconds from timedelta.
By default, Python returns only one day seconds, not all timedelta seconds.
:param value: Timedelta instance.
"""
return SECONDS_PER_DAY * value.days + value.seconds | [
"def",
"timedelta_seconds",
"(",
"value",
":",
"datetime",
".",
"timedelta",
")",
"->",
"int",
":",
"return",
"SECONDS_PER_DAY",
"*",
"value",
".",
"days",
"+",
"value",
".",
"seconds"
] | Return full number of seconds from timedelta.
By default, Python returns only one day seconds, not all timedelta seconds.
:param value: Timedelta instance. | [
"Return",
"full",
"number",
"of",
"seconds",
"from",
"timedelta",
"."
] | train | https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/timedelta.py#L181-L188 |
playpauseandstop/rororo | rororo/timedelta.py | timedelta_to_str | def timedelta_to_str(value: datetime.timedelta, fmt: str = None) -> str:
"""Display the timedelta formatted according to the given string.
You should use global setting ``TIMEDELTA_FORMAT`` to specify default
format to this function there (like ``DATE_FORMAT`` for builtin ``date``
template filter).
Default value for ``TIMEDELTA_FORMAT`` is ``'G:i'``.
Format uses the same policy as Django ``date`` template filter or
PHP ``date`` function with several differences.
Available format strings:
+------------------+-----------------------------+------------------------+
| Format character | Description | Example output |
+==================+=============================+========================+
| ``a`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``A`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``b`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``B`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``c`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``d`` | Total days, 2 digits with | ``'01'``, ``'41'`` |
| | leading zeros. Do not | |
| | combine with ``w`` format. | |
+------------------+-----------------------------+------------------------+
| ``D`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``f`` | Magic "full" format with | ``'2w 4d 1:28:07'`` |
| | short labels. | |
+------------------+-----------------------------+------------------------+
| ``F`` | Magic "full" format with | ``'2 weeks, 4 days, |
| | normal labels. | 1:28:07'`` |
+------------------+-----------------------------+------------------------+
| ``g`` | Day, not total, hours | ``'0'`` to ``'23'`` |
| | without leading zeros. To | |
| | use with ``d``, ``j``, or | |
| | ``w``. | |
+------------------+-----------------------------+------------------------+
| ``G`` | Total hours without | ``'1'``, ``'433'`` |
| | leading zeros. Do not | |
| | combine with ``g`` or | |
| | ``h`` formats. | |
+------------------+-----------------------------+------------------------+
| ``h`` | Day, not total, hours with | ``'00'`` to ``'23'`` |
| | leading zeros. To use with | |
| | ``d`` or ``w``. | |
+------------------+-----------------------------+------------------------+
| ``H`` | Total hours with leading | ``'01', ``'433'`` |
| | zeros. Do not combine with | |
| | ``g`` or ``h`` formats. | |
+------------------+-----------------------------+------------------------+
| ``i`` | Hour, not total, minutes, 2 | ``00`` to ``'59'`` |
| | digits with leading zeros | |
| | To use with ``g``, ``G``, | |
| | ``h`` or ``H`` formats. | |
+------------------+-----------------------------+------------------------+
| ``I`` | Total minutes, 2 digits or | ``'01'``, ``'433'`` |
| | more with leading zeros. Do | |
| | not combine with ``i`` | |
| | format. | |
+------------------+-----------------------------+------------------------+
| ``j`` | Total days, one or 2 digits | ``'1'``, ``'41'`` |
| | without leading zeros. Do | |
| | not combine with ``w`` | |
| | format. | |
+------------------+-----------------------------+------------------------+
| ``J`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``l`` | Days long label. | ``'day'`` or |
| | Pluralized and localized. | ``'days'`` |
+------------------+-----------------------------+------------------------+
| ``L`` | Weeks long label. | ``'week'`` or |
| | Pluralized and localized. | ``'weeks'`` |
+------------------+-----------------------------+------------------------+
| ``m`` | Week days long label. | ``'day'`` or |
| | Pluralized and localized. | ``'days'`` |
+------------------+-----------------------------+------------------------+
| ``M`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``n`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``N`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``O`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``P`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``r`` | Standart Python timedelta | ``'18 d 1:28:07'`` |
| | representation with short | |
| | labels. | |
+------------------+-----------------------------+------------------------+
| ``R`` | Standart Python timedelta | ``'18 days, 1:28:07'`` |
| | representation with normal | |
| | labels. | |
+------------------+-----------------------------+------------------------+
| ``s`` | Minute, not total, seconds, | ``'00'`` to ``'59'`` |
| | 2 digits with leading | |
| | zeros. To use with ``i`` or | |
| | ``I``. | |
+------------------+-----------------------------+------------------------+
| ``S`` | Total seconds. 2 digits or | ``'00'``, ``'433'`` |
| | more with leading zeros. Do | |
| | not combine with ``s`` | |
| | format. | |
+------------------+-----------------------------+------------------------+
| ``t`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``T`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``u`` | Second, not total, | ``0`` to ``999999`` |
| | microseconds. | |
+------------------+-----------------------------+------------------------+
| ``U`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``w`` | Week, not total, days, one | ``0`` to ``6`` |
| | digit without leading | |
| | zeros. To use with ``W``. | |
+------------------+-----------------------------+------------------------+
| ``W`` | Total weeks, one or more | ``'1'``, ``'41'`` |
| | digits without leading | |
| | zeros. | |
+------------------+-----------------------------+------------------------+
| ``y`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``Y`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``z`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``Z`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
For example,
::
>>> import datetime
>>> from rororo.timedelta import timedelta_to_str
>>> delta = datetime.timedelta(seconds=99660)
>>> timedelta_to_str(delta)
... '27:41'
>>> timedelta_to_str(delta, 'r')
... '1d 3:41:00'
>>> timedelta_to_str(delta, 'f')
... '1d 3:41'
>>> timedelta_to_str(delta, 'W L, w l, H:i:s')
... '0 weeks, 1 day, 03:41:00'
Couple words about magic "full" formats. These formats show weeks number
with week label, days number with day label and seconds only if weeks
number, days number or seconds greater that zero.
For example,
::
>>> import datetime
>>> from rororo.timedelta import timedelta_to_str
>>> delta = datetime.timedelta(hours=12)
>>> timedelta_to_str(delta, 'f')
... '12:00'
>>> timedelta_to_str(delta, 'F')
... '12:00'
>>> delta = datetime.timedelta(hours=12, seconds=30)
>>> timedelta_to_str(delta, 'f')
... '12:00:30'
>>> timedelta_to_str(delta, 'F')
... '12:00:30'
>>> delta = datetime.timedelta(hours=168)
>>> timedelta_to_str(delta, 'f')
... '1w 0:00'
>>> timedelta_to_str(delta, 'F')
... '1 week, 0:00'
:param value: Timedelta instance to convert to string.
:param fmt: Format to use for conversion.
"""
# Only ``datetime.timedelta`` instances allowed for this function
if not isinstance(value, datetime.timedelta):
raise ValueError(
'Value should be a "datetime.timedelta" instance. You use {0}.'
.format(type(value)))
# Generate total data
days = value.days
microseconds = value.microseconds
seconds = timedelta_seconds(value)
hours = seconds // 3600
minutes = seconds // 60
weeks = days // 7
# Generate collapsed data
day_hours = hours - days * 24
hour_minutes = minutes - hours * 60
minute_seconds = seconds - minutes * 60
week_days = days - weeks * 7
days_label = 'day' if days % 10 == 1 else 'days'
short_days_label = 'd'
short_week_days_label = 'd'
short_weeks_label = 'w'
week_days_label = 'day' if week_days % 10 == 1 else 'days'
weeks_label = 'week' if weeks % 10 == 1 else 'weeks'
# Collect data
data = locals()
fmt = fmt or TIMEDELTA_FORMAT
processed = ''
for part in fmt:
if part in TIMEDELTA_FORMATS:
is_full_part = part in ('f', 'F')
is_repr_part = part in ('r', 'R')
part = TIMEDELTA_FORMATS[part][0]
if is_full_part or is_repr_part:
if is_repr_part and not days:
part = part.replace('%(days)d', '')
part = part.replace('%(days_label)s,', '')
part = part.replace('%(short_days_label)s', '')
if is_full_part and not minute_seconds:
part = part.replace(':%(minute_seconds)02d', '')
if is_full_part and not weeks:
part = part.replace('%(weeks)d', '')
part = part.replace('%(short_weeks_label)s', '')
part = part.replace('%(weeks_label)s,', '')
if is_full_part and not week_days:
part = part.replace('%(week_days)d', '')
part = part.replace('%(short_week_days_label)s', '')
part = part.replace('%(week_days_label)s,', '')
part = part.strip()
part = ' '.join(part.split())
processed += part
return processed % data | python | def timedelta_to_str(value: datetime.timedelta, fmt: str = None) -> str:
"""Display the timedelta formatted according to the given string.
You should use global setting ``TIMEDELTA_FORMAT`` to specify default
format to this function there (like ``DATE_FORMAT`` for builtin ``date``
template filter).
Default value for ``TIMEDELTA_FORMAT`` is ``'G:i'``.
Format uses the same policy as Django ``date`` template filter or
PHP ``date`` function with several differences.
Available format strings:
+------------------+-----------------------------+------------------------+
| Format character | Description | Example output |
+==================+=============================+========================+
| ``a`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``A`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``b`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``B`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``c`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``d`` | Total days, 2 digits with | ``'01'``, ``'41'`` |
| | leading zeros. Do not | |
| | combine with ``w`` format. | |
+------------------+-----------------------------+------------------------+
| ``D`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``f`` | Magic "full" format with | ``'2w 4d 1:28:07'`` |
| | short labels. | |
+------------------+-----------------------------+------------------------+
| ``F`` | Magic "full" format with | ``'2 weeks, 4 days, |
| | normal labels. | 1:28:07'`` |
+------------------+-----------------------------+------------------------+
| ``g`` | Day, not total, hours | ``'0'`` to ``'23'`` |
| | without leading zeros. To | |
| | use with ``d``, ``j``, or | |
| | ``w``. | |
+------------------+-----------------------------+------------------------+
| ``G`` | Total hours without | ``'1'``, ``'433'`` |
| | leading zeros. Do not | |
| | combine with ``g`` or | |
| | ``h`` formats. | |
+------------------+-----------------------------+------------------------+
| ``h`` | Day, not total, hours with | ``'00'`` to ``'23'`` |
| | leading zeros. To use with | |
| | ``d`` or ``w``. | |
+------------------+-----------------------------+------------------------+
| ``H`` | Total hours with leading | ``'01', ``'433'`` |
| | zeros. Do not combine with | |
| | ``g`` or ``h`` formats. | |
+------------------+-----------------------------+------------------------+
| ``i`` | Hour, not total, minutes, 2 | ``00`` to ``'59'`` |
| | digits with leading zeros | |
| | To use with ``g``, ``G``, | |
| | ``h`` or ``H`` formats. | |
+------------------+-----------------------------+------------------------+
| ``I`` | Total minutes, 2 digits or | ``'01'``, ``'433'`` |
| | more with leading zeros. Do | |
| | not combine with ``i`` | |
| | format. | |
+------------------+-----------------------------+------------------------+
| ``j`` | Total days, one or 2 digits | ``'1'``, ``'41'`` |
| | without leading zeros. Do | |
| | not combine with ``w`` | |
| | format. | |
+------------------+-----------------------------+------------------------+
| ``J`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``l`` | Days long label. | ``'day'`` or |
| | Pluralized and localized. | ``'days'`` |
+------------------+-----------------------------+------------------------+
| ``L`` | Weeks long label. | ``'week'`` or |
| | Pluralized and localized. | ``'weeks'`` |
+------------------+-----------------------------+------------------------+
| ``m`` | Week days long label. | ``'day'`` or |
| | Pluralized and localized. | ``'days'`` |
+------------------+-----------------------------+------------------------+
| ``M`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``n`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``N`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``O`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``P`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``r`` | Standart Python timedelta | ``'18 d 1:28:07'`` |
| | representation with short | |
| | labels. | |
+------------------+-----------------------------+------------------------+
| ``R`` | Standart Python timedelta | ``'18 days, 1:28:07'`` |
| | representation with normal | |
| | labels. | |
+------------------+-----------------------------+------------------------+
| ``s`` | Minute, not total, seconds, | ``'00'`` to ``'59'`` |
| | 2 digits with leading | |
| | zeros. To use with ``i`` or | |
| | ``I``. | |
+------------------+-----------------------------+------------------------+
| ``S`` | Total seconds. 2 digits or | ``'00'``, ``'433'`` |
| | more with leading zeros. Do | |
| | not combine with ``s`` | |
| | format. | |
+------------------+-----------------------------+------------------------+
| ``t`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``T`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``u`` | Second, not total, | ``0`` to ``999999`` |
| | microseconds. | |
+------------------+-----------------------------+------------------------+
| ``U`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``w`` | Week, not total, days, one | ``0`` to ``6`` |
| | digit without leading | |
| | zeros. To use with ``W``. | |
+------------------+-----------------------------+------------------------+
| ``W`` | Total weeks, one or more | ``'1'``, ``'41'`` |
| | digits without leading | |
| | zeros. | |
+------------------+-----------------------------+------------------------+
| ``y`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``Y`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``z`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``Z`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
For example,
::
>>> import datetime
>>> from rororo.timedelta import timedelta_to_str
>>> delta = datetime.timedelta(seconds=99660)
>>> timedelta_to_str(delta)
... '27:41'
>>> timedelta_to_str(delta, 'r')
... '1d 3:41:00'
>>> timedelta_to_str(delta, 'f')
... '1d 3:41'
>>> timedelta_to_str(delta, 'W L, w l, H:i:s')
... '0 weeks, 1 day, 03:41:00'
Couple words about magic "full" formats. These formats show weeks number
with week label, days number with day label and seconds only if weeks
number, days number or seconds greater that zero.
For example,
::
>>> import datetime
>>> from rororo.timedelta import timedelta_to_str
>>> delta = datetime.timedelta(hours=12)
>>> timedelta_to_str(delta, 'f')
... '12:00'
>>> timedelta_to_str(delta, 'F')
... '12:00'
>>> delta = datetime.timedelta(hours=12, seconds=30)
>>> timedelta_to_str(delta, 'f')
... '12:00:30'
>>> timedelta_to_str(delta, 'F')
... '12:00:30'
>>> delta = datetime.timedelta(hours=168)
>>> timedelta_to_str(delta, 'f')
... '1w 0:00'
>>> timedelta_to_str(delta, 'F')
... '1 week, 0:00'
:param value: Timedelta instance to convert to string.
:param fmt: Format to use for conversion.
"""
# Only ``datetime.timedelta`` instances allowed for this function
if not isinstance(value, datetime.timedelta):
raise ValueError(
'Value should be a "datetime.timedelta" instance. You use {0}.'
.format(type(value)))
# Generate total data
days = value.days
microseconds = value.microseconds
seconds = timedelta_seconds(value)
hours = seconds // 3600
minutes = seconds // 60
weeks = days // 7
# Generate collapsed data
day_hours = hours - days * 24
hour_minutes = minutes - hours * 60
minute_seconds = seconds - minutes * 60
week_days = days - weeks * 7
days_label = 'day' if days % 10 == 1 else 'days'
short_days_label = 'd'
short_week_days_label = 'd'
short_weeks_label = 'w'
week_days_label = 'day' if week_days % 10 == 1 else 'days'
weeks_label = 'week' if weeks % 10 == 1 else 'weeks'
# Collect data
data = locals()
fmt = fmt or TIMEDELTA_FORMAT
processed = ''
for part in fmt:
if part in TIMEDELTA_FORMATS:
is_full_part = part in ('f', 'F')
is_repr_part = part in ('r', 'R')
part = TIMEDELTA_FORMATS[part][0]
if is_full_part or is_repr_part:
if is_repr_part and not days:
part = part.replace('%(days)d', '')
part = part.replace('%(days_label)s,', '')
part = part.replace('%(short_days_label)s', '')
if is_full_part and not minute_seconds:
part = part.replace(':%(minute_seconds)02d', '')
if is_full_part and not weeks:
part = part.replace('%(weeks)d', '')
part = part.replace('%(short_weeks_label)s', '')
part = part.replace('%(weeks_label)s,', '')
if is_full_part and not week_days:
part = part.replace('%(week_days)d', '')
part = part.replace('%(short_week_days_label)s', '')
part = part.replace('%(week_days_label)s,', '')
part = part.strip()
part = ' '.join(part.split())
processed += part
return processed % data | [
"def",
"timedelta_to_str",
"(",
"value",
":",
"datetime",
".",
"timedelta",
",",
"fmt",
":",
"str",
"=",
"None",
")",
"->",
"str",
":",
"# Only ``datetime.timedelta`` instances allowed for this function",
"if",
"not",
"isinstance",
"(",
"value",
",",
"datetime",
"... | Display the timedelta formatted according to the given string.
You should use global setting ``TIMEDELTA_FORMAT`` to specify default
format to this function there (like ``DATE_FORMAT`` for builtin ``date``
template filter).
Default value for ``TIMEDELTA_FORMAT`` is ``'G:i'``.
Format uses the same policy as Django ``date`` template filter or
PHP ``date`` function with several differences.
Available format strings:
+------------------+-----------------------------+------------------------+
| Format character | Description | Example output |
+==================+=============================+========================+
| ``a`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``A`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``b`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``B`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``c`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``d`` | Total days, 2 digits with | ``'01'``, ``'41'`` |
| | leading zeros. Do not | |
| | combine with ``w`` format. | |
+------------------+-----------------------------+------------------------+
| ``D`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``f`` | Magic "full" format with | ``'2w 4d 1:28:07'`` |
| | short labels. | |
+------------------+-----------------------------+------------------------+
| ``F`` | Magic "full" format with | ``'2 weeks, 4 days, |
| | normal labels. | 1:28:07'`` |
+------------------+-----------------------------+------------------------+
| ``g`` | Day, not total, hours | ``'0'`` to ``'23'`` |
| | without leading zeros. To | |
| | use with ``d``, ``j``, or | |
| | ``w``. | |
+------------------+-----------------------------+------------------------+
| ``G`` | Total hours without | ``'1'``, ``'433'`` |
| | leading zeros. Do not | |
| | combine with ``g`` or | |
| | ``h`` formats. | |
+------------------+-----------------------------+------------------------+
| ``h`` | Day, not total, hours with | ``'00'`` to ``'23'`` |
| | leading zeros. To use with | |
| | ``d`` or ``w``. | |
+------------------+-----------------------------+------------------------+
| ``H`` | Total hours with leading | ``'01', ``'433'`` |
| | zeros. Do not combine with | |
| | ``g`` or ``h`` formats. | |
+------------------+-----------------------------+------------------------+
| ``i`` | Hour, not total, minutes, 2 | ``00`` to ``'59'`` |
| | digits with leading zeros | |
| | To use with ``g``, ``G``, | |
| | ``h`` or ``H`` formats. | |
+------------------+-----------------------------+------------------------+
| ``I`` | Total minutes, 2 digits or | ``'01'``, ``'433'`` |
| | more with leading zeros. Do | |
| | not combine with ``i`` | |
| | format. | |
+------------------+-----------------------------+------------------------+
| ``j`` | Total days, one or 2 digits | ``'1'``, ``'41'`` |
| | without leading zeros. Do | |
| | not combine with ``w`` | |
| | format. | |
+------------------+-----------------------------+------------------------+
| ``J`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``l`` | Days long label. | ``'day'`` or |
| | Pluralized and localized. | ``'days'`` |
+------------------+-----------------------------+------------------------+
| ``L`` | Weeks long label. | ``'week'`` or |
| | Pluralized and localized. | ``'weeks'`` |
+------------------+-----------------------------+------------------------+
| ``m`` | Week days long label. | ``'day'`` or |
| | Pluralized and localized. | ``'days'`` |
+------------------+-----------------------------+------------------------+
| ``M`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``n`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``N`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``O`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``P`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``r`` | Standart Python timedelta | ``'18 d 1:28:07'`` |
| | representation with short | |
| | labels. | |
+------------------+-----------------------------+------------------------+
| ``R`` | Standart Python timedelta | ``'18 days, 1:28:07'`` |
| | representation with normal | |
| | labels. | |
+------------------+-----------------------------+------------------------+
| ``s`` | Minute, not total, seconds, | ``'00'`` to ``'59'`` |
| | 2 digits with leading | |
| | zeros. To use with ``i`` or | |
| | ``I``. | |
+------------------+-----------------------------+------------------------+
| ``S`` | Total seconds. 2 digits or | ``'00'``, ``'433'`` |
| | more with leading zeros. Do | |
| | not combine with ``s`` | |
| | format. | |
+------------------+-----------------------------+------------------------+
| ``t`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``T`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``u`` | Second, not total, | ``0`` to ``999999`` |
| | microseconds. | |
+------------------+-----------------------------+------------------------+
| ``U`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``w`` | Week, not total, days, one | ``0`` to ``6`` |
| | digit without leading | |
| | zeros. To use with ``W``. | |
+------------------+-----------------------------+------------------------+
| ``W`` | Total weeks, one or more | ``'1'``, ``'41'`` |
| | digits without leading | |
| | zeros. | |
+------------------+-----------------------------+------------------------+
| ``y`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``Y`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``z`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``Z`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
For example,
::
>>> import datetime
>>> from rororo.timedelta import timedelta_to_str
>>> delta = datetime.timedelta(seconds=99660)
>>> timedelta_to_str(delta)
... '27:41'
>>> timedelta_to_str(delta, 'r')
... '1d 3:41:00'
>>> timedelta_to_str(delta, 'f')
... '1d 3:41'
>>> timedelta_to_str(delta, 'W L, w l, H:i:s')
... '0 weeks, 1 day, 03:41:00'
Couple words about magic "full" formats. These formats show weeks number
with week label, days number with day label and seconds only if weeks
number, days number or seconds greater that zero.
For example,
::
>>> import datetime
>>> from rororo.timedelta import timedelta_to_str
>>> delta = datetime.timedelta(hours=12)
>>> timedelta_to_str(delta, 'f')
... '12:00'
>>> timedelta_to_str(delta, 'F')
... '12:00'
>>> delta = datetime.timedelta(hours=12, seconds=30)
>>> timedelta_to_str(delta, 'f')
... '12:00:30'
>>> timedelta_to_str(delta, 'F')
... '12:00:30'
>>> delta = datetime.timedelta(hours=168)
>>> timedelta_to_str(delta, 'f')
... '1w 0:00'
>>> timedelta_to_str(delta, 'F')
... '1 week, 0:00'
:param value: Timedelta instance to convert to string.
:param fmt: Format to use for conversion. | [
"Display",
"the",
"timedelta",
"formatted",
"according",
"to",
"the",
"given",
"string",
"."
] | train | https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/timedelta.py#L191-L438 |
OSSOS/MOP | src/ossos/core/ossos/pipeline.py | align | def align(expnums, ccd, version='s', dry_run=False):
"""Create a 'shifts' file that transforms the space/flux/time scale of all images to the first image.
This function relies on the .fwhm, .trans.jmp, .phot and .zeropoint.used files for inputs.
The scaling we are computing here is for use in planting sources into the image at the same sky/flux locations
while accounting for motions of sources with time.
:param expnums: list of MegaPrime exposure numbers to add artificial KBOs to,
the first frame in the list is the reference.
:param ccd: which ccd to work on.
:param version: Add sources to the 'o', 'p' or 's' images
:param dry_run: don't push results to VOSpace.
"""
# Get the images and supporting files that we need from the VOSpace area
# get_image and get_file check if the image/file is already on disk.
# re-computed fluxes from the PSF stars and then recompute x/y/flux scaling.
# some dictionaries to hold the various scale
pos = {}
apcor = {}
mags = {}
zmag = {}
mjdates = {}
for expnum in expnums:
filename = storage.get_image(expnum, ccd=ccd, version=version)
zmag[expnum] = storage.get_zeropoint(expnum, ccd, prefix=None, version=version)
mjdates[expnum] = float(fits.open(filename)[0].header.get('MJD-OBS'))
apcor[expnum] = [float(x) for x in open(storage.get_file(expnum,
ccd=ccd,
version=version,
ext=storage.APCOR_EXT)).read().split()]
keys = ['crval1', 'cd1_1', 'cd1_2', 'crval2', 'cd2_1', 'cd2_2']
# load the .trans.jmp values into a 'wcs' like dictionary.
# .trans.jmp maps current frame to reference frame in pixel coordinates.
# the reference frame of all the frames supplied must be the same.
shifts = dict(zip(keys, [float(x) for x in open(storage.get_file(expnum,
ccd=ccd,
version=version,
ext='trans.jmp')).read().split()]))
shifts['crpix1'] = 0.0
shifts['crpix2'] = 0.0
# now create a wcs object based on those transforms, this wcs links the current frame's
# pixel coordinates to the reference frame's pixel coordinates.
w = get_wcs(shifts)
# get the PHOT file that was produced by the mkpsf routine
logging.debug("Reading .phot file {}".format(expnum))
phot = ascii.read(storage.get_file(expnum, ccd=ccd, version=version, ext='phot'), format='daophot')
# compute the small-aperture magnitudes of the stars used in the PSF
import daophot
logging.debug("Running phot on {}".format(filename))
mags[expnum] = daophot.phot(filename,
phot['XCENTER'],
phot['YCENTER'],
aperture=apcor[expnum][0],
sky=apcor[expnum][1] + 1,
swidth=apcor[expnum][0],
zmag=zmag[expnum])
# covert the x/y positions to positions in Frame 1 based on the trans.jmp values.
logging.debug("Doing the XY translation to refrence frame: {}".format(w))
(x, y) = w.wcs_pix2world(mags[expnum]["XCENTER"], mags[expnum]["YCENTER"], 1)
pos[expnum] = numpy.transpose([x, y])
# match this exposures PSF stars position against those in the first image of the set.
logging.debug("Matching lists")
idx1, idx2 = util.match_lists(pos[expnums[0]], pos[expnum])
# compute the magnitdue offset between the current frame and the reference.
dmags = numpy.ma.array(mags[expnums[0]]["MAG"] - apcor[expnums[0]][2] -
(mags[expnum]["MAG"][idx1] - apcor[expnum][2]),
mask=idx1.mask)
dmags.sort()
logging.debug("Computed dmags between input and reference: {}".format(dmags))
error_count = 0
error_count += 1
logging.debug("{}".format(error_count))
# compute the median and determine if that shift is small compared to the scatter.
try:
midx = int(numpy.sum(numpy.any([~dmags.mask], axis=0)) / 2.0)
dmag = float(dmags[midx])
logging.debug("Computed a mag delta of: {}".format(dmag))
except Exception as e:
logging.error(str(e))
logging.error("Failed to compute mag offset between plant and found using: {}".format(dmags))
dmag = 99.99
error_count += 1
logging.debug("{}".format(error_count))
try:
if math.fabs(dmag) > 3 * (dmags.std() + 0.01):
logging.warning("Magnitude shift {} between {} and {} is large: {}".format(dmag,
expnums[0],
expnum,
shifts))
except Exception as e:
logging.error(str(e))
error_count += 1
logging.debug("{}".format(error_count))
shifts['dmag'] = dmag
shifts['emag'] = dmags.std()
shifts['nmag'] = len(dmags.mask) - dmags.mask.sum()
shifts['dmjd'] = mjdates[expnums[0]] - mjdates[expnum]
shift_file = os.path.basename(storage.get_uri(expnum, ccd, version, '.shifts'))
error_count += 1
logging.debug("{}".format(error_count))
try:
fh = open(shift_file, 'w')
fh.write(json.dumps(shifts, sort_keys=True, indent=4, separators=(',', ': ')))
fh.write('\n')
fh.close()
except Exception as e:
logging.error("Creation of SHIFTS file failed while trying to write: {}".format(shifts))
raise e
error_count += 1
logging.debug("{}".format(error_count))
if not dry_run:
storage.copy(shift_file, storage.get_uri(expnum, ccd, version, '.shifts')) | python | def align(expnums, ccd, version='s', dry_run=False):
"""Create a 'shifts' file that transforms the space/flux/time scale of all images to the first image.
This function relies on the .fwhm, .trans.jmp, .phot and .zeropoint.used files for inputs.
The scaling we are computing here is for use in planting sources into the image at the same sky/flux locations
while accounting for motions of sources with time.
:param expnums: list of MegaPrime exposure numbers to add artificial KBOs to,
the first frame in the list is the reference.
:param ccd: which ccd to work on.
:param version: Add sources to the 'o', 'p' or 's' images
:param dry_run: don't push results to VOSpace.
"""
# Get the images and supporting files that we need from the VOSpace area
# get_image and get_file check if the image/file is already on disk.
# re-computed fluxes from the PSF stars and then recompute x/y/flux scaling.
# some dictionaries to hold the various scale
pos = {}
apcor = {}
mags = {}
zmag = {}
mjdates = {}
for expnum in expnums:
filename = storage.get_image(expnum, ccd=ccd, version=version)
zmag[expnum] = storage.get_zeropoint(expnum, ccd, prefix=None, version=version)
mjdates[expnum] = float(fits.open(filename)[0].header.get('MJD-OBS'))
apcor[expnum] = [float(x) for x in open(storage.get_file(expnum,
ccd=ccd,
version=version,
ext=storage.APCOR_EXT)).read().split()]
keys = ['crval1', 'cd1_1', 'cd1_2', 'crval2', 'cd2_1', 'cd2_2']
# load the .trans.jmp values into a 'wcs' like dictionary.
# .trans.jmp maps current frame to reference frame in pixel coordinates.
# the reference frame of all the frames supplied must be the same.
shifts = dict(zip(keys, [float(x) for x in open(storage.get_file(expnum,
ccd=ccd,
version=version,
ext='trans.jmp')).read().split()]))
shifts['crpix1'] = 0.0
shifts['crpix2'] = 0.0
# now create a wcs object based on those transforms, this wcs links the current frame's
# pixel coordinates to the reference frame's pixel coordinates.
w = get_wcs(shifts)
# get the PHOT file that was produced by the mkpsf routine
logging.debug("Reading .phot file {}".format(expnum))
phot = ascii.read(storage.get_file(expnum, ccd=ccd, version=version, ext='phot'), format='daophot')
# compute the small-aperture magnitudes of the stars used in the PSF
import daophot
logging.debug("Running phot on {}".format(filename))
mags[expnum] = daophot.phot(filename,
phot['XCENTER'],
phot['YCENTER'],
aperture=apcor[expnum][0],
sky=apcor[expnum][1] + 1,
swidth=apcor[expnum][0],
zmag=zmag[expnum])
# covert the x/y positions to positions in Frame 1 based on the trans.jmp values.
logging.debug("Doing the XY translation to refrence frame: {}".format(w))
(x, y) = w.wcs_pix2world(mags[expnum]["XCENTER"], mags[expnum]["YCENTER"], 1)
pos[expnum] = numpy.transpose([x, y])
# match this exposures PSF stars position against those in the first image of the set.
logging.debug("Matching lists")
idx1, idx2 = util.match_lists(pos[expnums[0]], pos[expnum])
# compute the magnitdue offset between the current frame and the reference.
dmags = numpy.ma.array(mags[expnums[0]]["MAG"] - apcor[expnums[0]][2] -
(mags[expnum]["MAG"][idx1] - apcor[expnum][2]),
mask=idx1.mask)
dmags.sort()
logging.debug("Computed dmags between input and reference: {}".format(dmags))
error_count = 0
error_count += 1
logging.debug("{}".format(error_count))
# compute the median and determine if that shift is small compared to the scatter.
try:
midx = int(numpy.sum(numpy.any([~dmags.mask], axis=0)) / 2.0)
dmag = float(dmags[midx])
logging.debug("Computed a mag delta of: {}".format(dmag))
except Exception as e:
logging.error(str(e))
logging.error("Failed to compute mag offset between plant and found using: {}".format(dmags))
dmag = 99.99
error_count += 1
logging.debug("{}".format(error_count))
try:
if math.fabs(dmag) > 3 * (dmags.std() + 0.01):
logging.warning("Magnitude shift {} between {} and {} is large: {}".format(dmag,
expnums[0],
expnum,
shifts))
except Exception as e:
logging.error(str(e))
error_count += 1
logging.debug("{}".format(error_count))
shifts['dmag'] = dmag
shifts['emag'] = dmags.std()
shifts['nmag'] = len(dmags.mask) - dmags.mask.sum()
shifts['dmjd'] = mjdates[expnums[0]] - mjdates[expnum]
shift_file = os.path.basename(storage.get_uri(expnum, ccd, version, '.shifts'))
error_count += 1
logging.debug("{}".format(error_count))
try:
fh = open(shift_file, 'w')
fh.write(json.dumps(shifts, sort_keys=True, indent=4, separators=(',', ': ')))
fh.write('\n')
fh.close()
except Exception as e:
logging.error("Creation of SHIFTS file failed while trying to write: {}".format(shifts))
raise e
error_count += 1
logging.debug("{}".format(error_count))
if not dry_run:
storage.copy(shift_file, storage.get_uri(expnum, ccd, version, '.shifts')) | [
"def",
"align",
"(",
"expnums",
",",
"ccd",
",",
"version",
"=",
"'s'",
",",
"dry_run",
"=",
"False",
")",
":",
"# Get the images and supporting files that we need from the VOSpace area",
"# get_image and get_file check if the image/file is already on disk.",
"# re-computed fluxe... | Create a 'shifts' file that transforms the space/flux/time scale of all images to the first image.
This function relies on the .fwhm, .trans.jmp, .phot and .zeropoint.used files for inputs.
The scaling we are computing here is for use in planting sources into the image at the same sky/flux locations
while accounting for motions of sources with time.
:param expnums: list of MegaPrime exposure numbers to add artificial KBOs to,
the first frame in the list is the reference.
:param ccd: which ccd to work on.
:param version: Add sources to the 'o', 'p' or 's' images
:param dry_run: don't push results to VOSpace. | [
"Create",
"a",
"shifts",
"file",
"that",
"transforms",
"the",
"space",
"/",
"flux",
"/",
"time",
"scale",
"of",
"all",
"images",
"to",
"the",
"first",
"image",
"."
] | train | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/pipeline.py#L21-L149 |
OSSOS/MOP | src/ossos/core/ossos/plant.py | Range.dist | def dist(self):
"""
How should the values in range be sampled, uniformly or via some function.
:return:
"""
if self.func is None:
return random.uniform(self.min, self.max)
if self._dist is None:
x = numpy.arange(self.min, self.max, (self.max-self.min)/1000.0)
p = self.func(x).cumsum()
p -= p.min()
p /= p.max()
self._dist = interpolate.interp1d(p, x)
return self._dist(random.random()) | python | def dist(self):
"""
How should the values in range be sampled, uniformly or via some function.
:return:
"""
if self.func is None:
return random.uniform(self.min, self.max)
if self._dist is None:
x = numpy.arange(self.min, self.max, (self.max-self.min)/1000.0)
p = self.func(x).cumsum()
p -= p.min()
p /= p.max()
self._dist = interpolate.interp1d(p, x)
return self._dist(random.random()) | [
"def",
"dist",
"(",
"self",
")",
":",
"if",
"self",
".",
"func",
"is",
"None",
":",
"return",
"random",
".",
"uniform",
"(",
"self",
".",
"min",
",",
"self",
".",
"max",
")",
"if",
"self",
".",
"_dist",
"is",
"None",
":",
"x",
"=",
"numpy",
"."... | How should the values in range be sampled, uniformly or via some function.
:return: | [
"How",
"should",
"the",
"values",
"in",
"range",
"be",
"sampled",
"uniformly",
"or",
"via",
"some",
"function",
".",
":",
"return",
":"
] | train | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/plant.py#L57-L70 |
OSSOS/MOP | src/ossos/core/ossos/plant.py | KBOGenerator.next | def next(self):
"""
:return: a set of values that can be used for an planted object builder.
"""
# x y mag pix rate angle ''/h rate id
# 912.48 991.06 22.01 57.32 -45.23 10.60 0
self._n -= 1
if self._n < 0:
raise StopIteration()
return {'x': self.x(), 'y': self.y(), 'mag': self.mag(), 'sky_rate': self.rate(), 'angle': self.angle(),
'id': self.id} | python | def next(self):
"""
:return: a set of values that can be used for an planted object builder.
"""
# x y mag pix rate angle ''/h rate id
# 912.48 991.06 22.01 57.32 -45.23 10.60 0
self._n -= 1
if self._n < 0:
raise StopIteration()
return {'x': self.x(), 'y': self.y(), 'mag': self.mag(), 'sky_rate': self.rate(), 'angle': self.angle(),
'id': self.id} | [
"def",
"next",
"(",
"self",
")",
":",
"# x y mag pix rate angle ''/h rate id",
"# 912.48 991.06 22.01 57.32 -45.23 10.60 0",
"self",
".",
"_n",
"-=",
"1",
"if",
"self",
".",
"_n",
"<",
"0",
":",
"raise",
"StopIt... | :return: a set of values that can be used for an planted object builder. | [
":",
"return",
":",
"a",
"set",
"of",
"values",
"that",
"can",
"be",
"used",
"for",
"an",
"planted",
"object",
"builder",
"."
] | train | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/plant.py#L114-L124 |
viswa-swami/python-foscam | libpyfoscam/foscam.py | FoscamCamera.send_command | def send_command(self, cmd, params=None, raw=False):
'''
Send command to foscam.
'''
paramstr = ''
if params:
paramstr = urlencode(params)
paramstr = '&' + paramstr if paramstr else ''
cmdurl = 'http://%s/cgi-bin/CGIProxy.fcgi?usr=%s&pwd=%s&cmd=%s%s' % (
self.url,
self.usr,
self.pwd,
cmd,
paramstr,
)
if self.ssl and ssl_enabled:
cmdurl = cmdurl.replace('http:','https:')
# Parse parameters from response string.
if self.verbose:
print ('Send Foscam command: %s' % cmdurl)
try:
raw_string = ''
if self.ssl and ssl_enabled:
gcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1) # disable cert
raw_string = urlopen(cmdurl,context=gcontext, timeout=5).read()
else:
raw_string = urlopen(cmdurl,timeout=5).read()
if raw:
if self.verbose:
print ('Returning raw Foscam response: len=%d' % len(raw_string))
return FOSCAM_SUCCESS, raw_string
root = ET.fromstring(raw_string)
except:
if self.verbose:
print ('Foscam exception: ' + raw_string)
return ERROR_FOSCAM_UNAVAILABLE, None
code = ERROR_FOSCAM_UNKNOWN
params = OrderedDict()
for child in root.iter():
if child.tag == 'result':
code = int(child.text)
elif child.tag != 'CGI_Result':
params[child.tag] = unquote(child.text)
if self.verbose:
print ('Received Foscam response: %s, %s' % (code, params))
return code, params | python | def send_command(self, cmd, params=None, raw=False):
'''
Send command to foscam.
'''
paramstr = ''
if params:
paramstr = urlencode(params)
paramstr = '&' + paramstr if paramstr else ''
cmdurl = 'http://%s/cgi-bin/CGIProxy.fcgi?usr=%s&pwd=%s&cmd=%s%s' % (
self.url,
self.usr,
self.pwd,
cmd,
paramstr,
)
if self.ssl and ssl_enabled:
cmdurl = cmdurl.replace('http:','https:')
# Parse parameters from response string.
if self.verbose:
print ('Send Foscam command: %s' % cmdurl)
try:
raw_string = ''
if self.ssl and ssl_enabled:
gcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1) # disable cert
raw_string = urlopen(cmdurl,context=gcontext, timeout=5).read()
else:
raw_string = urlopen(cmdurl,timeout=5).read()
if raw:
if self.verbose:
print ('Returning raw Foscam response: len=%d' % len(raw_string))
return FOSCAM_SUCCESS, raw_string
root = ET.fromstring(raw_string)
except:
if self.verbose:
print ('Foscam exception: ' + raw_string)
return ERROR_FOSCAM_UNAVAILABLE, None
code = ERROR_FOSCAM_UNKNOWN
params = OrderedDict()
for child in root.iter():
if child.tag == 'result':
code = int(child.text)
elif child.tag != 'CGI_Result':
params[child.tag] = unquote(child.text)
if self.verbose:
print ('Received Foscam response: %s, %s' % (code, params))
return code, params | [
"def",
"send_command",
"(",
"self",
",",
"cmd",
",",
"params",
"=",
"None",
",",
"raw",
"=",
"False",
")",
":",
"paramstr",
"=",
"''",
"if",
"params",
":",
"paramstr",
"=",
"urlencode",
"(",
"params",
")",
"paramstr",
"=",
"'&'",
"+",
"paramstr",
"if... | Send command to foscam. | [
"Send",
"command",
"to",
"foscam",
"."
] | train | https://github.com/viswa-swami/python-foscam/blob/d76f2f7016959b7b758751637fad103c9032e488/libpyfoscam/foscam.py#L74-L122 |
viswa-swami/python-foscam | libpyfoscam/foscam.py | FoscamCamera.execute_command | def execute_command(self, cmd, params=None, callback=None, raw=False):
'''
Execute a command and return a parsed response.
'''
def execute_with_callbacks(cmd, params=None, callback=None, raw=False):
code, params = self.send_command(cmd, params, raw)
if callback:
callback(code, params)
return code, params
if self.daemon:
t = Thread(target=execute_with_callbacks,
args=(cmd, ), kwargs={'params':params, 'callback':callback, 'raw':raw})
t.daemon = True
t.start()
else:
return execute_with_callbacks(cmd, params, callback, raw) | python | def execute_command(self, cmd, params=None, callback=None, raw=False):
'''
Execute a command and return a parsed response.
'''
def execute_with_callbacks(cmd, params=None, callback=None, raw=False):
code, params = self.send_command(cmd, params, raw)
if callback:
callback(code, params)
return code, params
if self.daemon:
t = Thread(target=execute_with_callbacks,
args=(cmd, ), kwargs={'params':params, 'callback':callback, 'raw':raw})
t.daemon = True
t.start()
else:
return execute_with_callbacks(cmd, params, callback, raw) | [
"def",
"execute_command",
"(",
"self",
",",
"cmd",
",",
"params",
"=",
"None",
",",
"callback",
"=",
"None",
",",
"raw",
"=",
"False",
")",
":",
"def",
"execute_with_callbacks",
"(",
"cmd",
",",
"params",
"=",
"None",
",",
"callback",
"=",
"None",
",",... | Execute a command and return a parsed response. | [
"Execute",
"a",
"command",
"and",
"return",
"a",
"parsed",
"response",
"."
] | train | https://github.com/viswa-swami/python-foscam/blob/d76f2f7016959b7b758751637fad103c9032e488/libpyfoscam/foscam.py#L124-L140 |
viswa-swami/python-foscam | libpyfoscam/foscam.py | FoscamCamera.set_ip_info | def set_ip_info(self, is_dhcp, ip='', gate='', mask='',
dns1='', dns2='', callback=None):
'''
isDHCP: 0(False), 1(True)
System will reboot automatically to take effect after call this CGI command.
'''
params = {'isDHCP': is_dhcp,
'ip': ip,
'gate': gate,
'mask': mask,
'dns1': dns1,
'dns2': dns2,
}
return self.execute_command('setIpInfo', params, callback=callback) | python | def set_ip_info(self, is_dhcp, ip='', gate='', mask='',
dns1='', dns2='', callback=None):
'''
isDHCP: 0(False), 1(True)
System will reboot automatically to take effect after call this CGI command.
'''
params = {'isDHCP': is_dhcp,
'ip': ip,
'gate': gate,
'mask': mask,
'dns1': dns1,
'dns2': dns2,
}
return self.execute_command('setIpInfo', params, callback=callback) | [
"def",
"set_ip_info",
"(",
"self",
",",
"is_dhcp",
",",
"ip",
"=",
"''",
",",
"gate",
"=",
"''",
",",
"mask",
"=",
"''",
",",
"dns1",
"=",
"''",
",",
"dns2",
"=",
"''",
",",
"callback",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'isDHCP'",
":"... | isDHCP: 0(False), 1(True)
System will reboot automatically to take effect after call this CGI command. | [
"isDHCP",
":",
"0",
"(",
"False",
")",
"1",
"(",
"True",
")",
"System",
"will",
"reboot",
"automatically",
"to",
"take",
"effect",
"after",
"call",
"this",
"CGI",
"command",
"."
] | train | https://github.com/viswa-swami/python-foscam/blob/d76f2f7016959b7b758751637fad103c9032e488/libpyfoscam/foscam.py#L150-L164 |
viswa-swami/python-foscam | libpyfoscam/foscam.py | FoscamCamera.set_port_info | def set_port_info(self, webport, mediaport, httpsport,
onvifport, callback=None):
'''
Set http port and media port of camera.
'''
params = {'webPort' : webport,
'mediaPort' : mediaport,
'httpsPort' : httpsport,
'onvifPort' : onvifport,
}
return self.execute_command('setPortInfo', params, callback=callback) | python | def set_port_info(self, webport, mediaport, httpsport,
onvifport, callback=None):
'''
Set http port and media port of camera.
'''
params = {'webPort' : webport,
'mediaPort' : mediaport,
'httpsPort' : httpsport,
'onvifPort' : onvifport,
}
return self.execute_command('setPortInfo', params, callback=callback) | [
"def",
"set_port_info",
"(",
"self",
",",
"webport",
",",
"mediaport",
",",
"httpsport",
",",
"onvifport",
",",
"callback",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'webPort'",
":",
"webport",
",",
"'mediaPort'",
":",
"mediaport",
",",
"'httpsPort'",
":... | Set http port and media port of camera. | [
"Set",
"http",
"port",
"and",
"media",
"port",
"of",
"camera",
"."
] | train | https://github.com/viswa-swami/python-foscam/blob/d76f2f7016959b7b758751637fad103c9032e488/libpyfoscam/foscam.py#L172-L182 |
viswa-swami/python-foscam | libpyfoscam/foscam.py | FoscamCamera.get_wifi_list | def get_wifi_list(self, startno, callback=None):
'''
Get the aps around after refreshWifiList.
Note: Only 10 aps will be returned one time.
'''
params = {'startNo': startno}
return self.execute_command('getWifiList', params, callback=callback) | python | def get_wifi_list(self, startno, callback=None):
'''
Get the aps around after refreshWifiList.
Note: Only 10 aps will be returned one time.
'''
params = {'startNo': startno}
return self.execute_command('getWifiList', params, callback=callback) | [
"def",
"get_wifi_list",
"(",
"self",
",",
"startno",
",",
"callback",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'startNo'",
":",
"startno",
"}",
"return",
"self",
".",
"execute_command",
"(",
"'getWifiList'",
",",
"params",
",",
"callback",
"=",
"callbac... | Get the aps around after refreshWifiList.
Note: Only 10 aps will be returned one time. | [
"Get",
"the",
"aps",
"around",
"after",
"refreshWifiList",
".",
"Note",
":",
"Only",
"10",
"aps",
"will",
"be",
"returned",
"one",
"time",
"."
] | train | https://github.com/viswa-swami/python-foscam/blob/d76f2f7016959b7b758751637fad103c9032e488/libpyfoscam/foscam.py#L192-L198 |
viswa-swami/python-foscam | libpyfoscam/foscam.py | FoscamCamera.set_wifi_setting | def set_wifi_setting(self, ssid, psk, isenable, isusewifi, nettype,
encryptype, authmode, keyformat, defaultkey,
key1='', key2='', key3='', key4='',
key1len=64, key2len=64, key3len=64, key4len=64,
callback=None):
'''
Set wifi config.
Camera will not connect to AP unless you enject your cable.
'''
params = {'isEnable' : isenable,
'isUseWifi' : isusewifi,
'ssid' : ssid,
'netType' : nettype,
'encryptType': encryptype,
'psk' : psk,
'authMode' : authmode,
'keyFormat' : keyformat,
'defaultKey' : defaultkey,
'key1' : key1,
'key2' : key2,
'key3' : key3,
'key4' : key4,
'key1Len' : key1len,
'key2Len' : key2len,
'key3Len' : key3len,
'key4Len' : key4len,
}
return self.execute_command('setWifiSetting', params, callback=callback) | python | def set_wifi_setting(self, ssid, psk, isenable, isusewifi, nettype,
encryptype, authmode, keyformat, defaultkey,
key1='', key2='', key3='', key4='',
key1len=64, key2len=64, key3len=64, key4len=64,
callback=None):
'''
Set wifi config.
Camera will not connect to AP unless you enject your cable.
'''
params = {'isEnable' : isenable,
'isUseWifi' : isusewifi,
'ssid' : ssid,
'netType' : nettype,
'encryptType': encryptype,
'psk' : psk,
'authMode' : authmode,
'keyFormat' : keyformat,
'defaultKey' : defaultkey,
'key1' : key1,
'key2' : key2,
'key3' : key3,
'key4' : key4,
'key1Len' : key1len,
'key2Len' : key2len,
'key3Len' : key3len,
'key4Len' : key4len,
}
return self.execute_command('setWifiSetting', params, callback=callback) | [
"def",
"set_wifi_setting",
"(",
"self",
",",
"ssid",
",",
"psk",
",",
"isenable",
",",
"isusewifi",
",",
"nettype",
",",
"encryptype",
",",
"authmode",
",",
"keyformat",
",",
"defaultkey",
",",
"key1",
"=",
"''",
",",
"key2",
"=",
"''",
",",
"key3",
"=... | Set wifi config.
Camera will not connect to AP unless you enject your cable. | [
"Set",
"wifi",
"config",
".",
"Camera",
"will",
"not",
"connect",
"to",
"AP",
"unless",
"you",
"enject",
"your",
"cable",
"."
] | train | https://github.com/viswa-swami/python-foscam/blob/d76f2f7016959b7b758751637fad103c9032e488/libpyfoscam/foscam.py#L200-L227 |
viswa-swami/python-foscam | libpyfoscam/foscam.py | FoscamCamera.set_upnp_config | def set_upnp_config(self, isenable, callback=None):
'''
Set UPnP config
'''
params = {'isEnable': isenable}
return self.execute_command('setUPnPConfig', params, callback=callback) | python | def set_upnp_config(self, isenable, callback=None):
'''
Set UPnP config
'''
params = {'isEnable': isenable}
return self.execute_command('setUPnPConfig', params, callback=callback) | [
"def",
"set_upnp_config",
"(",
"self",
",",
"isenable",
",",
"callback",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'isEnable'",
":",
"isenable",
"}",
"return",
"self",
".",
"execute_command",
"(",
"'setUPnPConfig'",
",",
"params",
",",
"callback",
"=",
"... | Set UPnP config | [
"Set",
"UPnP",
"config"
] | train | https://github.com/viswa-swami/python-foscam/blob/d76f2f7016959b7b758751637fad103c9032e488/libpyfoscam/foscam.py#L241-L246 |
viswa-swami/python-foscam | libpyfoscam/foscam.py | FoscamCamera.set_ddns_config | def set_ddns_config(self, isenable, hostname, ddnsserver,
user, password, callback=None):
'''
Set DDNS config.
'''
params = {'isEnable': isenable,
'hostName': hostname,
'ddnsServer': ddnsserver,
'user': user,
'password': password,
}
return self.execute_command('setDDNSConfig', params, callback=callback) | python | def set_ddns_config(self, isenable, hostname, ddnsserver,
user, password, callback=None):
'''
Set DDNS config.
'''
params = {'isEnable': isenable,
'hostName': hostname,
'ddnsServer': ddnsserver,
'user': user,
'password': password,
}
return self.execute_command('setDDNSConfig', params, callback=callback) | [
"def",
"set_ddns_config",
"(",
"self",
",",
"isenable",
",",
"hostname",
",",
"ddnsserver",
",",
"user",
",",
"password",
",",
"callback",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'isEnable'",
":",
"isenable",
",",
"'hostName'",
":",
"hostname",
",",
... | Set DDNS config. | [
"Set",
"DDNS",
"config",
"."
] | train | https://github.com/viswa-swami/python-foscam/blob/d76f2f7016959b7b758751637fad103c9032e488/libpyfoscam/foscam.py#L254-L265 |
viswa-swami/python-foscam | libpyfoscam/foscam.py | FoscamCamera.set_sub_video_stream_type | def set_sub_video_stream_type(self, format, callback=None):
'''
Set the stream fromat of sub stream.
Supported format: (1) H264 : 0
(2) MotionJpeg 1
'''
params = {'format': format}
return self.execute_command('setSubVideoStreamType',
params, callback=callback) | python | def set_sub_video_stream_type(self, format, callback=None):
'''
Set the stream fromat of sub stream.
Supported format: (1) H264 : 0
(2) MotionJpeg 1
'''
params = {'format': format}
return self.execute_command('setSubVideoStreamType',
params, callback=callback) | [
"def",
"set_sub_video_stream_type",
"(",
"self",
",",
"format",
",",
"callback",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'format'",
":",
"format",
"}",
"return",
"self",
".",
"execute_command",
"(",
"'setSubVideoStreamType'",
",",
"params",
",",
"callback"... | Set the stream fromat of sub stream.
Supported format: (1) H264 : 0
(2) MotionJpeg 1 | [
"Set",
"the",
"stream",
"fromat",
"of",
"sub",
"stream",
".",
"Supported",
"format",
":",
"(",
"1",
")",
"H264",
":",
"0",
"(",
"2",
")",
"MotionJpeg",
"1"
] | train | https://github.com/viswa-swami/python-foscam/blob/d76f2f7016959b7b758751637fad103c9032e488/libpyfoscam/foscam.py#L276-L284 |
viswa-swami/python-foscam | libpyfoscam/foscam.py | FoscamCamera.set_sub_stream_format | def set_sub_stream_format(self, format, callback=None):
'''
Set the stream fromat of sub stream????
'''
params = {'format': format}
return self.execute_command('setSubStreamFormat',
params, callback=callback) | python | def set_sub_stream_format(self, format, callback=None):
'''
Set the stream fromat of sub stream????
'''
params = {'format': format}
return self.execute_command('setSubStreamFormat',
params, callback=callback) | [
"def",
"set_sub_stream_format",
"(",
"self",
",",
"format",
",",
"callback",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'format'",
":",
"format",
"}",
"return",
"self",
".",
"execute_command",
"(",
"'setSubStreamFormat'",
",",
"params",
",",
"callback",
"="... | Set the stream fromat of sub stream???? | [
"Set",
"the",
"stream",
"fromat",
"of",
"sub",
"stream????"
] | train | https://github.com/viswa-swami/python-foscam/blob/d76f2f7016959b7b758751637fad103c9032e488/libpyfoscam/foscam.py#L286-L292 |
viswa-swami/python-foscam | libpyfoscam/foscam.py | FoscamCamera.set_main_video_stream_type | def set_main_video_stream_type(self, streamtype, callback=None):
'''
Set the stream type of main stream
'''
params = {'streamType': streamtype}
return self.execute_command('setMainVideoStreamType',
params, callback=callback) | python | def set_main_video_stream_type(self, streamtype, callback=None):
'''
Set the stream type of main stream
'''
params = {'streamType': streamtype}
return self.execute_command('setMainVideoStreamType',
params, callback=callback) | [
"def",
"set_main_video_stream_type",
"(",
"self",
",",
"streamtype",
",",
"callback",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'streamType'",
":",
"streamtype",
"}",
"return",
"self",
".",
"execute_command",
"(",
"'setMainVideoStreamType'",
",",
"params",
","... | Set the stream type of main stream | [
"Set",
"the",
"stream",
"type",
"of",
"main",
"stream"
] | train | https://github.com/viswa-swami/python-foscam/blob/d76f2f7016959b7b758751637fad103c9032e488/libpyfoscam/foscam.py#L300-L306 |
viswa-swami/python-foscam | libpyfoscam/foscam.py | FoscamCamera.set_video_stream_param | def set_video_stream_param(self, streamtype, resolution, bitrate,
framerate, gop, isvbr, callback=None):
'''
Set the video stream param of stream N
streamtype(0~3): Stream N.
resolution(0~4): 0 720P,
1 VGA(640*480),
2 VGA(640*360),
3 QVGA(320*240),
4 QVGA(320*180).
bitrate: Bit rate of stream type N(20480~2097152).
framerate: Frame rate of stream type N.
GOP: P frames between 1 frame of stream type N.
The suggest value is: X * framerate.
isvbr: 0(Not in use currently), 1(In use).
'''
params = {'streamType': streamtype,
'resolution': resolution,
'bitRate' : bitrate,
'frameRate' : framerate,
'GOP' : gop,
'isVBR' : isvbr
}
return self.execute_command('setVideoStreamParam',
params, callback=callback) | python | def set_video_stream_param(self, streamtype, resolution, bitrate,
framerate, gop, isvbr, callback=None):
'''
Set the video stream param of stream N
streamtype(0~3): Stream N.
resolution(0~4): 0 720P,
1 VGA(640*480),
2 VGA(640*360),
3 QVGA(320*240),
4 QVGA(320*180).
bitrate: Bit rate of stream type N(20480~2097152).
framerate: Frame rate of stream type N.
GOP: P frames between 1 frame of stream type N.
The suggest value is: X * framerate.
isvbr: 0(Not in use currently), 1(In use).
'''
params = {'streamType': streamtype,
'resolution': resolution,
'bitRate' : bitrate,
'frameRate' : framerate,
'GOP' : gop,
'isVBR' : isvbr
}
return self.execute_command('setVideoStreamParam',
params, callback=callback) | [
"def",
"set_video_stream_param",
"(",
"self",
",",
"streamtype",
",",
"resolution",
",",
"bitrate",
",",
"framerate",
",",
"gop",
",",
"isvbr",
",",
"callback",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'streamType'",
":",
"streamtype",
",",
"'resolution'"... | Set the video stream param of stream N
streamtype(0~3): Stream N.
resolution(0~4): 0 720P,
1 VGA(640*480),
2 VGA(640*360),
3 QVGA(320*240),
4 QVGA(320*180).
bitrate: Bit rate of stream type N(20480~2097152).
framerate: Frame rate of stream type N.
GOP: P frames between 1 frame of stream type N.
The suggest value is: X * framerate.
isvbr: 0(Not in use currently), 1(In use). | [
"Set",
"the",
"video",
"stream",
"param",
"of",
"stream",
"N",
"streamtype",
"(",
"0~3",
")",
":",
"Stream",
"N",
".",
"resolution",
"(",
"0~4",
")",
":",
"0",
"720P",
"1",
"VGA",
"(",
"640",
"*",
"480",
")",
"2",
"VGA",
"(",
"640",
"*",
"360",
... | train | https://github.com/viswa-swami/python-foscam/blob/d76f2f7016959b7b758751637fad103c9032e488/libpyfoscam/foscam.py#L314-L338 |
viswa-swami/python-foscam | libpyfoscam/foscam.py | FoscamCamera.mirror_video | def mirror_video(self, is_mirror, callback=None):
'''
Mirror video
``is_mirror``: 0 not mirror, 1 mirror
'''
params = {'isMirror': is_mirror}
return self.execute_command('mirrorVideo', params, callback=callback) | python | def mirror_video(self, is_mirror, callback=None):
'''
Mirror video
``is_mirror``: 0 not mirror, 1 mirror
'''
params = {'isMirror': is_mirror}
return self.execute_command('mirrorVideo', params, callback=callback) | [
"def",
"mirror_video",
"(",
"self",
",",
"is_mirror",
",",
"callback",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'isMirror'",
":",
"is_mirror",
"}",
"return",
"self",
".",
"execute_command",
"(",
"'mirrorVideo'",
",",
"params",
",",
"callback",
"=",
"cal... | Mirror video
``is_mirror``: 0 not mirror, 1 mirror | [
"Mirror",
"video",
"is_mirror",
":",
"0",
"not",
"mirror",
"1",
"mirror"
] | train | https://github.com/viswa-swami/python-foscam/blob/d76f2f7016959b7b758751637fad103c9032e488/libpyfoscam/foscam.py#L340-L346 |
viswa-swami/python-foscam | libpyfoscam/foscam.py | FoscamCamera.flip_video | def flip_video(self, is_flip, callback=None):
'''
Flip video
``is_flip``: 0 Not flip, 1 Flip
'''
params = {'isFlip': is_flip }
return self.execute_command('flipVideo', params, callback=callback) | python | def flip_video(self, is_flip, callback=None):
'''
Flip video
``is_flip``: 0 Not flip, 1 Flip
'''
params = {'isFlip': is_flip }
return self.execute_command('flipVideo', params, callback=callback) | [
"def",
"flip_video",
"(",
"self",
",",
"is_flip",
",",
"callback",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'isFlip'",
":",
"is_flip",
"}",
"return",
"self",
".",
"execute_command",
"(",
"'flipVideo'",
",",
"params",
",",
"callback",
"=",
"callback",
... | Flip video
``is_flip``: 0 Not flip, 1 Flip | [
"Flip",
"video",
"is_flip",
":",
"0",
"Not",
"flip",
"1",
"Flip"
] | train | https://github.com/viswa-swami/python-foscam/blob/d76f2f7016959b7b758751637fad103c9032e488/libpyfoscam/foscam.py#L348-L354 |
viswa-swami/python-foscam | libpyfoscam/foscam.py | FoscamCamera.change_user_name | def change_user_name(self, usrname, newusrname, callback=None):
'''
Change user name.
'''
params = {'usrName': usrname,
'newUsrName': newusrname,
}
return self.execute_command('changeUserName', params, callback=callback) | python | def change_user_name(self, usrname, newusrname, callback=None):
'''
Change user name.
'''
params = {'usrName': usrname,
'newUsrName': newusrname,
}
return self.execute_command('changeUserName', params, callback=callback) | [
"def",
"change_user_name",
"(",
"self",
",",
"usrname",
",",
"newusrname",
",",
"callback",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'usrName'",
":",
"usrname",
",",
"'newUsrName'",
":",
"newusrname",
",",
"}",
"return",
"self",
".",
"execute_command",
... | Change user name. | [
"Change",
"user",
"name",
"."
] | train | https://github.com/viswa-swami/python-foscam/blob/d76f2f7016959b7b758751637fad103c9032e488/libpyfoscam/foscam.py#L363-L370 |
viswa-swami/python-foscam | libpyfoscam/foscam.py | FoscamCamera.change_password | def change_password(self, usrname, oldpwd, newpwd, callback=None):
'''
Change password.
'''
params = {'usrName': usrname,
'oldPwd' : oldpwd,
'newPwd' : newpwd,
}
return self.execute_command('changePassword',
params, callback=callback) | python | def change_password(self, usrname, oldpwd, newpwd, callback=None):
'''
Change password.
'''
params = {'usrName': usrname,
'oldPwd' : oldpwd,
'newPwd' : newpwd,
}
return self.execute_command('changePassword',
params, callback=callback) | [
"def",
"change_password",
"(",
"self",
",",
"usrname",
",",
"oldpwd",
",",
"newpwd",
",",
"callback",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'usrName'",
":",
"usrname",
",",
"'oldPwd'",
":",
"oldpwd",
",",
"'newPwd'",
":",
"newpwd",
",",
"}",
"ret... | Change password. | [
"Change",
"password",
"."
] | train | https://github.com/viswa-swami/python-foscam/blob/d76f2f7016959b7b758751637fad103c9032e488/libpyfoscam/foscam.py#L372-L381 |
viswa-swami/python-foscam | libpyfoscam/foscam.py | FoscamCamera.set_system_time | def set_system_time(self, time_source, ntp_server, date_format,
time_format, time_zone, is_dst, dst, year,
mon, day, hour, minute, sec, callback=None):
'''
Set systeim time
'''
if ntp_server not in ['time.nist.gov',
'time.kriss.re.kr',
'time.windows.com',
'time.nuri.net',
]:
raise ValueError('Unsupported ntpServer')
params = {'timeSource': time_source,
'ntpServer' : ntp_server,
'dateFormat': date_format,
'timeFormat': time_format,
'timeZone' : time_zone,
'isDst' : is_dst,
'dst' : dst,
'year' : year,
'mon' : mon,
'day' : day,
'hour' : hour,
'minute' : minute,
'sec' : sec
}
return self.execute_command('setSystemTime', params, callback=callback) | python | def set_system_time(self, time_source, ntp_server, date_format,
time_format, time_zone, is_dst, dst, year,
mon, day, hour, minute, sec, callback=None):
'''
Set systeim time
'''
if ntp_server not in ['time.nist.gov',
'time.kriss.re.kr',
'time.windows.com',
'time.nuri.net',
]:
raise ValueError('Unsupported ntpServer')
params = {'timeSource': time_source,
'ntpServer' : ntp_server,
'dateFormat': date_format,
'timeFormat': time_format,
'timeZone' : time_zone,
'isDst' : is_dst,
'dst' : dst,
'year' : year,
'mon' : mon,
'day' : day,
'hour' : hour,
'minute' : minute,
'sec' : sec
}
return self.execute_command('setSystemTime', params, callback=callback) | [
"def",
"set_system_time",
"(",
"self",
",",
"time_source",
",",
"ntp_server",
",",
"date_format",
",",
"time_format",
",",
"time_zone",
",",
"is_dst",
",",
"dst",
",",
"year",
",",
"mon",
",",
"day",
",",
"hour",
",",
"minute",
",",
"sec",
",",
"callback... | Set systeim time | [
"Set",
"systeim",
"time"
] | train | https://github.com/viswa-swami/python-foscam/blob/d76f2f7016959b7b758751637fad103c9032e488/libpyfoscam/foscam.py#L385-L413 |
viswa-swami/python-foscam | libpyfoscam/foscam.py | FoscamCamera.set_dev_name | def set_dev_name(self, devname, callback=None):
'''
Set camera name
'''
params = {'devName': devname.encode('gbk')}
return self.execute_command('setDevName', params, callback=callback) | python | def set_dev_name(self, devname, callback=None):
'''
Set camera name
'''
params = {'devName': devname.encode('gbk')}
return self.execute_command('setDevName', params, callback=callback) | [
"def",
"set_dev_name",
"(",
"self",
",",
"devname",
",",
"callback",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'devName'",
":",
"devname",
".",
"encode",
"(",
"'gbk'",
")",
"}",
"return",
"self",
".",
"execute_command",
"(",
"'setDevName'",
",",
"param... | Set camera name | [
"Set",
"camera",
"name"
] | train | https://github.com/viswa-swami/python-foscam/blob/d76f2f7016959b7b758751637fad103c9032e488/libpyfoscam/foscam.py#L427-L432 |
viswa-swami/python-foscam | libpyfoscam/foscam.py | FoscamCamera.set_infra_led_config | def set_infra_led_config(self, mode, callback=None):
'''
Set Infrared LED configuration
cmd: setInfraLedConfig
mode(0,1): 0=Auto mode, 1=Manual mode
'''
params = {'mode': mode}
return self.execute_command('setInfraLedConfig', params, callback=callback) | python | def set_infra_led_config(self, mode, callback=None):
'''
Set Infrared LED configuration
cmd: setInfraLedConfig
mode(0,1): 0=Auto mode, 1=Manual mode
'''
params = {'mode': mode}
return self.execute_command('setInfraLedConfig', params, callback=callback) | [
"def",
"set_infra_led_config",
"(",
"self",
",",
"mode",
",",
"callback",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'mode'",
":",
"mode",
"}",
"return",
"self",
".",
"execute_command",
"(",
"'setInfraLedConfig'",
",",
"params",
",",
"callback",
"=",
"cal... | Set Infrared LED configuration
cmd: setInfraLedConfig
mode(0,1): 0=Auto mode, 1=Manual mode | [
"Set",
"Infrared",
"LED",
"configuration",
"cmd",
":",
"setInfraLedConfig",
"mode",
"(",
"0",
"1",
")",
":",
"0",
"=",
"Auto",
"mode",
"1",
"=",
"Manual",
"mode"
] | train | https://github.com/viswa-swami/python-foscam/blob/d76f2f7016959b7b758751637fad103c9032e488/libpyfoscam/foscam.py#L476-L483 |
viswa-swami/python-foscam | libpyfoscam/foscam.py | FoscamCamera.ptz_goto_preset | def ptz_goto_preset(self, name, callback=None):
'''
Move to preset.
'''
params = {'name': name}
return self.execute_command('ptzGotoPresetPoint', params, callback=callback) | python | def ptz_goto_preset(self, name, callback=None):
'''
Move to preset.
'''
params = {'name': name}
return self.execute_command('ptzGotoPresetPoint', params, callback=callback) | [
"def",
"ptz_goto_preset",
"(",
"self",
",",
"name",
",",
"callback",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'name'",
":",
"name",
"}",
"return",
"self",
".",
"execute_command",
"(",
"'ptzGotoPresetPoint'",
",",
"params",
",",
"callback",
"=",
"callbac... | Move to preset. | [
"Move",
"to",
"preset",
"."
] | train | https://github.com/viswa-swami/python-foscam/blob/d76f2f7016959b7b758751637fad103c9032e488/libpyfoscam/foscam.py#L560-L565 |
viswa-swami/python-foscam | libpyfoscam/foscam.py | FoscamCamera.set_motion_detection | def set_motion_detection(self, enabled=1):
'''
Get the current config and set the motion detection on or off
'''
result, current_config = self.get_motion_detect_config()
if result != FOSCAM_SUCCESS:
return result
current_config['isEnable'] = enabled
self.set_motion_detect_config(current_config)
return FOSCAM_SUCCESS | python | def set_motion_detection(self, enabled=1):
'''
Get the current config and set the motion detection on or off
'''
result, current_config = self.get_motion_detect_config()
if result != FOSCAM_SUCCESS:
return result
current_config['isEnable'] = enabled
self.set_motion_detect_config(current_config)
return FOSCAM_SUCCESS | [
"def",
"set_motion_detection",
"(",
"self",
",",
"enabled",
"=",
"1",
")",
":",
"result",
",",
"current_config",
"=",
"self",
".",
"get_motion_detect_config",
"(",
")",
"if",
"result",
"!=",
"FOSCAM_SUCCESS",
":",
"return",
"result",
"current_config",
"[",
"'i... | Get the current config and set the motion detection on or off | [
"Get",
"the",
"current",
"config",
"and",
"set",
"the",
"motion",
"detection",
"on",
"or",
"off"
] | train | https://github.com/viswa-swami/python-foscam/blob/d76f2f7016959b7b758751637fad103c9032e488/libpyfoscam/foscam.py#L618-L627 |
viswa-swami/python-foscam | libpyfoscam/foscam.py | FoscamCamera.set_motion_detection1 | def set_motion_detection1(self, enabled=1):
'''
Get the current config and set the motion detection on or off
'''
result, current_config = self.get_motion_detect_config1()
if result != FOSCAM_SUCCESS:
return result
current_config['isEnable'] = enabled
self.set_motion_detect_config1(current_config) | python | def set_motion_detection1(self, enabled=1):
'''
Get the current config and set the motion detection on or off
'''
result, current_config = self.get_motion_detect_config1()
if result != FOSCAM_SUCCESS:
return result
current_config['isEnable'] = enabled
self.set_motion_detect_config1(current_config) | [
"def",
"set_motion_detection1",
"(",
"self",
",",
"enabled",
"=",
"1",
")",
":",
"result",
",",
"current_config",
"=",
"self",
".",
"get_motion_detect_config1",
"(",
")",
"if",
"result",
"!=",
"FOSCAM_SUCCESS",
":",
"return",
"result",
"current_config",
"[",
"... | Get the current config and set the motion detection on or off | [
"Get",
"the",
"current",
"config",
"and",
"set",
"the",
"motion",
"detection",
"on",
"or",
"off"
] | train | https://github.com/viswa-swami/python-foscam/blob/d76f2f7016959b7b758751637fad103c9032e488/libpyfoscam/foscam.py#L656-L664 |
viswa-swami/python-foscam | libpyfoscam/foscam.py | FoscamCamera.set_alarm_record_config | def set_alarm_record_config(self, is_enable_prerecord=1,
prerecord_secs=5, alarm_record_secs=300, callback=None):
'''
Set alarm record config
Return: set result(0-success, -1-error)
'''
params = {'isEnablePreRecord': is_enable_prerecord,
'preRecordSecs' : prerecord_secs,
'alarmRecordSecs' : alarm_record_secs
}
return self.execute_command('setAlarmRecordConfig', params, callback=callback) | python | def set_alarm_record_config(self, is_enable_prerecord=1,
prerecord_secs=5, alarm_record_secs=300, callback=None):
'''
Set alarm record config
Return: set result(0-success, -1-error)
'''
params = {'isEnablePreRecord': is_enable_prerecord,
'preRecordSecs' : prerecord_secs,
'alarmRecordSecs' : alarm_record_secs
}
return self.execute_command('setAlarmRecordConfig', params, callback=callback) | [
"def",
"set_alarm_record_config",
"(",
"self",
",",
"is_enable_prerecord",
"=",
"1",
",",
"prerecord_secs",
"=",
"5",
",",
"alarm_record_secs",
"=",
"300",
",",
"callback",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'isEnablePreRecord'",
":",
"is_enable_prereco... | Set alarm record config
Return: set result(0-success, -1-error) | [
"Set",
"alarm",
"record",
"config",
"Return",
":",
"set",
"result",
"(",
"0",
"-",
"success",
"-",
"1",
"-",
"error",
")"
] | train | https://github.com/viswa-swami/python-foscam/blob/d76f2f7016959b7b758751637fad103c9032e488/libpyfoscam/foscam.py#L685-L695 |
viswa-swami/python-foscam | libpyfoscam/foscam.py | FoscamCamera.set_local_alarm_record_config | def set_local_alarm_record_config(self, is_enable_local_alarm_record = 1,
local_alarm_record_secs = 30, callback=None):
'''
Set local alarm-record config
`is_enable_local_alarm_record`: 0 disable, 1 enable
'''
params = {'isEnableLocalAlarmRecord': is_enable_local_alarm_record,
'localAlarmRecordSecs' : local_alarm_record_secs}
return self.execute_command('setLocalAlarmRecordConfig', params, callback=callback) | python | def set_local_alarm_record_config(self, is_enable_local_alarm_record = 1,
local_alarm_record_secs = 30, callback=None):
'''
Set local alarm-record config
`is_enable_local_alarm_record`: 0 disable, 1 enable
'''
params = {'isEnableLocalAlarmRecord': is_enable_local_alarm_record,
'localAlarmRecordSecs' : local_alarm_record_secs}
return self.execute_command('setLocalAlarmRecordConfig', params, callback=callback) | [
"def",
"set_local_alarm_record_config",
"(",
"self",
",",
"is_enable_local_alarm_record",
"=",
"1",
",",
"local_alarm_record_secs",
"=",
"30",
",",
"callback",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'isEnableLocalAlarmRecord'",
":",
"is_enable_local_alarm_record",
... | Set local alarm-record config
`is_enable_local_alarm_record`: 0 disable, 1 enable | [
"Set",
"local",
"alarm",
"-",
"record",
"config",
"is_enable_local_alarm_record",
":",
"0",
"disable",
"1",
"enable"
] | train | https://github.com/viswa-swami/python-foscam/blob/d76f2f7016959b7b758751637fad103c9032e488/libpyfoscam/foscam.py#L703-L711 |
viswa-swami/python-foscam | libpyfoscam/foscam.py | FoscamCamera.set_h264_frm_ref_mode | def set_h264_frm_ref_mode(self, mode=1, callback=None):
'''
Set frame shipping reference mode of H264 encode stream.
params:
`mode`: see docstr of meth::get_h264_frm_ref_mode
'''
params = {'mode': mode}
return self.execute_command('setH264FrmRefMode', params, callback) | python | def set_h264_frm_ref_mode(self, mode=1, callback=None):
'''
Set frame shipping reference mode of H264 encode stream.
params:
`mode`: see docstr of meth::get_h264_frm_ref_mode
'''
params = {'mode': mode}
return self.execute_command('setH264FrmRefMode', params, callback) | [
"def",
"set_h264_frm_ref_mode",
"(",
"self",
",",
"mode",
"=",
"1",
",",
"callback",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'mode'",
":",
"mode",
"}",
"return",
"self",
".",
"execute_command",
"(",
"'setH264FrmRefMode'",
",",
"params",
",",
"callback"... | Set frame shipping reference mode of H264 encode stream.
params:
`mode`: see docstr of meth::get_h264_frm_ref_mode | [
"Set",
"frame",
"shipping",
"reference",
"mode",
"of",
"H264",
"encode",
"stream",
".",
"params",
":",
"mode",
":",
"see",
"docstr",
"of",
"meth",
"::",
"get_h264_frm_ref_mode"
] | train | https://github.com/viswa-swami/python-foscam/blob/d76f2f7016959b7b758751637fad103c9032e488/libpyfoscam/foscam.py#L722-L729 |
viswa-swami/python-foscam | libpyfoscam/foscam.py | FoscamCamera.set_schedule_record_config | def set_schedule_record_config(self, is_enable, record_level,
space_full_mode, is_enable_audio,
schedule0 = 0, schedule1 = 0, schedule2 = 0,
schedule3 = 0, schedule4 = 0, schedule5 = 0,
schedule6 = 0, callback=None):
'''
Set schedule record config.
cmd: setScheduleRecordConfig
args: See docstring of meth::get_schedule_record_config
'''
params = {'isEnable' : is_enable,
'isEnableAudio': is_enable_audio,
'recordLevel' : record_level,
'spaceFullMode': space_full_mode,
'schedule0' : schedule0,
'schedule1' : schedule1,
'schedule2' : schedule2,
'schedule3' : schedule3,
'schedule4' : schedule4,
'schedule5' : schedule5,
'schedule6' : schedule6,
}
return self.execute_command('setScheduleRecordConfig', params, callback=callback) | python | def set_schedule_record_config(self, is_enable, record_level,
space_full_mode, is_enable_audio,
schedule0 = 0, schedule1 = 0, schedule2 = 0,
schedule3 = 0, schedule4 = 0, schedule5 = 0,
schedule6 = 0, callback=None):
'''
Set schedule record config.
cmd: setScheduleRecordConfig
args: See docstring of meth::get_schedule_record_config
'''
params = {'isEnable' : is_enable,
'isEnableAudio': is_enable_audio,
'recordLevel' : record_level,
'spaceFullMode': space_full_mode,
'schedule0' : schedule0,
'schedule1' : schedule1,
'schedule2' : schedule2,
'schedule3' : schedule3,
'schedule4' : schedule4,
'schedule5' : schedule5,
'schedule6' : schedule6,
}
return self.execute_command('setScheduleRecordConfig', params, callback=callback) | [
"def",
"set_schedule_record_config",
"(",
"self",
",",
"is_enable",
",",
"record_level",
",",
"space_full_mode",
",",
"is_enable_audio",
",",
"schedule0",
"=",
"0",
",",
"schedule1",
"=",
"0",
",",
"schedule2",
"=",
"0",
",",
"schedule3",
"=",
"0",
",",
"sch... | Set schedule record config.
cmd: setScheduleRecordConfig
args: See docstring of meth::get_schedule_record_config | [
"Set",
"schedule",
"record",
"config",
".",
"cmd",
":",
"setScheduleRecordConfig",
"args",
":",
"See",
"docstring",
"of",
"meth",
"::",
"get_schedule_record_config"
] | train | https://github.com/viswa-swami/python-foscam/blob/d76f2f7016959b7b758751637fad103c9032e488/libpyfoscam/foscam.py#L744-L767 |
viswa-swami/python-foscam | libpyfoscam/foscam.py | FoscamCamera.set_record_path | def set_record_path(self, path, callback=None):
'''
Set Record path: sd/ftp
cmd: setRecordPath
param:
path: (0,SD), (2, FTP)
'''
params = {'Path': path}
return self.execute_command('setRecordPath', params, callback=callback) | python | def set_record_path(self, path, callback=None):
'''
Set Record path: sd/ftp
cmd: setRecordPath
param:
path: (0,SD), (2, FTP)
'''
params = {'Path': path}
return self.execute_command('setRecordPath', params, callback=callback) | [
"def",
"set_record_path",
"(",
"self",
",",
"path",
",",
"callback",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'Path'",
":",
"path",
"}",
"return",
"self",
".",
"execute_command",
"(",
"'setRecordPath'",
",",
"params",
",",
"callback",
"=",
"callback",
... | Set Record path: sd/ftp
cmd: setRecordPath
param:
path: (0,SD), (2, FTP) | [
"Set",
"Record",
"path",
":",
"sd",
"/",
"ftp",
"cmd",
":",
"setRecordPath",
"param",
":",
"path",
":",
"(",
"0",
"SD",
")",
"(",
"2",
"FTP",
")"
] | train | https://github.com/viswa-swami/python-foscam/blob/d76f2f7016959b7b758751637fad103c9032e488/libpyfoscam/foscam.py#L780-L788 |
viswa-swami/python-foscam | libpyfoscam/foscam.py | FoscamCamera.get_log | def get_log(self, offset, count=10, callback=None):
'''
Retrieve log records from camera.
cmd: getLog
param:
offset: log offset for first record
count: number of records to return
'''
params = {'offset': offset, 'count': count}
return self.execute_command('getLog', params, callback=callback) | python | def get_log(self, offset, count=10, callback=None):
'''
Retrieve log records from camera.
cmd: getLog
param:
offset: log offset for first record
count: number of records to return
'''
params = {'offset': offset, 'count': count}
return self.execute_command('getLog', params, callback=callback) | [
"def",
"get_log",
"(",
"self",
",",
"offset",
",",
"count",
"=",
"10",
",",
"callback",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'offset'",
":",
"offset",
",",
"'count'",
":",
"count",
"}",
"return",
"self",
".",
"execute_command",
"(",
"'getLog'",
... | Retrieve log records from camera.
cmd: getLog
param:
offset: log offset for first record
count: number of records to return | [
"Retrieve",
"log",
"records",
"from",
"camera",
".",
"cmd",
":",
"getLog",
"param",
":",
"offset",
":",
"log",
"offset",
"for",
"first",
"record",
"count",
":",
"number",
"of",
"records",
"to",
"return"
] | train | https://github.com/viswa-swami/python-foscam/blob/d76f2f7016959b7b758751637fad103c9032e488/libpyfoscam/foscam.py#L815-L824 |
OSSOS/MOP | src/ossos/core/ossos/storage.py | get_apcor | def get_apcor(expnum, ccd, version='p', prefix=None):
"""
retrieve the aperture correction for this exposure
@param expnum:
@param ccd:
@param version:
@param prefix:
@return:
"""
uri = get_uri(expnum, ccd, ext=APCOR_EXT, version=version, prefix=prefix)
apcor_file_name = tempfile.NamedTemporaryFile()
client.copy(uri, apcor_file_name.name)
apcor_file_name.seek(0)
return [float(x) for x in apcor_file_name.readline().split()] | python | def get_apcor(expnum, ccd, version='p', prefix=None):
"""
retrieve the aperture correction for this exposure
@param expnum:
@param ccd:
@param version:
@param prefix:
@return:
"""
uri = get_uri(expnum, ccd, ext=APCOR_EXT, version=version, prefix=prefix)
apcor_file_name = tempfile.NamedTemporaryFile()
client.copy(uri, apcor_file_name.name)
apcor_file_name.seek(0)
return [float(x) for x in apcor_file_name.readline().split()] | [
"def",
"get_apcor",
"(",
"expnum",
",",
"ccd",
",",
"version",
"=",
"'p'",
",",
"prefix",
"=",
"None",
")",
":",
"uri",
"=",
"get_uri",
"(",
"expnum",
",",
"ccd",
",",
"ext",
"=",
"APCOR_EXT",
",",
"version",
"=",
"version",
",",
"prefix",
"=",
"pr... | retrieve the aperture correction for this exposure
@param expnum:
@param ccd:
@param version:
@param prefix:
@return: | [
"retrieve",
"the",
"aperture",
"correction",
"for",
"this",
"exposure"
] | train | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L108-L121 |
OSSOS/MOP | src/ossos/core/ossos/storage.py | cone_search | def cone_search(ra, dec, dra=0.01, ddec=0.01, mjdate=None, calibration_level=2, use_ssos=True,
collection='CFHTMEGAPIPE'):
"""Do a QUERY on the TAP service for all observations that are part of OSSOS (*P05/*P016)
where taken after mjd and have calibration 'observable'.
@param ra: RA center of search cont
@type ra: Quantity
@param dec: float degrees
@type dec: Quantity
@param dra: float degrees
@type dra: Quantity
@param ddec: float degrees
@type ddec: Quantity
@param calibration_level: What calibration level must the found image have,
@param mjdate: what data must the observation be to
@param collection: name of the data collection to be searched.
@param use_ssos: USE the SSOIS server to find comparison? False -> Use CAOM2 TAP query.
ke on.
this is a CAOM2 parameter of CADC, 2 means calibrated data.
"""
if use_ssos:
ssois_server = "http://www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/cadcbin/ssos/fixedssos.pl"
params = dict(pos="{0:f},{1:f}".format(ra.to(units.degree).value, dec.to(units.degree).value))
result = requests.get(ssois_server, params=params)
table = ascii.read(result.text, format='tab')
table = table[table['Telescope/Instrument'] == 'CFHT/MegaCam']
column_name_mapping = {'Image': 'collectionID',
'Filter': 'filter',
'Exptime': 'exptime'}
# rename the columns
for key in column_name_mapping:
table[key].name = column_name_mapping[key]
table['collectionID'] = [x[:-1] for x in table['collectionID']]
# compute the mjdate from the time string.
table['mjdate'] = Time(table['Date/Time']).mjd
return table
data = dict(QUERY=(" SELECT Observation.observationID as collectionID, "
" Plane.time_bounds_lower AS mjdate, "
" Plane.time_exposure AS exptime, "
" Plane.energy_bandpassName as filter"
" FROM caom2.Observation AS Observation "
" JOIN caom2.Plane AS Plane "
" ON Observation.obsID = Plane.obsID "
" WHERE ( Observation.collection = '{}' ) "
" AND Plane.calibrationLevel > {} "
" AND ( Plane.energy_bandpassName LIKE 'r.%' OR Plane.energy_bandpassName LIKE 'gri.%' ) "
" AND ( Observation.proposal_id LIKE '%P05' or Observation.proposal_id LIKE '%P06' )"
" AND Observation.target_name NOT LIKE 'WP%'"),
REQUEST="doQuery",
LANG="ADQL",
FORMAT="tsv")
data["QUERY"] = data["QUERY"].format(calibration_level, collection)
data["QUERY"] += (" AND "
" CONTAINS( BOX('ICRS', {}, {}, {}, {}), "
" Plane.position_bounds ) = 1 ").format(ra.to(units.degree).value, dec.to(units.degree).value,
dra.to(units.degree).value, ddec.to(units.degree).value)
if mjdate is not None:
data["QUERY"] += " AND Plane.time_bounds_lower < {} AND Plane.time_bounds_cval2 > {} ".format(
mjdate + 1.0 / 24.0,
mjdate - 1 / 24.0)
result = requests.get(TAP_WEB_SERVICE, params=data, verify=False)
logger.debug("Doing TAP Query using url: %s" % (str(result.url)))
table_reader = ascii.get_reader(Reader=ascii.Basic)
table_reader.header.splitter.delimiter = '\t'
table_reader.data.splitter.delimiter = '\t'
table = table_reader.read(result.text)
logger.debug(str(table))
return table | python | def cone_search(ra, dec, dra=0.01, ddec=0.01, mjdate=None, calibration_level=2, use_ssos=True,
collection='CFHTMEGAPIPE'):
"""Do a QUERY on the TAP service for all observations that are part of OSSOS (*P05/*P016)
where taken after mjd and have calibration 'observable'.
@param ra: RA center of search cont
@type ra: Quantity
@param dec: float degrees
@type dec: Quantity
@param dra: float degrees
@type dra: Quantity
@param ddec: float degrees
@type ddec: Quantity
@param calibration_level: What calibration level must the found image have,
@param mjdate: what data must the observation be to
@param collection: name of the data collection to be searched.
@param use_ssos: USE the SSOIS server to find comparison? False -> Use CAOM2 TAP query.
ke on.
this is a CAOM2 parameter of CADC, 2 means calibrated data.
"""
if use_ssos:
ssois_server = "http://www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/cadcbin/ssos/fixedssos.pl"
params = dict(pos="{0:f},{1:f}".format(ra.to(units.degree).value, dec.to(units.degree).value))
result = requests.get(ssois_server, params=params)
table = ascii.read(result.text, format='tab')
table = table[table['Telescope/Instrument'] == 'CFHT/MegaCam']
column_name_mapping = {'Image': 'collectionID',
'Filter': 'filter',
'Exptime': 'exptime'}
# rename the columns
for key in column_name_mapping:
table[key].name = column_name_mapping[key]
table['collectionID'] = [x[:-1] for x in table['collectionID']]
# compute the mjdate from the time string.
table['mjdate'] = Time(table['Date/Time']).mjd
return table
data = dict(QUERY=(" SELECT Observation.observationID as collectionID, "
" Plane.time_bounds_lower AS mjdate, "
" Plane.time_exposure AS exptime, "
" Plane.energy_bandpassName as filter"
" FROM caom2.Observation AS Observation "
" JOIN caom2.Plane AS Plane "
" ON Observation.obsID = Plane.obsID "
" WHERE ( Observation.collection = '{}' ) "
" AND Plane.calibrationLevel > {} "
" AND ( Plane.energy_bandpassName LIKE 'r.%' OR Plane.energy_bandpassName LIKE 'gri.%' ) "
" AND ( Observation.proposal_id LIKE '%P05' or Observation.proposal_id LIKE '%P06' )"
" AND Observation.target_name NOT LIKE 'WP%'"),
REQUEST="doQuery",
LANG="ADQL",
FORMAT="tsv")
data["QUERY"] = data["QUERY"].format(calibration_level, collection)
data["QUERY"] += (" AND "
" CONTAINS( BOX('ICRS', {}, {}, {}, {}), "
" Plane.position_bounds ) = 1 ").format(ra.to(units.degree).value, dec.to(units.degree).value,
dra.to(units.degree).value, ddec.to(units.degree).value)
if mjdate is not None:
data["QUERY"] += " AND Plane.time_bounds_lower < {} AND Plane.time_bounds_cval2 > {} ".format(
mjdate + 1.0 / 24.0,
mjdate - 1 / 24.0)
result = requests.get(TAP_WEB_SERVICE, params=data, verify=False)
logger.debug("Doing TAP Query using url: %s" % (str(result.url)))
table_reader = ascii.get_reader(Reader=ascii.Basic)
table_reader.header.splitter.delimiter = '\t'
table_reader.data.splitter.delimiter = '\t'
table = table_reader.read(result.text)
logger.debug(str(table))
return table | [
"def",
"cone_search",
"(",
"ra",
",",
"dec",
",",
"dra",
"=",
"0.01",
",",
"ddec",
"=",
"0.01",
",",
"mjdate",
"=",
"None",
",",
"calibration_level",
"=",
"2",
",",
"use_ssos",
"=",
"True",
",",
"collection",
"=",
"'CFHTMEGAPIPE'",
")",
":",
"if",
"u... | Do a QUERY on the TAP service for all observations that are part of OSSOS (*P05/*P016)
where taken after mjd and have calibration 'observable'.
@param ra: RA center of search cont
@type ra: Quantity
@param dec: float degrees
@type dec: Quantity
@param dra: float degrees
@type dra: Quantity
@param ddec: float degrees
@type ddec: Quantity
@param calibration_level: What calibration level must the found image have,
@param mjdate: what data must the observation be to
@param collection: name of the data collection to be searched.
@param use_ssos: USE the SSOIS server to find comparison? False -> Use CAOM2 TAP query.
ke on.
this is a CAOM2 parameter of CADC, 2 means calibrated data. | [
"Do",
"a",
"QUERY",
"on",
"the",
"TAP",
"service",
"for",
"all",
"observations",
"that",
"are",
"part",
"of",
"OSSOS",
"(",
"*",
"P05",
"/",
"*",
"P016",
")",
"where",
"taken",
"after",
"mjd",
"and",
"have",
"calibration",
"observable",
"."
] | train | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L138-L212 |
OSSOS/MOP | src/ossos/core/ossos/storage.py | populate | def populate(dataset_name, data_web_service_url=DATA_WEB_SERVICE + "CFHT"):
"""Given a dataset_name created the desired dbimages directories
and links to the raw data files stored at CADC.
@param dataset_name: the name of the CFHT dataset to make a link to.
@param data_web_servica_url: the URL of the data web service run by CADC.
"""
data_dest = get_uri(dataset_name, version='o', ext=FITS_EXT)
data_source = "%s/%so.{}" % (data_web_service_url, dataset_name, FITS_EXT)
mkdir(os.path.dirname(data_dest))
try:
client.link(data_source, data_dest)
except IOError as e:
if e.errno == errno.EEXIST:
pass
else:
raise e
header_dest = get_uri(dataset_name, version='o', ext='head')
header_source = "%s/%so.fits.fz?cutout=[0]" % (
data_web_service_url, dataset_name)
try:
client.link(header_source, header_dest)
except IOError as e:
if e.errno == errno.EEXIST:
pass
else:
raise e
header_dest = get_uri(dataset_name, version='p', ext='head')
header_source = "%s/%s/%sp.head" % (
'http://www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/data/pub', 'CFHTSG', dataset_name)
try:
client.link(header_source, header_dest)
except IOError as e:
if e.errno == errno.EEXIST:
pass
else:
raise e
return True | python | def populate(dataset_name, data_web_service_url=DATA_WEB_SERVICE + "CFHT"):
"""Given a dataset_name created the desired dbimages directories
and links to the raw data files stored at CADC.
@param dataset_name: the name of the CFHT dataset to make a link to.
@param data_web_servica_url: the URL of the data web service run by CADC.
"""
data_dest = get_uri(dataset_name, version='o', ext=FITS_EXT)
data_source = "%s/%so.{}" % (data_web_service_url, dataset_name, FITS_EXT)
mkdir(os.path.dirname(data_dest))
try:
client.link(data_source, data_dest)
except IOError as e:
if e.errno == errno.EEXIST:
pass
else:
raise e
header_dest = get_uri(dataset_name, version='o', ext='head')
header_source = "%s/%so.fits.fz?cutout=[0]" % (
data_web_service_url, dataset_name)
try:
client.link(header_source, header_dest)
except IOError as e:
if e.errno == errno.EEXIST:
pass
else:
raise e
header_dest = get_uri(dataset_name, version='p', ext='head')
header_source = "%s/%s/%sp.head" % (
'http://www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/data/pub', 'CFHTSG', dataset_name)
try:
client.link(header_source, header_dest)
except IOError as e:
if e.errno == errno.EEXIST:
pass
else:
raise e
return True | [
"def",
"populate",
"(",
"dataset_name",
",",
"data_web_service_url",
"=",
"DATA_WEB_SERVICE",
"+",
"\"CFHT\"",
")",
":",
"data_dest",
"=",
"get_uri",
"(",
"dataset_name",
",",
"version",
"=",
"'o'",
",",
"ext",
"=",
"FITS_EXT",
")",
"data_source",
"=",
"\"%s/%... | Given a dataset_name created the desired dbimages directories
and links to the raw data files stored at CADC.
@param dataset_name: the name of the CFHT dataset to make a link to.
@param data_web_servica_url: the URL of the data web service run by CADC. | [
"Given",
"a",
"dataset_name",
"created",
"the",
"desired",
"dbimages",
"directories",
"and",
"links",
"to",
"the",
"raw",
"data",
"files",
"stored",
"at",
"CADC",
"."
] | train | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L215-L257 |
OSSOS/MOP | src/ossos/core/ossos/storage.py | get_cands_uri | def get_cands_uri(field, ccd, version='p', ext='measure3.cands.astrom', prefix=None,
block=None):
"""
return the nominal URI for a candidate file.
@param field: the OSSOS field name
@param ccd: which CCD are the candidates on
@param version: either the 'p', or 's' (scrambled) candidates.
@param ext: Perhaps we'll change this one day.
@param prefix: if this is a 'fake' dataset then add 'fk'
@param block: Which BLOCK of the field are we looking at? eg. 15BS+1+1
@return:
"""
if prefix is None:
prefix = ""
if len(prefix) > 0:
prefix += "_"
if len(field) > 0:
field += "_"
if ext is None:
ext = ""
if len(ext) > 0 and ext[0] != ".":
ext = ".{}".format(ext)
measure3_dir = MEASURE3
if block is not None:
measure3_dir + "/{}".format(block)
return "{}/{}{}{}{}{}".format(measure3_dir, prefix, field, version, ccd, ext) | python | def get_cands_uri(field, ccd, version='p', ext='measure3.cands.astrom', prefix=None,
block=None):
"""
return the nominal URI for a candidate file.
@param field: the OSSOS field name
@param ccd: which CCD are the candidates on
@param version: either the 'p', or 's' (scrambled) candidates.
@param ext: Perhaps we'll change this one day.
@param prefix: if this is a 'fake' dataset then add 'fk'
@param block: Which BLOCK of the field are we looking at? eg. 15BS+1+1
@return:
"""
if prefix is None:
prefix = ""
if len(prefix) > 0:
prefix += "_"
if len(field) > 0:
field += "_"
if ext is None:
ext = ""
if len(ext) > 0 and ext[0] != ".":
ext = ".{}".format(ext)
measure3_dir = MEASURE3
if block is not None:
measure3_dir + "/{}".format(block)
return "{}/{}{}{}{}{}".format(measure3_dir, prefix, field, version, ccd, ext) | [
"def",
"get_cands_uri",
"(",
"field",
",",
"ccd",
",",
"version",
"=",
"'p'",
",",
"ext",
"=",
"'measure3.cands.astrom'",
",",
"prefix",
"=",
"None",
",",
"block",
"=",
"None",
")",
":",
"if",
"prefix",
"is",
"None",
":",
"prefix",
"=",
"\"\"",
"if",
... | return the nominal URI for a candidate file.
@param field: the OSSOS field name
@param ccd: which CCD are the candidates on
@param version: either the 'p', or 's' (scrambled) candidates.
@param ext: Perhaps we'll change this one day.
@param prefix: if this is a 'fake' dataset then add 'fk'
@param block: Which BLOCK of the field are we looking at? eg. 15BS+1+1
@return: | [
"return",
"the",
"nominal",
"URI",
"for",
"a",
"candidate",
"file",
"."
] | train | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L260-L289 |
OSSOS/MOP | src/ossos/core/ossos/storage.py | get_uri | def get_uri(expnum, ccd=None,
version='p', ext=FITS_EXT,
subdir=None, prefix=None):
"""
Build the uri for an OSSOS image stored in the dbimages
containerNode.
:rtype : basestring
expnum: CFHT exposure number
ccd: CCD in the mosaic [0-35]
version: one of p,s,o etc.
dbimages: dbimages containerNode.
@type subdir: str
@param expnum: int
@param ccd:
@param version:
@param ext:
@param subdir:
@param prefix:
"""
if subdir is None:
subdir = str(expnum)
if prefix is None:
prefix = ''
uri = os.path.join(DBIMAGES, subdir)
if ext is None:
ext = ''
elif len(ext) > 0 and ext[0] != '.':
ext = '.' + ext
if version is None:
version = ''
if ccd is None:
uri = os.path.join(uri,
'%s%s%s%s' % (prefix, str(expnum),
version,
ext))
else:
ccd = str(ccd).zfill(2)
uri = os.path.join(uri,
'ccd{}'.format(ccd),
'%s%s%s%s%s' % (prefix, str(expnum),
version,
ccd,
ext))
return uri | python | def get_uri(expnum, ccd=None,
version='p', ext=FITS_EXT,
subdir=None, prefix=None):
"""
Build the uri for an OSSOS image stored in the dbimages
containerNode.
:rtype : basestring
expnum: CFHT exposure number
ccd: CCD in the mosaic [0-35]
version: one of p,s,o etc.
dbimages: dbimages containerNode.
@type subdir: str
@param expnum: int
@param ccd:
@param version:
@param ext:
@param subdir:
@param prefix:
"""
if subdir is None:
subdir = str(expnum)
if prefix is None:
prefix = ''
uri = os.path.join(DBIMAGES, subdir)
if ext is None:
ext = ''
elif len(ext) > 0 and ext[0] != '.':
ext = '.' + ext
if version is None:
version = ''
if ccd is None:
uri = os.path.join(uri,
'%s%s%s%s' % (prefix, str(expnum),
version,
ext))
else:
ccd = str(ccd).zfill(2)
uri = os.path.join(uri,
'ccd{}'.format(ccd),
'%s%s%s%s%s' % (prefix, str(expnum),
version,
ccd,
ext))
return uri | [
"def",
"get_uri",
"(",
"expnum",
",",
"ccd",
"=",
"None",
",",
"version",
"=",
"'p'",
",",
"ext",
"=",
"FITS_EXT",
",",
"subdir",
"=",
"None",
",",
"prefix",
"=",
"None",
")",
":",
"if",
"subdir",
"is",
"None",
":",
"subdir",
"=",
"str",
"(",
"ex... | Build the uri for an OSSOS image stored in the dbimages
containerNode.
:rtype : basestring
expnum: CFHT exposure number
ccd: CCD in the mosaic [0-35]
version: one of p,s,o etc.
dbimages: dbimages containerNode.
@type subdir: str
@param expnum: int
@param ccd:
@param version:
@param ext:
@param subdir:
@param prefix: | [
"Build",
"the",
"uri",
"for",
"an",
"OSSOS",
"image",
"stored",
"in",
"the",
"dbimages",
"containerNode",
"."
] | train | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L292-L340 |
OSSOS/MOP | src/ossos/core/ossos/storage.py | get_tag | def get_tag(expnum, key):
"""given a key, return the vospace tag value.
@param expnum: Number of the CFHT exposure that a tag value is needed for
@param key: The process tag (such as mkpsf_00) that is being looked up.
@return: the value of the tag
@rtype: str
"""
uri = tag_uri(key)
force = uri not in get_tags(expnum)
value = get_tags(expnum, force=force).get(uri, None)
return value | python | def get_tag(expnum, key):
"""given a key, return the vospace tag value.
@param expnum: Number of the CFHT exposure that a tag value is needed for
@param key: The process tag (such as mkpsf_00) that is being looked up.
@return: the value of the tag
@rtype: str
"""
uri = tag_uri(key)
force = uri not in get_tags(expnum)
value = get_tags(expnum, force=force).get(uri, None)
return value | [
"def",
"get_tag",
"(",
"expnum",
",",
"key",
")",
":",
"uri",
"=",
"tag_uri",
"(",
"key",
")",
"force",
"=",
"uri",
"not",
"in",
"get_tags",
"(",
"expnum",
")",
"value",
"=",
"get_tags",
"(",
"expnum",
",",
"force",
"=",
"force",
")",
".",
"get",
... | given a key, return the vospace tag value.
@param expnum: Number of the CFHT exposure that a tag value is needed for
@param key: The process tag (such as mkpsf_00) that is being looked up.
@return: the value of the tag
@rtype: str | [
"given",
"a",
"key",
"return",
"the",
"vospace",
"tag",
"value",
"."
] | train | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L413-L425 |
OSSOS/MOP | src/ossos/core/ossos/storage.py | get_process_tag | def get_process_tag(program, ccd, version='p'):
"""
make a process tag have a suffix indicating which ccd its for.
@param program: Name of the process that a tag is built for.
@param ccd: the CCD number that this process ran on.
@param version: The version of the exposure (s, p, o) that the process ran on.
@return: The string that represents the processing tag.
"""
return "%s_%s%s" % (program, str(version), str(ccd).zfill(2)) | python | def get_process_tag(program, ccd, version='p'):
"""
make a process tag have a suffix indicating which ccd its for.
@param program: Name of the process that a tag is built for.
@param ccd: the CCD number that this process ran on.
@param version: The version of the exposure (s, p, o) that the process ran on.
@return: The string that represents the processing tag.
"""
return "%s_%s%s" % (program, str(version), str(ccd).zfill(2)) | [
"def",
"get_process_tag",
"(",
"program",
",",
"ccd",
",",
"version",
"=",
"'p'",
")",
":",
"return",
"\"%s_%s%s\"",
"%",
"(",
"program",
",",
"str",
"(",
"version",
")",
",",
"str",
"(",
"ccd",
")",
".",
"zfill",
"(",
"2",
")",
")"
] | make a process tag have a suffix indicating which ccd its for.
@param program: Name of the process that a tag is built for.
@param ccd: the CCD number that this process ran on.
@param version: The version of the exposure (s, p, o) that the process ran on.
@return: The string that represents the processing tag. | [
"make",
"a",
"process",
"tag",
"have",
"a",
"suffix",
"indicating",
"which",
"ccd",
"its",
"for",
"."
] | train | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L428-L436 |
OSSOS/MOP | src/ossos/core/ossos/storage.py | get_status | def get_status(task, prefix, expnum, version, ccd, return_message=False):
"""
Report back status of the given program by looking up the associated VOSpace annotation.
@param task: name of the process or task that will be checked.
@param prefix: prefix of the file that was processed (often fk or None)
@param expnum: which exposure number (or base filename)
@param version: which version of that exposure (p, s, o)
@param ccd: which CCD within the exposure.
@param return_message: Return what did the TAG said or just /True/False/ for Success/Failure?
@return: the status of the processing based on the annotation value.
"""
key = get_process_tag(prefix+task, ccd, version)
status = get_tag(expnum, key)
logger.debug('%s: %s' % (key, status))
if return_message:
return status
else:
return status == SUCCESS | python | def get_status(task, prefix, expnum, version, ccd, return_message=False):
"""
Report back status of the given program by looking up the associated VOSpace annotation.
@param task: name of the process or task that will be checked.
@param prefix: prefix of the file that was processed (often fk or None)
@param expnum: which exposure number (or base filename)
@param version: which version of that exposure (p, s, o)
@param ccd: which CCD within the exposure.
@param return_message: Return what did the TAG said or just /True/False/ for Success/Failure?
@return: the status of the processing based on the annotation value.
"""
key = get_process_tag(prefix+task, ccd, version)
status = get_tag(expnum, key)
logger.debug('%s: %s' % (key, status))
if return_message:
return status
else:
return status == SUCCESS | [
"def",
"get_status",
"(",
"task",
",",
"prefix",
",",
"expnum",
",",
"version",
",",
"ccd",
",",
"return_message",
"=",
"False",
")",
":",
"key",
"=",
"get_process_tag",
"(",
"prefix",
"+",
"task",
",",
"ccd",
",",
"version",
")",
"status",
"=",
"get_t... | Report back status of the given program by looking up the associated VOSpace annotation.
@param task: name of the process or task that will be checked.
@param prefix: prefix of the file that was processed (often fk or None)
@param expnum: which exposure number (or base filename)
@param version: which version of that exposure (p, s, o)
@param ccd: which CCD within the exposure.
@param return_message: Return what did the TAG said or just /True/False/ for Success/Failure?
@return: the status of the processing based on the annotation value. | [
"Report",
"back",
"status",
"of",
"the",
"given",
"program",
"by",
"looking",
"up",
"the",
"associated",
"VOSpace",
"annotation",
"."
] | train | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L571-L589 |
OSSOS/MOP | src/ossos/core/ossos/storage.py | set_status | def set_status(task, prefix, expnum, version, ccd, status):
"""
set the processing status of the given program.
@param task: name of the processing task
@param prefix: was there a prefix on the exposure number processed?
@param expnum: exposure number processed.
@param version: which version of the exposure? (p, s, o)
@param ccd: the number of the CCD processing.
@param status: What status to record: "SUCCESS" we hope.
@return: Success?
"""
return set_tag(expnum, get_process_tag(prefix+task, ccd, version), status) | python | def set_status(task, prefix, expnum, version, ccd, status):
"""
set the processing status of the given program.
@param task: name of the processing task
@param prefix: was there a prefix on the exposure number processed?
@param expnum: exposure number processed.
@param version: which version of the exposure? (p, s, o)
@param ccd: the number of the CCD processing.
@param status: What status to record: "SUCCESS" we hope.
@return: Success?
"""
return set_tag(expnum, get_process_tag(prefix+task, ccd, version), status) | [
"def",
"set_status",
"(",
"task",
",",
"prefix",
",",
"expnum",
",",
"version",
",",
"ccd",
",",
"status",
")",
":",
"return",
"set_tag",
"(",
"expnum",
",",
"get_process_tag",
"(",
"prefix",
"+",
"task",
",",
"ccd",
",",
"version",
")",
",",
"status",... | set the processing status of the given program.
@param task: name of the processing task
@param prefix: was there a prefix on the exposure number processed?
@param expnum: exposure number processed.
@param version: which version of the exposure? (p, s, o)
@param ccd: the number of the CCD processing.
@param status: What status to record: "SUCCESS" we hope.
@return: Success? | [
"set",
"the",
"processing",
"status",
"of",
"the",
"given",
"program",
"."
] | train | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L592-L603 |
OSSOS/MOP | src/ossos/core/ossos/storage.py | _cutout_expnum | def _cutout_expnum(observation, sky_coord, radius):
"""
Get a cutout from an exposure based on the RA/DEC location.
@param observation: The Observation object that contains the expusre number information.
@type observation: Observation
@param sky_coord: which RA/DEC is needed,
@type sky_coord: SkyCoord
@param radius:
@type radius: Quantity
@return: HDUList containing the cutout image.
@rtype: list(HDUList)
"""
uri = observation.get_image_uri()
cutout_filehandle = tempfile.NamedTemporaryFile()
disposition_filename = client.copy(uri + "({},{},{})".format(sky_coord.ra.to('degree').value,
sky_coord.dec.to('degree').value,
radius.to('degree').value),
cutout_filehandle.name,
disposition=True)
cutouts = decompose_content_decomposition(disposition_filename)
cutout_filehandle.seek(0)
hdulist = fits.open(cutout_filehandle)
hdulist.verify('silentfix+ignore')
logger.debug("Initial Length of HDUList: {}".format(len(hdulist)))
# Make sure here is a primaryHDU
if len(hdulist) == 1:
phdu = fits.PrimaryHDU()
phdu.header['ORIGIN'] = "OSSOS"
hdulist.insert(0, phdu)
logger.debug("Final Length of HDUList: {}".format(len(hdulist)))
if len(cutouts) != len(hdulist) - 1:
raise ValueError("Wrong number of cutout structures found in Content-Disposition response.")
for hdu in hdulist[1:]:
cutout = cutouts.pop(0)
if 'ASTLEVEL' not in hdu.header:
print("WARNING: ******* NO ASTLEVEL KEYWORD ********** for {0} ********".format(observation.get_image_uri))
hdu.header['ASTLEVEL'] = 0
hdu.header['EXTNO'] = cutout[0]
naxis1 = hdu.header['NAXIS1']
naxis2 = hdu.header['NAXIS2']
default_datasec = "[{}:{},{}:{}]".format(1, naxis1, 1, naxis2)
datasec = hdu.header.get('DATASEC', default_datasec)
datasec = datasec_to_list(datasec)
corners = datasec
for idx in range(len(corners)):
try:
corners[idx] = int(cutout[idx+1])
except Exception:
pass
hdu.header['DATASEC'] = reset_datasec("[{}:{},{}:{}]".format(corners[0],
corners[1],
corners[2],
corners[3]),
hdu.header.get('DATASEC', default_datasec),
hdu.header['NAXIS1'],
hdu.header['NAXIS2'])
hdu.header['XOFFSET'] = int(corners[0]) - 1
hdu.header['YOFFSET'] = int(corners[2]) - 1
hdu.converter = CoordinateConverter(hdu.header['XOFFSET'], hdu.header['YOFFSET'])
try:
hdu.wcs = WCS(hdu.header)
except Exception as ex:
logger.error("Failed trying to initialize the WCS for {}".format(uri))
raise ex
logger.debug("Sending back {}".format(hdulist))
return hdulist | python | def _cutout_expnum(observation, sky_coord, radius):
"""
Get a cutout from an exposure based on the RA/DEC location.
@param observation: The Observation object that contains the expusre number information.
@type observation: Observation
@param sky_coord: which RA/DEC is needed,
@type sky_coord: SkyCoord
@param radius:
@type radius: Quantity
@return: HDUList containing the cutout image.
@rtype: list(HDUList)
"""
uri = observation.get_image_uri()
cutout_filehandle = tempfile.NamedTemporaryFile()
disposition_filename = client.copy(uri + "({},{},{})".format(sky_coord.ra.to('degree').value,
sky_coord.dec.to('degree').value,
radius.to('degree').value),
cutout_filehandle.name,
disposition=True)
cutouts = decompose_content_decomposition(disposition_filename)
cutout_filehandle.seek(0)
hdulist = fits.open(cutout_filehandle)
hdulist.verify('silentfix+ignore')
logger.debug("Initial Length of HDUList: {}".format(len(hdulist)))
# Make sure here is a primaryHDU
if len(hdulist) == 1:
phdu = fits.PrimaryHDU()
phdu.header['ORIGIN'] = "OSSOS"
hdulist.insert(0, phdu)
logger.debug("Final Length of HDUList: {}".format(len(hdulist)))
if len(cutouts) != len(hdulist) - 1:
raise ValueError("Wrong number of cutout structures found in Content-Disposition response.")
for hdu in hdulist[1:]:
cutout = cutouts.pop(0)
if 'ASTLEVEL' not in hdu.header:
print("WARNING: ******* NO ASTLEVEL KEYWORD ********** for {0} ********".format(observation.get_image_uri))
hdu.header['ASTLEVEL'] = 0
hdu.header['EXTNO'] = cutout[0]
naxis1 = hdu.header['NAXIS1']
naxis2 = hdu.header['NAXIS2']
default_datasec = "[{}:{},{}:{}]".format(1, naxis1, 1, naxis2)
datasec = hdu.header.get('DATASEC', default_datasec)
datasec = datasec_to_list(datasec)
corners = datasec
for idx in range(len(corners)):
try:
corners[idx] = int(cutout[idx+1])
except Exception:
pass
hdu.header['DATASEC'] = reset_datasec("[{}:{},{}:{}]".format(corners[0],
corners[1],
corners[2],
corners[3]),
hdu.header.get('DATASEC', default_datasec),
hdu.header['NAXIS1'],
hdu.header['NAXIS2'])
hdu.header['XOFFSET'] = int(corners[0]) - 1
hdu.header['YOFFSET'] = int(corners[2]) - 1
hdu.converter = CoordinateConverter(hdu.header['XOFFSET'], hdu.header['YOFFSET'])
try:
hdu.wcs = WCS(hdu.header)
except Exception as ex:
logger.error("Failed trying to initialize the WCS for {}".format(uri))
raise ex
logger.debug("Sending back {}".format(hdulist))
return hdulist | [
"def",
"_cutout_expnum",
"(",
"observation",
",",
"sky_coord",
",",
"radius",
")",
":",
"uri",
"=",
"observation",
".",
"get_image_uri",
"(",
")",
"cutout_filehandle",
"=",
"tempfile",
".",
"NamedTemporaryFile",
"(",
")",
"disposition_filename",
"=",
"client",
"... | Get a cutout from an exposure based on the RA/DEC location.
@param observation: The Observation object that contains the expusre number information.
@type observation: Observation
@param sky_coord: which RA/DEC is needed,
@type sky_coord: SkyCoord
@param radius:
@type radius: Quantity
@return: HDUList containing the cutout image.
@rtype: list(HDUList) | [
"Get",
"a",
"cutout",
"from",
"an",
"exposure",
"based",
"on",
"the",
"RA",
"/",
"DEC",
"location",
"."
] | train | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L629-L701 |
OSSOS/MOP | src/ossos/core/ossos/storage.py | frame2expnum | def frame2expnum(frameid):
"""Given a standard OSSOS frameid return the expnum, version and ccdnum as a dictionary."""
result = {}
parts = re.search('(?P<expnum>\d{7})(?P<type>\S)(?P<ccd>\d\d)', frameid)
assert parts is not None
result['expnum'] = parts.group('expnum')
result['ccd'] = parts.group('ccd')
result['version'] = parts.group('type')
return result | python | def frame2expnum(frameid):
"""Given a standard OSSOS frameid return the expnum, version and ccdnum as a dictionary."""
result = {}
parts = re.search('(?P<expnum>\d{7})(?P<type>\S)(?P<ccd>\d\d)', frameid)
assert parts is not None
result['expnum'] = parts.group('expnum')
result['ccd'] = parts.group('ccd')
result['version'] = parts.group('type')
return result | [
"def",
"frame2expnum",
"(",
"frameid",
")",
":",
"result",
"=",
"{",
"}",
"parts",
"=",
"re",
".",
"search",
"(",
"'(?P<expnum>\\d{7})(?P<type>\\S)(?P<ccd>\\d\\d)'",
",",
"frameid",
")",
"assert",
"parts",
"is",
"not",
"None",
"result",
"[",
"'expnum'",
"]",
... | Given a standard OSSOS frameid return the expnum, version and ccdnum as a dictionary. | [
"Given",
"a",
"standard",
"OSSOS",
"frameid",
"return",
"the",
"expnum",
"version",
"and",
"ccdnum",
"as",
"a",
"dictionary",
"."
] | train | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L806-L814 |
OSSOS/MOP | src/ossos/core/ossos/storage.py | get_image | def get_image(expnum, ccd=None, version='p', ext=FITS_EXT,
subdir=None, prefix=None, cutout=None, return_file=True, flip_image=True):
"""Get a FITS file for this expnum/ccd from VOSpace.
@param cutout: (str)
@param return_file: return an filename (True) or HDUList (False)
@param expnum: CFHT exposure number (int)
@param ccd: @param ccd:
@param version: [p, s, o] (char)
@param ext:
@param subdir:
@param prefix:
@param flip_image: Should the image be x/y flipped after being retrieved?
@return: astropy.io.fits.PrimaryHDU
"""
filename = os.path.basename(get_uri(expnum, ccd, version, ext=ext, subdir=subdir, prefix=prefix))
if os.access(filename, os.F_OK) and return_file and cutout is None:
return filename
cutout_string = cutout
try:
if os.access(filename, os.F_OK) and cutout:
cutout = datasec_to_list(cutout)
hdulist = fits.open(filename)
if len(hdulist) > 1:
raise ValueError("Local cutout access not designed to work on MEFs yet.")
header = hdulist[0].header
cutout[0] = cutout[0] < 0 and header['NAXIS1'] - cutout[0] + 1 or cutout[0]
cutout[1] = cutout[1] < 0 and header['NAXIS1'] - cutout[1] + 1 or cutout[1]
cutout[2] = cutout[2] < 0 and header['NAXIS2'] - cutout[2] + 1 or cutout[2]
cutout[3] = cutout[3] < 0 and header['NAXIS2'] - cutout[3] + 1 or cutout[3]
logger.debug("DATA array shape: {}".format(hdulist[0].data.shape))
logger.debug("CUTOUT array: {} {} {} {}".format(cutout[0],
cutout[1],
cutout[2],
cutout[3]))
flip = cutout[0] < cutout[1] and 1 or -1
flop = cutout[2] < cutout[3] and 1 or -1
header['CRPIX1'] = (header.get("CRPIX1", 1) - cutout[0]) * flip + 1
header['CRPIX2'] = (header.get("CRPIX2", 1) - cutout[2]) * flop + 1
header['CD1_1'] = header.get("CD1_1", 1) * flip
header['CD2_1'] = header.get("CD2_1", 1) * flip
header['CD2_2'] = header.get("CD2_2", 1) * flop
header['CD1_2'] = header.get("CD1_2", 1) * flop
data = hdulist[0].data[cutout[2]-1:cutout[3], cutout[0]-1:cutout[1]]
hdulist[0].data = data
header['DATASEC'] = reset_datasec(cutout_string,
header['DATASEC'],
header['NAXIS1'],
header['NAXIS2'])
if return_file:
cutout_filename = os.path.splitext(filename)[0]+"_{}_{}_{}_{}.fits".format(cutout[0],
cutout[1],
cutout[2],
cutout[3])
hdulist.writeto(cutout_filename)
return cutout_filename
else:
return hdulist
except Exception as e:
logger.debug(str(e))
logger.debug("Failed trying to access local copy: {} with cutout [{}:{}, {}:{}], using VOSpace".format(
filename, cutout[2]-1, cutout[3], cutout[0]-1, cutout[1]))
cutout = cutout_string
if not subdir:
subdir = str(expnum)
logger.debug("Building list of possible uri locations")
# # here is the list of places we will look, in order
if version != 'p':
locations = [(get_uri(expnum, ccd, version, ext=ext, subdir=subdir, prefix=prefix),
cutout)]
else:
locations = []
logger.debug(str(locations))
if ccd is not None:
try:
for this_ext in [ext]:
ext_no = int(ccd) + 1
# extension 1 -> 18 + 37,36 should be flipped.
flip_these_extensions = range(1, 19)
flip_these_extensions.append(37)
flip_these_extensions.append(38)
flip = (cutout is None and "fits" in ext and (
(ext_no in flip_these_extensions and flip_image) and "[-*,-*]" or "[*,*]")) or cutout
locations.append((get_uri(expnum, version=version, ext=this_ext, subdir=subdir),
"[{}]{}".format(ext_no, flip)))
except Exception as e:
logger.error(str(e))
pass
else:
uri = get_uri(expnum, ccd, version, ext=ext, subdir=subdir, prefix=prefix)
locations.append((uri, cutout))
# uri = get_uri(expnum, ccd, version, ext=ext + ".fz", subdir=subdir, prefix=prefix)
# locations.append((uri, cutout))
err = errno.EFAULT
while len(locations) > 0:
(uri, cutout) = locations.pop(0)
try:
hdu_list = get_hdu(uri, cutout)
if return_file:
hdu_list.writeto(filename)
del hdu_list
return filename
else:
return hdu_list
except Exception as e:
err = getattr(e, 'errno', errno.EAGAIN)
logger.debug("{}".format(type(e)))
logger.debug("Failed to open {} cutout:{}".format(uri, cutout))
logger.debug("vos sent back error: {} code: {}".format(str(e), getattr(e, 'errno', 0)))
if err == errno.EAGAIN:
time.sleep(5)
return get_image(expnum, ccd=ccd, version=version, ext=ext,
subdir=subdir, prefix=prefix, cutout=cutout, return_file=return_file, flip_image=flip_image)
raise IOError(err, "Failed to get image at uri: {} using {} {} {} {}.".format(uri, expnum, version, ccd, cutout)) | python | def get_image(expnum, ccd=None, version='p', ext=FITS_EXT,
subdir=None, prefix=None, cutout=None, return_file=True, flip_image=True):
"""Get a FITS file for this expnum/ccd from VOSpace.
@param cutout: (str)
@param return_file: return an filename (True) or HDUList (False)
@param expnum: CFHT exposure number (int)
@param ccd: @param ccd:
@param version: [p, s, o] (char)
@param ext:
@param subdir:
@param prefix:
@param flip_image: Should the image be x/y flipped after being retrieved?
@return: astropy.io.fits.PrimaryHDU
"""
filename = os.path.basename(get_uri(expnum, ccd, version, ext=ext, subdir=subdir, prefix=prefix))
if os.access(filename, os.F_OK) and return_file and cutout is None:
return filename
cutout_string = cutout
try:
if os.access(filename, os.F_OK) and cutout:
cutout = datasec_to_list(cutout)
hdulist = fits.open(filename)
if len(hdulist) > 1:
raise ValueError("Local cutout access not designed to work on MEFs yet.")
header = hdulist[0].header
cutout[0] = cutout[0] < 0 and header['NAXIS1'] - cutout[0] + 1 or cutout[0]
cutout[1] = cutout[1] < 0 and header['NAXIS1'] - cutout[1] + 1 or cutout[1]
cutout[2] = cutout[2] < 0 and header['NAXIS2'] - cutout[2] + 1 or cutout[2]
cutout[3] = cutout[3] < 0 and header['NAXIS2'] - cutout[3] + 1 or cutout[3]
logger.debug("DATA array shape: {}".format(hdulist[0].data.shape))
logger.debug("CUTOUT array: {} {} {} {}".format(cutout[0],
cutout[1],
cutout[2],
cutout[3]))
flip = cutout[0] < cutout[1] and 1 or -1
flop = cutout[2] < cutout[3] and 1 or -1
header['CRPIX1'] = (header.get("CRPIX1", 1) - cutout[0]) * flip + 1
header['CRPIX2'] = (header.get("CRPIX2", 1) - cutout[2]) * flop + 1
header['CD1_1'] = header.get("CD1_1", 1) * flip
header['CD2_1'] = header.get("CD2_1", 1) * flip
header['CD2_2'] = header.get("CD2_2", 1) * flop
header['CD1_2'] = header.get("CD1_2", 1) * flop
data = hdulist[0].data[cutout[2]-1:cutout[3], cutout[0]-1:cutout[1]]
hdulist[0].data = data
header['DATASEC'] = reset_datasec(cutout_string,
header['DATASEC'],
header['NAXIS1'],
header['NAXIS2'])
if return_file:
cutout_filename = os.path.splitext(filename)[0]+"_{}_{}_{}_{}.fits".format(cutout[0],
cutout[1],
cutout[2],
cutout[3])
hdulist.writeto(cutout_filename)
return cutout_filename
else:
return hdulist
except Exception as e:
logger.debug(str(e))
logger.debug("Failed trying to access local copy: {} with cutout [{}:{}, {}:{}], using VOSpace".format(
filename, cutout[2]-1, cutout[3], cutout[0]-1, cutout[1]))
cutout = cutout_string
if not subdir:
subdir = str(expnum)
logger.debug("Building list of possible uri locations")
# # here is the list of places we will look, in order
if version != 'p':
locations = [(get_uri(expnum, ccd, version, ext=ext, subdir=subdir, prefix=prefix),
cutout)]
else:
locations = []
logger.debug(str(locations))
if ccd is not None:
try:
for this_ext in [ext]:
ext_no = int(ccd) + 1
# extension 1 -> 18 + 37,36 should be flipped.
flip_these_extensions = range(1, 19)
flip_these_extensions.append(37)
flip_these_extensions.append(38)
flip = (cutout is None and "fits" in ext and (
(ext_no in flip_these_extensions and flip_image) and "[-*,-*]" or "[*,*]")) or cutout
locations.append((get_uri(expnum, version=version, ext=this_ext, subdir=subdir),
"[{}]{}".format(ext_no, flip)))
except Exception as e:
logger.error(str(e))
pass
else:
uri = get_uri(expnum, ccd, version, ext=ext, subdir=subdir, prefix=prefix)
locations.append((uri, cutout))
# uri = get_uri(expnum, ccd, version, ext=ext + ".fz", subdir=subdir, prefix=prefix)
# locations.append((uri, cutout))
err = errno.EFAULT
while len(locations) > 0:
(uri, cutout) = locations.pop(0)
try:
hdu_list = get_hdu(uri, cutout)
if return_file:
hdu_list.writeto(filename)
del hdu_list
return filename
else:
return hdu_list
except Exception as e:
err = getattr(e, 'errno', errno.EAGAIN)
logger.debug("{}".format(type(e)))
logger.debug("Failed to open {} cutout:{}".format(uri, cutout))
logger.debug("vos sent back error: {} code: {}".format(str(e), getattr(e, 'errno', 0)))
if err == errno.EAGAIN:
time.sleep(5)
return get_image(expnum, ccd=ccd, version=version, ext=ext,
subdir=subdir, prefix=prefix, cutout=cutout, return_file=return_file, flip_image=flip_image)
raise IOError(err, "Failed to get image at uri: {} using {} {} {} {}.".format(uri, expnum, version, ccd, cutout)) | [
"def",
"get_image",
"(",
"expnum",
",",
"ccd",
"=",
"None",
",",
"version",
"=",
"'p'",
",",
"ext",
"=",
"FITS_EXT",
",",
"subdir",
"=",
"None",
",",
"prefix",
"=",
"None",
",",
"cutout",
"=",
"None",
",",
"return_file",
"=",
"True",
",",
"flip_image... | Get a FITS file for this expnum/ccd from VOSpace.
@param cutout: (str)
@param return_file: return an filename (True) or HDUList (False)
@param expnum: CFHT exposure number (int)
@param ccd: @param ccd:
@param version: [p, s, o] (char)
@param ext:
@param subdir:
@param prefix:
@param flip_image: Should the image be x/y flipped after being retrieved?
@return: astropy.io.fits.PrimaryHDU | [
"Get",
"a",
"FITS",
"file",
"for",
"this",
"expnum",
"/",
"ccd",
"from",
"VOSpace",
"."
] | train | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L821-L943 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.