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 |
|---|---|---|---|---|---|---|---|---|---|---|
ChristopherRabotin/bungiesearch | bungiesearch/managers.py | BungiesearchManager.custom_search | def custom_search(self, index, doc_type):
'''
Performs a search on a custom elasticsearch index and mapping. Will not attempt to map result objects.
'''
from bungiesearch import Bungiesearch
return Bungiesearch(raw_results=True).index(index).doc_type(doc_type) | python | def custom_search(self, index, doc_type):
'''
Performs a search on a custom elasticsearch index and mapping. Will not attempt to map result objects.
'''
from bungiesearch import Bungiesearch
return Bungiesearch(raw_results=True).index(index).doc_type(doc_type) | [
"def",
"custom_search",
"(",
"self",
",",
"index",
",",
"doc_type",
")",
":",
"from",
"bungiesearch",
"import",
"Bungiesearch",
"return",
"Bungiesearch",
"(",
"raw_results",
"=",
"True",
")",
".",
"index",
"(",
"index",
")",
".",
"doc_type",
"(",
"doc_type",... | Performs a search on a custom elasticsearch index and mapping. Will not attempt to map result objects. | [
"Performs",
"a",
"search",
"on",
"a",
"custom",
"elasticsearch",
"index",
"and",
"mapping",
".",
"Will",
"not",
"attempt",
"to",
"map",
"result",
"objects",
"."
] | train | https://github.com/ChristopherRabotin/bungiesearch/blob/13768342bc2698b214eb0003c2d113b6e273c30d/bungiesearch/managers.py#L24-L29 |
ChristopherRabotin/bungiesearch | bungiesearch/managers.py | BungiesearchManager.contribute_to_class | def contribute_to_class(self, cls, name):
'''
Sets up the signal processor. Since self.model is not available
in the constructor, we perform this operation here.
'''
super(BungiesearchManager, self).contribute_to_class(cls, name)
from . import Bungiesearch
from .... | python | def contribute_to_class(self, cls, name):
'''
Sets up the signal processor. Since self.model is not available
in the constructor, we perform this operation here.
'''
super(BungiesearchManager, self).contribute_to_class(cls, name)
from . import Bungiesearch
from .... | [
"def",
"contribute_to_class",
"(",
"self",
",",
"cls",
",",
"name",
")",
":",
"super",
"(",
"BungiesearchManager",
",",
"self",
")",
".",
"contribute_to_class",
"(",
"cls",
",",
"name",
")",
"from",
".",
"import",
"Bungiesearch",
"from",
".",
"signals",
"i... | Sets up the signal processor. Since self.model is not available
in the constructor, we perform this operation here. | [
"Sets",
"up",
"the",
"signal",
"processor",
".",
"Since",
"self",
".",
"model",
"is",
"not",
"available",
"in",
"the",
"constructor",
"we",
"perform",
"this",
"operation",
"here",
"."
] | train | https://github.com/ChristopherRabotin/bungiesearch/blob/13768342bc2698b214eb0003c2d113b6e273c30d/bungiesearch/managers.py#L31-L43 |
ChristopherRabotin/bungiesearch | bungiesearch/fields.py | django_field_to_index | def django_field_to_index(field, **attr):
'''
Returns the index field type that would likely be associated with each Django type.
'''
dj_type = field.get_internal_type()
if dj_type in ('DateField', 'DateTimeField'):
return DateField(**attr)
elif dj_type in ('BooleanField', 'NullBoolean... | python | def django_field_to_index(field, **attr):
'''
Returns the index field type that would likely be associated with each Django type.
'''
dj_type = field.get_internal_type()
if dj_type in ('DateField', 'DateTimeField'):
return DateField(**attr)
elif dj_type in ('BooleanField', 'NullBoolean... | [
"def",
"django_field_to_index",
"(",
"field",
",",
"*",
"*",
"attr",
")",
":",
"dj_type",
"=",
"field",
".",
"get_internal_type",
"(",
")",
"if",
"dj_type",
"in",
"(",
"'DateField'",
",",
"'DateTimeField'",
")",
":",
"return",
"DateField",
"(",
"*",
"*",
... | Returns the index field type that would likely be associated with each Django type. | [
"Returns",
"the",
"index",
"field",
"type",
"that",
"would",
"likely",
"be",
"associated",
"with",
"each",
"Django",
"type",
"."
] | train | https://github.com/ChristopherRabotin/bungiesearch/blob/13768342bc2698b214eb0003c2d113b6e273c30d/bungiesearch/fields.py#L145-L165 |
ChristopherRabotin/bungiesearch | bungiesearch/fields.py | AbstractField.value | def value(self, obj):
'''
Computes the value of this field to update the index.
:param obj: object instance, as a dictionary or as a model instance.
'''
if self.template_name:
t = loader.select_template([self.template_name])
return t.render(Context({'objec... | python | def value(self, obj):
'''
Computes the value of this field to update the index.
:param obj: object instance, as a dictionary or as a model instance.
'''
if self.template_name:
t = loader.select_template([self.template_name])
return t.render(Context({'objec... | [
"def",
"value",
"(",
"self",
",",
"obj",
")",
":",
"if",
"self",
".",
"template_name",
":",
"t",
"=",
"loader",
".",
"select_template",
"(",
"[",
"self",
".",
"template_name",
"]",
")",
"return",
"t",
".",
"render",
"(",
"Context",
"(",
"{",
"'object... | Computes the value of this field to update the index.
:param obj: object instance, as a dictionary or as a model instance. | [
"Computes",
"the",
"value",
"of",
"this",
"field",
"to",
"update",
"the",
"index",
".",
":",
"param",
"obj",
":",
"object",
"instance",
"as",
"a",
"dictionary",
"or",
"as",
"a",
"model",
"instance",
"."
] | train | https://github.com/ChristopherRabotin/bungiesearch/blob/13768342bc2698b214eb0003c2d113b6e273c30d/bungiesearch/fields.py#L67-L94 |
ponty/EasyProcess | easyprocess/unicodeutil.py | split_command | def split_command(cmd, posix=None):
'''
- cmd is string list -> nothing to do
- cmd is string -> split it using shlex
:param cmd: string ('ls -l') or list of strings (['ls','-l'])
:rtype: string list
'''
if not isinstance(cmd, string_types):
# cmd is string list
pass
e... | python | def split_command(cmd, posix=None):
'''
- cmd is string list -> nothing to do
- cmd is string -> split it using shlex
:param cmd: string ('ls -l') or list of strings (['ls','-l'])
:rtype: string list
'''
if not isinstance(cmd, string_types):
# cmd is string list
pass
e... | [
"def",
"split_command",
"(",
"cmd",
",",
"posix",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"cmd",
",",
"string_types",
")",
":",
"# cmd is string list",
"pass",
"else",
":",
"if",
"not",
"PY3",
":",
"# cmd is string",
"# The shlex module currentl... | - cmd is string list -> nothing to do
- cmd is string -> split it using shlex
:param cmd: string ('ls -l') or list of strings (['ls','-l'])
:rtype: string list | [
"-",
"cmd",
"is",
"string",
"list",
"-",
">",
"nothing",
"to",
"do",
"-",
"cmd",
"is",
"string",
"-",
">",
"split",
"it",
"using",
"shlex"
] | train | https://github.com/ponty/EasyProcess/blob/81c2923339e09a86b6a2b8c12dc960f1bc67db9c/easyprocess/unicodeutil.py#L20-L47 |
ChristopherRabotin/bungiesearch | bungiesearch/indices.py | ModelIndex.get_mapping | def get_mapping(self, meta_fields=True):
'''
Returns the mapping for the index as a dictionary.
:param meta_fields: Also include elasticsearch meta fields in the dictionary.
:return: a dictionary which can be used to generate the elasticsearch index mapping for this doctype.
'''... | python | def get_mapping(self, meta_fields=True):
'''
Returns the mapping for the index as a dictionary.
:param meta_fields: Also include elasticsearch meta fields in the dictionary.
:return: a dictionary which can be used to generate the elasticsearch index mapping for this doctype.
'''... | [
"def",
"get_mapping",
"(",
"self",
",",
"meta_fields",
"=",
"True",
")",
":",
"return",
"{",
"'properties'",
":",
"dict",
"(",
"(",
"name",
",",
"field",
".",
"json",
"(",
")",
")",
"for",
"name",
",",
"field",
"in",
"iteritems",
"(",
"self",
".",
... | Returns the mapping for the index as a dictionary.
:param meta_fields: Also include elasticsearch meta fields in the dictionary.
:return: a dictionary which can be used to generate the elasticsearch index mapping for this doctype. | [
"Returns",
"the",
"mapping",
"for",
"the",
"index",
"as",
"a",
"dictionary",
"."
] | train | https://github.com/ChristopherRabotin/bungiesearch/blob/13768342bc2698b214eb0003c2d113b6e273c30d/bungiesearch/indices.py#L71-L78 |
ChristopherRabotin/bungiesearch | bungiesearch/indices.py | ModelIndex.collect_analysis | def collect_analysis(self):
'''
:return: a dictionary which is used to get the serialized analyzer definition from the analyzer class.
'''
analysis = {}
for field in self.fields.values():
for analyzer_name in ('analyzer', 'index_analyzer', 'search_analyzer'):
... | python | def collect_analysis(self):
'''
:return: a dictionary which is used to get the serialized analyzer definition from the analyzer class.
'''
analysis = {}
for field in self.fields.values():
for analyzer_name in ('analyzer', 'index_analyzer', 'search_analyzer'):
... | [
"def",
"collect_analysis",
"(",
"self",
")",
":",
"analysis",
"=",
"{",
"}",
"for",
"field",
"in",
"self",
".",
"fields",
".",
"values",
"(",
")",
":",
"for",
"analyzer_name",
"in",
"(",
"'analyzer'",
",",
"'index_analyzer'",
",",
"'search_analyzer'",
")",... | :return: a dictionary which is used to get the serialized analyzer definition from the analyzer class. | [
":",
"return",
":",
"a",
"dictionary",
"which",
"is",
"used",
"to",
"get",
"the",
"serialized",
"analyzer",
"definition",
"from",
"the",
"analyzer",
"class",
"."
] | train | https://github.com/ChristopherRabotin/bungiesearch/blob/13768342bc2698b214eb0003c2d113b6e273c30d/bungiesearch/indices.py#L80-L102 |
ChristopherRabotin/bungiesearch | bungiesearch/indices.py | ModelIndex.serialize_object | def serialize_object(self, obj, obj_pk=None):
'''
Serializes an object for it to be added to the index.
:param obj: Object to be serialized. Optional if obj_pk is passed.
:param obj_pk: Object primary key. Superseded by `obj` if available.
:return: A dictionary representing the ... | python | def serialize_object(self, obj, obj_pk=None):
'''
Serializes an object for it to be added to the index.
:param obj: Object to be serialized. Optional if obj_pk is passed.
:param obj_pk: Object primary key. Superseded by `obj` if available.
:return: A dictionary representing the ... | [
"def",
"serialize_object",
"(",
"self",
",",
"obj",
",",
"obj_pk",
"=",
"None",
")",
":",
"if",
"not",
"obj",
":",
"try",
":",
"# We're using `filter` followed by `values` in order to only fetch the required fields.",
"obj",
"=",
"self",
".",
"model",
".",
"objects"... | Serializes an object for it to be added to the index.
:param obj: Object to be serialized. Optional if obj_pk is passed.
:param obj_pk: Object primary key. Superseded by `obj` if available.
:return: A dictionary representing the object as defined in the mapping. | [
"Serializes",
"an",
"object",
"for",
"it",
"to",
"be",
"added",
"to",
"the",
"index",
"."
] | train | https://github.com/ChristopherRabotin/bungiesearch/blob/13768342bc2698b214eb0003c2d113b6e273c30d/bungiesearch/indices.py#L104-L129 |
ChristopherRabotin/bungiesearch | bungiesearch/indices.py | ModelIndex._get_fields | def _get_fields(self, fields, excludes, hotfixes):
'''
Given any explicit fields to include and fields to exclude, add
additional fields based on the associated model. If the field needs a hotfix, apply it.
'''
final_fields = {}
fields = fields or []
excludes = ex... | python | def _get_fields(self, fields, excludes, hotfixes):
'''
Given any explicit fields to include and fields to exclude, add
additional fields based on the associated model. If the field needs a hotfix, apply it.
'''
final_fields = {}
fields = fields or []
excludes = ex... | [
"def",
"_get_fields",
"(",
"self",
",",
"fields",
",",
"excludes",
",",
"hotfixes",
")",
":",
"final_fields",
"=",
"{",
"}",
"fields",
"=",
"fields",
"or",
"[",
"]",
"excludes",
"=",
"excludes",
"or",
"[",
"]",
"for",
"f",
"in",
"self",
".",
"model",... | Given any explicit fields to include and fields to exclude, add
additional fields based on the associated model. If the field needs a hotfix, apply it. | [
"Given",
"any",
"explicit",
"fields",
"to",
"include",
"and",
"fields",
"to",
"exclude",
"add",
"additional",
"fields",
"based",
"on",
"the",
"associated",
"model",
".",
"If",
"the",
"field",
"needs",
"a",
"hotfix",
"apply",
"it",
"."
] | train | https://github.com/ChristopherRabotin/bungiesearch/blob/13768342bc2698b214eb0003c2d113b6e273c30d/bungiesearch/indices.py#L131-L166 |
cwacek/python-jsonschema-objects | python_jsonschema_objects/wrapper_types.py | ArrayWrapper.validate_items | def validate_items(self):
""" Validates the items in the backing array, including
performing type validation.
Sets the _typed property and clears the dirty flag as a side effect
Returns:
The typed array
"""
logger.debug(fmt("Validating {}", self))
fr... | python | def validate_items(self):
""" Validates the items in the backing array, including
performing type validation.
Sets the _typed property and clears the dirty flag as a side effect
Returns:
The typed array
"""
logger.debug(fmt("Validating {}", self))
fr... | [
"def",
"validate_items",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"fmt",
"(",
"\"Validating {}\"",
",",
"self",
")",
")",
"from",
"python_jsonschema_objects",
"import",
"classbuilder",
"if",
"self",
".",
"__itemtype__",
"is",
"None",
":",
"return",
... | Validates the items in the backing array, including
performing type validation.
Sets the _typed property and clears the dirty flag as a side effect
Returns:
The typed array | [
"Validates",
"the",
"items",
"in",
"the",
"backing",
"array",
"including",
"performing",
"type",
"validation",
"."
] | train | https://github.com/cwacek/python-jsonschema-objects/blob/54c82bfaec9c099c472663742abfc7de373a5e49/python_jsonschema_objects/wrapper_types.py#L149-L221 |
cwacek/python-jsonschema-objects | python_jsonschema_objects/wrapper_types.py | ArrayWrapper.create | def create(name, item_constraint=None, **addl_constraints):
""" Create an array validator based on the passed in constraints.
If item_constraint is a tuple, it is assumed that tuple validation
is being performed. If it is a class or dictionary, list validation
will be performed. Classes... | python | def create(name, item_constraint=None, **addl_constraints):
""" Create an array validator based on the passed in constraints.
If item_constraint is a tuple, it is assumed that tuple validation
is being performed. If it is a class or dictionary, list validation
will be performed. Classes... | [
"def",
"create",
"(",
"name",
",",
"item_constraint",
"=",
"None",
",",
"*",
"*",
"addl_constraints",
")",
":",
"logger",
".",
"debug",
"(",
"fmt",
"(",
"\"Constructing ArrayValidator with {} and {}\"",
",",
"item_constraint",
",",
"addl_constraints",
")",
")",
... | Create an array validator based on the passed in constraints.
If item_constraint is a tuple, it is assumed that tuple validation
is being performed. If it is a class or dictionary, list validation
will be performed. Classes are assumed to be subclasses of ProtocolBase,
while dictionarie... | [
"Create",
"an",
"array",
"validator",
"based",
"on",
"the",
"passed",
"in",
"constraints",
"."
] | train | https://github.com/cwacek/python-jsonschema-objects/blob/54c82bfaec9c099c472663742abfc7de373a5e49/python_jsonschema_objects/wrapper_types.py#L224-L323 |
cwacek/python-jsonschema-objects | python_jsonschema_objects/markdown_support.py | SpecialFencedCodeExtension.extendMarkdown | def extendMarkdown(self, md, md_globals):
""" Add FencedBlockPreprocessor to the Markdown instance. """
md.registerExtension(self)
md.preprocessors.add('fenced_code_block',
SpecialFencePreprocessor(md),
">normalize_whitespace") | python | def extendMarkdown(self, md, md_globals):
""" Add FencedBlockPreprocessor to the Markdown instance. """
md.registerExtension(self)
md.preprocessors.add('fenced_code_block',
SpecialFencePreprocessor(md),
">normalize_whitespace") | [
"def",
"extendMarkdown",
"(",
"self",
",",
"md",
",",
"md_globals",
")",
":",
"md",
".",
"registerExtension",
"(",
"self",
")",
"md",
".",
"preprocessors",
".",
"add",
"(",
"'fenced_code_block'",
",",
"SpecialFencePreprocessor",
"(",
"md",
")",
",",
"\">norm... | Add FencedBlockPreprocessor to the Markdown instance. | [
"Add",
"FencedBlockPreprocessor",
"to",
"the",
"Markdown",
"instance",
"."
] | train | https://github.com/cwacek/python-jsonschema-objects/blob/54c82bfaec9c099c472663742abfc7de373a5e49/python_jsonschema_objects/markdown_support.py#L28-L34 |
cwacek/python-jsonschema-objects | setup.py | parse_requirements | def parse_requirements(path):
"""Rudimentary parser for the `requirements.txt` file
We just want to separate regular packages from links to pass them to the
`install_requires` and `dependency_links` params of the `setup()`
function properly.
"""
try:
print(os.path.join(os.path.dirname(_... | python | def parse_requirements(path):
"""Rudimentary parser for the `requirements.txt` file
We just want to separate regular packages from links to pass them to the
`install_requires` and `dependency_links` params of the `setup()`
function properly.
"""
try:
print(os.path.join(os.path.dirname(_... | [
"def",
"parse_requirements",
"(",
"path",
")",
":",
"try",
":",
"print",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"*",
"path",
".",
"splitlines",
"(",
")",
")",
")",
"requirements",
"="... | Rudimentary parser for the `requirements.txt` file
We just want to separate regular packages from links to pass them to the
`install_requires` and `dependency_links` params of the `setup()`
function properly. | [
"Rudimentary",
"parser",
"for",
"the",
"requirements",
".",
"txt",
"file"
] | train | https://github.com/cwacek/python-jsonschema-objects/blob/54c82bfaec9c099c472663742abfc7de373a5e49/setup.py#L16-L41 |
cwacek/python-jsonschema-objects | python_jsonschema_objects/util.py | propmerge | def propmerge(into, data_from):
""" Merge JSON schema requirements into a dictionary """
newprops = copy.deepcopy(into)
for prop, propval in six.iteritems(data_from):
if prop not in newprops:
newprops[prop] = propval
continue
new_sp = newprops[prop]
for subp... | python | def propmerge(into, data_from):
""" Merge JSON schema requirements into a dictionary """
newprops = copy.deepcopy(into)
for prop, propval in six.iteritems(data_from):
if prop not in newprops:
newprops[prop] = propval
continue
new_sp = newprops[prop]
for subp... | [
"def",
"propmerge",
"(",
"into",
",",
"data_from",
")",
":",
"newprops",
"=",
"copy",
".",
"deepcopy",
"(",
"into",
")",
"for",
"prop",
",",
"propval",
"in",
"six",
".",
"iteritems",
"(",
"data_from",
")",
":",
"if",
"prop",
"not",
"in",
"newprops",
... | Merge JSON schema requirements into a dictionary | [
"Merge",
"JSON",
"schema",
"requirements",
"into",
"a",
"dictionary"
] | train | https://github.com/cwacek/python-jsonschema-objects/blob/54c82bfaec9c099c472663742abfc7de373a5e49/python_jsonschema_objects/util.py#L68-L106 |
cwacek/python-jsonschema-objects | python_jsonschema_objects/classbuilder.py | ProtocolBase.as_dict | def as_dict(self):
""" Return a dictionary containing the current values
of the object.
Returns:
(dict): The object represented as a dictionary
"""
out = {}
for prop in self:
propval = getattr(self, prop)
if hasattr(propval, 'for_json... | python | def as_dict(self):
""" Return a dictionary containing the current values
of the object.
Returns:
(dict): The object represented as a dictionary
"""
out = {}
for prop in self:
propval = getattr(self, prop)
if hasattr(propval, 'for_json... | [
"def",
"as_dict",
"(",
"self",
")",
":",
"out",
"=",
"{",
"}",
"for",
"prop",
"in",
"self",
":",
"propval",
"=",
"getattr",
"(",
"self",
",",
"prop",
")",
"if",
"hasattr",
"(",
"propval",
",",
"'for_json'",
")",
":",
"out",
"[",
"prop",
"]",
"=",... | Return a dictionary containing the current values
of the object.
Returns:
(dict): The object represented as a dictionary | [
"Return",
"a",
"dictionary",
"containing",
"the",
"current",
"values",
"of",
"the",
"object",
"."
] | train | https://github.com/cwacek/python-jsonschema-objects/blob/54c82bfaec9c099c472663742abfc7de373a5e49/python_jsonschema_objects/classbuilder.py#L47-L67 |
cwacek/python-jsonschema-objects | python_jsonschema_objects/classbuilder.py | ProtocolBase.from_json | def from_json(cls, jsonmsg):
""" Create an object directly from a JSON string.
Applies general validation after creating the
object to check whether all required fields are
present.
Args:
jsonmsg (str): An object encoded as a JSON string
Returns:
... | python | def from_json(cls, jsonmsg):
""" Create an object directly from a JSON string.
Applies general validation after creating the
object to check whether all required fields are
present.
Args:
jsonmsg (str): An object encoded as a JSON string
Returns:
... | [
"def",
"from_json",
"(",
"cls",
",",
"jsonmsg",
")",
":",
"import",
"json",
"msg",
"=",
"json",
".",
"loads",
"(",
"jsonmsg",
")",
"obj",
"=",
"cls",
"(",
"*",
"*",
"msg",
")",
"obj",
".",
"validate",
"(",
")",
"return",
"obj"
] | Create an object directly from a JSON string.
Applies general validation after creating the
object to check whether all required fields are
present.
Args:
jsonmsg (str): An object encoded as a JSON string
Returns:
An object of the generated type
... | [
"Create",
"an",
"object",
"directly",
"from",
"a",
"JSON",
"string",
"."
] | train | https://github.com/cwacek/python-jsonschema-objects/blob/54c82bfaec9c099c472663742abfc7de373a5e49/python_jsonschema_objects/classbuilder.py#L96-L117 |
cwacek/python-jsonschema-objects | python_jsonschema_objects/classbuilder.py | ProtocolBase.validate | def validate(self):
""" Applies all defined validation to the current
state of the object, and raises an error if
they are not all met.
Raises:
ValidationError: if validations do not pass
"""
missing = self.missing_property_names()
if len(missing) >... | python | def validate(self):
""" Applies all defined validation to the current
state of the object, and raises an error if
they are not all met.
Raises:
ValidationError: if validations do not pass
"""
missing = self.missing_property_names()
if len(missing) >... | [
"def",
"validate",
"(",
"self",
")",
":",
"missing",
"=",
"self",
".",
"missing_property_names",
"(",
")",
"if",
"len",
"(",
"missing",
")",
">",
"0",
":",
"raise",
"validators",
".",
"ValidationError",
"(",
"\"'{0}' are required attributes for {1}\"",
".",
"f... | Applies all defined validation to the current
state of the object, and raises an error if
they are not all met.
Raises:
ValidationError: if validations do not pass | [
"Applies",
"all",
"defined",
"validation",
"to",
"the",
"current",
"state",
"of",
"the",
"object",
"and",
"raises",
"an",
"error",
"if",
"they",
"are",
"not",
"all",
"met",
"."
] | train | https://github.com/cwacek/python-jsonschema-objects/blob/54c82bfaec9c099c472663742abfc7de373a5e49/python_jsonschema_objects/classbuilder.py#L258-L291 |
cwacek/python-jsonschema-objects | python_jsonschema_objects/classbuilder.py | ProtocolBase.missing_property_names | def missing_property_names(self):
"""
Returns a list of properties which are required and missing.
Properties are excluded from this list if they are allowed to be null.
:return: list of missing properties.
"""
propname = lambda x: self.__prop_names__[x]
missin... | python | def missing_property_names(self):
"""
Returns a list of properties which are required and missing.
Properties are excluded from this list if they are allowed to be null.
:return: list of missing properties.
"""
propname = lambda x: self.__prop_names__[x]
missin... | [
"def",
"missing_property_names",
"(",
"self",
")",
":",
"propname",
"=",
"lambda",
"x",
":",
"self",
".",
"__prop_names__",
"[",
"x",
"]",
"missing",
"=",
"[",
"]",
"for",
"x",
"in",
"self",
".",
"__required__",
":",
"# Allow the null type",
"propinfo",
"=... | Returns a list of properties which are required and missing.
Properties are excluded from this list if they are allowed to be null.
:return: list of missing properties. | [
"Returns",
"a",
"list",
"of",
"properties",
"which",
"are",
"required",
"and",
"missing",
"."
] | train | https://github.com/cwacek/python-jsonschema-objects/blob/54c82bfaec9c099c472663742abfc7de373a5e49/python_jsonschema_objects/classbuilder.py#L293-L327 |
cwacek/python-jsonschema-objects | python_jsonschema_objects/classbuilder.py | ClassBuilder.construct | def construct(self, uri, *args, **kw):
""" Wrapper to debug things """
logger.debug(util.lazy_format("Constructing {0}", uri))
if ('override' not in kw or kw['override'] is False) \
and uri in self.resolved:
logger.debug(util.lazy_format("Using existing {0}", uri))
... | python | def construct(self, uri, *args, **kw):
""" Wrapper to debug things """
logger.debug(util.lazy_format("Constructing {0}", uri))
if ('override' not in kw or kw['override'] is False) \
and uri in self.resolved:
logger.debug(util.lazy_format("Using existing {0}", uri))
... | [
"def",
"construct",
"(",
"self",
",",
"uri",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"logger",
".",
"debug",
"(",
"util",
".",
"lazy_format",
"(",
"\"Constructing {0}\"",
",",
"uri",
")",
")",
"if",
"(",
"'override'",
"not",
"in",
"kw",
"o... | Wrapper to debug things | [
"Wrapper",
"to",
"debug",
"things"
] | train | https://github.com/cwacek/python-jsonschema-objects/blob/54c82bfaec9c099c472663742abfc7de373a5e49/python_jsonschema_objects/classbuilder.py#L413-L424 |
cwacek/python-jsonschema-objects | python_jsonschema_objects/classbuilder.py | ClassBuilder._build_literal | def _build_literal(self, nm, clsdata):
"""@todo: Docstring for _build_literal
:nm: @todo
:clsdata: @todo
:returns: @todo
"""
cls = type(str(nm), tuple((LiteralValue,)), {
'__propinfo__': {
'__literal__': clsdata,
'__title__': clsdata.get('title'),
... | python | def _build_literal(self, nm, clsdata):
"""@todo: Docstring for _build_literal
:nm: @todo
:clsdata: @todo
:returns: @todo
"""
cls = type(str(nm), tuple((LiteralValue,)), {
'__propinfo__': {
'__literal__': clsdata,
'__title__': clsdata.get('title'),
... | [
"def",
"_build_literal",
"(",
"self",
",",
"nm",
",",
"clsdata",
")",
":",
"cls",
"=",
"type",
"(",
"str",
"(",
"nm",
")",
",",
"tuple",
"(",
"(",
"LiteralValue",
",",
")",
")",
",",
"{",
"'__propinfo__'",
":",
"{",
"'__literal__'",
":",
"clsdata",
... | @todo: Docstring for _build_literal
:nm: @todo
:clsdata: @todo
:returns: @todo | [
"@todo",
":",
"Docstring",
"for",
"_build_literal"
] | train | https://github.com/cwacek/python-jsonschema-objects/blob/54c82bfaec9c099c472663742abfc7de373a5e49/python_jsonschema_objects/classbuilder.py#L540-L555 |
cwacek/python-jsonschema-objects | python_jsonschema_objects/classbuilder.py | ClassBuilder._build_object | def _build_object(self, nm, clsdata, parents,**kw):
logger.debug(util.lazy_format("Building object {0}", nm))
# To support circular references, we tag objects that we're
# currently building as "under construction"
self.under_construction.add(nm)
props = {}
defaults = s... | python | def _build_object(self, nm, clsdata, parents,**kw):
logger.debug(util.lazy_format("Building object {0}", nm))
# To support circular references, we tag objects that we're
# currently building as "under construction"
self.under_construction.add(nm)
props = {}
defaults = s... | [
"def",
"_build_object",
"(",
"self",
",",
"nm",
",",
"clsdata",
",",
"parents",
",",
"*",
"*",
"kw",
")",
":",
"logger",
".",
"debug",
"(",
"util",
".",
"lazy_format",
"(",
"\"Building object {0}\"",
",",
"nm",
")",
")",
"# To support circular references, we... | If this object itself has a 'oneOf' designation, then
make the validation 'type' the list of potential objects. | [
"If",
"this",
"object",
"itself",
"has",
"a",
"oneOf",
"designation",
"then",
"make",
"the",
"validation",
"type",
"the",
"list",
"of",
"potential",
"objects",
"."
] | train | https://github.com/cwacek/python-jsonschema-objects/blob/54c82bfaec9c099c472663742abfc7de373a5e49/python_jsonschema_objects/classbuilder.py#L557-L736 |
cwacek/python-jsonschema-objects | python_jsonschema_objects/__init__.py | ObjectBuilder.build_classes | def build_classes(self,strict=False, named_only=False, standardize_names=True):
"""
Build all of the classes named in the JSONSchema.
Class names will be transformed using inflection by default, so names
with spaces in the schema will be camelcased, while names without
spaces wi... | python | def build_classes(self,strict=False, named_only=False, standardize_names=True):
"""
Build all of the classes named in the JSONSchema.
Class names will be transformed using inflection by default, so names
with spaces in the schema will be camelcased, while names without
spaces wi... | [
"def",
"build_classes",
"(",
"self",
",",
"strict",
"=",
"False",
",",
"named_only",
"=",
"False",
",",
"standardize_names",
"=",
"True",
")",
":",
"kw",
"=",
"{",
"\"strict\"",
":",
"strict",
"}",
"builder",
"=",
"classbuilder",
".",
"ClassBuilder",
"(",
... | Build all of the classes named in the JSONSchema.
Class names will be transformed using inflection by default, so names
with spaces in the schema will be camelcased, while names without
spaces will have internal capitalization dropped. Thus "Home Address"
becomes "HomeAddress", while "H... | [
"Build",
"all",
"of",
"the",
"classes",
"named",
"in",
"the",
"JSONSchema",
"."
] | train | https://github.com/cwacek/python-jsonschema-objects/blob/54c82bfaec9c099c472663742abfc7de373a5e49/python_jsonschema_objects/__init__.py#L95-L145 |
pytroll/python-geotiepoints | geotiepoints/basic_interpolator.py | BasicSatelliteInterpolator._interp | def _interp(self, data):
"""The interpolation method implemented here is a kind of a billinear
interpolation. The input *data* field is first interpolated along the
rows and subsequently along its columns.
The final size of the interpolated *data* field is determined by the
la... | python | def _interp(self, data):
"""The interpolation method implemented here is a kind of a billinear
interpolation. The input *data* field is first interpolated along the
rows and subsequently along its columns.
The final size of the interpolated *data* field is determined by the
la... | [
"def",
"_interp",
"(",
"self",
",",
"data",
")",
":",
"row_interpol_data",
"=",
"self",
".",
"_interp_axis",
"(",
"data",
",",
"0",
")",
"interpol_data",
"=",
"self",
".",
"_interp_axis",
"(",
"row_interpol_data",
",",
"1",
")",
"return",
"interpol_data"
] | The interpolation method implemented here is a kind of a billinear
interpolation. The input *data* field is first interpolated along the
rows and subsequently along its columns.
The final size of the interpolated *data* field is determined by the
last indices in self.row_indices and s... | [
"The",
"interpolation",
"method",
"implemented",
"here",
"is",
"a",
"kind",
"of",
"a",
"billinear",
"interpolation",
".",
"The",
"input",
"*",
"data",
"*",
"field",
"is",
"first",
"interpolated",
"along",
"the",
"rows",
"and",
"subsequently",
"along",
"its",
... | train | https://github.com/pytroll/python-geotiepoints/blob/7c5cc8a887f8534cc2839c716c2c560aeaf77659/geotiepoints/basic_interpolator.py#L29-L40 |
pytroll/python-geotiepoints | geotiepoints/basic_interpolator.py | BasicSatelliteInterpolator._interp_axis | def _interp_axis(self, data, axis):
"""The *data* field contains the data to be interpolated. It is
expected that values reach out to the *data* boundaries.
With *axis*=0 this method interpolates along rows and *axis*=1 it
interpolates along colums.
For column mode the *data* in... | python | def _interp_axis(self, data, axis):
"""The *data* field contains the data to be interpolated. It is
expected that values reach out to the *data* boundaries.
With *axis*=0 this method interpolates along rows and *axis*=1 it
interpolates along colums.
For column mode the *data* in... | [
"def",
"_interp_axis",
"(",
"self",
",",
"data",
",",
"axis",
")",
":",
"if",
"axis",
"==",
"0",
":",
"return",
"self",
".",
"_pandas_interp",
"(",
"data",
",",
"self",
".",
"row_indices",
")",
"if",
"axis",
"==",
"1",
":",
"data_transposed",
"=",
"d... | The *data* field contains the data to be interpolated. It is
expected that values reach out to the *data* boundaries.
With *axis*=0 this method interpolates along rows and *axis*=1 it
interpolates along colums.
For column mode the *data* input is transposed before interpolation
... | [
"The",
"*",
"data",
"*",
"field",
"contains",
"the",
"data",
"to",
"be",
"interpolated",
".",
"It",
"is",
"expected",
"that",
"values",
"reach",
"out",
"to",
"the",
"*",
"data",
"*",
"boundaries",
".",
"With",
"*",
"axis",
"*",
"=",
"0",
"this",
"met... | train | https://github.com/pytroll/python-geotiepoints/blob/7c5cc8a887f8534cc2839c716c2c560aeaf77659/geotiepoints/basic_interpolator.py#L44-L62 |
pytroll/python-geotiepoints | geotiepoints/basic_interpolator.py | BasicSatelliteInterpolator._pandas_interp | def _pandas_interp(self, data, indices):
"""The actual transformation based on the following stackoverflow
entry: http://stackoverflow.com/a/10465162
"""
new_index = np.arange(indices[-1] + 1)
data_frame = DataFrame(data, index=indices)
data_frame_reindexed = data_frame... | python | def _pandas_interp(self, data, indices):
"""The actual transformation based on the following stackoverflow
entry: http://stackoverflow.com/a/10465162
"""
new_index = np.arange(indices[-1] + 1)
data_frame = DataFrame(data, index=indices)
data_frame_reindexed = data_frame... | [
"def",
"_pandas_interp",
"(",
"self",
",",
"data",
",",
"indices",
")",
":",
"new_index",
"=",
"np",
".",
"arange",
"(",
"indices",
"[",
"-",
"1",
"]",
"+",
"1",
")",
"data_frame",
"=",
"DataFrame",
"(",
"data",
",",
"index",
"=",
"indices",
")",
"... | The actual transformation based on the following stackoverflow
entry: http://stackoverflow.com/a/10465162 | [
"The",
"actual",
"transformation",
"based",
"on",
"the",
"following",
"stackoverflow",
"entry",
":",
"http",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"a",
"/",
"10465162"
] | train | https://github.com/pytroll/python-geotiepoints/blob/7c5cc8a887f8534cc2839c716c2c560aeaf77659/geotiepoints/basic_interpolator.py#L65-L79 |
pytroll/python-geotiepoints | geotiepoints/basic_interpolator.py | BasicSatelliteInterpolator.interpolate | def interpolate(self):
"""Do the interpolation and return resulting longitudes and latitudes.
"""
self.latitude = self._interp(self.lat_tiepoint)
self.longitude = self._interp(self.lon_tiepoint)
return self.latitude, self.longitude | python | def interpolate(self):
"""Do the interpolation and return resulting longitudes and latitudes.
"""
self.latitude = self._interp(self.lat_tiepoint)
self.longitude = self._interp(self.lon_tiepoint)
return self.latitude, self.longitude | [
"def",
"interpolate",
"(",
"self",
")",
":",
"self",
".",
"latitude",
"=",
"self",
".",
"_interp",
"(",
"self",
".",
"lat_tiepoint",
")",
"self",
".",
"longitude",
"=",
"self",
".",
"_interp",
"(",
"self",
".",
"lon_tiepoint",
")",
"return",
"self",
".... | Do the interpolation and return resulting longitudes and latitudes. | [
"Do",
"the",
"interpolation",
"and",
"return",
"resulting",
"longitudes",
"and",
"latitudes",
"."
] | train | https://github.com/pytroll/python-geotiepoints/blob/7c5cc8a887f8534cc2839c716c2c560aeaf77659/geotiepoints/basic_interpolator.py#L82-L88 |
EliotBerriot/lifter | lifter/backends/python.py | DummyStore._execute | def _execute(self, query, model, adapter, raw=False):
"""
We have to override this because in some situation
(such as with Filebackend, or any dummy backend)
we have to parse / adapt results *before* when can execute the query
"""
values = self.load(model, adapter)
... | python | def _execute(self, query, model, adapter, raw=False):
"""
We have to override this because in some situation
(such as with Filebackend, or any dummy backend)
we have to parse / adapt results *before* when can execute the query
"""
values = self.load(model, adapter)
... | [
"def",
"_execute",
"(",
"self",
",",
"query",
",",
"model",
",",
"adapter",
",",
"raw",
"=",
"False",
")",
":",
"values",
"=",
"self",
".",
"load",
"(",
"model",
",",
"adapter",
")",
"return",
"IterableStore",
"(",
"values",
"=",
"values",
")",
".",
... | We have to override this because in some situation
(such as with Filebackend, or any dummy backend)
we have to parse / adapt results *before* when can execute the query | [
"We",
"have",
"to",
"override",
"this",
"because",
"in",
"some",
"situation",
"(",
"such",
"as",
"with",
"Filebackend",
"or",
"any",
"dummy",
"backend",
")",
"we",
"have",
"to",
"parse",
"/",
"adapt",
"results",
"*",
"before",
"*",
"when",
"can",
"execut... | train | https://github.com/EliotBerriot/lifter/blob/9b4394b476cddd952b2af9540affc03f2977163d/lifter/backends/python.py#L177-L184 |
EliotBerriot/lifter | lifter/caches.py | Cache.get | def get(self, key, default=None, reraise=False):
"""
Get the given key from the cache, if present.
A default value can be provided in case the requested key is not present,
otherwise, None will be returned.
:param key: the key to query
:type key: str
:param defau... | python | def get(self, key, default=None, reraise=False):
"""
Get the given key from the cache, if present.
A default value can be provided in case the requested key is not present,
otherwise, None will be returned.
:param key: the key to query
:type key: str
:param defau... | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
",",
"reraise",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"enabled",
":",
"if",
"reraise",
":",
"raise",
"exceptions",
".",
"DisabledCache",
"(",
")",
"return",
"default",
"t... | Get the given key from the cache, if present.
A default value can be provided in case the requested key is not present,
otherwise, None will be returned.
:param key: the key to query
:type key: str
:param default: the value to return if the key does not exist in cache
:p... | [
"Get",
"the",
"given",
"key",
"from",
"the",
"cache",
"if",
"present",
".",
"A",
"default",
"value",
"can",
"be",
"provided",
"in",
"case",
"the",
"requested",
"key",
"is",
"not",
"present",
"otherwise",
"None",
"will",
"be",
"returned",
"."
] | train | https://github.com/EliotBerriot/lifter/blob/9b4394b476cddd952b2af9540affc03f2977163d/lifter/caches.py#L30-L68 |
EliotBerriot/lifter | lifter/caches.py | Cache.set | def set(self, key, value, timeout=NotSet):
"""
Set the given key to the given value in the cache.
A timeout may be provided, otherwise, the :py:attr:`Cache.default_timeout`
will be used.
:param key: the key to which the value will be bound
:type key: str
:param v... | python | def set(self, key, value, timeout=NotSet):
"""
Set the given key to the given value in the cache.
A timeout may be provided, otherwise, the :py:attr:`Cache.default_timeout`
will be used.
:param key: the key to which the value will be bound
:type key: str
:param v... | [
"def",
"set",
"(",
"self",
",",
"key",
",",
"value",
",",
"timeout",
"=",
"NotSet",
")",
":",
"if",
"not",
"self",
".",
"enabled",
":",
"return",
"if",
"hasattr",
"(",
"value",
",",
"'__call__'",
")",
":",
"value",
"=",
"value",
"(",
")",
"if",
"... | Set the given key to the given value in the cache.
A timeout may be provided, otherwise, the :py:attr:`Cache.default_timeout`
will be used.
:param key: the key to which the value will be bound
:type key: str
:param value: the value to store in the cache
:param timeout: t... | [
"Set",
"the",
"given",
"key",
"to",
"the",
"given",
"value",
"in",
"the",
"cache",
".",
"A",
"timeout",
"may",
"be",
"provided",
"otherwise",
"the",
":",
"py",
":",
"attr",
":",
"Cache",
".",
"default_timeout",
"will",
"be",
"used",
"."
] | train | https://github.com/EliotBerriot/lifter/blob/9b4394b476cddd952b2af9540affc03f2977163d/lifter/caches.py#L70-L97 |
EliotBerriot/lifter | lifter/utils.py | resolve_attr | def resolve_attr(obj, name):
"""A custom attrgetter that operates both on dictionaries and objects"""
# TODO: setup some hinting, so we can go directly to the correct
# Maybe it's a dict ? Let's try dict lookup, it's the fastest
try:
return obj[name]
except TypeError:
pass
except... | python | def resolve_attr(obj, name):
"""A custom attrgetter that operates both on dictionaries and objects"""
# TODO: setup some hinting, so we can go directly to the correct
# Maybe it's a dict ? Let's try dict lookup, it's the fastest
try:
return obj[name]
except TypeError:
pass
except... | [
"def",
"resolve_attr",
"(",
"obj",
",",
"name",
")",
":",
"# TODO: setup some hinting, so we can go directly to the correct",
"# Maybe it's a dict ? Let's try dict lookup, it's the fastest",
"try",
":",
"return",
"obj",
"[",
"name",
"]",
"except",
"TypeError",
":",
"pass",
... | A custom attrgetter that operates both on dictionaries and objects | [
"A",
"custom",
"attrgetter",
"that",
"operates",
"both",
"on",
"dictionaries",
"and",
"objects"
] | train | https://github.com/EliotBerriot/lifter/blob/9b4394b476cddd952b2af9540affc03f2977163d/lifter/utils.py#L56-L84 |
EliotBerriot/lifter | lifter/utils.py | unique_everseen | def unique_everseen(seq):
"""Solution found here : http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order"""
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))] | python | def unique_everseen(seq):
"""Solution found here : http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order"""
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))] | [
"def",
"unique_everseen",
"(",
"seq",
")",
":",
"seen",
"=",
"set",
"(",
")",
"seen_add",
"=",
"seen",
".",
"add",
"return",
"[",
"x",
"for",
"x",
"in",
"seq",
"if",
"not",
"(",
"x",
"in",
"seen",
"or",
"seen_add",
"(",
"x",
")",
")",
"]"
] | Solution found here : http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order | [
"Solution",
"found",
"here",
":",
"http",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"questions",
"/",
"480214",
"/",
"how",
"-",
"do",
"-",
"you",
"-",
"remove",
"-",
"duplicates",
"-",
"from",
"-",
"a",
"-",
"list",
"-",
"in",
"-",
"python",
"-... | train | https://github.com/EliotBerriot/lifter/blob/9b4394b476cddd952b2af9540affc03f2977163d/lifter/utils.py#L87-L91 |
EliotBerriot/lifter | lifter/query.py | QuerySet.hints | def hints(self, **kwargs):
"""
Use this method to update hints value of the underlying query
example: queryset.hints(permissive=False)
"""
new_query = self.query.clone()
new_query.hints.update(kwargs)
return self._clone(query=new_query) | python | def hints(self, **kwargs):
"""
Use this method to update hints value of the underlying query
example: queryset.hints(permissive=False)
"""
new_query = self.query.clone()
new_query.hints.update(kwargs)
return self._clone(query=new_query) | [
"def",
"hints",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"new_query",
"=",
"self",
".",
"query",
".",
"clone",
"(",
")",
"new_query",
".",
"hints",
".",
"update",
"(",
"kwargs",
")",
"return",
"self",
".",
"_clone",
"(",
"query",
"=",
"new_q... | Use this method to update hints value of the underlying query
example: queryset.hints(permissive=False) | [
"Use",
"this",
"method",
"to",
"update",
"hints",
"value",
"of",
"the",
"underlying",
"query",
"example",
":",
"queryset",
".",
"hints",
"(",
"permissive",
"=",
"False",
")"
] | train | https://github.com/EliotBerriot/lifter/blob/9b4394b476cddd952b2af9540affc03f2977163d/lifter/query.py#L280-L288 |
EliotBerriot/lifter | lifter/query.py | QuerySet.build_filter_from_kwargs | def build_filter_from_kwargs(self, **kwargs):
"""Convert django-s like lookup to SQLAlchemy ones"""
query = None
for path_to_convert, value in kwargs.items():
path_parts = path_to_convert.split('__')
lookup_class = None
try:
# We check if the ... | python | def build_filter_from_kwargs(self, **kwargs):
"""Convert django-s like lookup to SQLAlchemy ones"""
query = None
for path_to_convert, value in kwargs.items():
path_parts = path_to_convert.split('__')
lookup_class = None
try:
# We check if the ... | [
"def",
"build_filter_from_kwargs",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"query",
"=",
"None",
"for",
"path_to_convert",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"path_parts",
"=",
"path_to_convert",
".",
"split",
"(",
"'__'",
... | Convert django-s like lookup to SQLAlchemy ones | [
"Convert",
"django",
"-",
"s",
"like",
"lookup",
"to",
"SQLAlchemy",
"ones"
] | train | https://github.com/EliotBerriot/lifter/blob/9b4394b476cddd952b2af9540affc03f2977163d/lifter/query.py#L345-L369 |
EliotBerriot/lifter | lifter/query.py | QuerySet.locally | def locally(self):
"""
Will execute the current queryset and pass it to the python backend
so user can run query on the local dataset (instead of contacting the store)
"""
from .backends import python
from . import models
store = python.IterableStore(values=self... | python | def locally(self):
"""
Will execute the current queryset and pass it to the python backend
so user can run query on the local dataset (instead of contacting the store)
"""
from .backends import python
from . import models
store = python.IterableStore(values=self... | [
"def",
"locally",
"(",
"self",
")",
":",
"from",
".",
"backends",
"import",
"python",
"from",
".",
"import",
"models",
"store",
"=",
"python",
".",
"IterableStore",
"(",
"values",
"=",
"self",
")",
"return",
"store",
".",
"query",
"(",
"self",
".",
"ma... | Will execute the current queryset and pass it to the python backend
so user can run query on the local dataset (instead of contacting the store) | [
"Will",
"execute",
"the",
"current",
"queryset",
"and",
"pass",
"it",
"to",
"the",
"python",
"backend",
"so",
"user",
"can",
"run",
"query",
"on",
"the",
"local",
"dataset",
"(",
"instead",
"of",
"contacting",
"the",
"store",
")"
] | train | https://github.com/EliotBerriot/lifter/blob/9b4394b476cddd952b2af9540affc03f2977163d/lifter/query.py#L512-L522 |
pytroll/python-geotiepoints | geotiepoints/__init__.py | get_scene_splits | def get_scene_splits(nlines_swath, nlines_scan, n_cpus):
"""Calculate the line numbers where the swath will be split in smaller
granules for parallel processing"""
nscans = nlines_swath // nlines_scan
if nscans < n_cpus:
nscans_subscene = 1
else:
nscans_subscene = nscans // n_cpus
... | python | def get_scene_splits(nlines_swath, nlines_scan, n_cpus):
"""Calculate the line numbers where the swath will be split in smaller
granules for parallel processing"""
nscans = nlines_swath // nlines_scan
if nscans < n_cpus:
nscans_subscene = 1
else:
nscans_subscene = nscans // n_cpus
... | [
"def",
"get_scene_splits",
"(",
"nlines_swath",
",",
"nlines_scan",
",",
"n_cpus",
")",
":",
"nscans",
"=",
"nlines_swath",
"//",
"nlines_scan",
"if",
"nscans",
"<",
"n_cpus",
":",
"nscans_subscene",
"=",
"1",
"else",
":",
"nscans_subscene",
"=",
"nscans",
"//... | Calculate the line numbers where the swath will be split in smaller
granules for parallel processing | [
"Calculate",
"the",
"line",
"numbers",
"where",
"the",
"swath",
"will",
"be",
"split",
"in",
"smaller",
"granules",
"for",
"parallel",
"processing"
] | train | https://github.com/pytroll/python-geotiepoints/blob/7c5cc8a887f8534cc2839c716c2c560aeaf77659/geotiepoints/__init__.py#L40-L51 |
pytroll/python-geotiepoints | geotiepoints/__init__.py | metop20kmto1km | def metop20kmto1km(lons20km, lats20km):
"""Getting 1km geolocation for metop avhrr from 20km tiepoints.
"""
cols20km = np.array([0] + list(range(4, 2048, 20)) + [2047])
cols1km = np.arange(2048)
lines = lons20km.shape[0]
rows20km = np.arange(lines)
rows1km = np.arange(lines)
along_track... | python | def metop20kmto1km(lons20km, lats20km):
"""Getting 1km geolocation for metop avhrr from 20km tiepoints.
"""
cols20km = np.array([0] + list(range(4, 2048, 20)) + [2047])
cols1km = np.arange(2048)
lines = lons20km.shape[0]
rows20km = np.arange(lines)
rows1km = np.arange(lines)
along_track... | [
"def",
"metop20kmto1km",
"(",
"lons20km",
",",
"lats20km",
")",
":",
"cols20km",
"=",
"np",
".",
"array",
"(",
"[",
"0",
"]",
"+",
"list",
"(",
"range",
"(",
"4",
",",
"2048",
",",
"20",
")",
")",
"+",
"[",
"2047",
"]",
")",
"cols1km",
"=",
"np... | Getting 1km geolocation for metop avhrr from 20km tiepoints. | [
"Getting",
"1km",
"geolocation",
"for",
"metop",
"avhrr",
"from",
"20km",
"tiepoints",
"."
] | train | https://github.com/pytroll/python-geotiepoints/blob/7c5cc8a887f8534cc2839c716c2c560aeaf77659/geotiepoints/__init__.py#L54-L71 |
pytroll/python-geotiepoints | geotiepoints/__init__.py | modis5kmto1km | def modis5kmto1km(lons5km, lats5km):
"""Getting 1km geolocation for modis from 5km tiepoints.
http://www.icare.univ-lille1.fr/tutorials/MODIS_geolocation
"""
cols5km = np.arange(2, 1354, 5) / 5.0
cols1km = np.arange(1354) / 5.0
lines = lons5km.shape[0] * 5
rows5km = np.arange(2, lines, 5) /... | python | def modis5kmto1km(lons5km, lats5km):
"""Getting 1km geolocation for modis from 5km tiepoints.
http://www.icare.univ-lille1.fr/tutorials/MODIS_geolocation
"""
cols5km = np.arange(2, 1354, 5) / 5.0
cols1km = np.arange(1354) / 5.0
lines = lons5km.shape[0] * 5
rows5km = np.arange(2, lines, 5) /... | [
"def",
"modis5kmto1km",
"(",
"lons5km",
",",
"lats5km",
")",
":",
"cols5km",
"=",
"np",
".",
"arange",
"(",
"2",
",",
"1354",
",",
"5",
")",
"/",
"5.0",
"cols1km",
"=",
"np",
".",
"arange",
"(",
"1354",
")",
"/",
"5.0",
"lines",
"=",
"lons5km",
"... | Getting 1km geolocation for modis from 5km tiepoints.
http://www.icare.univ-lille1.fr/tutorials/MODIS_geolocation | [
"Getting",
"1km",
"geolocation",
"for",
"modis",
"from",
"5km",
"tiepoints",
"."
] | train | https://github.com/pytroll/python-geotiepoints/blob/7c5cc8a887f8534cc2839c716c2c560aeaf77659/geotiepoints/__init__.py#L74-L96 |
pytroll/python-geotiepoints | geotiepoints/__init__.py | _multi | def _multi(fun, lons, lats, chunk_size, cores=1):
"""Work on multiple cores.
"""
pool = Pool(processes=cores)
splits = get_scene_splits(lons.shape[0], chunk_size, cores)
lons_parts = np.vsplit(lons, splits)
lats_parts = np.vsplit(lats, splits)
results = [pool.apply_async(fun,
... | python | def _multi(fun, lons, lats, chunk_size, cores=1):
"""Work on multiple cores.
"""
pool = Pool(processes=cores)
splits = get_scene_splits(lons.shape[0], chunk_size, cores)
lons_parts = np.vsplit(lons, splits)
lats_parts = np.vsplit(lats, splits)
results = [pool.apply_async(fun,
... | [
"def",
"_multi",
"(",
"fun",
",",
"lons",
",",
"lats",
",",
"chunk_size",
",",
"cores",
"=",
"1",
")",
":",
"pool",
"=",
"Pool",
"(",
"processes",
"=",
"cores",
")",
"splits",
"=",
"get_scene_splits",
"(",
"lons",
".",
"shape",
"[",
"0",
"]",
",",
... | Work on multiple cores. | [
"Work",
"on",
"multiple",
"cores",
"."
] | train | https://github.com/pytroll/python-geotiepoints/blob/7c5cc8a887f8534cc2839c716c2c560aeaf77659/geotiepoints/__init__.py#L99-L119 |
pytroll/python-geotiepoints | geotiepoints/__init__.py | modis1kmto500m | def modis1kmto500m(lons1km, lats1km, cores=1):
"""Getting 500m geolocation for modis from 1km tiepoints.
http://www.icare.univ-lille1.fr/tutorials/MODIS_geolocation
"""
if cores > 1:
return _multi(modis1kmto500m, lons1km, lats1km, 10, cores)
cols1km = np.arange(1354)
cols500m = np.aran... | python | def modis1kmto500m(lons1km, lats1km, cores=1):
"""Getting 500m geolocation for modis from 1km tiepoints.
http://www.icare.univ-lille1.fr/tutorials/MODIS_geolocation
"""
if cores > 1:
return _multi(modis1kmto500m, lons1km, lats1km, 10, cores)
cols1km = np.arange(1354)
cols500m = np.aran... | [
"def",
"modis1kmto500m",
"(",
"lons1km",
",",
"lats1km",
",",
"cores",
"=",
"1",
")",
":",
"if",
"cores",
">",
"1",
":",
"return",
"_multi",
"(",
"modis1kmto500m",
",",
"lons1km",
",",
"lats1km",
",",
"10",
",",
"cores",
")",
"cols1km",
"=",
"np",
".... | Getting 500m geolocation for modis from 1km tiepoints.
http://www.icare.univ-lille1.fr/tutorials/MODIS_geolocation | [
"Getting",
"500m",
"geolocation",
"for",
"modis",
"from",
"1km",
"tiepoints",
"."
] | train | https://github.com/pytroll/python-geotiepoints/blob/7c5cc8a887f8534cc2839c716c2c560aeaf77659/geotiepoints/__init__.py#L122-L147 |
pytroll/python-geotiepoints | geotiepoints/__init__.py | modis1kmto250m | def modis1kmto250m(lons1km, lats1km, cores=1):
"""Getting 250m geolocation for modis from 1km tiepoints.
http://www.icare.univ-lille1.fr/tutorials/MODIS_geolocation
"""
if cores > 1:
return _multi(modis1kmto250m, lons1km, lats1km, 10, cores)
cols1km = np.arange(1354)
cols250m = np.aran... | python | def modis1kmto250m(lons1km, lats1km, cores=1):
"""Getting 250m geolocation for modis from 1km tiepoints.
http://www.icare.univ-lille1.fr/tutorials/MODIS_geolocation
"""
if cores > 1:
return _multi(modis1kmto250m, lons1km, lats1km, 10, cores)
cols1km = np.arange(1354)
cols250m = np.aran... | [
"def",
"modis1kmto250m",
"(",
"lons1km",
",",
"lats1km",
",",
"cores",
"=",
"1",
")",
":",
"if",
"cores",
">",
"1",
":",
"return",
"_multi",
"(",
"modis1kmto250m",
",",
"lons1km",
",",
"lats1km",
",",
"10",
",",
"cores",
")",
"cols1km",
"=",
"np",
".... | Getting 250m geolocation for modis from 1km tiepoints.
http://www.icare.univ-lille1.fr/tutorials/MODIS_geolocation | [
"Getting",
"250m",
"geolocation",
"for",
"modis",
"from",
"1km",
"tiepoints",
"."
] | train | https://github.com/pytroll/python-geotiepoints/blob/7c5cc8a887f8534cc2839c716c2c560aeaf77659/geotiepoints/__init__.py#L150-L177 |
pytroll/python-geotiepoints | geotiepoints/interpolator.py | generic_modis5kmto1km | def generic_modis5kmto1km(*data5km):
"""Getting 1km data for modis from 5km tiepoints.
"""
cols5km = np.arange(2, 1354, 5)
cols1km = np.arange(1354)
lines = data5km[0].shape[0] * 5
rows5km = np.arange(2, lines, 5)
rows1km = np.arange(lines)
along_track_order = 1
cross_track_order = ... | python | def generic_modis5kmto1km(*data5km):
"""Getting 1km data for modis from 5km tiepoints.
"""
cols5km = np.arange(2, 1354, 5)
cols1km = np.arange(1354)
lines = data5km[0].shape[0] * 5
rows5km = np.arange(2, lines, 5)
rows1km = np.arange(lines)
along_track_order = 1
cross_track_order = ... | [
"def",
"generic_modis5kmto1km",
"(",
"*",
"data5km",
")",
":",
"cols5km",
"=",
"np",
".",
"arange",
"(",
"2",
",",
"1354",
",",
"5",
")",
"cols1km",
"=",
"np",
".",
"arange",
"(",
"1354",
")",
"lines",
"=",
"data5km",
"[",
"0",
"]",
".",
"shape",
... | Getting 1km data for modis from 5km tiepoints. | [
"Getting",
"1km",
"data",
"for",
"modis",
"from",
"5km",
"tiepoints",
"."
] | train | https://github.com/pytroll/python-geotiepoints/blob/7c5cc8a887f8534cc2839c716c2c560aeaf77659/geotiepoints/interpolator.py#L29-L48 |
pytroll/python-geotiepoints | geotiepoints/interpolator.py | Interpolator.fill_borders | def fill_borders(self, *args):
"""Extrapolate tiepoint lons and lats to fill in the border of the
chunks.
"""
to_run = []
cases = {"y": self._fill_row_borders,
"x": self._fill_col_borders}
for dim in args:
try:
to_run.append(c... | python | def fill_borders(self, *args):
"""Extrapolate tiepoint lons and lats to fill in the border of the
chunks.
"""
to_run = []
cases = {"y": self._fill_row_borders,
"x": self._fill_col_borders}
for dim in args:
try:
to_run.append(c... | [
"def",
"fill_borders",
"(",
"self",
",",
"*",
"args",
")",
":",
"to_run",
"=",
"[",
"]",
"cases",
"=",
"{",
"\"y\"",
":",
"self",
".",
"_fill_row_borders",
",",
"\"x\"",
":",
"self",
".",
"_fill_col_borders",
"}",
"for",
"dim",
"in",
"args",
":",
"tr... | Extrapolate tiepoint lons and lats to fill in the border of the
chunks. | [
"Extrapolate",
"tiepoint",
"lons",
"and",
"lats",
"to",
"fill",
"in",
"the",
"border",
"of",
"the",
"chunks",
"."
] | train | https://github.com/pytroll/python-geotiepoints/blob/7c5cc8a887f8534cc2839c716c2c560aeaf77659/geotiepoints/interpolator.py#L113-L128 |
pytroll/python-geotiepoints | geotiepoints/interpolator.py | Interpolator._extrapolate_cols | def _extrapolate_cols(self, data, first=True, last=True):
"""Extrapolate the column of data, to get the first and last together
with the data.
"""
if first:
pos = self.col_indices[:2]
first_column = _linear_extrapolate(pos,
... | python | def _extrapolate_cols(self, data, first=True, last=True):
"""Extrapolate the column of data, to get the first and last together
with the data.
"""
if first:
pos = self.col_indices[:2]
first_column = _linear_extrapolate(pos,
... | [
"def",
"_extrapolate_cols",
"(",
"self",
",",
"data",
",",
"first",
"=",
"True",
",",
"last",
"=",
"True",
")",
":",
"if",
"first",
":",
"pos",
"=",
"self",
".",
"col_indices",
"[",
":",
"2",
"]",
"first_column",
"=",
"_linear_extrapolate",
"(",
"pos",... | Extrapolate the column of data, to get the first and last together
with the data. | [
"Extrapolate",
"the",
"column",
"of",
"data",
"to",
"get",
"the",
"first",
"and",
"last",
"together",
"with",
"the",
"data",
"."
] | train | https://github.com/pytroll/python-geotiepoints/blob/7c5cc8a887f8534cc2839c716c2c560aeaf77659/geotiepoints/interpolator.py#L130-L158 |
pytroll/python-geotiepoints | geotiepoints/interpolator.py | Interpolator._fill_col_borders | def _fill_col_borders(self):
"""Add the first and last column to the data by extrapolation.
"""
first = True
last = True
if self.col_indices[0] == self.hcol_indices[0]:
first = False
if self.col_indices[-1] == self.hcol_indices[-1]:
last = False
... | python | def _fill_col_borders(self):
"""Add the first and last column to the data by extrapolation.
"""
first = True
last = True
if self.col_indices[0] == self.hcol_indices[0]:
first = False
if self.col_indices[-1] == self.hcol_indices[-1]:
last = False
... | [
"def",
"_fill_col_borders",
"(",
"self",
")",
":",
"first",
"=",
"True",
"last",
"=",
"True",
"if",
"self",
".",
"col_indices",
"[",
"0",
"]",
"==",
"self",
".",
"hcol_indices",
"[",
"0",
"]",
":",
"first",
"=",
"False",
"if",
"self",
".",
"col_indic... | Add the first and last column to the data by extrapolation. | [
"Add",
"the",
"first",
"and",
"last",
"column",
"to",
"the",
"data",
"by",
"extrapolation",
"."
] | train | https://github.com/pytroll/python-geotiepoints/blob/7c5cc8a887f8534cc2839c716c2c560aeaf77659/geotiepoints/interpolator.py#L160-L182 |
pytroll/python-geotiepoints | geotiepoints/interpolator.py | Interpolator._extrapolate_rows | def _extrapolate_rows(self, data, row_indices, first_index, last_index):
"""Extrapolate the rows of data, to get the first and last together
with the data.
"""
pos = row_indices[:2]
first_row = _linear_extrapolate(pos,
(data[0, :], data[1,... | python | def _extrapolate_rows(self, data, row_indices, first_index, last_index):
"""Extrapolate the rows of data, to get the first and last together
with the data.
"""
pos = row_indices[:2]
first_row = _linear_extrapolate(pos,
(data[0, :], data[1,... | [
"def",
"_extrapolate_rows",
"(",
"self",
",",
"data",
",",
"row_indices",
",",
"first_index",
",",
"last_index",
")",
":",
"pos",
"=",
"row_indices",
"[",
":",
"2",
"]",
"first_row",
"=",
"_linear_extrapolate",
"(",
"pos",
",",
"(",
"data",
"[",
"0",
","... | Extrapolate the rows of data, to get the first and last together
with the data. | [
"Extrapolate",
"the",
"rows",
"of",
"data",
"to",
"get",
"the",
"first",
"and",
"last",
"together",
"with",
"the",
"data",
"."
] | train | https://github.com/pytroll/python-geotiepoints/blob/7c5cc8a887f8534cc2839c716c2c560aeaf77659/geotiepoints/interpolator.py#L184-L199 |
pytroll/python-geotiepoints | geotiepoints/interpolator.py | Interpolator._fill_row_borders | def _fill_row_borders(self):
"""Add the first and last rows to the data by extrapolation.
"""
lines = len(self.hrow_indices)
chunk_size = self.chunk_size or lines
factor = len(self.hrow_indices) / len(self.row_indices)
tmp_data = []
for num in range(len(self.tie_... | python | def _fill_row_borders(self):
"""Add the first and last rows to the data by extrapolation.
"""
lines = len(self.hrow_indices)
chunk_size = self.chunk_size or lines
factor = len(self.hrow_indices) / len(self.row_indices)
tmp_data = []
for num in range(len(self.tie_... | [
"def",
"_fill_row_borders",
"(",
"self",
")",
":",
"lines",
"=",
"len",
"(",
"self",
".",
"hrow_indices",
")",
"chunk_size",
"=",
"self",
".",
"chunk_size",
"or",
"lines",
"factor",
"=",
"len",
"(",
"self",
".",
"hrow_indices",
")",
"/",
"len",
"(",
"s... | Add the first and last rows to the data by extrapolation. | [
"Add",
"the",
"first",
"and",
"last",
"rows",
"to",
"the",
"data",
"by",
"extrapolation",
"."
] | train | https://github.com/pytroll/python-geotiepoints/blob/7c5cc8a887f8534cc2839c716c2c560aeaf77659/geotiepoints/interpolator.py#L201-L237 |
pytroll/python-geotiepoints | geotiepoints/interpolator.py | Interpolator._interp | def _interp(self):
"""Interpolate the cartesian coordinates.
"""
if np.all(self.hrow_indices == self.row_indices):
return self._interp1d()
xpoints, ypoints = np.meshgrid(self.hrow_indices,
self.hcol_indices)
for num, data in en... | python | def _interp(self):
"""Interpolate the cartesian coordinates.
"""
if np.all(self.hrow_indices == self.row_indices):
return self._interp1d()
xpoints, ypoints = np.meshgrid(self.hrow_indices,
self.hcol_indices)
for num, data in en... | [
"def",
"_interp",
"(",
"self",
")",
":",
"if",
"np",
".",
"all",
"(",
"self",
".",
"hrow_indices",
"==",
"self",
".",
"row_indices",
")",
":",
"return",
"self",
".",
"_interp1d",
"(",
")",
"xpoints",
",",
"ypoints",
"=",
"np",
".",
"meshgrid",
"(",
... | Interpolate the cartesian coordinates. | [
"Interpolate",
"the",
"cartesian",
"coordinates",
"."
] | train | https://github.com/pytroll/python-geotiepoints/blob/7c5cc8a887f8534cc2839c716c2c560aeaf77659/geotiepoints/interpolator.py#L239-L257 |
pytroll/python-geotiepoints | geotiepoints/interpolator.py | Interpolator._interp1d | def _interp1d(self):
"""Interpolate in one dimension.
"""
lines = len(self.hrow_indices)
for num, data in enumerate(self.tie_data):
self.new_data[num] = np.empty((len(self.hrow_indices),
len(self.hcol_indices)),
... | python | def _interp1d(self):
"""Interpolate in one dimension.
"""
lines = len(self.hrow_indices)
for num, data in enumerate(self.tie_data):
self.new_data[num] = np.empty((len(self.hrow_indices),
len(self.hcol_indices)),
... | [
"def",
"_interp1d",
"(",
"self",
")",
":",
"lines",
"=",
"len",
"(",
"self",
".",
"hrow_indices",
")",
"for",
"num",
",",
"data",
"in",
"enumerate",
"(",
"self",
".",
"tie_data",
")",
":",
"self",
".",
"new_data",
"[",
"num",
"]",
"=",
"np",
".",
... | Interpolate in one dimension. | [
"Interpolate",
"in",
"one",
"dimension",
"."
] | train | https://github.com/pytroll/python-geotiepoints/blob/7c5cc8a887f8534cc2839c716c2c560aeaf77659/geotiepoints/interpolator.py#L259-L272 |
pytroll/python-geotiepoints | geotiepoints/geointerpolator.py | get_lons_from_cartesian | def get_lons_from_cartesian(x__, y__):
"""Get longitudes from cartesian coordinates.
"""
return rad2deg(arccos(x__ / sqrt(x__ ** 2 + y__ ** 2))) * sign(y__) | python | def get_lons_from_cartesian(x__, y__):
"""Get longitudes from cartesian coordinates.
"""
return rad2deg(arccos(x__ / sqrt(x__ ** 2 + y__ ** 2))) * sign(y__) | [
"def",
"get_lons_from_cartesian",
"(",
"x__",
",",
"y__",
")",
":",
"return",
"rad2deg",
"(",
"arccos",
"(",
"x__",
"/",
"sqrt",
"(",
"x__",
"**",
"2",
"+",
"y__",
"**",
"2",
")",
")",
")",
"*",
"sign",
"(",
"y__",
")"
] | Get longitudes from cartesian coordinates. | [
"Get",
"longitudes",
"from",
"cartesian",
"coordinates",
"."
] | train | https://github.com/pytroll/python-geotiepoints/blob/7c5cc8a887f8534cc2839c716c2c560aeaf77659/geotiepoints/geointerpolator.py#L87-L90 |
pytroll/python-geotiepoints | geotiepoints/geointerpolator.py | get_lats_from_cartesian | def get_lats_from_cartesian(x__, y__, z__, thr=0.8):
"""Get latitudes from cartesian coordinates.
"""
# if we are at low latitudes - small z, then get the
# latitudes only from z. If we are at high latitudes (close to the poles)
# then derive the latitude using x and y:
lats = np.where(np.logic... | python | def get_lats_from_cartesian(x__, y__, z__, thr=0.8):
"""Get latitudes from cartesian coordinates.
"""
# if we are at low latitudes - small z, then get the
# latitudes only from z. If we are at high latitudes (close to the poles)
# then derive the latitude using x and y:
lats = np.where(np.logic... | [
"def",
"get_lats_from_cartesian",
"(",
"x__",
",",
"y__",
",",
"z__",
",",
"thr",
"=",
"0.8",
")",
":",
"# if we are at low latitudes - small z, then get the",
"# latitudes only from z. If we are at high latitudes (close to the poles)",
"# then derive the latitude using x and y:",
... | Get latitudes from cartesian coordinates. | [
"Get",
"latitudes",
"from",
"cartesian",
"coordinates",
"."
] | train | https://github.com/pytroll/python-geotiepoints/blob/7c5cc8a887f8534cc2839c716c2c560aeaf77659/geotiepoints/geointerpolator.py#L92-L105 |
pytroll/python-geotiepoints | geotiepoints/geointerpolator.py | GeoInterpolator.set_tiepoints | def set_tiepoints(self, lon, lat):
"""Defines the lon,lat tie points.
"""
self.lon_tiepoint = lon
self.lat_tiepoint = lat | python | def set_tiepoints(self, lon, lat):
"""Defines the lon,lat tie points.
"""
self.lon_tiepoint = lon
self.lat_tiepoint = lat | [
"def",
"set_tiepoints",
"(",
"self",
",",
"lon",
",",
"lat",
")",
":",
"self",
".",
"lon_tiepoint",
"=",
"lon",
"self",
".",
"lat_tiepoint",
"=",
"lat"
] | Defines the lon,lat tie points. | [
"Defines",
"the",
"lon",
"lat",
"tie",
"points",
"."
] | train | https://github.com/pytroll/python-geotiepoints/blob/7c5cc8a887f8534cc2839c716c2c560aeaf77659/geotiepoints/geointerpolator.py#L75-L79 |
pytroll/python-geotiepoints | geotiepoints/modisinterpolator.py | compute_expansion_alignment | def compute_expansion_alignment(satz_a, satz_b, satz_c, satz_d):
"""All angles in radians."""
zeta_a = satz_a
zeta_b = satz_b
phi_a = compute_phi(zeta_a)
phi_b = compute_phi(zeta_b)
theta_a = compute_theta(zeta_a, phi_a)
theta_b = compute_theta(zeta_b, phi_b)
phi = (phi_a + phi_b) / 2
... | python | def compute_expansion_alignment(satz_a, satz_b, satz_c, satz_d):
"""All angles in radians."""
zeta_a = satz_a
zeta_b = satz_b
phi_a = compute_phi(zeta_a)
phi_b = compute_phi(zeta_b)
theta_a = compute_theta(zeta_a, phi_a)
theta_b = compute_theta(zeta_b, phi_b)
phi = (phi_a + phi_b) / 2
... | [
"def",
"compute_expansion_alignment",
"(",
"satz_a",
",",
"satz_b",
",",
"satz_c",
",",
"satz_d",
")",
":",
"zeta_a",
"=",
"satz_a",
"zeta_b",
"=",
"satz_b",
"phi_a",
"=",
"compute_phi",
"(",
"zeta_a",
")",
"phi_b",
"=",
"compute_phi",
"(",
"zeta_b",
")",
... | All angles in radians. | [
"All",
"angles",
"in",
"radians",
"."
] | train | https://github.com/pytroll/python-geotiepoints/blob/7c5cc8a887f8534cc2839c716c2c560aeaf77659/geotiepoints/modisinterpolator.py#L51-L73 |
pytroll/python-geotiepoints | geotiepoints/modisinterpolator.py | lonlat2xyz | def lonlat2xyz(lons, lats):
"""Convert lons and lats to cartesian coordinates."""
R = 6370997.0
x_coords = R * da.cos(da.deg2rad(lats)) * da.cos(da.deg2rad(lons))
y_coords = R * da.cos(da.deg2rad(lats)) * da.sin(da.deg2rad(lons))
z_coords = R * da.sin(da.deg2rad(lats))
return x_coords, y_coords,... | python | def lonlat2xyz(lons, lats):
"""Convert lons and lats to cartesian coordinates."""
R = 6370997.0
x_coords = R * da.cos(da.deg2rad(lats)) * da.cos(da.deg2rad(lons))
y_coords = R * da.cos(da.deg2rad(lats)) * da.sin(da.deg2rad(lons))
z_coords = R * da.sin(da.deg2rad(lats))
return x_coords, y_coords,... | [
"def",
"lonlat2xyz",
"(",
"lons",
",",
"lats",
")",
":",
"R",
"=",
"6370997.0",
"x_coords",
"=",
"R",
"*",
"da",
".",
"cos",
"(",
"da",
".",
"deg2rad",
"(",
"lats",
")",
")",
"*",
"da",
".",
"cos",
"(",
"da",
".",
"deg2rad",
"(",
"lons",
")",
... | Convert lons and lats to cartesian coordinates. | [
"Convert",
"lons",
"and",
"lats",
"to",
"cartesian",
"coordinates",
"."
] | train | https://github.com/pytroll/python-geotiepoints/blob/7c5cc8a887f8534cc2839c716c2c560aeaf77659/geotiepoints/modisinterpolator.py#L250-L256 |
pytroll/python-geotiepoints | geotiepoints/modisinterpolator.py | xyz2lonlat | def xyz2lonlat(x__, y__, z__):
"""Get longitudes from cartesian coordinates.
"""
R = 6370997.0
lons = da.rad2deg(da.arccos(x__ / da.sqrt(x__ ** 2 + y__ ** 2))) * da.sign(y__)
lats = da.sign(z__) * (90 - da.rad2deg(da.arcsin(da.sqrt(x__ ** 2 + y__ ** 2) / R)))
return lons, lats | python | def xyz2lonlat(x__, y__, z__):
"""Get longitudes from cartesian coordinates.
"""
R = 6370997.0
lons = da.rad2deg(da.arccos(x__ / da.sqrt(x__ ** 2 + y__ ** 2))) * da.sign(y__)
lats = da.sign(z__) * (90 - da.rad2deg(da.arcsin(da.sqrt(x__ ** 2 + y__ ** 2) / R)))
return lons, lats | [
"def",
"xyz2lonlat",
"(",
"x__",
",",
"y__",
",",
"z__",
")",
":",
"R",
"=",
"6370997.0",
"lons",
"=",
"da",
".",
"rad2deg",
"(",
"da",
".",
"arccos",
"(",
"x__",
"/",
"da",
".",
"sqrt",
"(",
"x__",
"**",
"2",
"+",
"y__",
"**",
"2",
")",
")",... | Get longitudes from cartesian coordinates. | [
"Get",
"longitudes",
"from",
"cartesian",
"coordinates",
"."
] | train | https://github.com/pytroll/python-geotiepoints/blob/7c5cc8a887f8534cc2839c716c2c560aeaf77659/geotiepoints/modisinterpolator.py#L258-L265 |
EliotBerriot/lifter | lifter/backends/base.py | setup_fields | def setup_fields(attrs):
"""
Collect all fields declared on the class and remove them from attrs
"""
fields = {}
iterator = list(attrs.items())
for key, value in iterator:
if not isinstance(value, Field):
continue
fields[key] = value
del attrs[key]
return ... | python | def setup_fields(attrs):
"""
Collect all fields declared on the class and remove them from attrs
"""
fields = {}
iterator = list(attrs.items())
for key, value in iterator:
if not isinstance(value, Field):
continue
fields[key] = value
del attrs[key]
return ... | [
"def",
"setup_fields",
"(",
"attrs",
")",
":",
"fields",
"=",
"{",
"}",
"iterator",
"=",
"list",
"(",
"attrs",
".",
"items",
"(",
")",
")",
"for",
"key",
",",
"value",
"in",
"iterator",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"Field",
")... | Collect all fields declared on the class and remove them from attrs | [
"Collect",
"all",
"fields",
"declared",
"on",
"the",
"class",
"and",
"remove",
"them",
"from",
"attrs"
] | train | https://github.com/EliotBerriot/lifter/blob/9b4394b476cddd952b2af9540affc03f2977163d/lifter/backends/base.py#L20-L31 |
openstax/cnxml | cnxml/jing.py | _parse_jing_line | def _parse_jing_line(line):
"""Parse a line of jing output to a list of line, column, type
and message.
"""
parts = line.split(':', 4)
filename, line, column, type_, message = [x.strip() for x in parts]
if type_ == 'fatal':
if message in KNOWN_FATAL_MESSAGES_MAPPING:
message... | python | def _parse_jing_line(line):
"""Parse a line of jing output to a list of line, column, type
and message.
"""
parts = line.split(':', 4)
filename, line, column, type_, message = [x.strip() for x in parts]
if type_ == 'fatal':
if message in KNOWN_FATAL_MESSAGES_MAPPING:
message... | [
"def",
"_parse_jing_line",
"(",
"line",
")",
":",
"parts",
"=",
"line",
".",
"split",
"(",
"':'",
",",
"4",
")",
"filename",
",",
"line",
",",
"column",
",",
"type_",
",",
"message",
"=",
"[",
"x",
".",
"strip",
"(",
")",
"for",
"x",
"in",
"parts... | Parse a line of jing output to a list of line, column, type
and message. | [
"Parse",
"a",
"line",
"of",
"jing",
"output",
"to",
"a",
"list",
"of",
"line",
"column",
"type",
"and",
"message",
"."
] | train | https://github.com/openstax/cnxml/blob/ddce4016ef204c509861cdc328815ddc361378c9/cnxml/jing.py#L25-L35 |
openstax/cnxml | cnxml/jing.py | _parse_jing_output | def _parse_jing_output(output):
"""Parse the jing output into a tuple of line, column, type and message.
"""
output = output.strip()
values = [_parse_jing_line(l) for l in output.split('\n') if l]
return tuple(values) | python | def _parse_jing_output(output):
"""Parse the jing output into a tuple of line, column, type and message.
"""
output = output.strip()
values = [_parse_jing_line(l) for l in output.split('\n') if l]
return tuple(values) | [
"def",
"_parse_jing_output",
"(",
"output",
")",
":",
"output",
"=",
"output",
".",
"strip",
"(",
")",
"values",
"=",
"[",
"_parse_jing_line",
"(",
"l",
")",
"for",
"l",
"in",
"output",
".",
"split",
"(",
"'\\n'",
")",
"if",
"l",
"]",
"return",
"tupl... | Parse the jing output into a tuple of line, column, type and message. | [
"Parse",
"the",
"jing",
"output",
"into",
"a",
"tuple",
"of",
"line",
"column",
"type",
"and",
"message",
"."
] | train | https://github.com/openstax/cnxml/blob/ddce4016ef204c509861cdc328815ddc361378c9/cnxml/jing.py#L38-L44 |
openstax/cnxml | cnxml/jing.py | jing | def jing(rng_filepath, *xml_filepaths):
"""Run jing.jar using the RNG file against the given XML file."""
cmd = ['java', '-jar']
cmd.extend([str(JING_JAR), str(rng_filepath)])
for xml_filepath in xml_filepaths:
cmd.append(str(xml_filepath))
proc = subprocess.Popen(cmd,
... | python | def jing(rng_filepath, *xml_filepaths):
"""Run jing.jar using the RNG file against the given XML file."""
cmd = ['java', '-jar']
cmd.extend([str(JING_JAR), str(rng_filepath)])
for xml_filepath in xml_filepaths:
cmd.append(str(xml_filepath))
proc = subprocess.Popen(cmd,
... | [
"def",
"jing",
"(",
"rng_filepath",
",",
"*",
"xml_filepaths",
")",
":",
"cmd",
"=",
"[",
"'java'",
",",
"'-jar'",
"]",
"cmd",
".",
"extend",
"(",
"[",
"str",
"(",
"JING_JAR",
")",
",",
"str",
"(",
"rng_filepath",
")",
"]",
")",
"for",
"xml_filepath"... | Run jing.jar using the RNG file against the given XML file. | [
"Run",
"jing",
".",
"jar",
"using",
"the",
"RNG",
"file",
"against",
"the",
"given",
"XML",
"file",
"."
] | train | https://github.com/openstax/cnxml/blob/ddce4016ef204c509861cdc328815ddc361378c9/cnxml/jing.py#L47-L59 |
asottile/aspy.refactor_imports | aspy/refactor_imports/import_obj.py | import_obj_from_str | def import_obj_from_str(s):
"""Returns an import object (either ImportImport or FromImport) from text.
"""
ast_obj = ast.parse(s).body[0]
return ast_type_to_import_type[type(ast_obj)](ast_obj) | python | def import_obj_from_str(s):
"""Returns an import object (either ImportImport or FromImport) from text.
"""
ast_obj = ast.parse(s).body[0]
return ast_type_to_import_type[type(ast_obj)](ast_obj) | [
"def",
"import_obj_from_str",
"(",
"s",
")",
":",
"ast_obj",
"=",
"ast",
".",
"parse",
"(",
"s",
")",
".",
"body",
"[",
"0",
"]",
"return",
"ast_type_to_import_type",
"[",
"type",
"(",
"ast_obj",
")",
"]",
"(",
"ast_obj",
")"
] | Returns an import object (either ImportImport or FromImport) from text. | [
"Returns",
"an",
"import",
"object",
"(",
"either",
"ImportImport",
"or",
"FromImport",
")",
"from",
"text",
"."
] | train | https://github.com/asottile/aspy.refactor_imports/blob/8815983d373f734bca2007ea598020a6b23d7c59/aspy/refactor_imports/import_obj.py#L185-L189 |
asottile/aspy.refactor_imports | aspy/refactor_imports/import_obj.py | AbstractImportObj.from_str | def from_str(cls, s):
"""Construct an import object from a string."""
ast_obj = ast.parse(s).body[0]
if not isinstance(ast_obj, cls._expected_ast_type):
raise AssertionError(
'Expected ast of type {!r} but got {!r}'.format(
cls._expected_ast_type,
... | python | def from_str(cls, s):
"""Construct an import object from a string."""
ast_obj = ast.parse(s).body[0]
if not isinstance(ast_obj, cls._expected_ast_type):
raise AssertionError(
'Expected ast of type {!r} but got {!r}'.format(
cls._expected_ast_type,
... | [
"def",
"from_str",
"(",
"cls",
",",
"s",
")",
":",
"ast_obj",
"=",
"ast",
".",
"parse",
"(",
"s",
")",
".",
"body",
"[",
"0",
"]",
"if",
"not",
"isinstance",
"(",
"ast_obj",
",",
"cls",
".",
"_expected_ast_type",
")",
":",
"raise",
"AssertionError",
... | Construct an import object from a string. | [
"Construct",
"an",
"import",
"object",
"from",
"a",
"string",
"."
] | train | https://github.com/asottile/aspy.refactor_imports/blob/8815983d373f734bca2007ea598020a6b23d7c59/aspy/refactor_imports/import_obj.py#L26-L36 |
asottile/aspy.refactor_imports | aspy/refactor_imports/sort.py | sort | def sort(imports, separate=True, import_before_from=True, **classify_kwargs):
"""Sort import objects into groups.
:param list imports: FromImport / ImportImport objects
:param bool separate: Whether to classify and return separate segments
of imports based on classification.
:param bool import_... | python | def sort(imports, separate=True, import_before_from=True, **classify_kwargs):
"""Sort import objects into groups.
:param list imports: FromImport / ImportImport objects
:param bool separate: Whether to classify and return separate segments
of imports based on classification.
:param bool import_... | [
"def",
"sort",
"(",
"imports",
",",
"separate",
"=",
"True",
",",
"import_before_from",
"=",
"True",
",",
"*",
"*",
"classify_kwargs",
")",
":",
"if",
"separate",
":",
"def",
"classify_func",
"(",
"obj",
")",
":",
"return",
"classify_import",
"(",
"obj",
... | Sort import objects into groups.
:param list imports: FromImport / ImportImport objects
:param bool separate: Whether to classify and return separate segments
of imports based on classification.
:param bool import_before_from: Whether to sort `import ...` imports before
`from ...` imports.
... | [
"Sort",
"import",
"objects",
"into",
"groups",
"."
] | train | https://github.com/asottile/aspy.refactor_imports/blob/8815983d373f734bca2007ea598020a6b23d7c59/aspy/refactor_imports/sort.py#L19-L99 |
asottile/aspy.refactor_imports | aspy/refactor_imports/classify.py | classify_import | def classify_import(module_name, application_directories=('.',)):
"""Classifies an import by its package.
Returns a value in ImportType.__all__
:param text module_name: The dotted notation of a module
:param tuple application_directories: tuple of paths which are considered
application roots.
... | python | def classify_import(module_name, application_directories=('.',)):
"""Classifies an import by its package.
Returns a value in ImportType.__all__
:param text module_name: The dotted notation of a module
:param tuple application_directories: tuple of paths which are considered
application roots.
... | [
"def",
"classify_import",
"(",
"module_name",
",",
"application_directories",
"=",
"(",
"'.'",
",",
")",
")",
":",
"# Only really care about the first part of the path",
"base",
",",
"_",
",",
"_",
"=",
"module_name",
".",
"partition",
"(",
"'.'",
")",
"found",
... | Classifies an import by its package.
Returns a value in ImportType.__all__
:param text module_name: The dotted notation of a module
:param tuple application_directories: tuple of paths which are considered
application roots. | [
"Classifies",
"an",
"import",
"by",
"its",
"package",
"."
] | train | https://github.com/asottile/aspy.refactor_imports/blob/8815983d373f734bca2007ea598020a6b23d7c59/aspy/refactor_imports/classify.py#L124-L159 |
openstax/cnxml | cnxml/cli.py | _arg_parser | def _arg_parser():
"""Factory for creating the argument parser"""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('xml', nargs='*')
return parser | python | def _arg_parser():
"""Factory for creating the argument parser"""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('xml', nargs='*')
return parser | [
"def",
"_arg_parser",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"__doc__",
")",
"parser",
".",
"add_argument",
"(",
"'xml'",
",",
"nargs",
"=",
"'*'",
")",
"return",
"parser"
] | Factory for creating the argument parser | [
"Factory",
"for",
"creating",
"the",
"argument",
"parser"
] | train | https://github.com/openstax/cnxml/blob/ddce4016ef204c509861cdc328815ddc361378c9/cnxml/cli.py#L27-L31 |
openstax/cnxml | cnxml/parse.py | parse_metadata | def parse_metadata(elm_tree):
"""Given an element-like object (:mod:`lxml.etree`)
lookup the metadata and return the found elements
:param elm_tree: the root xml element
:type elm_tree: an element-like object from :mod:`lxml.etree`
:returns: common metadata properties
:rtype: dict
"""
... | python | def parse_metadata(elm_tree):
"""Given an element-like object (:mod:`lxml.etree`)
lookup the metadata and return the found elements
:param elm_tree: the root xml element
:type elm_tree: an element-like object from :mod:`lxml.etree`
:returns: common metadata properties
:rtype: dict
"""
... | [
"def",
"parse_metadata",
"(",
"elm_tree",
")",
":",
"xpath",
"=",
"make_cnx_xpath",
"(",
"elm_tree",
")",
"role_xpath",
"=",
"lambda",
"xp",
":",
"tuple",
"(",
"xpath",
"(",
"xp",
")",
"[",
"0",
"]",
".",
"split",
"(",
")",
")",
"# noqa: E731",
"props"... | Given an element-like object (:mod:`lxml.etree`)
lookup the metadata and return the found elements
:param elm_tree: the root xml element
:type elm_tree: an element-like object from :mod:`lxml.etree`
:returns: common metadata properties
:rtype: dict | [
"Given",
"an",
"element",
"-",
"like",
"object",
"(",
":",
"mod",
":",
"lxml",
".",
"etree",
")",
"lookup",
"the",
"metadata",
"and",
"return",
"the",
"found",
"elements"
] | train | https://github.com/openstax/cnxml/blob/ddce4016ef204c509861cdc328815ddc361378c9/cnxml/parse.py#L63-L101 |
openstax/cnxml | cnxml/validation.py | validate_cnxml | def validate_cnxml(*content_filepaths):
"""Validates the given CNXML file against the cnxml-jing.rng RNG."""
content_filepaths = [Path(path).resolve() for path in content_filepaths]
return jing(CNXML_JING_RNG, *content_filepaths) | python | def validate_cnxml(*content_filepaths):
"""Validates the given CNXML file against the cnxml-jing.rng RNG."""
content_filepaths = [Path(path).resolve() for path in content_filepaths]
return jing(CNXML_JING_RNG, *content_filepaths) | [
"def",
"validate_cnxml",
"(",
"*",
"content_filepaths",
")",
":",
"content_filepaths",
"=",
"[",
"Path",
"(",
"path",
")",
".",
"resolve",
"(",
")",
"for",
"path",
"in",
"content_filepaths",
"]",
"return",
"jing",
"(",
"CNXML_JING_RNG",
",",
"*",
"content_fi... | Validates the given CNXML file against the cnxml-jing.rng RNG. | [
"Validates",
"the",
"given",
"CNXML",
"file",
"against",
"the",
"cnxml",
"-",
"jing",
".",
"rng",
"RNG",
"."
] | train | https://github.com/openstax/cnxml/blob/ddce4016ef204c509861cdc328815ddc361378c9/cnxml/validation.py#L20-L23 |
openstax/cnxml | cnxml/validation.py | validate_collxml | def validate_collxml(*content_filepaths):
"""Validates the given COLLXML file against the collxml-jing.rng RNG."""
content_filepaths = [Path(path).resolve() for path in content_filepaths]
return jing(COLLXML_JING_RNG, *content_filepaths) | python | def validate_collxml(*content_filepaths):
"""Validates the given COLLXML file against the collxml-jing.rng RNG."""
content_filepaths = [Path(path).resolve() for path in content_filepaths]
return jing(COLLXML_JING_RNG, *content_filepaths) | [
"def",
"validate_collxml",
"(",
"*",
"content_filepaths",
")",
":",
"content_filepaths",
"=",
"[",
"Path",
"(",
"path",
")",
".",
"resolve",
"(",
")",
"for",
"path",
"in",
"content_filepaths",
"]",
"return",
"jing",
"(",
"COLLXML_JING_RNG",
",",
"*",
"conten... | Validates the given COLLXML file against the collxml-jing.rng RNG. | [
"Validates",
"the",
"given",
"COLLXML",
"file",
"against",
"the",
"collxml",
"-",
"jing",
".",
"rng",
"RNG",
"."
] | train | https://github.com/openstax/cnxml/blob/ddce4016ef204c509861cdc328815ddc361378c9/cnxml/validation.py#L26-L29 |
fhcrc/taxtastic | taxtastic/subcommands/rollback.py | action | def action(args):
"""Roll back commands on a refpkg.
*args* should be an argparse object with fields refpkg (giving the
path to the refpkg to operate on) and n (giving the number of
operations to roll back).
"""
log.info('loading reference package')
r = refpkg.Refpkg(args.refpkg, create=Fa... | python | def action(args):
"""Roll back commands on a refpkg.
*args* should be an argparse object with fields refpkg (giving the
path to the refpkg to operate on) and n (giving the number of
operations to roll back).
"""
log.info('loading reference package')
r = refpkg.Refpkg(args.refpkg, create=Fa... | [
"def",
"action",
"(",
"args",
")",
":",
"log",
".",
"info",
"(",
"'loading reference package'",
")",
"r",
"=",
"refpkg",
".",
"Refpkg",
"(",
"args",
".",
"refpkg",
",",
"create",
"=",
"False",
")",
"# First check if we can do n rollbacks",
"q",
"=",
"r",
"... | Roll back commands on a refpkg.
*args* should be an argparse object with fields refpkg (giving the
path to the refpkg to operate on) and n (giving the number of
operations to roll back). | [
"Roll",
"back",
"commands",
"on",
"a",
"refpkg",
"."
] | train | https://github.com/fhcrc/taxtastic/blob/4e874b7f2cc146178828bfba386314f8c342722b/taxtastic/subcommands/rollback.py#L39-L63 |
amicks/Speculator | speculator/market.py | set_targets | def set_targets(x, delta=10):
""" Sets target market trend for a date
Args:
x: Pandas DataFrame of market features
delta: Positive number defining a price buffer between what is
classified as a bullish/bearish market for the training set.
delta is equivalent to the total... | python | def set_targets(x, delta=10):
""" Sets target market trend for a date
Args:
x: Pandas DataFrame of market features
delta: Positive number defining a price buffer between what is
classified as a bullish/bearish market for the training set.
delta is equivalent to the total... | [
"def",
"set_targets",
"(",
"x",
",",
"delta",
"=",
"10",
")",
":",
"data",
"=",
"[",
"]",
"# Keep track of targets",
"for",
"row",
",",
"_",
"in",
"x",
".",
"iterrows",
"(",
")",
":",
"if",
"row",
"==",
"x",
".",
"shape",
"[",
"0",
"]",
"-",
"1... | Sets target market trend for a date
Args:
x: Pandas DataFrame of market features
delta: Positive number defining a price buffer between what is
classified as a bullish/bearish market for the training set.
delta is equivalent to the total size of the neutral price zone.
... | [
"Sets",
"target",
"market",
"trend",
"for",
"a",
"date"
] | train | https://github.com/amicks/Speculator/blob/f7d6590aded20b1e1b5df16a4b27228ee821c4ab/speculator/market.py#L111-L145 |
amicks/Speculator | speculator/market.py | eval_features | def eval_features(json):
""" Gets technical analysis features from market data JSONs
Args:
json: JSON data as a list of dict dates, where the keys are
the raw market statistics.
Returns:
Dict of market features and their values
"""
return {'close' : json[-1]['close']... | python | def eval_features(json):
""" Gets technical analysis features from market data JSONs
Args:
json: JSON data as a list of dict dates, where the keys are
the raw market statistics.
Returns:
Dict of market features and their values
"""
return {'close' : json[-1]['close']... | [
"def",
"eval_features",
"(",
"json",
")",
":",
"return",
"{",
"'close'",
":",
"json",
"[",
"-",
"1",
"]",
"[",
"'close'",
"]",
",",
"'sma'",
":",
"SMA",
".",
"eval_from_json",
"(",
"json",
")",
",",
"'rsi'",
":",
"RSI",
".",
"eval_from_json",
"(",
... | Gets technical analysis features from market data JSONs
Args:
json: JSON data as a list of dict dates, where the keys are
the raw market statistics.
Returns:
Dict of market features and their values | [
"Gets",
"technical",
"analysis",
"features",
"from",
"market",
"data",
"JSONs"
] | train | https://github.com/amicks/Speculator/blob/f7d6590aded20b1e1b5df16a4b27228ee821c4ab/speculator/market.py#L147-L161 |
amicks/Speculator | speculator/market.py | target_code_to_name | def target_code_to_name(code):
""" Converts an int target code to a target name
Since self.TARGET_CODES is a 1:1 mapping, perform a reverse lookup
to get the more readable name.
Args:
code: Value from self.TARGET_CODES
Returns:
String target name corresponding to the given code.
... | python | def target_code_to_name(code):
""" Converts an int target code to a target name
Since self.TARGET_CODES is a 1:1 mapping, perform a reverse lookup
to get the more readable name.
Args:
code: Value from self.TARGET_CODES
Returns:
String target name corresponding to the given code.
... | [
"def",
"target_code_to_name",
"(",
"code",
")",
":",
"TARGET_NAMES",
"=",
"{",
"v",
":",
"k",
"for",
"k",
",",
"v",
"in",
"TARGET_CODES",
".",
"items",
"(",
")",
"}",
"return",
"TARGET_NAMES",
"[",
"code",
"]"
] | Converts an int target code to a target name
Since self.TARGET_CODES is a 1:1 mapping, perform a reverse lookup
to get the more readable name.
Args:
code: Value from self.TARGET_CODES
Returns:
String target name corresponding to the given code. | [
"Converts",
"an",
"int",
"target",
"code",
"to",
"a",
"target",
"name"
] | train | https://github.com/amicks/Speculator/blob/f7d6590aded20b1e1b5df16a4b27228ee821c4ab/speculator/market.py#L163-L176 |
amicks/Speculator | speculator/market.py | setup_model | def setup_model(x, y, model_type='random_forest', seed=None, **kwargs):
""" Initializes a machine learning model
Args:
x: Pandas DataFrame, X axis of features
y: Pandas Series, Y axis of targets
model_type: Machine Learning model to use
Valid values: 'random_forest'
... | python | def setup_model(x, y, model_type='random_forest', seed=None, **kwargs):
""" Initializes a machine learning model
Args:
x: Pandas DataFrame, X axis of features
y: Pandas Series, Y axis of targets
model_type: Machine Learning model to use
Valid values: 'random_forest'
... | [
"def",
"setup_model",
"(",
"x",
",",
"y",
",",
"model_type",
"=",
"'random_forest'",
",",
"seed",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"len",
"(",
"x",
")",
">",
"1",
"and",
"len",
"(",
"y",
")",
">",
"1",
",",
"'Not enough d... | Initializes a machine learning model
Args:
x: Pandas DataFrame, X axis of features
y: Pandas Series, Y axis of targets
model_type: Machine Learning model to use
Valid values: 'random_forest'
seed: Random state to use when splitting sets and creating the model
**k... | [
"Initializes",
"a",
"machine",
"learning",
"model"
] | train | https://github.com/amicks/Speculator/blob/f7d6590aded20b1e1b5df16a4b27228ee821c4ab/speculator/market.py#L178-L208 |
amicks/Speculator | speculator/market.py | Market.get_json | def get_json(self):
""" Gets market chart data from today to a previous date """
today = dt.now()
DIRECTION = 'last'
epochs = date.get_end_start_epochs(today.year, today.month, today.day,
DIRECTION, self.unit, self.count)
return poloniex... | python | def get_json(self):
""" Gets market chart data from today to a previous date """
today = dt.now()
DIRECTION = 'last'
epochs = date.get_end_start_epochs(today.year, today.month, today.day,
DIRECTION, self.unit, self.count)
return poloniex... | [
"def",
"get_json",
"(",
"self",
")",
":",
"today",
"=",
"dt",
".",
"now",
"(",
")",
"DIRECTION",
"=",
"'last'",
"epochs",
"=",
"date",
".",
"get_end_start_epochs",
"(",
"today",
".",
"year",
",",
"today",
".",
"month",
",",
"today",
".",
"day",
",",
... | Gets market chart data from today to a previous date | [
"Gets",
"market",
"chart",
"data",
"from",
"today",
"to",
"a",
"previous",
"date"
] | train | https://github.com/amicks/Speculator/blob/f7d6590aded20b1e1b5df16a4b27228ee821c4ab/speculator/market.py#L52-L59 |
amicks/Speculator | speculator/market.py | Market.set_features | def set_features(self, partition=1):
""" Parses market data JSON for technical analysis indicators
Args:
partition: Int of how many dates to take into consideration
when evaluating technical analysis indicators.
Returns:
Pandas DataFrame instance with co... | python | def set_features(self, partition=1):
""" Parses market data JSON for technical analysis indicators
Args:
partition: Int of how many dates to take into consideration
when evaluating technical analysis indicators.
Returns:
Pandas DataFrame instance with co... | [
"def",
"set_features",
"(",
"self",
",",
"partition",
"=",
"1",
")",
":",
"if",
"len",
"(",
"self",
".",
"json",
")",
"<",
"partition",
"+",
"1",
":",
"raise",
"ValueError",
"(",
"'Not enough dates for the specified partition size: {0}. Try a smaller partition.'",
... | Parses market data JSON for technical analysis indicators
Args:
partition: Int of how many dates to take into consideration
when evaluating technical analysis indicators.
Returns:
Pandas DataFrame instance with columns as numpy.float32 features. | [
"Parses",
"market",
"data",
"JSON",
"for",
"technical",
"analysis",
"indicators"
] | train | https://github.com/amicks/Speculator/blob/f7d6590aded20b1e1b5df16a4b27228ee821c4ab/speculator/market.py#L61-L78 |
amicks/Speculator | speculator/market.py | Market.set_long_features | def set_long_features(self, features, columns_to_set=[], partition=2):
""" Sets features of double the duration
Example: Setting 14 day RSIs to longer will create add a
feature column of a 28 day RSIs.
Args:
features: Pandas DataFrame instance with columns as numpy.floa... | python | def set_long_features(self, features, columns_to_set=[], partition=2):
""" Sets features of double the duration
Example: Setting 14 day RSIs to longer will create add a
feature column of a 28 day RSIs.
Args:
features: Pandas DataFrame instance with columns as numpy.floa... | [
"def",
"set_long_features",
"(",
"self",
",",
"features",
",",
"columns_to_set",
"=",
"[",
"]",
",",
"partition",
"=",
"2",
")",
":",
"# Create long features DataFrame",
"features_long",
"=",
"self",
".",
"set_features",
"(",
"partition",
"=",
"2",
"*",
"parti... | Sets features of double the duration
Example: Setting 14 day RSIs to longer will create add a
feature column of a 28 day RSIs.
Args:
features: Pandas DataFrame instance with columns as numpy.float32 features.
columns_to_set: List of strings of feature names to make ... | [
"Sets",
"features",
"of",
"double",
"the",
"duration"
] | train | https://github.com/amicks/Speculator/blob/f7d6590aded20b1e1b5df16a4b27228ee821c4ab/speculator/market.py#L80-L109 |
amicks/Speculator | speculator/models/random_forest.py | RandomForest.feature_importances | def feature_importances(self):
""" Return list of features and their importance in classification """
feature_names = [feature for feature in self.features.train]
return list(zip(feature_names, self.feature_importances_)) | python | def feature_importances(self):
""" Return list of features and their importance in classification """
feature_names = [feature for feature in self.features.train]
return list(zip(feature_names, self.feature_importances_)) | [
"def",
"feature_importances",
"(",
"self",
")",
":",
"feature_names",
"=",
"[",
"feature",
"for",
"feature",
"in",
"self",
".",
"features",
".",
"train",
"]",
"return",
"list",
"(",
"zip",
"(",
"feature_names",
",",
"self",
".",
"feature_importances_",
")",
... | Return list of features and their importance in classification | [
"Return",
"list",
"of",
"features",
"and",
"their",
"importance",
"in",
"classification"
] | train | https://github.com/amicks/Speculator/blob/f7d6590aded20b1e1b5df16a4b27228ee821c4ab/speculator/models/random_forest.py#L31-L34 |
seznam/shelter | shelter/commands/runserver.py | ProcessWrapper.exitcode | def exitcode(self):
"""
Process exit code. :const:`0` when process exited successfully,
positive number when exception was occurred, negative number when
process was signaled and :data:`None` when process has not exited
yet.
"""
if self._process is None:
... | python | def exitcode(self):
"""
Process exit code. :const:`0` when process exited successfully,
positive number when exception was occurred, negative number when
process was signaled and :data:`None` when process has not exited
yet.
"""
if self._process is None:
... | [
"def",
"exitcode",
"(",
"self",
")",
":",
"if",
"self",
".",
"_process",
"is",
"None",
":",
"raise",
"ProcessError",
"(",
"\"Process '%s' has not been started yet\"",
"%",
"self",
".",
"name",
")",
"return",
"self",
".",
"_process",
".",
"exitcode"
] | Process exit code. :const:`0` when process exited successfully,
positive number when exception was occurred, negative number when
process was signaled and :data:`None` when process has not exited
yet. | [
"Process",
"exit",
"code",
".",
":",
"const",
":",
"0",
"when",
"process",
"exited",
"successfully",
"positive",
"number",
"when",
"exception",
"was",
"occurred",
"negative",
"number",
"when",
"process",
"was",
"signaled",
"and",
":",
"data",
":",
"None",
"w... | train | https://github.com/seznam/shelter/blob/c652b0ff1cca70158f8fc97d9210c1fa5961ac1c/shelter/commands/runserver.py#L75-L85 |
seznam/shelter | shelter/commands/runserver.py | ProcessWrapper.start | def start(self):
"""
Run the process.
"""
if self:
raise ProcessError(
"Process '%s' has been already started" % self.name)
first_run = not self.has_started
# Run process
self._process = self._process_cls(*self._process_args)
se... | python | def start(self):
"""
Run the process.
"""
if self:
raise ProcessError(
"Process '%s' has been already started" % self.name)
first_run = not self.has_started
# Run process
self._process = self._process_cls(*self._process_args)
se... | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
":",
"raise",
"ProcessError",
"(",
"\"Process '%s' has been already started\"",
"%",
"self",
".",
"name",
")",
"first_run",
"=",
"not",
"self",
".",
"has_started",
"# Run process",
"self",
".",
"_process",
"... | Run the process. | [
"Run",
"the",
"process",
"."
] | train | https://github.com/seznam/shelter/blob/c652b0ff1cca70158f8fc97d9210c1fa5961ac1c/shelter/commands/runserver.py#L104-L127 |
seznam/shelter | shelter/commands/runserver.py | TornadoProcess.stop | def stop(self):
"""
Stop the worker.
"""
if self._http_server is not None:
self._http_server.stop()
tornado.ioloop.IOLoop.instance().add_callback(
tornado.ioloop.IOLoop.instance().stop) | python | def stop(self):
"""
Stop the worker.
"""
if self._http_server is not None:
self._http_server.stop()
tornado.ioloop.IOLoop.instance().add_callback(
tornado.ioloop.IOLoop.instance().stop) | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"self",
".",
"_http_server",
"is",
"not",
"None",
":",
"self",
".",
"_http_server",
".",
"stop",
"(",
")",
"tornado",
".",
"ioloop",
".",
"IOLoop",
".",
"instance",
"(",
")",
".",
"add_callback",
"(",
"torn... | Stop the worker. | [
"Stop",
"the",
"worker",
"."
] | train | https://github.com/seznam/shelter/blob/c652b0ff1cca70158f8fc97d9210c1fa5961ac1c/shelter/commands/runserver.py#L164-L171 |
seznam/shelter | shelter/commands/runserver.py | TornadoProcess.run | def run(self):
"""
Tornado worker which handles HTTP requests.
"""
setproctitle.setproctitle("{:s}: worker {:s}".format(
self.context.config.name,
self._tornado_app.settings['interface'].name))
self.logger.info(
"Worker '%s' has been started wi... | python | def run(self):
"""
Tornado worker which handles HTTP requests.
"""
setproctitle.setproctitle("{:s}: worker {:s}".format(
self.context.config.name,
self._tornado_app.settings['interface'].name))
self.logger.info(
"Worker '%s' has been started wi... | [
"def",
"run",
"(",
"self",
")",
":",
"setproctitle",
".",
"setproctitle",
"(",
"\"{:s}: worker {:s}\"",
".",
"format",
"(",
"self",
".",
"context",
".",
"config",
".",
"name",
",",
"self",
".",
"_tornado_app",
".",
"settings",
"[",
"'interface'",
"]",
".",... | Tornado worker which handles HTTP requests. | [
"Tornado",
"worker",
"which",
"handles",
"HTTP",
"requests",
"."
] | train | https://github.com/seznam/shelter/blob/c652b0ff1cca70158f8fc97d9210c1fa5961ac1c/shelter/commands/runserver.py#L173-L224 |
seznam/shelter | shelter/commands/runserver.py | RunServer.initialize | def initialize(self):
"""
Initialize instance attributes. You can override this method in
the subclasses.
"""
self.main_pid = os.getpid()
self.processes.extend(self.init_service_processes())
self.processes.extend(self.init_tornado_workers()) | python | def initialize(self):
"""
Initialize instance attributes. You can override this method in
the subclasses.
"""
self.main_pid = os.getpid()
self.processes.extend(self.init_service_processes())
self.processes.extend(self.init_tornado_workers()) | [
"def",
"initialize",
"(",
"self",
")",
":",
"self",
".",
"main_pid",
"=",
"os",
".",
"getpid",
"(",
")",
"self",
".",
"processes",
".",
"extend",
"(",
"self",
".",
"init_service_processes",
"(",
")",
")",
"self",
".",
"processes",
".",
"extend",
"(",
... | Initialize instance attributes. You can override this method in
the subclasses. | [
"Initialize",
"instance",
"attributes",
".",
"You",
"can",
"override",
"this",
"method",
"in",
"the",
"subclasses",
"."
] | train | https://github.com/seznam/shelter/blob/c652b0ff1cca70158f8fc97d9210c1fa5961ac1c/shelter/commands/runserver.py#L238-L245 |
seznam/shelter | shelter/commands/runserver.py | RunServer.sigusr1_handler | def sigusr1_handler(self, unused_signum, unused_frame):
"""
Handle SIGUSR1 signal. Call function which is defined in the
**settings.SIGUSR1_HANDLER**. If main process, forward the
signal to all child processes.
"""
for process in self.processes:
if process.pid... | python | def sigusr1_handler(self, unused_signum, unused_frame):
"""
Handle SIGUSR1 signal. Call function which is defined in the
**settings.SIGUSR1_HANDLER**. If main process, forward the
signal to all child processes.
"""
for process in self.processes:
if process.pid... | [
"def",
"sigusr1_handler",
"(",
"self",
",",
"unused_signum",
",",
"unused_frame",
")",
":",
"for",
"process",
"in",
"self",
".",
"processes",
":",
"if",
"process",
".",
"pid",
"and",
"os",
".",
"getpid",
"(",
")",
"==",
"self",
".",
"main_pid",
":",
"t... | Handle SIGUSR1 signal. Call function which is defined in the
**settings.SIGUSR1_HANDLER**. If main process, forward the
signal to all child processes. | [
"Handle",
"SIGUSR1",
"signal",
".",
"Call",
"function",
"which",
"is",
"defined",
"in",
"the",
"**",
"settings",
".",
"SIGUSR1_HANDLER",
"**",
".",
"If",
"main",
"process",
"forward",
"the",
"signal",
"to",
"all",
"child",
"processes",
"."
] | train | https://github.com/seznam/shelter/blob/c652b0ff1cca70158f8fc97d9210c1fa5961ac1c/shelter/commands/runserver.py#L247-L260 |
seznam/shelter | shelter/commands/runserver.py | RunServer.init_service_processes | def init_service_processes(self):
"""
Prepare processes defined in the **settings.SERVICE_PROCESSES**.
Return :class:`list` of the :class:`ProcessWrapper` instances.
"""
processes = []
for process_struct in getattr(
self.context.config.settings, 'SERVICE_... | python | def init_service_processes(self):
"""
Prepare processes defined in the **settings.SERVICE_PROCESSES**.
Return :class:`list` of the :class:`ProcessWrapper` instances.
"""
processes = []
for process_struct in getattr(
self.context.config.settings, 'SERVICE_... | [
"def",
"init_service_processes",
"(",
"self",
")",
":",
"processes",
"=",
"[",
"]",
"for",
"process_struct",
"in",
"getattr",
"(",
"self",
".",
"context",
".",
"config",
".",
"settings",
",",
"'SERVICE_PROCESSES'",
",",
"(",
")",
")",
":",
"process_cls",
"... | Prepare processes defined in the **settings.SERVICE_PROCESSES**.
Return :class:`list` of the :class:`ProcessWrapper` instances. | [
"Prepare",
"processes",
"defined",
"in",
"the",
"**",
"settings",
".",
"SERVICE_PROCESSES",
"**",
".",
"Return",
":",
"class",
":",
"list",
"of",
"the",
":",
"class",
":",
"ProcessWrapper",
"instances",
"."
] | train | https://github.com/seznam/shelter/blob/c652b0ff1cca70158f8fc97d9210c1fa5961ac1c/shelter/commands/runserver.py#L262-L284 |
seznam/shelter | shelter/commands/runserver.py | RunServer.init_tornado_workers | def init_tornado_workers(self):
"""
Prepare worker instances for all Tornado applications. Return
:class:`list` of the :class:`ProcessWrapper` instances.
"""
workers = []
for tornado_app in get_tornado_apps(self.context, debug=False):
interface = tornado_app.... | python | def init_tornado_workers(self):
"""
Prepare worker instances for all Tornado applications. Return
:class:`list` of the :class:`ProcessWrapper` instances.
"""
workers = []
for tornado_app in get_tornado_apps(self.context, debug=False):
interface = tornado_app.... | [
"def",
"init_tornado_workers",
"(",
"self",
")",
":",
"workers",
"=",
"[",
"]",
"for",
"tornado_app",
"in",
"get_tornado_apps",
"(",
"self",
".",
"context",
",",
"debug",
"=",
"False",
")",
":",
"interface",
"=",
"tornado_app",
".",
"settings",
"[",
"'inte... | Prepare worker instances for all Tornado applications. Return
:class:`list` of the :class:`ProcessWrapper` instances. | [
"Prepare",
"worker",
"instances",
"for",
"all",
"Tornado",
"applications",
".",
"Return",
":",
"class",
":",
"list",
"of",
"the",
":",
"class",
":",
"ProcessWrapper",
"instances",
"."
] | train | https://github.com/seznam/shelter/blob/c652b0ff1cca70158f8fc97d9210c1fa5961ac1c/shelter/commands/runserver.py#L286-L328 |
seznam/shelter | shelter/commands/runserver.py | RunServer.start_processes | def start_processes(self, max_restarts=-1):
"""
Start processes and check their status. When some process crashes,
start it again. *max_restarts* is maximum amount of the restarts
across all processes. *processes* is a :class:`list` of the
:class:`ProcessWrapper` instances.
... | python | def start_processes(self, max_restarts=-1):
"""
Start processes and check their status. When some process crashes,
start it again. *max_restarts* is maximum amount of the restarts
across all processes. *processes* is a :class:`list` of the
:class:`ProcessWrapper` instances.
... | [
"def",
"start_processes",
"(",
"self",
",",
"max_restarts",
"=",
"-",
"1",
")",
":",
"while",
"1",
":",
"for",
"process",
"in",
"self",
".",
"processes",
":",
"if",
"not",
"process",
":",
"# When process has not been started, start it",
"if",
"not",
"process",... | Start processes and check their status. When some process crashes,
start it again. *max_restarts* is maximum amount of the restarts
across all processes. *processes* is a :class:`list` of the
:class:`ProcessWrapper` instances. | [
"Start",
"processes",
"and",
"check",
"their",
"status",
".",
"When",
"some",
"process",
"crashes",
"start",
"it",
"again",
".",
"*",
"max_restarts",
"*",
"is",
"maximum",
"amount",
"of",
"the",
"restarts",
"across",
"all",
"processes",
".",
"*",
"processes"... | train | https://github.com/seznam/shelter/blob/c652b0ff1cca70158f8fc97d9210c1fa5961ac1c/shelter/commands/runserver.py#L330-L383 |
seznam/shelter | shelter/commands/runserver.py | RunServer.command | def command(self):
"""
**runserver** command implementation.
"""
setproctitle.setproctitle(
"{:s}: master process '{:s}'".format(
self.context.config.name, " ".join(sys.argv)
))
# Init and start processes
try:
self.star... | python | def command(self):
"""
**runserver** command implementation.
"""
setproctitle.setproctitle(
"{:s}: master process '{:s}'".format(
self.context.config.name, " ".join(sys.argv)
))
# Init and start processes
try:
self.star... | [
"def",
"command",
"(",
"self",
")",
":",
"setproctitle",
".",
"setproctitle",
"(",
"\"{:s}: master process '{:s}'\"",
".",
"format",
"(",
"self",
".",
"context",
".",
"config",
".",
"name",
",",
"\" \"",
".",
"join",
"(",
"sys",
".",
"argv",
")",
")",
")... | **runserver** command implementation. | [
"**",
"runserver",
"**",
"command",
"implementation",
"."
] | train | https://github.com/seznam/shelter/blob/c652b0ff1cca70158f8fc97d9210c1fa5961ac1c/shelter/commands/runserver.py#L385-L401 |
fhcrc/taxtastic | taxtastic/lonely.py | taxtable_to_tree | def taxtable_to_tree(handle):
"""Read a CSV taxonomy from *handle* into a Tree."""
c = csv.reader(handle, quoting=csv.QUOTE_NONNUMERIC)
header = next(c)
rootdict = dict(list(zip(header, next(c))))
t = Tree(rootdict['tax_id'], rank=rootdict[
'rank'], tax_name=rootdict['tax_name'])
fo... | python | def taxtable_to_tree(handle):
"""Read a CSV taxonomy from *handle* into a Tree."""
c = csv.reader(handle, quoting=csv.QUOTE_NONNUMERIC)
header = next(c)
rootdict = dict(list(zip(header, next(c))))
t = Tree(rootdict['tax_id'], rank=rootdict[
'rank'], tax_name=rootdict['tax_name'])
fo... | [
"def",
"taxtable_to_tree",
"(",
"handle",
")",
":",
"c",
"=",
"csv",
".",
"reader",
"(",
"handle",
",",
"quoting",
"=",
"csv",
".",
"QUOTE_NONNUMERIC",
")",
"header",
"=",
"next",
"(",
"c",
")",
"rootdict",
"=",
"dict",
"(",
"list",
"(",
"zip",
"(",
... | Read a CSV taxonomy from *handle* into a Tree. | [
"Read",
"a",
"CSV",
"taxonomy",
"from",
"*",
"handle",
"*",
"into",
"a",
"Tree",
"."
] | train | https://github.com/fhcrc/taxtastic/blob/4e874b7f2cc146178828bfba386314f8c342722b/taxtastic/lonely.py#L70-L81 |
fhcrc/taxtastic | taxtastic/lonely.py | lonely_company | def lonely_company(taxonomy, tax_ids):
"""Return a set of species tax_ids which will makes those in *tax_ids* not lonely.
The returned species will probably themselves be lonely.
"""
return [taxonomy.species_below(taxonomy.sibling_of(t)) for t in tax_ids] | python | def lonely_company(taxonomy, tax_ids):
"""Return a set of species tax_ids which will makes those in *tax_ids* not lonely.
The returned species will probably themselves be lonely.
"""
return [taxonomy.species_below(taxonomy.sibling_of(t)) for t in tax_ids] | [
"def",
"lonely_company",
"(",
"taxonomy",
",",
"tax_ids",
")",
":",
"return",
"[",
"taxonomy",
".",
"species_below",
"(",
"taxonomy",
".",
"sibling_of",
"(",
"t",
")",
")",
"for",
"t",
"in",
"tax_ids",
"]"
] | Return a set of species tax_ids which will makes those in *tax_ids* not lonely.
The returned species will probably themselves be lonely. | [
"Return",
"a",
"set",
"of",
"species",
"tax_ids",
"which",
"will",
"makes",
"those",
"in",
"*",
"tax_ids",
"*",
"not",
"lonely",
"."
] | train | https://github.com/fhcrc/taxtastic/blob/4e874b7f2cc146178828bfba386314f8c342722b/taxtastic/lonely.py#L84-L89 |
fhcrc/taxtastic | taxtastic/lonely.py | solid_company | def solid_company(taxonomy, tax_ids):
"""Return a set of non-lonely species tax_ids that will make those in *tax_ids* not lonely."""
res = []
for t in tax_ids:
res.extend(taxonomy.nary_subtree(taxonomy.sibling_of(t), 2) or [])
return res | python | def solid_company(taxonomy, tax_ids):
"""Return a set of non-lonely species tax_ids that will make those in *tax_ids* not lonely."""
res = []
for t in tax_ids:
res.extend(taxonomy.nary_subtree(taxonomy.sibling_of(t), 2) or [])
return res | [
"def",
"solid_company",
"(",
"taxonomy",
",",
"tax_ids",
")",
":",
"res",
"=",
"[",
"]",
"for",
"t",
"in",
"tax_ids",
":",
"res",
".",
"extend",
"(",
"taxonomy",
".",
"nary_subtree",
"(",
"taxonomy",
".",
"sibling_of",
"(",
"t",
")",
",",
"2",
")",
... | Return a set of non-lonely species tax_ids that will make those in *tax_ids* not lonely. | [
"Return",
"a",
"set",
"of",
"non",
"-",
"lonely",
"species",
"tax_ids",
"that",
"will",
"make",
"those",
"in",
"*",
"tax_ids",
"*",
"not",
"lonely",
"."
] | train | https://github.com/fhcrc/taxtastic/blob/4e874b7f2cc146178828bfba386314f8c342722b/taxtastic/lonely.py#L92-L97 |
amicks/Speculator | speculator/features/OBV.py | OBV.eval_algorithm | def eval_algorithm(curr, prev):
""" Evaluates OBV
Args:
curr: Dict of current volume and close
prev: Dict of previous OBV and close
Returns:
Float of OBV
"""
if curr['close'] > prev['close']:
v = curr['volume']
elif curr['... | python | def eval_algorithm(curr, prev):
""" Evaluates OBV
Args:
curr: Dict of current volume and close
prev: Dict of previous OBV and close
Returns:
Float of OBV
"""
if curr['close'] > prev['close']:
v = curr['volume']
elif curr['... | [
"def",
"eval_algorithm",
"(",
"curr",
",",
"prev",
")",
":",
"if",
"curr",
"[",
"'close'",
"]",
">",
"prev",
"[",
"'close'",
"]",
":",
"v",
"=",
"curr",
"[",
"'volume'",
"]",
"elif",
"curr",
"[",
"'close'",
"]",
"<",
"prev",
"[",
"'close'",
"]",
... | Evaluates OBV
Args:
curr: Dict of current volume and close
prev: Dict of previous OBV and close
Returns:
Float of OBV | [
"Evaluates",
"OBV"
] | train | https://github.com/amicks/Speculator/blob/f7d6590aded20b1e1b5df16a4b27228ee821c4ab/speculator/features/OBV.py#L14-L30 |
amicks/Speculator | speculator/features/OBV.py | OBV.eval_from_json | def eval_from_json(json):
""" Evaluates OBV from JSON (typically Poloniex API response)
Args:
json: List of dates where each entry is a dict of raw market data.
Returns:
Float of OBV
"""
closes = poloniex.get_attribute(json, 'close')
volumes = po... | python | def eval_from_json(json):
""" Evaluates OBV from JSON (typically Poloniex API response)
Args:
json: List of dates where each entry is a dict of raw market data.
Returns:
Float of OBV
"""
closes = poloniex.get_attribute(json, 'close')
volumes = po... | [
"def",
"eval_from_json",
"(",
"json",
")",
":",
"closes",
"=",
"poloniex",
".",
"get_attribute",
"(",
"json",
",",
"'close'",
")",
"volumes",
"=",
"poloniex",
".",
"get_attribute",
"(",
"json",
",",
"'volume'",
")",
"obv",
"=",
"0",
"for",
"date",
"in",
... | Evaluates OBV from JSON (typically Poloniex API response)
Args:
json: List of dates where each entry is a dict of raw market data.
Returns:
Float of OBV | [
"Evaluates",
"OBV",
"from",
"JSON",
"(",
"typically",
"Poloniex",
"API",
"response",
")"
] | train | https://github.com/amicks/Speculator/blob/f7d6590aded20b1e1b5df16a4b27228ee821c4ab/speculator/features/OBV.py#L32-L48 |
fhcrc/taxtastic | taxtastic/refpkg.py | scratch_file | def scratch_file(unlink=True, **kwargs):
"""Create a temporary file and return its name.
Additional arguments are passed to :class:`tempfile.NamedTemporaryFile`
At the start of the with block a secure, temporary file is created
and its name returned. At the end of the with block it is
deleted.
... | python | def scratch_file(unlink=True, **kwargs):
"""Create a temporary file and return its name.
Additional arguments are passed to :class:`tempfile.NamedTemporaryFile`
At the start of the with block a secure, temporary file is created
and its name returned. At the end of the with block it is
deleted.
... | [
"def",
"scratch_file",
"(",
"unlink",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'delete'",
"]",
"=",
"False",
"tf",
"=",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"*",
"*",
"kwargs",
")",
"tf",
".",
"close",
"(",
")",
"try",
... | Create a temporary file and return its name.
Additional arguments are passed to :class:`tempfile.NamedTemporaryFile`
At the start of the with block a secure, temporary file is created
and its name returned. At the end of the with block it is
deleted. | [
"Create",
"a",
"temporary",
"file",
"and",
"return",
"its",
"name",
"."
] | train | https://github.com/fhcrc/taxtastic/blob/4e874b7f2cc146178828bfba386314f8c342722b/taxtastic/refpkg.py#L66-L82 |
fhcrc/taxtastic | taxtastic/refpkg.py | Refpkg.open | def open(self, name, *mode):
"""
Return an open file object for a file in the reference package.
"""
return self.file_factory(self.file_path(name), *mode) | python | def open(self, name, *mode):
"""
Return an open file object for a file in the reference package.
"""
return self.file_factory(self.file_path(name), *mode) | [
"def",
"open",
"(",
"self",
",",
"name",
",",
"*",
"mode",
")",
":",
"return",
"self",
".",
"file_factory",
"(",
"self",
".",
"file_path",
"(",
"name",
")",
",",
"*",
"mode",
")"
] | Return an open file object for a file in the reference package. | [
"Return",
"an",
"open",
"file",
"object",
"for",
"a",
"file",
"in",
"the",
"reference",
"package",
"."
] | train | https://github.com/fhcrc/taxtastic/blob/4e874b7f2cc146178828bfba386314f8c342722b/taxtastic/refpkg.py#L227-L231 |
fhcrc/taxtastic | taxtastic/refpkg.py | Refpkg.open_resource | def open_resource(self, resource, *mode):
"""
Return an open file object for a particular named resource in this
reference package.
"""
return self.open(self.resource_name(resource), *mode) | python | def open_resource(self, resource, *mode):
"""
Return an open file object for a particular named resource in this
reference package.
"""
return self.open(self.resource_name(resource), *mode) | [
"def",
"open_resource",
"(",
"self",
",",
"resource",
",",
"*",
"mode",
")",
":",
"return",
"self",
".",
"open",
"(",
"self",
".",
"resource_name",
"(",
"resource",
")",
",",
"*",
"mode",
")"
] | Return an open file object for a particular named resource in this
reference package. | [
"Return",
"an",
"open",
"file",
"object",
"for",
"a",
"particular",
"named",
"resource",
"in",
"this",
"reference",
"package",
"."
] | train | https://github.com/fhcrc/taxtastic/blob/4e874b7f2cc146178828bfba386314f8c342722b/taxtastic/refpkg.py#L240-L245 |
fhcrc/taxtastic | taxtastic/refpkg.py | Refpkg.resource_name | def resource_name(self, resource):
"""
Return the name of the file within the reference package for a
particular named resource.
"""
if not(resource in self.contents['files']):
raise ValueError("No such resource %r in refpkg" % (resource,))
return self.content... | python | def resource_name(self, resource):
"""
Return the name of the file within the reference package for a
particular named resource.
"""
if not(resource in self.contents['files']):
raise ValueError("No such resource %r in refpkg" % (resource,))
return self.content... | [
"def",
"resource_name",
"(",
"self",
",",
"resource",
")",
":",
"if",
"not",
"(",
"resource",
"in",
"self",
".",
"contents",
"[",
"'files'",
"]",
")",
":",
"raise",
"ValueError",
"(",
"\"No such resource %r in refpkg\"",
"%",
"(",
"resource",
",",
")",
")"... | Return the name of the file within the reference package for a
particular named resource. | [
"Return",
"the",
"name",
"of",
"the",
"file",
"within",
"the",
"reference",
"package",
"for",
"a",
"particular",
"named",
"resource",
"."
] | train | https://github.com/fhcrc/taxtastic/blob/4e874b7f2cc146178828bfba386314f8c342722b/taxtastic/refpkg.py#L247-L254 |
fhcrc/taxtastic | taxtastic/refpkg.py | Refpkg.resource_md5 | def resource_md5(self, resource):
"""Return the stored MD5 sum for a particular named resource."""
if not(resource in self.contents['md5']):
raise ValueError("No such resource %r in refpkg" % (resource,))
return self.contents['md5'][resource] | python | def resource_md5(self, resource):
"""Return the stored MD5 sum for a particular named resource."""
if not(resource in self.contents['md5']):
raise ValueError("No such resource %r in refpkg" % (resource,))
return self.contents['md5'][resource] | [
"def",
"resource_md5",
"(",
"self",
",",
"resource",
")",
":",
"if",
"not",
"(",
"resource",
"in",
"self",
".",
"contents",
"[",
"'md5'",
"]",
")",
":",
"raise",
"ValueError",
"(",
"\"No such resource %r in refpkg\"",
"%",
"(",
"resource",
",",
")",
")",
... | Return the stored MD5 sum for a particular named resource. | [
"Return",
"the",
"stored",
"MD5",
"sum",
"for",
"a",
"particular",
"named",
"resource",
"."
] | train | https://github.com/fhcrc/taxtastic/blob/4e874b7f2cc146178828bfba386314f8c342722b/taxtastic/refpkg.py#L256-L260 |
fhcrc/taxtastic | taxtastic/refpkg.py | Refpkg._set_defaults | def _set_defaults(self):
"""
Set some default values in the manifest.
This method should be called after loading from disk, but before
checking the integrity of the reference package.
"""
self.contents.setdefault('log', [])
self.contents.setdefault('rollback', No... | python | def _set_defaults(self):
"""
Set some default values in the manifest.
This method should be called after loading from disk, but before
checking the integrity of the reference package.
"""
self.contents.setdefault('log', [])
self.contents.setdefault('rollback', No... | [
"def",
"_set_defaults",
"(",
"self",
")",
":",
"self",
".",
"contents",
".",
"setdefault",
"(",
"'log'",
",",
"[",
"]",
")",
"self",
".",
"contents",
".",
"setdefault",
"(",
"'rollback'",
",",
"None",
")",
"self",
".",
"contents",
".",
"setdefault",
"(... | Set some default values in the manifest.
This method should be called after loading from disk, but before
checking the integrity of the reference package. | [
"Set",
"some",
"default",
"values",
"in",
"the",
"manifest",
"."
] | train | https://github.com/fhcrc/taxtastic/blob/4e874b7f2cc146178828bfba386314f8c342722b/taxtastic/refpkg.py#L277-L286 |
fhcrc/taxtastic | taxtastic/refpkg.py | Refpkg._sync_to_disk | def _sync_to_disk(self):
"""Write any changes made on Refpkg to disk.
Other methods of Refpkg that alter the contents of the package
will call this method themselves. Generally you should never
have to call it by hand. The only exception would be if
another program has changed... | python | def _sync_to_disk(self):
"""Write any changes made on Refpkg to disk.
Other methods of Refpkg that alter the contents of the package
will call this method themselves. Generally you should never
have to call it by hand. The only exception would be if
another program has changed... | [
"def",
"_sync_to_disk",
"(",
"self",
")",
":",
"with",
"self",
".",
"open_manifest",
"(",
"'w'",
")",
"as",
"h",
":",
"json",
".",
"dump",
"(",
"self",
".",
"contents",
",",
"h",
",",
"indent",
"=",
"4",
")",
"h",
".",
"write",
"(",
"'\\n'",
")"
... | Write any changes made on Refpkg to disk.
Other methods of Refpkg that alter the contents of the package
will call this method themselves. Generally you should never
have to call it by hand. The only exception would be if
another program has changed the Refpkg on disk while your
... | [
"Write",
"any",
"changes",
"made",
"on",
"Refpkg",
"to",
"disk",
"."
] | train | https://github.com/fhcrc/taxtastic/blob/4e874b7f2cc146178828bfba386314f8c342722b/taxtastic/refpkg.py#L288-L300 |
fhcrc/taxtastic | taxtastic/refpkg.py | Refpkg._sync_from_disk | def _sync_from_disk(self):
"""Read any changes made on disk to this Refpkg.
This is necessary if other programs are making changes to the
Refpkg on disk and your program must be synchronized to them.
"""
try:
fobj = self.open_manifest('r')
except IOError as ... | python | def _sync_from_disk(self):
"""Read any changes made on disk to this Refpkg.
This is necessary if other programs are making changes to the
Refpkg on disk and your program must be synchronized to them.
"""
try:
fobj = self.open_manifest('r')
except IOError as ... | [
"def",
"_sync_from_disk",
"(",
"self",
")",
":",
"try",
":",
"fobj",
"=",
"self",
".",
"open_manifest",
"(",
"'r'",
")",
"except",
"IOError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
"ENOENT",
":",
"raise",
"ValueError",
"(",
"\"c... | Read any changes made on disk to this Refpkg.
This is necessary if other programs are making changes to the
Refpkg on disk and your program must be synchronized to them. | [
"Read",
"any",
"changes",
"made",
"on",
"disk",
"to",
"this",
"Refpkg",
"."
] | train | https://github.com/fhcrc/taxtastic/blob/4e874b7f2cc146178828bfba386314f8c342722b/taxtastic/refpkg.py#L302-L323 |
fhcrc/taxtastic | taxtastic/refpkg.py | Refpkg._add_file | def _add_file(self, key, path):
"""Copy a file into the reference package."""
filename = os.path.basename(path)
base, ext = os.path.splitext(filename)
if os.path.exists(self.file_path(filename)):
with tempfile.NamedTemporaryFile(
dir=self.path, prefix=base... | python | def _add_file(self, key, path):
"""Copy a file into the reference package."""
filename = os.path.basename(path)
base, ext = os.path.splitext(filename)
if os.path.exists(self.file_path(filename)):
with tempfile.NamedTemporaryFile(
dir=self.path, prefix=base... | [
"def",
"_add_file",
"(",
"self",
",",
"key",
",",
"path",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"path",
")",
"base",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"if",
"os",
".",
"path",... | Copy a file into the reference package. | [
"Copy",
"a",
"file",
"into",
"the",
"reference",
"package",
"."
] | train | https://github.com/fhcrc/taxtastic/blob/4e874b7f2cc146178828bfba386314f8c342722b/taxtastic/refpkg.py#L325-L334 |
fhcrc/taxtastic | taxtastic/refpkg.py | Refpkg.is_invalid | def is_invalid(self):
"""Check if this RefPkg is invalid.
Valid means that it contains a properly named manifest, and
each of the files described in the manifest exists and has the
proper MD5 hashsum.
If the Refpkg is valid, is_invalid returns False. Otherwise it
retur... | python | def is_invalid(self):
"""Check if this RefPkg is invalid.
Valid means that it contains a properly named manifest, and
each of the files described in the manifest exists and has the
proper MD5 hashsum.
If the Refpkg is valid, is_invalid returns False. Otherwise it
retur... | [
"def",
"is_invalid",
"(",
"self",
")",
":",
"# Manifest file contains the proper keys",
"for",
"k",
"in",
"[",
"'metadata'",
",",
"'files'",
",",
"'md5'",
"]",
":",
"if",
"not",
"(",
"k",
"in",
"self",
".",
"contents",
")",
":",
"return",
"\"Manifest file mi... | Check if this RefPkg is invalid.
Valid means that it contains a properly named manifest, and
each of the files described in the manifest exists and has the
proper MD5 hashsum.
If the Refpkg is valid, is_invalid returns False. Otherwise it
returns a nonempty string describing t... | [
"Check",
"if",
"this",
"RefPkg",
"is",
"invalid",
"."
] | train | https://github.com/fhcrc/taxtastic/blob/4e874b7f2cc146178828bfba386314f8c342722b/taxtastic/refpkg.py#L369-L435 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.