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
devopshq/youtrack
youtrack/import_helper.py
create_custom_field
def create_custom_field(connection, cf_type, cf_name, auto_attached, value_names=None, bundle_policy="0"): """ Creates custom field prototype(if not exist) and sets default values bundle if needed Args: connection: An opened Connection instance. cf_type: Type of custom field to be created ...
python
def create_custom_field(connection, cf_type, cf_name, auto_attached, value_names=None, bundle_policy="0"): """ Creates custom field prototype(if not exist) and sets default values bundle if needed Args: connection: An opened Connection instance. cf_type: Type of custom field to be created ...
[ "def", "create_custom_field", "(", "connection", ",", "cf_type", ",", "cf_name", ",", "auto_attached", ",", "value_names", "=", "None", ",", "bundle_policy", "=", "\"0\"", ")", ":", "if", "(", "value_names", "is", "None", ")", "and", "(", "not", "auto_attach...
Creates custom field prototype(if not exist) and sets default values bundle if needed Args: connection: An opened Connection instance. cf_type: Type of custom field to be created cf_name: Name of custom field that should be created (if not exists) auto_attached: If this field shoul...
[ "Creates", "custom", "field", "prototype", "(", "if", "not", "exist", ")", "and", "sets", "default", "values", "bundle", "if", "needed" ]
train
https://github.com/devopshq/youtrack/blob/c4ec19aca253ae30ac8eee7976a2f330e480a73b/youtrack/import_helper.py#L32-L72
devopshq/youtrack
youtrack/import_helper.py
process_custom_field
def process_custom_field(connection, project_id, cf_type, cf_name, value_names=None): """ Creates custom field and attaches it to the project. If custom field already exists and has type cf_type it is attached to the project. If it has another type, LogicException is raised. If project field already exi...
python
def process_custom_field(connection, project_id, cf_type, cf_name, value_names=None): """ Creates custom field and attaches it to the project. If custom field already exists and has type cf_type it is attached to the project. If it has another type, LogicException is raised. If project field already exi...
[ "def", "process_custom_field", "(", "connection", ",", "project_id", ",", "cf_type", ",", "cf_name", ",", "value_names", "=", "None", ")", ":", "_create_custom_field_prototype", "(", "connection", ",", "cf_type", ",", "cf_name", ")", "if", "cf_type", "[", "0", ...
Creates custom field and attaches it to the project. If custom field already exists and has type cf_type it is attached to the project. If it has another type, LogicException is raised. If project field already exists, uses it and bundle from it. If not, creates project field and bundle with name <cf_name>_...
[ "Creates", "custom", "field", "and", "attaches", "it", "to", "the", "project", ".", "If", "custom", "field", "already", "exists", "and", "has", "type", "cf_type", "it", "is", "attached", "to", "the", "project", ".", "If", "it", "has", "another", "type", ...
train
https://github.com/devopshq/youtrack/blob/c4ec19aca253ae30ac8eee7976a2f330e480a73b/youtrack/import_helper.py#L93-L136
devopshq/youtrack
youtrack/import_helper.py
add_values_to_bundle_safe
def add_values_to_bundle_safe(connection, bundle, values): """ Adds values to specified bundle. Checks, whether each value already contains in bundle. If yes, it is not added. Args: connection: An opened Connection instance. bundle: Bundle instance to add values in. values: Values, ...
python
def add_values_to_bundle_safe(connection, bundle, values): """ Adds values to specified bundle. Checks, whether each value already contains in bundle. If yes, it is not added. Args: connection: An opened Connection instance. bundle: Bundle instance to add values in. values: Values, ...
[ "def", "add_values_to_bundle_safe", "(", "connection", ",", "bundle", ",", "values", ")", ":", "for", "value", "in", "values", ":", "try", ":", "connection", ".", "addValueToBundle", "(", "bundle", ",", "value", ")", "except", "YouTrackException", "as", "e", ...
Adds values to specified bundle. Checks, whether each value already contains in bundle. If yes, it is not added. Args: connection: An opened Connection instance. bundle: Bundle instance to add values in. values: Values, that should be added in bundle. Raises: YouTrackException:...
[ "Adds", "values", "to", "specified", "bundle", ".", "Checks", "whether", "each", "value", "already", "contains", "in", "bundle", ".", "If", "yes", "it", "is", "not", "added", "." ]
train
https://github.com/devopshq/youtrack/blob/c4ec19aca253ae30ac8eee7976a2f330e480a73b/youtrack/import_helper.py#L139-L159
jpadilla/django-rest-framework-yaml
rest_framework_yaml/parsers.py
YAMLParser.parse
def parse(self, stream, media_type=None, parser_context=None): """ Parses the incoming bytestream as YAML and returns the resulting data. """ assert yaml, 'YAMLParser requires pyyaml to be installed' parser_context = parser_context or {} encoding = parser_context.get('en...
python
def parse(self, stream, media_type=None, parser_context=None): """ Parses the incoming bytestream as YAML and returns the resulting data. """ assert yaml, 'YAMLParser requires pyyaml to be installed' parser_context = parser_context or {} encoding = parser_context.get('en...
[ "def", "parse", "(", "self", ",", "stream", ",", "media_type", "=", "None", ",", "parser_context", "=", "None", ")", ":", "assert", "yaml", ",", "'YAMLParser requires pyyaml to be installed'", "parser_context", "=", "parser_context", "or", "{", "}", "encoding", ...
Parses the incoming bytestream as YAML and returns the resulting data.
[ "Parses", "the", "incoming", "bytestream", "as", "YAML", "and", "returns", "the", "resulting", "data", "." ]
train
https://github.com/jpadilla/django-rest-framework-yaml/blob/4067e59874cdfe33fa36a25f275d3c91fffa15fe/rest_framework_yaml/parsers.py#L21-L34
jpadilla/django-rest-framework-yaml
rest_framework_yaml/renderers.py
YAMLRenderer.render
def render(self, data, accepted_media_type=None, renderer_context=None): """ Renders `data` into serialized YAML. """ assert yaml, 'YAMLRenderer requires pyyaml to be installed' if data is None: return '' return yaml.dump( data, strea...
python
def render(self, data, accepted_media_type=None, renderer_context=None): """ Renders `data` into serialized YAML. """ assert yaml, 'YAMLRenderer requires pyyaml to be installed' if data is None: return '' return yaml.dump( data, strea...
[ "def", "render", "(", "self", ",", "data", ",", "accepted_media_type", "=", "None", ",", "renderer_context", "=", "None", ")", ":", "assert", "yaml", ",", "'YAMLRenderer requires pyyaml to be installed'", "if", "data", "is", "None", ":", "return", "''", "return"...
Renders `data` into serialized YAML.
[ "Renders", "data", "into", "serialized", "YAML", "." ]
train
https://github.com/jpadilla/django-rest-framework-yaml/blob/4067e59874cdfe33fa36a25f275d3c91fffa15fe/rest_framework_yaml/renderers.py#L24-L40
ocadotechnology/django-closuretree
closuretree/models.py
create_closure_model
def create_closure_model(cls): """Creates a <Model>Closure model in the same module as the model.""" meta_vals = { 'unique_together': (("parent", "child"),) } if getattr(cls._meta, 'db_table', None): meta_vals['db_table'] = '%sclosure' % getattr(cls._meta, 'db_table') model = type('...
python
def create_closure_model(cls): """Creates a <Model>Closure model in the same module as the model.""" meta_vals = { 'unique_together': (("parent", "child"),) } if getattr(cls._meta, 'db_table', None): meta_vals['db_table'] = '%sclosure' % getattr(cls._meta, 'db_table') model = type('...
[ "def", "create_closure_model", "(", "cls", ")", ":", "meta_vals", "=", "{", "'unique_together'", ":", "(", "(", "\"parent\"", ",", "\"child\"", ")", ",", ")", "}", "if", "getattr", "(", "cls", ".", "_meta", ",", "'db_table'", ",", "None", ")", ":", "me...
Creates a <Model>Closure model in the same module as the model.
[ "Creates", "a", "<Model", ">", "Closure", "model", "in", "the", "same", "module", "as", "the", "model", "." ]
train
https://github.com/ocadotechnology/django-closuretree/blob/432717b20907f2e475a28de3605924f69b7d67b5/closuretree/models.py#L42-L64
ocadotechnology/django-closuretree
closuretree/models.py
ClosureModel._toplevel
def _toplevel(cls): """Find the top level of the chain we're in. For example, if we have: C inheriting from B inheriting from A inheriting from ClosureModel C._toplevel() will return A. """ superclasses = ( list(set(ClosureModel.__subclasses__()) ...
python
def _toplevel(cls): """Find the top level of the chain we're in. For example, if we have: C inheriting from B inheriting from A inheriting from ClosureModel C._toplevel() will return A. """ superclasses = ( list(set(ClosureModel.__subclasses__()) ...
[ "def", "_toplevel", "(", "cls", ")", ":", "superclasses", "=", "(", "list", "(", "set", "(", "ClosureModel", ".", "__subclasses__", "(", ")", ")", "&", "set", "(", "cls", ".", "_meta", ".", "get_parent_list", "(", ")", ")", ")", ")", "return", "next"...
Find the top level of the chain we're in. For example, if we have: C inheriting from B inheriting from A inheriting from ClosureModel C._toplevel() will return A.
[ "Find", "the", "top", "level", "of", "the", "chain", "we", "re", "in", "." ]
train
https://github.com/ocadotechnology/django-closuretree/blob/432717b20907f2e475a28de3605924f69b7d67b5/closuretree/models.py#L120-L131
ocadotechnology/django-closuretree
closuretree/models.py
ClosureModel.rebuildtable
def rebuildtable(cls): """Regenerate the entire closuretree.""" cls._closure_model.objects.all().delete() cls._closure_model.objects.bulk_create([cls._closure_model( parent_id=x['pk'], child_id=x['pk'], depth=0 ) for x in cls.objects.values("pk")]) ...
python
def rebuildtable(cls): """Regenerate the entire closuretree.""" cls._closure_model.objects.all().delete() cls._closure_model.objects.bulk_create([cls._closure_model( parent_id=x['pk'], child_id=x['pk'], depth=0 ) for x in cls.objects.values("pk")]) ...
[ "def", "rebuildtable", "(", "cls", ")", ":", "cls", ".", "_closure_model", ".", "objects", ".", "all", "(", ")", ".", "delete", "(", ")", "cls", ".", "_closure_model", ".", "objects", ".", "bulk_create", "(", "[", "cls", ".", "_closure_model", "(", "pa...
Regenerate the entire closuretree.
[ "Regenerate", "the", "entire", "closuretree", "." ]
train
https://github.com/ocadotechnology/django-closuretree/blob/432717b20907f2e475a28de3605924f69b7d67b5/closuretree/models.py#L134-L143
ocadotechnology/django-closuretree
closuretree/models.py
ClosureModel._closure_parent_pk
def _closure_parent_pk(self): """What our parent pk is in the closure tree.""" if hasattr(self, "%s_id" % self._closure_parent_attr): return getattr(self, "%s_id" % self._closure_parent_attr) else: parent = getattr(self, self._closure_parent_attr) return paren...
python
def _closure_parent_pk(self): """What our parent pk is in the closure tree.""" if hasattr(self, "%s_id" % self._closure_parent_attr): return getattr(self, "%s_id" % self._closure_parent_attr) else: parent = getattr(self, self._closure_parent_attr) return paren...
[ "def", "_closure_parent_pk", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "\"%s_id\"", "%", "self", ".", "_closure_parent_attr", ")", ":", "return", "getattr", "(", "self", ",", "\"%s_id\"", "%", "self", ".", "_closure_parent_attr", ")", "else",...
What our parent pk is in the closure tree.
[ "What", "our", "parent", "pk", "is", "in", "the", "closure", "tree", "." ]
train
https://github.com/ocadotechnology/django-closuretree/blob/432717b20907f2e475a28de3605924f69b7d67b5/closuretree/models.py#L176-L182
ocadotechnology/django-closuretree
closuretree/models.py
ClosureModel._closure_deletelink
def _closure_deletelink(self, oldparentpk): """Remove incorrect links from the closure tree.""" self._closure_model.objects.filter( **{ "parent__%s__child" % self._closure_parentref(): oldparentpk, "child__%s__parent" % self._closure_childref(): self.pk ...
python
def _closure_deletelink(self, oldparentpk): """Remove incorrect links from the closure tree.""" self._closure_model.objects.filter( **{ "parent__%s__child" % self._closure_parentref(): oldparentpk, "child__%s__parent" % self._closure_childref(): self.pk ...
[ "def", "_closure_deletelink", "(", "self", ",", "oldparentpk", ")", ":", "self", ".", "_closure_model", ".", "objects", ".", "filter", "(", "*", "*", "{", "\"parent__%s__child\"", "%", "self", ".", "_closure_parentref", "(", ")", ":", "oldparentpk", ",", "\"...
Remove incorrect links from the closure tree.
[ "Remove", "incorrect", "links", "from", "the", "closure", "tree", "." ]
train
https://github.com/ocadotechnology/django-closuretree/blob/432717b20907f2e475a28de3605924f69b7d67b5/closuretree/models.py#L184-L191
ocadotechnology/django-closuretree
closuretree/models.py
ClosureModel._closure_createlink
def _closure_createlink(self): """Create a link in the closure tree.""" linkparents = self._closure_model.objects.filter( child__pk=self._closure_parent_pk ).values("parent", "depth") linkchildren = self._closure_model.objects.filter( parent__pk=self.pk )....
python
def _closure_createlink(self): """Create a link in the closure tree.""" linkparents = self._closure_model.objects.filter( child__pk=self._closure_parent_pk ).values("parent", "depth") linkchildren = self._closure_model.objects.filter( parent__pk=self.pk )....
[ "def", "_closure_createlink", "(", "self", ")", ":", "linkparents", "=", "self", ".", "_closure_model", ".", "objects", ".", "filter", "(", "child__pk", "=", "self", ".", "_closure_parent_pk", ")", ".", "values", "(", "\"parent\"", ",", "\"depth\"", ")", "li...
Create a link in the closure tree.
[ "Create", "a", "link", "in", "the", "closure", "tree", "." ]
train
https://github.com/ocadotechnology/django-closuretree/blob/432717b20907f2e475a28de3605924f69b7d67b5/closuretree/models.py#L193-L206
ocadotechnology/django-closuretree
closuretree/models.py
ClosureModel.get_ancestors
def get_ancestors(self, include_self=False, depth=None): """Return all the ancestors of this object.""" if self.is_root_node(): if not include_self: return self._toplevel().objects.none() else: # Filter on pk for efficiency. return ...
python
def get_ancestors(self, include_self=False, depth=None): """Return all the ancestors of this object.""" if self.is_root_node(): if not include_self: return self._toplevel().objects.none() else: # Filter on pk for efficiency. return ...
[ "def", "get_ancestors", "(", "self", ",", "include_self", "=", "False", ",", "depth", "=", "None", ")", ":", "if", "self", ".", "is_root_node", "(", ")", ":", "if", "not", "include_self", ":", "return", "self", ".", "_toplevel", "(", ")", ".", "objects...
Return all the ancestors of this object.
[ "Return", "all", "the", "ancestors", "of", "this", "object", "." ]
train
https://github.com/ocadotechnology/django-closuretree/blob/432717b20907f2e475a28de3605924f69b7d67b5/closuretree/models.py#L208-L223
ocadotechnology/django-closuretree
closuretree/models.py
ClosureModel.get_descendants
def get_descendants(self, include_self=False, depth=None): """Return all the descendants of this object.""" params = {"%s__parent" % self._closure_childref():self.pk} if depth is not None: params["%s__depth__lte" % self._closure_childref()] = depth descendants = self._topleve...
python
def get_descendants(self, include_self=False, depth=None): """Return all the descendants of this object.""" params = {"%s__parent" % self._closure_childref():self.pk} if depth is not None: params["%s__depth__lte" % self._closure_childref()] = depth descendants = self._topleve...
[ "def", "get_descendants", "(", "self", ",", "include_self", "=", "False", ",", "depth", "=", "None", ")", ":", "params", "=", "{", "\"%s__parent\"", "%", "self", ".", "_closure_childref", "(", ")", ":", "self", ".", "pk", "}", "if", "depth", "is", "not...
Return all the descendants of this object.
[ "Return", "all", "the", "descendants", "of", "this", "object", "." ]
train
https://github.com/ocadotechnology/django-closuretree/blob/432717b20907f2e475a28de3605924f69b7d67b5/closuretree/models.py#L225-L233
ocadotechnology/django-closuretree
closuretree/models.py
ClosureModel.prepopulate
def prepopulate(self, queryset): """Perpopulate a descendants query's children efficiently. Call like: blah.prepopulate(blah.get_descendants().select_related(stuff)) """ objs = list(queryset) hashobjs = dict([(x.pk, x) for x in objs] + [(self.pk, self)]) for descendan...
python
def prepopulate(self, queryset): """Perpopulate a descendants query's children efficiently. Call like: blah.prepopulate(blah.get_descendants().select_related(stuff)) """ objs = list(queryset) hashobjs = dict([(x.pk, x) for x in objs] + [(self.pk, self)]) for descendan...
[ "def", "prepopulate", "(", "self", ",", "queryset", ")", ":", "objs", "=", "list", "(", "queryset", ")", "hashobjs", "=", "dict", "(", "[", "(", "x", ".", "pk", ",", "x", ")", "for", "x", "in", "objs", "]", "+", "[", "(", "self", ".", "pk", "...
Perpopulate a descendants query's children efficiently. Call like: blah.prepopulate(blah.get_descendants().select_related(stuff))
[ "Perpopulate", "a", "descendants", "query", "s", "children", "efficiently", ".", "Call", "like", ":", "blah", ".", "prepopulate", "(", "blah", ".", "get_descendants", "()", ".", "select_related", "(", "stuff", "))" ]
train
https://github.com/ocadotechnology/django-closuretree/blob/432717b20907f2e475a28de3605924f69b7d67b5/closuretree/models.py#L235-L246
ocadotechnology/django-closuretree
closuretree/models.py
ClosureModel.get_children
def get_children(self): """Return all the children of this object.""" if hasattr(self, '_cached_children'): children = self._toplevel().objects.filter( pk__in=[n.pk for n in self._cached_children] ) children._result_cache = self._cached_children ...
python
def get_children(self): """Return all the children of this object.""" if hasattr(self, '_cached_children'): children = self._toplevel().objects.filter( pk__in=[n.pk for n in self._cached_children] ) children._result_cache = self._cached_children ...
[ "def", "get_children", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'_cached_children'", ")", ":", "children", "=", "self", ".", "_toplevel", "(", ")", ".", "objects", ".", "filter", "(", "pk__in", "=", "[", "n", ".", "pk", "for", "n", ...
Return all the children of this object.
[ "Return", "all", "the", "children", "of", "this", "object", "." ]
train
https://github.com/ocadotechnology/django-closuretree/blob/432717b20907f2e475a28de3605924f69b7d67b5/closuretree/models.py#L248-L257
ocadotechnology/django-closuretree
closuretree/models.py
ClosureModel.get_root
def get_root(self): """Return the furthest ancestor of this node.""" if self.is_root_node(): return self return self.get_ancestors().order_by( "-%s__depth" % self._closure_parentref() )[0]
python
def get_root(self): """Return the furthest ancestor of this node.""" if self.is_root_node(): return self return self.get_ancestors().order_by( "-%s__depth" % self._closure_parentref() )[0]
[ "def", "get_root", "(", "self", ")", ":", "if", "self", ".", "is_root_node", "(", ")", ":", "return", "self", "return", "self", ".", "get_ancestors", "(", ")", ".", "order_by", "(", "\"-%s__depth\"", "%", "self", ".", "_closure_parentref", "(", ")", ")",...
Return the furthest ancestor of this node.
[ "Return", "the", "furthest", "ancestor", "of", "this", "node", "." ]
train
https://github.com/ocadotechnology/django-closuretree/blob/432717b20907f2e475a28de3605924f69b7d67b5/closuretree/models.py#L259-L266
ocadotechnology/django-closuretree
closuretree/models.py
ClosureModel.is_descendant_of
def is_descendant_of(self, other, include_self=False): """Is this node a descendant of `other`?""" if other.pk == self.pk: return include_self return self._closure_model.objects.filter( parent=other, child=self ).exclude(pk=self.pk).exists()
python
def is_descendant_of(self, other, include_self=False): """Is this node a descendant of `other`?""" if other.pk == self.pk: return include_self return self._closure_model.objects.filter( parent=other, child=self ).exclude(pk=self.pk).exists()
[ "def", "is_descendant_of", "(", "self", ",", "other", ",", "include_self", "=", "False", ")", ":", "if", "other", ".", "pk", "==", "self", ".", "pk", ":", "return", "include_self", "return", "self", ".", "_closure_model", ".", "objects", ".", "filter", "...
Is this node a descendant of `other`?
[ "Is", "this", "node", "a", "descendant", "of", "other", "?" ]
train
https://github.com/ocadotechnology/django-closuretree/blob/432717b20907f2e475a28de3605924f69b7d67b5/closuretree/models.py#L276-L284
ocadotechnology/django-closuretree
closuretree/models.py
ClosureModel.is_ancestor_of
def is_ancestor_of(self, other, include_self=False): """Is this node an ancestor of `other`?""" return other.is_descendant_of(self, include_self=include_self)
python
def is_ancestor_of(self, other, include_self=False): """Is this node an ancestor of `other`?""" return other.is_descendant_of(self, include_self=include_self)
[ "def", "is_ancestor_of", "(", "self", ",", "other", ",", "include_self", "=", "False", ")", ":", "return", "other", ".", "is_descendant_of", "(", "self", ",", "include_self", "=", "include_self", ")" ]
Is this node an ancestor of `other`?
[ "Is", "this", "node", "an", "ancestor", "of", "other", "?" ]
train
https://github.com/ocadotechnology/django-closuretree/blob/432717b20907f2e475a28de3605924f69b7d67b5/closuretree/models.py#L286-L288
debrouwere/python-ballpark
ballpark/utils.py
quantize
def quantize(number, digits=0, q=builtins.round): """ Quantize to somewhere in between a magnitude. For example: * ceil(55.25, 1.2) => 55.26 * floor(55.25, 1.2) => 55.24 * round(55.3333, 2.5) => 55.335 * round(12.345, 1.1) == round(12.345, 2) == 12.34 """ base, fra...
python
def quantize(number, digits=0, q=builtins.round): """ Quantize to somewhere in between a magnitude. For example: * ceil(55.25, 1.2) => 55.26 * floor(55.25, 1.2) => 55.24 * round(55.3333, 2.5) => 55.335 * round(12.345, 1.1) == round(12.345, 2) == 12.34 """ base, fra...
[ "def", "quantize", "(", "number", ",", "digits", "=", "0", ",", "q", "=", "builtins", ".", "round", ")", ":", "base", ",", "fraction", "=", "split", "(", "digits", ")", "# quantization beyond an order of magnitude results in a variable amount", "# of decimal digits ...
Quantize to somewhere in between a magnitude. For example: * ceil(55.25, 1.2) => 55.26 * floor(55.25, 1.2) => 55.24 * round(55.3333, 2.5) => 55.335 * round(12.345, 1.1) == round(12.345, 2) == 12.34
[ "Quantize", "to", "somewhere", "in", "between", "a", "magnitude", "." ]
train
https://github.com/debrouwere/python-ballpark/blob/0b871cdf5b4b5f50e5f3f3d044558801783381c4/ballpark/utils.py#L44-L70
debrouwere/python-ballpark
ballpark/utils.py
vectorize
def vectorize(fn): """ Allows a method to accept a list argument, but internally deal only with a single item of that list. """ @functools.wraps(fn) def vectorized_function(values, *vargs, **kwargs): return [fn(value, *vargs, **kwargs) for value in values] return vectorized_functio...
python
def vectorize(fn): """ Allows a method to accept a list argument, but internally deal only with a single item of that list. """ @functools.wraps(fn) def vectorized_function(values, *vargs, **kwargs): return [fn(value, *vargs, **kwargs) for value in values] return vectorized_functio...
[ "def", "vectorize", "(", "fn", ")", ":", "@", "functools", ".", "wraps", "(", "fn", ")", "def", "vectorized_function", "(", "values", ",", "*", "vargs", ",", "*", "*", "kwargs", ")", ":", "return", "[", "fn", "(", "value", ",", "*", "vargs", ",", ...
Allows a method to accept a list argument, but internally deal only with a single item of that list.
[ "Allows", "a", "method", "to", "accept", "a", "list", "argument", "but", "internally", "deal", "only", "with", "a", "single", "item", "of", "that", "list", "." ]
train
https://github.com/debrouwere/python-ballpark/blob/0b871cdf5b4b5f50e5f3f3d044558801783381c4/ballpark/utils.py#L100-L110
debrouwere/python-ballpark
ballpark/notation.py
engineering
def engineering(value, precision=3, prefix=False, prefixes=SI): """ Convert a number to engineering notation. """ display = decimal.Context(prec=precision) value = decimal.Decimal(value).normalize(context=display) string = value.to_eng_string() if prefix: prefixes = {e(exponent): prefix fo...
python
def engineering(value, precision=3, prefix=False, prefixes=SI): """ Convert a number to engineering notation. """ display = decimal.Context(prec=precision) value = decimal.Decimal(value).normalize(context=display) string = value.to_eng_string() if prefix: prefixes = {e(exponent): prefix fo...
[ "def", "engineering", "(", "value", ",", "precision", "=", "3", ",", "prefix", "=", "False", ",", "prefixes", "=", "SI", ")", ":", "display", "=", "decimal", ".", "Context", "(", "prec", "=", "precision", ")", "value", "=", "decimal", ".", "Decimal", ...
Convert a number to engineering notation.
[ "Convert", "a", "number", "to", "engineering", "notation", "." ]
train
https://github.com/debrouwere/python-ballpark/blob/0b871cdf5b4b5f50e5f3f3d044558801783381c4/ballpark/notation.py#L90-L101
debrouwere/python-ballpark
ballpark/notation.py
business
def business(values, precision=3, prefix=True, prefixes=SI, statistic=median, default=''): """ Convert a list of numbers to the engineering notation appropriate to a reference point like the minimum, the median or the mean -- think of it as "business notation". Any number will have at most the amou...
python
def business(values, precision=3, prefix=True, prefixes=SI, statistic=median, default=''): """ Convert a list of numbers to the engineering notation appropriate to a reference point like the minimum, the median or the mean -- think of it as "business notation". Any number will have at most the amou...
[ "def", "business", "(", "values", ",", "precision", "=", "3", ",", "prefix", "=", "True", ",", "prefixes", "=", "SI", ",", "statistic", "=", "median", ",", "default", "=", "''", ")", ":", "reference", "=", "statistic", "(", "values", ")", "if", "not"...
Convert a list of numbers to the engineering notation appropriate to a reference point like the minimum, the median or the mean -- think of it as "business notation". Any number will have at most the amount of significant digits of the reference point, that is, the function will round beyond the de...
[ "Convert", "a", "list", "of", "numbers", "to", "the", "engineering", "notation", "appropriate", "to", "a", "reference", "point", "like", "the", "minimum", "the", "median", "or", "the", "mean", "--", "think", "of", "it", "as", "business", "notation", "." ]
train
https://github.com/debrouwere/python-ballpark/blob/0b871cdf5b4b5f50e5f3f3d044558801783381c4/ballpark/notation.py#L105-L156
pmclanahan/django-celery-email
djcelery_email/utils.py
chunked
def chunked(iterator, chunksize): """ Yields items from 'iterator' in chunks of size 'chunksize'. >>> list(chunked([1, 2, 3, 4, 5], chunksize=2)) [(1, 2), (3, 4), (5,)] """ chunk = [] for idx, item in enumerate(iterator, 1): chunk.append(item) if idx % chunksize == 0: ...
python
def chunked(iterator, chunksize): """ Yields items from 'iterator' in chunks of size 'chunksize'. >>> list(chunked([1, 2, 3, 4, 5], chunksize=2)) [(1, 2), (3, 4), (5,)] """ chunk = [] for idx, item in enumerate(iterator, 1): chunk.append(item) if idx % chunksize == 0: ...
[ "def", "chunked", "(", "iterator", ",", "chunksize", ")", ":", "chunk", "=", "[", "]", "for", "idx", ",", "item", "in", "enumerate", "(", "iterator", ",", "1", ")", ":", "chunk", ".", "append", "(", "item", ")", "if", "idx", "%", "chunksize", "==",...
Yields items from 'iterator' in chunks of size 'chunksize'. >>> list(chunked([1, 2, 3, 4, 5], chunksize=2)) [(1, 2), (3, 4), (5,)]
[ "Yields", "items", "from", "iterator", "in", "chunks", "of", "size", "chunksize", "." ]
train
https://github.com/pmclanahan/django-celery-email/blob/6d0684b3d2d6751c4e5066f9215e130e6a91ea78/djcelery_email/utils.py#L10-L24
ClearcodeHQ/mirakuru
src/mirakuru/tcp.py
TCPExecutor.pre_start_check
def pre_start_check(self): """ Check if process accepts connections. .. note:: Process will be considered started, when it'll be able to accept TCP connections as defined in initializer. """ try: sock = socket.socket() sock.connec...
python
def pre_start_check(self): """ Check if process accepts connections. .. note:: Process will be considered started, when it'll be able to accept TCP connections as defined in initializer. """ try: sock = socket.socket() sock.connec...
[ "def", "pre_start_check", "(", "self", ")", ":", "try", ":", "sock", "=", "socket", ".", "socket", "(", ")", "sock", ".", "connect", "(", "(", "self", ".", "host", ",", "self", ".", "port", ")", ")", "return", "True", "except", "(", "socket", ".", ...
Check if process accepts connections. .. note:: Process will be considered started, when it'll be able to accept TCP connections as defined in initializer.
[ "Check", "if", "process", "accepts", "connections", "." ]
train
https://github.com/ClearcodeHQ/mirakuru/blob/38203f328479ac9356d468a20daa743807194698/src/mirakuru/tcp.py#L55-L72
ClearcodeHQ/mirakuru
src/mirakuru/http.py
HTTPExecutor.after_start_check
def after_start_check(self): """Check if defined URL returns expected status to a HEAD request.""" try: conn = HTTPConnection(self.host, self.port) conn.request('HEAD', self.url.path) status = str(conn.getresponse().status) if status == self.status or se...
python
def after_start_check(self): """Check if defined URL returns expected status to a HEAD request.""" try: conn = HTTPConnection(self.host, self.port) conn.request('HEAD', self.url.path) status = str(conn.getresponse().status) if status == self.status or se...
[ "def", "after_start_check", "(", "self", ")", ":", "try", ":", "conn", "=", "HTTPConnection", "(", "self", ".", "host", ",", "self", ".", "port", ")", "conn", ".", "request", "(", "'HEAD'", ",", "self", ".", "url", ".", "path", ")", "status", "=", ...
Check if defined URL returns expected status to a HEAD request.
[ "Check", "if", "defined", "URL", "returns", "expected", "status", "to", "a", "HEAD", "request", "." ]
train
https://github.com/ClearcodeHQ/mirakuru/blob/38203f328479ac9356d468a20daa743807194698/src/mirakuru/http.py#L75-L88
ClearcodeHQ/mirakuru
src/mirakuru/output.py
OutputExecutor.start
def start(self): """ Start process. :returns: itself :rtype: OutputExecutor .. note:: Process will be considered started, when defined banner will appear in process output. """ super(OutputExecutor, self).start() # get a polling...
python
def start(self): """ Start process. :returns: itself :rtype: OutputExecutor .. note:: Process will be considered started, when defined banner will appear in process output. """ super(OutputExecutor, self).start() # get a polling...
[ "def", "start", "(", "self", ")", ":", "super", "(", "OutputExecutor", ",", "self", ")", ".", "start", "(", ")", "# get a polling object", "self", ".", "poll_obj", "=", "select", ".", "poll", "(", ")", "# register a file descriptor", "# POLLIN because we will wa...
Start process. :returns: itself :rtype: OutputExecutor .. note:: Process will be considered started, when defined banner will appear in process output.
[ "Start", "process", "." ]
train
https://github.com/ClearcodeHQ/mirakuru/blob/38203f328479ac9356d468a20daa743807194698/src/mirakuru/output.py#L50-L78
ClearcodeHQ/mirakuru
src/mirakuru/output.py
OutputExecutor._wait_for_output
def _wait_for_output(self): """ Check if output matches banner. .. warning:: Waiting for I/O completion. It does not work on Windows. Sorry. """ # Here we should get an empty list or list with a tuple [(fd, event)] # When we get list with a tuple we can use r...
python
def _wait_for_output(self): """ Check if output matches banner. .. warning:: Waiting for I/O completion. It does not work on Windows. Sorry. """ # Here we should get an empty list or list with a tuple [(fd, event)] # When we get list with a tuple we can use r...
[ "def", "_wait_for_output", "(", "self", ")", ":", "# Here we should get an empty list or list with a tuple [(fd, event)]", "# When we get list with a tuple we can use readline method on", "# the file descriptor.", "poll_result", "=", "self", ".", "poll_obj", ".", "poll", "(", "0", ...
Check if output matches banner. .. warning:: Waiting for I/O completion. It does not work on Windows. Sorry.
[ "Check", "if", "output", "matches", "banner", "." ]
train
https://github.com/ClearcodeHQ/mirakuru/blob/38203f328479ac9356d468a20daa743807194698/src/mirakuru/output.py#L80-L97
divio/django-emailit
emailit/api.py
construct_mail
def construct_mail(recipients=None, context=None, template_base='emailit/email', subject=None, message=None, site=None, subject_templates=None, body_templates=None, html_templates=None, from_email=None, language=None, **kwargs): """ usage: construct_mail(['my@email.com'...
python
def construct_mail(recipients=None, context=None, template_base='emailit/email', subject=None, message=None, site=None, subject_templates=None, body_templates=None, html_templates=None, from_email=None, language=None, **kwargs): """ usage: construct_mail(['my@email.com'...
[ "def", "construct_mail", "(", "recipients", "=", "None", ",", "context", "=", "None", ",", "template_base", "=", "'emailit/email'", ",", "subject", "=", "None", ",", "message", "=", "None", ",", "site", "=", "None", ",", "subject_templates", "=", "None", "...
usage: construct_mail(['my@email.com'], {'my_obj': obj}, template_base='myapp/emails/my_obj_notification').send() :param recipients: recipient or list of recipients :param context: context for template rendering :param template_base: the base template. '.subject.txt', '.body.txt' and '.body.html' will b...
[ "usage", ":", "construct_mail", "(", "[", "my" ]
train
https://github.com/divio/django-emailit/blob/02dc9ca94035d3f3100416e4956b7e60fa52b345/emailit/api.py#L20-L84
ClearcodeHQ/mirakuru
src/mirakuru/base.py
cleanup_subprocesses
def cleanup_subprocesses(): """On python exit: find possibly running subprocesses and kill them.""" # pylint: disable=redefined-outer-name, reimported # atexit functions tends to loose global imports sometimes so reimport # everything what is needed again here: import os import errno from mi...
python
def cleanup_subprocesses(): """On python exit: find possibly running subprocesses and kill them.""" # pylint: disable=redefined-outer-name, reimported # atexit functions tends to loose global imports sometimes so reimport # everything what is needed again here: import os import errno from mi...
[ "def", "cleanup_subprocesses", "(", ")", ":", "# pylint: disable=redefined-outer-name, reimported", "# atexit functions tends to loose global imports sometimes so reimport", "# everything what is needed again here:", "import", "os", "import", "errno", "from", "mirakuru", ".", "base_env...
On python exit: find possibly running subprocesses and kill them.
[ "On", "python", "exit", ":", "find", "possibly", "running", "subprocesses", "and", "kill", "them", "." ]
train
https://github.com/ClearcodeHQ/mirakuru/blob/38203f328479ac9356d468a20daa743807194698/src/mirakuru/base.py#L54-L70
ClearcodeHQ/mirakuru
src/mirakuru/base.py
SimpleExecutor.start
def start(self): """ Start defined process. After process gets started, timeout countdown begins as well. :returns: itself :rtype: SimpleExecutor .. note:: We want to open ``stdin``, ``stdout`` and ``stderr`` as text streams in universal newline...
python
def start(self): """ Start defined process. After process gets started, timeout countdown begins as well. :returns: itself :rtype: SimpleExecutor .. note:: We want to open ``stdin``, ``stdout`` and ``stderr`` as text streams in universal newline...
[ "def", "start", "(", "self", ")", ":", "if", "self", ".", "process", "is", "None", ":", "command", "=", "self", ".", "command", "if", "not", "self", ".", "_shell", ":", "command", "=", "self", ".", "command_parts", "env", "=", "os", ".", "environ", ...
Start defined process. After process gets started, timeout countdown begins as well. :returns: itself :rtype: SimpleExecutor .. note:: We want to open ``stdin``, ``stdout`` and ``stderr`` as text streams in universal newlines mode, so we have to set ...
[ "Start", "defined", "process", "." ]
train
https://github.com/ClearcodeHQ/mirakuru/blob/38203f328479ac9356d468a20daa743807194698/src/mirakuru/base.py#L153-L199
ClearcodeHQ/mirakuru
src/mirakuru/base.py
SimpleExecutor._clear_process
def _clear_process(self): """ Close stdin/stdout of subprocess. It is required because of ResourceWarning in Python 3. """ if self.process: if self.process.stdin: self.process.stdin.close() if self.process.stdout: self.proc...
python
def _clear_process(self): """ Close stdin/stdout of subprocess. It is required because of ResourceWarning in Python 3. """ if self.process: if self.process.stdin: self.process.stdin.close() if self.process.stdout: self.proc...
[ "def", "_clear_process", "(", "self", ")", ":", "if", "self", ".", "process", ":", "if", "self", ".", "process", ".", "stdin", ":", "self", ".", "process", ".", "stdin", ".", "close", "(", ")", "if", "self", ".", "process", ".", "stdout", ":", "sel...
Close stdin/stdout of subprocess. It is required because of ResourceWarning in Python 3.
[ "Close", "stdin", "/", "stdout", "of", "subprocess", "." ]
train
https://github.com/ClearcodeHQ/mirakuru/blob/38203f328479ac9356d468a20daa743807194698/src/mirakuru/base.py#L205-L219
ClearcodeHQ/mirakuru
src/mirakuru/base.py
SimpleExecutor._kill_all_kids
def _kill_all_kids(self, sig): """ Kill all subprocesses (and its subprocesses) that executor started. This function tries to kill all leftovers in process tree that current executor may have left. It uses environment variable to recognise if process have origin in this Executor...
python
def _kill_all_kids(self, sig): """ Kill all subprocesses (and its subprocesses) that executor started. This function tries to kill all leftovers in process tree that current executor may have left. It uses environment variable to recognise if process have origin in this Executor...
[ "def", "_kill_all_kids", "(", "self", ",", "sig", ")", ":", "pids", "=", "processes_with_env", "(", "ENV_UUID", ",", "self", ".", "_uuid", ")", "for", "pid", "in", "pids", ":", "log", ".", "debug", "(", "\"Killing process %d ...\"", ",", "pid", ")", "try...
Kill all subprocesses (and its subprocesses) that executor started. This function tries to kill all leftovers in process tree that current executor may have left. It uses environment variable to recognise if process have origin in this Executor so it does not give 100 % and some daemons...
[ "Kill", "all", "subprocesses", "(", "and", "its", "subprocesses", ")", "that", "executor", "started", "." ]
train
https://github.com/ClearcodeHQ/mirakuru/blob/38203f328479ac9356d468a20daa743807194698/src/mirakuru/base.py#L221-L246
ClearcodeHQ/mirakuru
src/mirakuru/base.py
SimpleExecutor.kill
def kill(self, wait=True, sig=None): """ Kill the process if running. :param bool wait: set to `True` to wait for the process to end, or False, to simply proceed after sending signal. :param int sig: signal used to kill process run by the executor. None by defaul...
python
def kill(self, wait=True, sig=None): """ Kill the process if running. :param bool wait: set to `True` to wait for the process to end, or False, to simply proceed after sending signal. :param int sig: signal used to kill process run by the executor. None by defaul...
[ "def", "kill", "(", "self", ",", "wait", "=", "True", ",", "sig", "=", "None", ")", ":", "if", "sig", "is", "None", ":", "sig", "=", "self", ".", "_sig_kill", "if", "self", ".", "running", "(", ")", ":", "os", ".", "killpg", "(", "self", ".", ...
Kill the process if running. :param bool wait: set to `True` to wait for the process to end, or False, to simply proceed after sending signal. :param int sig: signal used to kill process run by the executor. None by default. :returns: itself :rtype: SimpleExecuto...
[ "Kill", "the", "process", "if", "running", "." ]
train
https://github.com/ClearcodeHQ/mirakuru/blob/38203f328479ac9356d468a20daa743807194698/src/mirakuru/base.py#L308-L328
ClearcodeHQ/mirakuru
src/mirakuru/base.py
SimpleExecutor.wait_for
def wait_for(self, wait_for): """ Wait for callback to return True. Simply returns if wait_for condition has been met, raises TimeoutExpired otherwise and kills the process. :param callback wait_for: callback to call :raises: mirakuru.exceptions.TimeoutExpired :...
python
def wait_for(self, wait_for): """ Wait for callback to return True. Simply returns if wait_for condition has been met, raises TimeoutExpired otherwise and kills the process. :param callback wait_for: callback to call :raises: mirakuru.exceptions.TimeoutExpired :...
[ "def", "wait_for", "(", "self", ",", "wait_for", ")", ":", "while", "self", ".", "check_timeout", "(", ")", ":", "if", "wait_for", "(", ")", ":", "return", "self", "time", ".", "sleep", "(", "self", ".", "_sleep", ")", "self", ".", "kill", "(", ")"...
Wait for callback to return True. Simply returns if wait_for condition has been met, raises TimeoutExpired otherwise and kills the process. :param callback wait_for: callback to call :raises: mirakuru.exceptions.TimeoutExpired :returns: itself :rtype: SimpleExecutor
[ "Wait", "for", "callback", "to", "return", "True", "." ]
train
https://github.com/ClearcodeHQ/mirakuru/blob/38203f328479ac9356d468a20daa743807194698/src/mirakuru/base.py#L335-L353
ClearcodeHQ/mirakuru
src/mirakuru/base.py
Executor.start
def start(self): """ Start executor with additional checks. Checks if previous executor isn't running then start process (executor) and wait until it's started. :returns: itself :rtype: Executor """ if self.pre_start_check(): # Some other exec...
python
def start(self): """ Start executor with additional checks. Checks if previous executor isn't running then start process (executor) and wait until it's started. :returns: itself :rtype: Executor """ if self.pre_start_check(): # Some other exec...
[ "def", "start", "(", "self", ")", ":", "if", "self", ".", "pre_start_check", "(", ")", ":", "# Some other executor (or process) is running with same config:", "raise", "AlreadyRunning", "(", "self", ")", "super", "(", "Executor", ",", "self", ")", ".", "start", ...
Start executor with additional checks. Checks if previous executor isn't running then start process (executor) and wait until it's started. :returns: itself :rtype: Executor
[ "Start", "executor", "with", "additional", "checks", "." ]
train
https://github.com/ClearcodeHQ/mirakuru/blob/38203f328479ac9356d468a20daa743807194698/src/mirakuru/base.py#L416-L432
ClearcodeHQ/mirakuru
src/mirakuru/base.py
Executor.check_subprocess
def check_subprocess(self): """ Make sure the process didn't exit with an error and run the checks. :rtype: bool :return: the actual check status :raise ProcessExitedWithError: when the main process exits with an error """ exit_code = self.process.pol...
python
def check_subprocess(self): """ Make sure the process didn't exit with an error and run the checks. :rtype: bool :return: the actual check status :raise ProcessExitedWithError: when the main process exits with an error """ exit_code = self.process.pol...
[ "def", "check_subprocess", "(", "self", ")", ":", "exit_code", "=", "self", ".", "process", ".", "poll", "(", ")", "if", "exit_code", "is", "not", "None", "and", "exit_code", "!=", "0", ":", "# The main process exited with an error. Clean up the children", "# if a...
Make sure the process didn't exit with an error and run the checks. :rtype: bool :return: the actual check status :raise ProcessExitedWithError: when the main process exits with an error
[ "Make", "sure", "the", "process", "didn", "t", "exit", "with", "an", "error", "and", "run", "the", "checks", "." ]
train
https://github.com/ClearcodeHQ/mirakuru/blob/38203f328479ac9356d468a20daa743807194698/src/mirakuru/base.py#L434-L451
ClearcodeHQ/mirakuru
src/mirakuru/base_env.py
processes_with_env_psutil
def processes_with_env_psutil(env_name, env_value): """ Find PIDs of processes having environment variable matching given one. Internally it uses `psutil` library. :param str env_name: name of environment variable to be found :param str env_value: environment variable value prefix :return: pro...
python
def processes_with_env_psutil(env_name, env_value): """ Find PIDs of processes having environment variable matching given one. Internally it uses `psutil` library. :param str env_name: name of environment variable to be found :param str env_value: environment variable value prefix :return: pro...
[ "def", "processes_with_env_psutil", "(", "env_name", ",", "env_value", ")", ":", "pids", "=", "set", "(", ")", "for", "proc", "in", "psutil", ".", "process_iter", "(", ")", ":", "try", ":", "pinfo", "=", "proc", ".", "as_dict", "(", "attrs", "=", "[", ...
Find PIDs of processes having environment variable matching given one. Internally it uses `psutil` library. :param str env_name: name of environment variable to be found :param str env_value: environment variable value prefix :return: process identifiers (PIDs) of processes that have certain ...
[ "Find", "PIDs", "of", "processes", "having", "environment", "variable", "matching", "given", "one", "." ]
train
https://github.com/ClearcodeHQ/mirakuru/blob/38203f328479ac9356d468a20daa743807194698/src/mirakuru/base_env.py#L38-L63
ClearcodeHQ/mirakuru
src/mirakuru/base_env.py
processes_with_env_ps
def processes_with_env_ps(env_name, env_value): """ Find PIDs of processes having environment variable matching given one. It uses `$ ps xe -o pid,cmd` command so it works only on systems having such command available (Linux, MacOS). If not available function will just log error. :param str en...
python
def processes_with_env_ps(env_name, env_value): """ Find PIDs of processes having environment variable matching given one. It uses `$ ps xe -o pid,cmd` command so it works only on systems having such command available (Linux, MacOS). If not available function will just log error. :param str en...
[ "def", "processes_with_env_ps", "(", "env_name", ",", "env_value", ")", ":", "pids", "=", "set", "(", ")", "ps_xe", "=", "''", "try", ":", "cmd", "=", "'ps'", ",", "'xe'", ",", "'-o'", ",", "'pid,cmd'", "ps_xe", "=", "subprocess", ".", "check_output", ...
Find PIDs of processes having environment variable matching given one. It uses `$ ps xe -o pid,cmd` command so it works only on systems having such command available (Linux, MacOS). If not available function will just log error. :param str env_name: name of environment variable to be found :param ...
[ "Find", "PIDs", "of", "processes", "having", "environment", "variable", "matching", "given", "one", "." ]
train
https://github.com/ClearcodeHQ/mirakuru/blob/38203f328479ac9356d468a20daa743807194698/src/mirakuru/base_env.py#L66-L101
Mic92/kshape
kshape/core.py
_ncc_c
def _ncc_c(x, y): """ >>> _ncc_c([1,2,3,4], [1,2,3,4]) array([ 0.13333333, 0.36666667, 0.66666667, 1. , 0.66666667, 0.36666667, 0.13333333]) >>> _ncc_c([1,1,1], [1,1,1]) array([ 0.33333333, 0.66666667, 1. , 0.66666667, 0.33333333]) >>> _ncc_c([1,2,3], [-1,-1,-1...
python
def _ncc_c(x, y): """ >>> _ncc_c([1,2,3,4], [1,2,3,4]) array([ 0.13333333, 0.36666667, 0.66666667, 1. , 0.66666667, 0.36666667, 0.13333333]) >>> _ncc_c([1,1,1], [1,1,1]) array([ 0.33333333, 0.66666667, 1. , 0.66666667, 0.33333333]) >>> _ncc_c([1,2,3], [-1,-1,-1...
[ "def", "_ncc_c", "(", "x", ",", "y", ")", ":", "den", "=", "np", ".", "array", "(", "norm", "(", "x", ")", "*", "norm", "(", "y", ")", ")", "den", "[", "den", "==", "0", "]", "=", "np", ".", "Inf", "x_len", "=", "len", "(", "x", ")", "f...
>>> _ncc_c([1,2,3,4], [1,2,3,4]) array([ 0.13333333, 0.36666667, 0.66666667, 1. , 0.66666667, 0.36666667, 0.13333333]) >>> _ncc_c([1,1,1], [1,1,1]) array([ 0.33333333, 0.66666667, 1. , 0.66666667, 0.33333333]) >>> _ncc_c([1,2,3], [-1,-1,-1]) array([-0.15430335, -0....
[ ">>>", "_ncc_c", "(", "[", "1", "2", "3", "4", "]", "[", "1", "2", "3", "4", "]", ")", "array", "(", "[", "0", ".", "13333333", "0", ".", "36666667", "0", ".", "66666667", "1", ".", "0", ".", "66666667", "0", ".", "36666667", "0", ".", "133...
train
https://github.com/Mic92/kshape/blob/d9e8ec0bae9293f7b25550c1d2d39f2a22dabe4b/kshape/core.py#L46-L63
Mic92/kshape
kshape/core.py
_ncc_c_2dim
def _ncc_c_2dim(x, y): """ Variant of NCCc that operates with 2 dimensional X arrays and 1 dimensional y vector Returns a 2 dimensional array of normalized fourier transforms """ den = np.array(norm(x, axis=1) * norm(y)) den[den == 0] = np.Inf x_len = x.shape[-1] fft_size = 1 << (2*...
python
def _ncc_c_2dim(x, y): """ Variant of NCCc that operates with 2 dimensional X arrays and 1 dimensional y vector Returns a 2 dimensional array of normalized fourier transforms """ den = np.array(norm(x, axis=1) * norm(y)) den[den == 0] = np.Inf x_len = x.shape[-1] fft_size = 1 << (2*...
[ "def", "_ncc_c_2dim", "(", "x", ",", "y", ")", ":", "den", "=", "np", ".", "array", "(", "norm", "(", "x", ",", "axis", "=", "1", ")", "*", "norm", "(", "y", ")", ")", "den", "[", "den", "==", "0", "]", "=", "np", ".", "Inf", "x_len", "="...
Variant of NCCc that operates with 2 dimensional X arrays and 1 dimensional y vector Returns a 2 dimensional array of normalized fourier transforms
[ "Variant", "of", "NCCc", "that", "operates", "with", "2", "dimensional", "X", "arrays", "and", "1", "dimensional", "y", "vector" ]
train
https://github.com/Mic92/kshape/blob/d9e8ec0bae9293f7b25550c1d2d39f2a22dabe4b/kshape/core.py#L66-L79
Mic92/kshape
kshape/core.py
_ncc_c_3dim
def _ncc_c_3dim(x, y): """ Variant of NCCc that operates with 2 dimensional X arrays and 2 dimensional y vector Returns a 3 dimensional array of normalized fourier transforms """ den = norm(x, axis=1)[:, None] * norm(y, axis=1) den[den == 0] = np.Inf x_len = x.shape[-1] fft_size = 1...
python
def _ncc_c_3dim(x, y): """ Variant of NCCc that operates with 2 dimensional X arrays and 2 dimensional y vector Returns a 3 dimensional array of normalized fourier transforms """ den = norm(x, axis=1)[:, None] * norm(y, axis=1) den[den == 0] = np.Inf x_len = x.shape[-1] fft_size = 1...
[ "def", "_ncc_c_3dim", "(", "x", ",", "y", ")", ":", "den", "=", "norm", "(", "x", ",", "axis", "=", "1", ")", "[", ":", ",", "None", "]", "*", "norm", "(", "y", ",", "axis", "=", "1", ")", "den", "[", "den", "==", "0", "]", "=", "np", "...
Variant of NCCc that operates with 2 dimensional X arrays and 2 dimensional y vector Returns a 3 dimensional array of normalized fourier transforms
[ "Variant", "of", "NCCc", "that", "operates", "with", "2", "dimensional", "X", "arrays", "and", "2", "dimensional", "y", "vector" ]
train
https://github.com/Mic92/kshape/blob/d9e8ec0bae9293f7b25550c1d2d39f2a22dabe4b/kshape/core.py#L82-L95
Mic92/kshape
kshape/core.py
_sbd
def _sbd(x, y): """ >>> _sbd([1,1,1], [1,1,1]) (-2.2204460492503131e-16, array([1, 1, 1])) >>> _sbd([0,1,2], [1,2,3]) (0.043817112532485103, array([1, 2, 3])) >>> _sbd([1,2,3], [0,1,2]) (0.043817112532485103, array([0, 1, 2])) """ ncc = _ncc_c(x, y) idx = ncc.argmax() dist = ...
python
def _sbd(x, y): """ >>> _sbd([1,1,1], [1,1,1]) (-2.2204460492503131e-16, array([1, 1, 1])) >>> _sbd([0,1,2], [1,2,3]) (0.043817112532485103, array([1, 2, 3])) >>> _sbd([1,2,3], [0,1,2]) (0.043817112532485103, array([0, 1, 2])) """ ncc = _ncc_c(x, y) idx = ncc.argmax() dist = ...
[ "def", "_sbd", "(", "x", ",", "y", ")", ":", "ncc", "=", "_ncc_c", "(", "x", ",", "y", ")", "idx", "=", "ncc", ".", "argmax", "(", ")", "dist", "=", "1", "-", "ncc", "[", "idx", "]", "yshift", "=", "roll_zeropad", "(", "y", ",", "(", "idx",...
>>> _sbd([1,1,1], [1,1,1]) (-2.2204460492503131e-16, array([1, 1, 1])) >>> _sbd([0,1,2], [1,2,3]) (0.043817112532485103, array([1, 2, 3])) >>> _sbd([1,2,3], [0,1,2]) (0.043817112532485103, array([0, 1, 2]))
[ ">>>", "_sbd", "(", "[", "1", "1", "1", "]", "[", "1", "1", "1", "]", ")", "(", "-", "2", ".", "2204460492503131e", "-", "16", "array", "(", "[", "1", "1", "1", "]", "))", ">>>", "_sbd", "(", "[", "0", "1", "2", "]", "[", "1", "2", "3",...
train
https://github.com/Mic92/kshape/blob/d9e8ec0bae9293f7b25550c1d2d39f2a22dabe4b/kshape/core.py#L98-L112
Mic92/kshape
kshape/core.py
_extract_shape
def _extract_shape(idx, x, j, cur_center): """ >>> _extract_shape(np.array([0,1,2]), np.array([[1,2,3], [4,5,6]]), 1, np.array([0,3,4])) array([-1., 0., 1.]) >>> _extract_shape(np.array([0,1,2]), np.array([[-1,2,3], [4,-5,6]]), 1, np.array([0,3,4])) array([-0.96836405, 1.02888681, -0.06052275]) ...
python
def _extract_shape(idx, x, j, cur_center): """ >>> _extract_shape(np.array([0,1,2]), np.array([[1,2,3], [4,5,6]]), 1, np.array([0,3,4])) array([-1., 0., 1.]) >>> _extract_shape(np.array([0,1,2]), np.array([[-1,2,3], [4,-5,6]]), 1, np.array([0,3,4])) array([-0.96836405, 1.02888681, -0.06052275]) ...
[ "def", "_extract_shape", "(", "idx", ",", "x", ",", "j", ",", "cur_center", ")", ":", "_a", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "idx", ")", ")", ":", "if", "idx", "[", "i", "]", "==", "j", ":", "if", "cur_center", ".", ...
>>> _extract_shape(np.array([0,1,2]), np.array([[1,2,3], [4,5,6]]), 1, np.array([0,3,4])) array([-1., 0., 1.]) >>> _extract_shape(np.array([0,1,2]), np.array([[-1,2,3], [4,-5,6]]), 1, np.array([0,3,4])) array([-0.96836405, 1.02888681, -0.06052275]) >>> _extract_shape(np.array([1,0,1,0]), np.array([[1...
[ ">>>", "_extract_shape", "(", "np", ".", "array", "(", "[", "0", "1", "2", "]", ")", "np", ".", "array", "(", "[[", "1", "2", "3", "]", "[", "4", "5", "6", "]]", ")", "1", "np", ".", "array", "(", "[", "0", "3", "4", "]", "))", "array", ...
train
https://github.com/Mic92/kshape/blob/d9e8ec0bae9293f7b25550c1d2d39f2a22dabe4b/kshape/core.py#L115-L155
Mic92/kshape
kshape/core.py
_kshape
def _kshape(x, k): """ >>> from numpy.random import seed; seed(0) >>> _kshape(np.array([[1,2,3,4], [0,1,2,3], [-1,1,-1,1], [1,2,2,3]]), 2) (array([0, 0, 1, 0]), array([[-1.2244258 , -0.35015476, 0.52411628, 1.05046429], [-0.8660254 , 0.8660254 , -0.8660254 , 0.8660254 ]])) """ m =...
python
def _kshape(x, k): """ >>> from numpy.random import seed; seed(0) >>> _kshape(np.array([[1,2,3,4], [0,1,2,3], [-1,1,-1,1], [1,2,2,3]]), 2) (array([0, 0, 1, 0]), array([[-1.2244258 , -0.35015476, 0.52411628, 1.05046429], [-0.8660254 , 0.8660254 , -0.8660254 , 0.8660254 ]])) """ m =...
[ "def", "_kshape", "(", "x", ",", "k", ")", ":", "m", "=", "x", ".", "shape", "[", "0", "]", "idx", "=", "randint", "(", "0", ",", "k", ",", "size", "=", "m", ")", "centroids", "=", "np", ".", "zeros", "(", "(", "k", ",", "x", ".", "shape"...
>>> from numpy.random import seed; seed(0) >>> _kshape(np.array([[1,2,3,4], [0,1,2,3], [-1,1,-1,1], [1,2,2,3]]), 2) (array([0, 0, 1, 0]), array([[-1.2244258 , -0.35015476, 0.52411628, 1.05046429], [-0.8660254 , 0.8660254 , -0.8660254 , 0.8660254 ]]))
[ ">>>", "from", "numpy", ".", "random", "import", "seed", ";", "seed", "(", "0", ")", ">>>", "_kshape", "(", "np", ".", "array", "(", "[[", "1", "2", "3", "4", "]", "[", "0", "1", "2", "3", "]", "[", "-", "1", "1", "-", "1", "1", "]", "[",...
train
https://github.com/Mic92/kshape/blob/d9e8ec0bae9293f7b25550c1d2d39f2a22dabe4b/kshape/core.py#L158-L181
DinoTools/python-flextls
flextls/helper.py
get_version_by_version_id
def get_version_by_version_id(version_id): """ Get the internal version ID be the version. :param Tuple version_id: Major and minor version number :return: Internal version ID :rtype: Integer|None """ for ver in registry.version_info: if ver.version_id == version_id: ret...
python
def get_version_by_version_id(version_id): """ Get the internal version ID be the version. :param Tuple version_id: Major and minor version number :return: Internal version ID :rtype: Integer|None """ for ver in registry.version_info: if ver.version_id == version_id: ret...
[ "def", "get_version_by_version_id", "(", "version_id", ")", ":", "for", "ver", "in", "registry", ".", "version_info", ":", "if", "ver", ".", "version_id", "==", "version_id", ":", "return", "ver", ".", "id", "return", "None" ]
Get the internal version ID be the version. :param Tuple version_id: Major and minor version number :return: Internal version ID :rtype: Integer|None
[ "Get", "the", "internal", "version", "ID", "be", "the", "version", "." ]
train
https://github.com/DinoTools/python-flextls/blob/c73448f20e79b1969adcc2271b91d8edda517857/flextls/helper.py#L4-L16
DinoTools/python-flextls
flextls/helper.py
get_version_name
def get_version_name(version_id): """ Get the name of a protocol version by the internal version ID. :param Integer version_id: Internal protocol version ID :return: Name of the version :rtype: String """ ver = registry.version_info.get(version_id) if ver: return ver.name r...
python
def get_version_name(version_id): """ Get the name of a protocol version by the internal version ID. :param Integer version_id: Internal protocol version ID :return: Name of the version :rtype: String """ ver = registry.version_info.get(version_id) if ver: return ver.name r...
[ "def", "get_version_name", "(", "version_id", ")", ":", "ver", "=", "registry", ".", "version_info", ".", "get", "(", "version_id", ")", "if", "ver", ":", "return", "ver", ".", "name", "return", "'unknown'" ]
Get the name of a protocol version by the internal version ID. :param Integer version_id: Internal protocol version ID :return: Name of the version :rtype: String
[ "Get", "the", "name", "of", "a", "protocol", "version", "by", "the", "internal", "version", "ID", "." ]
train
https://github.com/DinoTools/python-flextls/blob/c73448f20e79b1969adcc2271b91d8edda517857/flextls/helper.py#L19-L31
DinoTools/python-flextls
flextls/helper.py
get_version_id
def get_version_id(protocol_version): """ Get a tuple with major and minor version number :param Integer protocol_version: Internal version ID :return: Tuple of major and minor protocol version :rtype: Tuple """ ver = registry.version_info.get(protocol_version) if ver: return ve...
python
def get_version_id(protocol_version): """ Get a tuple with major and minor version number :param Integer protocol_version: Internal version ID :return: Tuple of major and minor protocol version :rtype: Tuple """ ver = registry.version_info.get(protocol_version) if ver: return ve...
[ "def", "get_version_id", "(", "protocol_version", ")", ":", "ver", "=", "registry", ".", "version_info", ".", "get", "(", "protocol_version", ")", "if", "ver", ":", "return", "ver", ".", "version_id" ]
Get a tuple with major and minor version number :param Integer protocol_version: Internal version ID :return: Tuple of major and minor protocol version :rtype: Tuple
[ "Get", "a", "tuple", "with", "major", "and", "minor", "version", "number" ]
train
https://github.com/DinoTools/python-flextls/blob/c73448f20e79b1969adcc2271b91d8edda517857/flextls/helper.py#L34-L44
Iotic-Labs/py-lz4framed
lz4framed/__init__.py
Compressor.update
def update(self, b): # pylint: disable=method-hidden,invalid-name """Compress data given in b, returning compressed result either from this function or writing to fp). Note: sometimes output might be zero length (if being buffered by lz4). Raises Lz4FramedNoDataError if input is of zero l...
python
def update(self, b): # pylint: disable=method-hidden,invalid-name """Compress data given in b, returning compressed result either from this function or writing to fp). Note: sometimes output might be zero length (if being buffered by lz4). Raises Lz4FramedNoDataError if input is of zero l...
[ "def", "update", "(", "self", ",", "b", ")", ":", "# pylint: disable=method-hidden,invalid-name", "with", "self", ".", "__lock", ":", "output", "=", "compress_update", "(", "self", ".", "__ctx", ",", "b", ")", "if", "self", ".", "__write", ":", "self", "."...
Compress data given in b, returning compressed result either from this function or writing to fp). Note: sometimes output might be zero length (if being buffered by lz4). Raises Lz4FramedNoDataError if input is of zero length.
[ "Compress", "data", "given", "in", "b", "returning", "compressed", "result", "either", "from", "this", "function", "or", "writing", "to", "fp", ")", ".", "Note", ":", "sometimes", "output", "might", "be", "zero", "length", "(", "if", "being", "buffered", "...
train
https://github.com/Iotic-Labs/py-lz4framed/blob/e91a89df7b656d8b1d8092e12c0697cb1fd8597c/lz4framed/__init__.py#L112-L127
Iotic-Labs/py-lz4framed
lz4framed/__init__.py
Compressor.end
def end(self): """Finalise lz4 frame, outputting any remaining as return from this function or by writing to fp)""" with self.__lock: if self.__write: self.__write(compress_end(self.__ctx)) else: return compress_end(self.__ctx)
python
def end(self): """Finalise lz4 frame, outputting any remaining as return from this function or by writing to fp)""" with self.__lock: if self.__write: self.__write(compress_end(self.__ctx)) else: return compress_end(self.__ctx)
[ "def", "end", "(", "self", ")", ":", "with", "self", ".", "__lock", ":", "if", "self", ".", "__write", ":", "self", ".", "__write", "(", "compress_end", "(", "self", ".", "__ctx", ")", ")", "else", ":", "return", "compress_end", "(", "self", ".", "...
Finalise lz4 frame, outputting any remaining as return from this function or by writing to fp)
[ "Finalise", "lz4", "frame", "outputting", "any", "remaining", "as", "return", "from", "this", "function", "or", "by", "writing", "to", "fp", ")" ]
train
https://github.com/Iotic-Labs/py-lz4framed/blob/e91a89df7b656d8b1d8092e12c0697cb1fd8597c/lz4framed/__init__.py#L136-L142
DinoTools/python-flextls
flextls/field.py
EnumField.get_value_name
def get_value_name(self, pretty=False): """ Get the name of the value :param Boolean pretty: Return the name in a pretty format :return: The name :rtype: String """ if pretty: return "%s (%x)" % ( self.enums.get(self._value, "n/a"), ...
python
def get_value_name(self, pretty=False): """ Get the name of the value :param Boolean pretty: Return the name in a pretty format :return: The name :rtype: String """ if pretty: return "%s (%x)" % ( self.enums.get(self._value, "n/a"), ...
[ "def", "get_value_name", "(", "self", ",", "pretty", "=", "False", ")", ":", "if", "pretty", ":", "return", "\"%s (%x)\"", "%", "(", "self", ".", "enums", ".", "get", "(", "self", ".", "_value", ",", "\"n/a\"", ")", ",", "self", ".", "_value", ")", ...
Get the name of the value :param Boolean pretty: Return the name in a pretty format :return: The name :rtype: String
[ "Get", "the", "name", "of", "the", "value" ]
train
https://github.com/DinoTools/python-flextls/blob/c73448f20e79b1969adcc2271b91d8edda517857/flextls/field.py#L157-L171
DinoTools/python-flextls
flextls/field.py
EnumField.set_value
def set_value(self, value, force=False): """ Set the value. :param String|Integer value: The value to set. Must be in the enum list. :param Boolean force: Set the value without checking it :raises ValueError: If value name given but it isn't available :raises TypeError:...
python
def set_value(self, value, force=False): """ Set the value. :param String|Integer value: The value to set. Must be in the enum list. :param Boolean force: Set the value without checking it :raises ValueError: If value name given but it isn't available :raises TypeError:...
[ "def", "set_value", "(", "self", ",", "value", ",", "force", "=", "False", ")", ":", "if", "force", ":", "self", ".", "_value", "=", "value", "return", "if", "value", "is", "None", ":", "self", ".", "_value", "=", "value", "return", "if", "isinstance...
Set the value. :param String|Integer value: The value to set. Must be in the enum list. :param Boolean force: Set the value without checking it :raises ValueError: If value name given but it isn't available :raises TypeError: If value is not String or Integer
[ "Set", "the", "value", "." ]
train
https://github.com/DinoTools/python-flextls/blob/c73448f20e79b1969adcc2271b91d8edda517857/flextls/field.py#L173-L207
DinoTools/python-flextls
flextls/field.py
ECParametersField.dissect
def dissect(self, data): """ Dissect the field. :param bytes data: The data to extract the field value from :return: The rest of the data not used to dissect the field value :rtype: bytes """ size = struct.calcsize("B") if len(data) < size: r...
python
def dissect(self, data): """ Dissect the field. :param bytes data: The data to extract the field value from :return: The rest of the data not used to dissect the field value :rtype: bytes """ size = struct.calcsize("B") if len(data) < size: r...
[ "def", "dissect", "(", "self", ",", "data", ")", ":", "size", "=", "struct", ".", "calcsize", "(", "\"B\"", ")", "if", "len", "(", "data", ")", "<", "size", ":", "raise", "NotEnoughData", "(", "\"Not enough data to decode field '%s' value\"", "%", "self", ...
Dissect the field. :param bytes data: The data to extract the field value from :return: The rest of the data not used to dissect the field value :rtype: bytes
[ "Dissect", "the", "field", "." ]
train
https://github.com/DinoTools/python-flextls/blob/c73448f20e79b1969adcc2271b91d8edda517857/flextls/field.py#L771-L794
noisyboiler/wampy
wampy/auth.py
compute_wcs
def compute_wcs(key, challenge): """ Compute an WAMP-CRA authentication signature from an authentication challenge and a (derived) key. :param key: The key derived (via PBKDF2) from the secret. :type key: str/bytes :param challenge: The authentication challenge to sign. :type challenge: str...
python
def compute_wcs(key, challenge): """ Compute an WAMP-CRA authentication signature from an authentication challenge and a (derived) key. :param key: The key derived (via PBKDF2) from the secret. :type key: str/bytes :param challenge: The authentication challenge to sign. :type challenge: str...
[ "def", "compute_wcs", "(", "key", ",", "challenge", ")", ":", "key", "=", "key", ".", "encode", "(", "'utf8'", ")", "challenge", "=", "challenge", ".", "encode", "(", "'utf8'", ")", "sig", "=", "hmac", ".", "new", "(", "key", ",", "challenge", ",", ...
Compute an WAMP-CRA authentication signature from an authentication challenge and a (derived) key. :param key: The key derived (via PBKDF2) from the secret. :type key: str/bytes :param challenge: The authentication challenge to sign. :type challenge: str/bytes :return: The authentication signa...
[ "Compute", "an", "WAMP", "-", "CRA", "authentication", "signature", "from", "an", "authentication", "challenge", "and", "a", "(", "derived", ")", "key", "." ]
train
https://github.com/noisyboiler/wampy/blob/7c7ef246fec1b2bf3ec3a0e24c85c42fdd99d4bf/wampy/auth.py#L10-L26
noisyboiler/wampy
wampy/session.py
Session._register_procedure
def _register_procedure(self, procedure_name, invocation_policy="single"): """ Register a "procedure" on a Client as callable over the Router. """ options = {"invoke": invocation_policy} message = Register(procedure=procedure_name, options=options) request_id = message.request_id...
python
def _register_procedure(self, procedure_name, invocation_policy="single"): """ Register a "procedure" on a Client as callable over the Router. """ options = {"invoke": invocation_policy} message = Register(procedure=procedure_name, options=options) request_id = message.request_id...
[ "def", "_register_procedure", "(", "self", ",", "procedure_name", ",", "invocation_policy", "=", "\"single\"", ")", ":", "options", "=", "{", "\"invoke\"", ":", "invocation_policy", "}", "message", "=", "Register", "(", "procedure", "=", "procedure_name", ",", "...
Register a "procedure" on a Client as callable over the Router.
[ "Register", "a", "procedure", "on", "a", "Client", "as", "callable", "over", "the", "Router", "." ]
train
https://github.com/noisyboiler/wampy/blob/7c7ef246fec1b2bf3ec3a0e24c85c42fdd99d4bf/wampy/session.py#L237-L251
noisyboiler/wampy
wampy/peers/routers.py
Crossbar.start
def start(self): """ Start Crossbar.io in a subprocess. """ if self.started is True: raise WampyError("Router already started") # will attempt to connect or start up the CrossBar crossbar_config_path = self.config_path cbdir = self.crossbar_directory ...
python
def start(self): """ Start Crossbar.io in a subprocess. """ if self.started is True: raise WampyError("Router already started") # will attempt to connect or start up the CrossBar crossbar_config_path = self.config_path cbdir = self.crossbar_directory ...
[ "def", "start", "(", "self", ")", ":", "if", "self", ".", "started", "is", "True", ":", "raise", "WampyError", "(", "\"Router already started\"", ")", "# will attempt to connect or start up the CrossBar", "crossbar_config_path", "=", "self", ".", "config_path", "cbdir...
Start Crossbar.io in a subprocess.
[ "Start", "Crossbar", ".", "io", "in", "a", "subprocess", "." ]
train
https://github.com/noisyboiler/wampy/blob/7c7ef246fec1b2bf3ec3a0e24c85c42fdd99d4bf/wampy/peers/routers.py#L112-L137
noisyboiler/wampy
wampy/transports/websocket/connection.py
WebSocket._get_handshake_headers
def _get_handshake_headers(self, upgrade): """ Do an HTTP upgrade handshake with the server. Websockets upgrade from HTTP rather than TCP largely because it was assumed that servers which provide websockets will always be talking to a browser. Maybe a reasonable assumption once upon a t...
python
def _get_handshake_headers(self, upgrade): """ Do an HTTP upgrade handshake with the server. Websockets upgrade from HTTP rather than TCP largely because it was assumed that servers which provide websockets will always be talking to a browser. Maybe a reasonable assumption once upon a t...
[ "def", "_get_handshake_headers", "(", "self", ",", "upgrade", ")", ":", "headers", "=", "[", "]", "# https://tools.ietf.org/html/rfc6455", "headers", ".", "append", "(", "\"GET {} HTTP/1.1\"", ".", "format", "(", "self", ".", "websocket_location", ")", ")", "heade...
Do an HTTP upgrade handshake with the server. Websockets upgrade from HTTP rather than TCP largely because it was assumed that servers which provide websockets will always be talking to a browser. Maybe a reasonable assumption once upon a time... The headers here will go a little furth...
[ "Do", "an", "HTTP", "upgrade", "handshake", "with", "the", "server", "." ]
train
https://github.com/noisyboiler/wampy/blob/7c7ef246fec1b2bf3ec3a0e24c85c42fdd99d4bf/wampy/transports/websocket/connection.py#L183-L216
noisyboiler/wampy
wampy/mixins.py
ParseUrlMixin.parse_url
def parse_url(self): """ Parses a URL of the form: - ws://host[:port][path] - wss://host[:port][path] - ws+unix:///path/to/my.socket """ self.scheme = None self.resource = None self.host = None self.port = None if self.url is None: ...
python
def parse_url(self): """ Parses a URL of the form: - ws://host[:port][path] - wss://host[:port][path] - ws+unix:///path/to/my.socket """ self.scheme = None self.resource = None self.host = None self.port = None if self.url is None: ...
[ "def", "parse_url", "(", "self", ")", ":", "self", ".", "scheme", "=", "None", "self", ".", "resource", "=", "None", "self", ".", "host", "=", "None", "self", ".", "port", "=", "None", "if", "self", ".", "url", "is", "None", ":", "return", "scheme"...
Parses a URL of the form: - ws://host[:port][path] - wss://host[:port][path] - ws+unix:///path/to/my.socket
[ "Parses", "a", "URL", "of", "the", "form", ":" ]
train
https://github.com/noisyboiler/wampy/blob/7c7ef246fec1b2bf3ec3a0e24c85c42fdd99d4bf/wampy/mixins.py#L12-L64
noisyboiler/wampy
wampy/transports/websocket/frames.py
FrameFactory.generate_mask
def generate_mask(cls, mask_key, data): """ Mask data. :Parameters: mask_key: byte string 4 byte string(byte), e.g. '\x10\xc6\xc4\x16' data: str data to mask """ # Masking of WebSocket traffic from client to server is required ...
python
def generate_mask(cls, mask_key, data): """ Mask data. :Parameters: mask_key: byte string 4 byte string(byte), e.g. '\x10\xc6\xc4\x16' data: str data to mask """ # Masking of WebSocket traffic from client to server is required ...
[ "def", "generate_mask", "(", "cls", ",", "mask_key", ",", "data", ")", ":", "# Masking of WebSocket traffic from client to server is required", "# because of the unlikely chance that malicious code could cause", "# some broken proxies to do the wrong thing and use this as an", "# attack of...
Mask data. :Parameters: mask_key: byte string 4 byte string(byte), e.g. '\x10\xc6\xc4\x16' data: str data to mask
[ "Mask", "data", "." ]
train
https://github.com/noisyboiler/wampy/blob/7c7ef246fec1b2bf3ec3a0e24c85c42fdd99d4bf/wampy/transports/websocket/frames.py#L194-L222
noisyboiler/wampy
wampy/transports/websocket/frames.py
FrameFactory.generate_bytes
def generate_bytes(cls, payload, fin_bit, opcode, mask_payload): """ Format data to string (buffered_bytes) to send to server. """ # the first byte contains the FIN bit, the 3 RSV bits and the # 4 opcode bits and for a client will *always* be 1000 0001 (or 129). # so we want the ...
python
def generate_bytes(cls, payload, fin_bit, opcode, mask_payload): """ Format data to string (buffered_bytes) to send to server. """ # the first byte contains the FIN bit, the 3 RSV bits and the # 4 opcode bits and for a client will *always* be 1000 0001 (or 129). # so we want the ...
[ "def", "generate_bytes", "(", "cls", ",", "payload", ",", "fin_bit", ",", "opcode", ",", "mask_payload", ")", ":", "# the first byte contains the FIN bit, the 3 RSV bits and the", "# 4 opcode bits and for a client will *always* be 1000 0001 (or 129).", "# so we want the first byte to...
Format data to string (buffered_bytes) to send to server.
[ "Format", "data", "to", "string", "(", "buffered_bytes", ")", "to", "send", "to", "server", "." ]
train
https://github.com/noisyboiler/wampy/blob/7c7ef246fec1b2bf3ec3a0e24c85c42fdd99d4bf/wampy/transports/websocket/frames.py#L225-L296
eddieantonio/perfection
perfection/forest.py
ForestGraph.add_edge
def add_edge(self, edge): """ Add edge (u, v) to the graph. Raises InvariantError if adding the edge would form a cycle. """ u, v = edge both_exist = u in self.vertices and v in self.vertices # Using `is` because if they belong to the same component, they MUST ...
python
def add_edge(self, edge): """ Add edge (u, v) to the graph. Raises InvariantError if adding the edge would form a cycle. """ u, v = edge both_exist = u in self.vertices and v in self.vertices # Using `is` because if they belong to the same component, they MUST ...
[ "def", "add_edge", "(", "self", ",", "edge", ")", ":", "u", ",", "v", "=", "edge", "both_exist", "=", "u", "in", "self", ".", "vertices", "and", "v", "in", "self", ".", "vertices", "# Using `is` because if they belong to the same component, they MUST", "# share ...
Add edge (u, v) to the graph. Raises InvariantError if adding the edge would form a cycle.
[ "Add", "edge", "(", "u", "v", ")", "to", "the", "graph", ".", "Raises", "InvariantError", "if", "adding", "the", "edge", "would", "form", "a", "cycle", "." ]
train
https://github.com/eddieantonio/perfection/blob/69b7a06b31a15bd9534c69d4bdcc2e48e8ddfc43/perfection/forest.py#L61-L90
eddieantonio/perfection
perfection/forest.py
ForestGraph.edges
def edges(self): """ Edges of this graph, in canonical order. """ canonical_edges = set() for v1, neighbours in self._vertices.items(): for v2 in neighbours: edge = self.canonical_order((v1, v2)) canonical_edges.add(edge) return...
python
def edges(self): """ Edges of this graph, in canonical order. """ canonical_edges = set() for v1, neighbours in self._vertices.items(): for v2 in neighbours: edge = self.canonical_order((v1, v2)) canonical_edges.add(edge) return...
[ "def", "edges", "(", "self", ")", ":", "canonical_edges", "=", "set", "(", ")", "for", "v1", ",", "neighbours", "in", "self", ".", "_vertices", ".", "items", "(", ")", ":", "for", "v2", "in", "neighbours", ":", "edge", "=", "self", ".", "canonical_or...
Edges of this graph, in canonical order.
[ "Edges", "of", "this", "graph", "in", "canonical", "order", "." ]
train
https://github.com/eddieantonio/perfection/blob/69b7a06b31a15bd9534c69d4bdcc2e48e8ddfc43/perfection/forest.py#L104-L113
eddieantonio/perfection
perfection/czech.py
ordered_deduplicate
def ordered_deduplicate(sequence): """ Returns the sequence as a tuple with the duplicates removed, preserving input order. Any duplicates following the first occurrence are removed. >>> ordered_deduplicate([1, 2, 3, 1, 32, 1, 2]) (1, 2, 3, 32) Based on recipe from this StackOverflow post...
python
def ordered_deduplicate(sequence): """ Returns the sequence as a tuple with the duplicates removed, preserving input order. Any duplicates following the first occurrence are removed. >>> ordered_deduplicate([1, 2, 3, 1, 32, 1, 2]) (1, 2, 3, 32) Based on recipe from this StackOverflow post...
[ "def", "ordered_deduplicate", "(", "sequence", ")", ":", "seen", "=", "set", "(", ")", "# Micro optimization: each call to seen_add saves an extra attribute", "# lookup in most iterations of the loop.", "seen_add", "=", "seen", ".", "add", "return", "tuple", "(", "x", "fo...
Returns the sequence as a tuple with the duplicates removed, preserving input order. Any duplicates following the first occurrence are removed. >>> ordered_deduplicate([1, 2, 3, 1, 32, 1, 2]) (1, 2, 3, 32) Based on recipe from this StackOverflow post: http://stackoverflow.com/a/480227
[ "Returns", "the", "sequence", "as", "a", "tuple", "with", "the", "duplicates", "removed", "preserving", "input", "order", ".", "Any", "duplicates", "following", "the", "first", "occurrence", "are", "removed", "." ]
train
https://github.com/eddieantonio/perfection/blob/69b7a06b31a15bd9534c69d4bdcc2e48e8ddfc43/perfection/czech.py#L194-L212
eddieantonio/perfection
perfection/czech.py
hash_parameters
def hash_parameters(words, minimize_indices=False): """ Gives hash parameters for the given set of words. >>> info = hash_parameters('sun mon tue wed thu fri sat'.split()) >>> len(info.t1) 21 >>> len(info.t2) 21 >>> len(info.g) # g values are 1-indexed... 22 """ # Ensure tha...
python
def hash_parameters(words, minimize_indices=False): """ Gives hash parameters for the given set of words. >>> info = hash_parameters('sun mon tue wed thu fri sat'.split()) >>> len(info.t1) 21 >>> len(info.t2) 21 >>> len(info.g) # g values are 1-indexed... 22 """ # Ensure tha...
[ "def", "hash_parameters", "(", "words", ",", "minimize_indices", "=", "False", ")", ":", "# Ensure that we have an indexable sequence.", "words", "=", "tuple", "(", "words", ")", "# Delegate to the hash builder.", "return", "CzechHashBuilder", "(", "words", ")", ".", ...
Gives hash parameters for the given set of words. >>> info = hash_parameters('sun mon tue wed thu fri sat'.split()) >>> len(info.t1) 21 >>> len(info.t2) 21 >>> len(info.g) # g values are 1-indexed... 22
[ "Gives", "hash", "parameters", "for", "the", "given", "set", "of", "words", "." ]
train
https://github.com/eddieantonio/perfection/blob/69b7a06b31a15bd9534c69d4bdcc2e48e8ddfc43/perfection/czech.py#L217-L233
eddieantonio/perfection
perfection/czech.py
make_pickable_hash
def make_pickable_hash(words, *args, **kwargs): """ Creates an ordered, minimal perfect hash function for the given sequence of words. >>> hf = make_pickable_hash(['sun', 'mon', 'tue', 'wed', 'thu', ... 'fri', 'sat']) >>> hf('fri') 5 >>> hf('sun') 0 """ ...
python
def make_pickable_hash(words, *args, **kwargs): """ Creates an ordered, minimal perfect hash function for the given sequence of words. >>> hf = make_pickable_hash(['sun', 'mon', 'tue', 'wed', 'thu', ... 'fri', 'sat']) >>> hf('fri') 5 >>> hf('sun') 0 """ ...
[ "def", "make_pickable_hash", "(", "words", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "PickableHash", "(", "CzechHashBuilder", "(", "words", ",", "*", "args", ",", "*", "*", "kwargs", ")", ")", ".", "czech_hash" ]
Creates an ordered, minimal perfect hash function for the given sequence of words. >>> hf = make_pickable_hash(['sun', 'mon', 'tue', 'wed', 'thu', ... 'fri', 'sat']) >>> hf('fri') 5 >>> hf('sun') 0
[ "Creates", "an", "ordered", "minimal", "perfect", "hash", "function", "for", "the", "given", "sequence", "of", "words", "." ]
train
https://github.com/eddieantonio/perfection/blob/69b7a06b31a15bd9534c69d4bdcc2e48e8ddfc43/perfection/czech.py#L272-L284
eddieantonio/perfection
perfection/czech.py
make_dict
def make_dict(name, words, *args, **kwargs): """ make_dict(name, words, *args, **kwargs) -> mapping subclass Takes a sequence of words (or a pre-built Czech HashInfo) and returns a mapping subclass called `name` (used a dict) that employs the use of the minimal perfect hash. This mapping subcl...
python
def make_dict(name, words, *args, **kwargs): """ make_dict(name, words, *args, **kwargs) -> mapping subclass Takes a sequence of words (or a pre-built Czech HashInfo) and returns a mapping subclass called `name` (used a dict) that employs the use of the minimal perfect hash. This mapping subcl...
[ "def", "make_dict", "(", "name", ",", "words", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "info", "=", "CzechHashBuilder", "(", "words", ",", "*", "args", ",", "*", "*", "kwargs", ")", "# Create a docstring that at least describes where the class cam...
make_dict(name, words, *args, **kwargs) -> mapping subclass Takes a sequence of words (or a pre-built Czech HashInfo) and returns a mapping subclass called `name` (used a dict) that employs the use of the minimal perfect hash. This mapping subclass has guaranteed O(1) worst-case lookups, additions, ...
[ "make_dict", "(", "name", "words", "*", "args", "**", "kwargs", ")", "-", ">", "mapping", "subclass" ]
train
https://github.com/eddieantonio/perfection/blob/69b7a06b31a15bd9534c69d4bdcc2e48e8ddfc43/perfection/czech.py#L287-L322
eddieantonio/perfection
perfection/czech.py
CzechHashBuilder.hash_function
def hash_function(self): """ Returns the hash function proper. Ensures that `self` is not bound to the returned closure. """ assert hasattr(self, 'f1') and hasattr(self, 'f2') # These are not just convenient aliases for the given # attributes; if `self` would cre...
python
def hash_function(self): """ Returns the hash function proper. Ensures that `self` is not bound to the returned closure. """ assert hasattr(self, 'f1') and hasattr(self, 'f2') # These are not just convenient aliases for the given # attributes; if `self` would cre...
[ "def", "hash_function", "(", "self", ")", ":", "assert", "hasattr", "(", "self", ",", "'f1'", ")", "and", "hasattr", "(", "self", ",", "'f2'", ")", "# These are not just convenient aliases for the given", "# attributes; if `self` would creep into the returned closure,", "...
Returns the hash function proper. Ensures that `self` is not bound to the returned closure.
[ "Returns", "the", "hash", "function", "proper", ".", "Ensures", "that", "self", "is", "not", "bound", "to", "the", "returned", "closure", "." ]
train
https://github.com/eddieantonio/perfection/blob/69b7a06b31a15bd9534c69d4bdcc2e48e8ddfc43/perfection/czech.py#L62-L83
eddieantonio/perfection
perfection/czech.py
CzechHashBuilder.generate_acyclic_graph
def generate_acyclic_graph(self): """ Generates an acyclic graph for the given words. Adds the graph, and a list of edge-word associations to the object. """ # Maximum length of each table, respectively. # Hardcoded n = cm, where c = 3 # There might be a good way...
python
def generate_acyclic_graph(self): """ Generates an acyclic graph for the given words. Adds the graph, and a list of edge-word associations to the object. """ # Maximum length of each table, respectively. # Hardcoded n = cm, where c = 3 # There might be a good way...
[ "def", "generate_acyclic_graph", "(", "self", ")", ":", "# Maximum length of each table, respectively.", "# Hardcoded n = cm, where c = 3", "# There might be a good way to choose an appropriate C,", "# but [1] suggests the average amount of iterations needed", "# to generate an acyclic graph is ...
Generates an acyclic graph for the given words. Adds the graph, and a list of edge-word associations to the object.
[ "Generates", "an", "acyclic", "graph", "for", "the", "given", "words", ".", "Adds", "the", "graph", "and", "a", "list", "of", "edge", "-", "word", "associations", "to", "the", "object", "." ]
train
https://github.com/eddieantonio/perfection/blob/69b7a06b31a15bd9534c69d4bdcc2e48e8ddfc43/perfection/czech.py#L87-L112
eddieantonio/perfection
perfection/czech.py
CzechHashBuilder.generate_random_table
def generate_random_table(self): """ Generates random tables for given word lists. """ table = list(range(0, self.n)) random.shuffle(table) return table
python
def generate_random_table(self): """ Generates random tables for given word lists. """ table = list(range(0, self.n)) random.shuffle(table) return table
[ "def", "generate_random_table", "(", "self", ")", ":", "table", "=", "list", "(", "range", "(", "0", ",", "self", ".", "n", ")", ")", "random", ".", "shuffle", "(", "table", ")", "return", "table" ]
Generates random tables for given word lists.
[ "Generates", "random", "tables", "for", "given", "word", "lists", "." ]
train
https://github.com/eddieantonio/perfection/blob/69b7a06b31a15bd9534c69d4bdcc2e48e8ddfc43/perfection/czech.py#L114-L120
eddieantonio/perfection
perfection/czech.py
CzechHashBuilder.generate_or_fail
def generate_or_fail(self): """ Attempts to generate a random acyclic graph, raising an InvariantError if unable to. """ t1 = self.generate_random_table() t2 = self.generate_random_table() f1 = self.generate_func(t1) f2 = self.generate_func(t2) ed...
python
def generate_or_fail(self): """ Attempts to generate a random acyclic graph, raising an InvariantError if unable to. """ t1 = self.generate_random_table() t2 = self.generate_random_table() f1 = self.generate_func(t1) f2 = self.generate_func(t2) ed...
[ "def", "generate_or_fail", "(", "self", ")", ":", "t1", "=", "self", ".", "generate_random_table", "(", ")", "t2", "=", "self", ".", "generate_random_table", "(", ")", "f1", "=", "self", ".", "generate_func", "(", "t1", ")", "f2", "=", "self", ".", "ge...
Attempts to generate a random acyclic graph, raising an InvariantError if unable to.
[ "Attempts", "to", "generate", "a", "random", "acyclic", "graph", "raising", "an", "InvariantError", "if", "unable", "to", "." ]
train
https://github.com/eddieantonio/perfection/blob/69b7a06b31a15bd9534c69d4bdcc2e48e8ddfc43/perfection/czech.py#L122-L148
eddieantonio/perfection
perfection/czech.py
CzechHashBuilder.generate_func
def generate_func(self, table): """ Generates a random table based mini-hashing function. """ # Ensure that `self` isn't suddenly in the closure... n = self.n def func(word): return sum(x * ord(c) for x, c in zip(table, word)) % n return func
python
def generate_func(self, table): """ Generates a random table based mini-hashing function. """ # Ensure that `self` isn't suddenly in the closure... n = self.n def func(word): return sum(x * ord(c) for x, c in zip(table, word)) % n return func
[ "def", "generate_func", "(", "self", ",", "table", ")", ":", "# Ensure that `self` isn't suddenly in the closure...", "n", "=", "self", ".", "n", "def", "func", "(", "word", ")", ":", "return", "sum", "(", "x", "*", "ord", "(", "c", ")", "for", "x", ",",...
Generates a random table based mini-hashing function.
[ "Generates", "a", "random", "table", "based", "mini", "-", "hashing", "function", "." ]
train
https://github.com/eddieantonio/perfection/blob/69b7a06b31a15bd9534c69d4bdcc2e48e8ddfc43/perfection/czech.py#L150-L161
eddieantonio/perfection
perfection/utils.py
create_dict_subclass
def create_dict_subclass(name, hash_func, slots, doc): """ Creates a dict subclass named name, using the hash_function to index hash_length items. Doc should be any additional documentation added to the class. """ hash_length = len(slots) # Returns array index -- raises a KeyError if the k...
python
def create_dict_subclass(name, hash_func, slots, doc): """ Creates a dict subclass named name, using the hash_function to index hash_length items. Doc should be any additional documentation added to the class. """ hash_length = len(slots) # Returns array index -- raises a KeyError if the k...
[ "def", "create_dict_subclass", "(", "name", ",", "hash_func", ",", "slots", ",", "doc", ")", ":", "hash_length", "=", "len", "(", "slots", ")", "# Returns array index -- raises a KeyError if the key does not match", "# its slot value.", "def", "index_or_key_error", "(", ...
Creates a dict subclass named name, using the hash_function to index hash_length items. Doc should be any additional documentation added to the class.
[ "Creates", "a", "dict", "subclass", "named", "name", "using", "the", "hash_function", "to", "index", "hash_length", "items", ".", "Doc", "should", "be", "any", "additional", "documentation", "added", "to", "the", "class", "." ]
train
https://github.com/eddieantonio/perfection/blob/69b7a06b31a15bd9534c69d4bdcc2e48e8ddfc43/perfection/utils.py#L10-L77
karimbahgat/PyGeoj
pygeoj.py
validate
def validate(data, skiperrors=False, fixerrors=True): """Checks that the geojson data is a feature collection, that it contains a proper "features" attribute, and that all features are valid too. Returns True if all goes well. - skiperrors will throw away any features that fail to validate. - fixer...
python
def validate(data, skiperrors=False, fixerrors=True): """Checks that the geojson data is a feature collection, that it contains a proper "features" attribute, and that all features are valid too. Returns True if all goes well. - skiperrors will throw away any features that fail to validate. - fixer...
[ "def", "validate", "(", "data", ",", "skiperrors", "=", "False", ",", "fixerrors", "=", "True", ")", ":", "if", "not", "\"type\"", "in", "data", ":", "if", "fixerrors", ":", "data", "[", "\"type\"", "]", "=", "\"FeatureCollection\"", "else", ":", "raise"...
Checks that the geojson data is a feature collection, that it contains a proper "features" attribute, and that all features are valid too. Returns True if all goes well. - skiperrors will throw away any features that fail to validate. - fixerrors will attempt to auto fix any minor errors without raisin...
[ "Checks", "that", "the", "geojson", "data", "is", "a", "feature", "collection", "that", "it", "contains", "a", "proper", "features", "attribute", "and", "that", "all", "features", "are", "valid", "too", ".", "Returns", "True", "if", "all", "goes", "well", ...
train
https://github.com/karimbahgat/PyGeoj/blob/b0f4e5f6a2d8289526fc7ee64a7b48d7b9a622a5/pygeoj.py#L733-L768
karimbahgat/PyGeoj
pygeoj.py
Geometry.validate
def validate(self, fixerrors=True): """ Validates that the geometry is correctly formatted according to the geometry type. Parameters: - **fixerrors** (optional): Attempts to fix minor errors without raising exceptions (defaults to True) Returns: - True if th...
python
def validate(self, fixerrors=True): """ Validates that the geometry is correctly formatted according to the geometry type. Parameters: - **fixerrors** (optional): Attempts to fix minor errors without raising exceptions (defaults to True) Returns: - True if th...
[ "def", "validate", "(", "self", ",", "fixerrors", "=", "True", ")", ":", "# validate nullgeometry or has type and coordinates keys", "if", "not", "self", ".", "_data", ":", "# null geometry, no further checking needed", "return", "True", "elif", "\"type\"", "not", "in",...
Validates that the geometry is correctly formatted according to the geometry type. Parameters: - **fixerrors** (optional): Attempts to fix minor errors without raising exceptions (defaults to True) Returns: - True if the geometry is valid. Raises: - An Exce...
[ "Validates", "that", "the", "geometry", "is", "correctly", "formatted", "according", "to", "the", "geometry", "type", "." ]
train
https://github.com/karimbahgat/PyGeoj/blob/b0f4e5f6a2d8289526fc7ee64a7b48d7b9a622a5/pygeoj.py#L259-L324
karimbahgat/PyGeoj
pygeoj.py
Feature.validate
def validate(self, fixerrors=True): """ Validates that the feature is correctly formatted. Parameters: - **fixerrors** (optional): Attempts to fix minor errors without raising exceptions (defaults to True) Returns: - True if the feature is valid. Rais...
python
def validate(self, fixerrors=True): """ Validates that the feature is correctly formatted. Parameters: - **fixerrors** (optional): Attempts to fix minor errors without raising exceptions (defaults to True) Returns: - True if the feature is valid. Rais...
[ "def", "validate", "(", "self", ",", "fixerrors", "=", "True", ")", ":", "if", "not", "\"type\"", "in", "self", ".", "_data", "or", "self", ".", "_data", "[", "\"type\"", "]", "!=", "\"Feature\"", ":", "if", "fixerrors", ":", "self", ".", "_data", "[...
Validates that the feature is correctly formatted. Parameters: - **fixerrors** (optional): Attempts to fix minor errors without raising exceptions (defaults to True) Returns: - True if the feature is valid. Raises: - An Exception if not valid.
[ "Validates", "that", "the", "feature", "is", "correctly", "formatted", "." ]
train
https://github.com/karimbahgat/PyGeoj/blob/b0f4e5f6a2d8289526fc7ee64a7b48d7b9a622a5/pygeoj.py#L392-L424
karimbahgat/PyGeoj
pygeoj.py
GeojsonFile.all_attributes
def all_attributes(self): """ Collect and return a list of all attributes/properties/fields used in any of the features. """ features = self._data["features"] if not features: return [] elif len(features) == 1: return features[0]["properties"].keys() else: ...
python
def all_attributes(self): """ Collect and return a list of all attributes/properties/fields used in any of the features. """ features = self._data["features"] if not features: return [] elif len(features) == 1: return features[0]["properties"].keys() else: ...
[ "def", "all_attributes", "(", "self", ")", ":", "features", "=", "self", ".", "_data", "[", "\"features\"", "]", "if", "not", "features", ":", "return", "[", "]", "elif", "len", "(", "features", ")", "==", "1", ":", "return", "features", "[", "0", "]...
Collect and return a list of all attributes/properties/fields used in any of the features.
[ "Collect", "and", "return", "a", "list", "of", "all", "attributes", "/", "properties", "/", "fields", "used", "in", "any", "of", "the", "features", "." ]
train
https://github.com/karimbahgat/PyGeoj/blob/b0f4e5f6a2d8289526fc7ee64a7b48d7b9a622a5/pygeoj.py#L521-L532
karimbahgat/PyGeoj
pygeoj.py
GeojsonFile.common_attributes
def common_attributes(self): """ Collect and return a list of attributes/properties/fields common to all features. """ features = self._data["features"] if not features: return [] elif len(features) == 1: return features[0]["properties"].keys() else: f...
python
def common_attributes(self): """ Collect and return a list of attributes/properties/fields common to all features. """ features = self._data["features"] if not features: return [] elif len(features) == 1: return features[0]["properties"].keys() else: f...
[ "def", "common_attributes", "(", "self", ")", ":", "features", "=", "self", ".", "_data", "[", "\"features\"", "]", "if", "not", "features", ":", "return", "[", "]", "elif", "len", "(", "features", ")", "==", "1", ":", "return", "features", "[", "0", ...
Collect and return a list of attributes/properties/fields common to all features.
[ "Collect", "and", "return", "a", "list", "of", "attributes", "/", "properties", "/", "fields", "common", "to", "all", "features", "." ]
train
https://github.com/karimbahgat/PyGeoj/blob/b0f4e5f6a2d8289526fc7ee64a7b48d7b9a622a5/pygeoj.py#L535-L546
karimbahgat/PyGeoj
pygeoj.py
GeojsonFile.add_feature
def add_feature(self, obj=None, geometry=None, properties=None): """ Adds a given feature. If obj isn't specified, geometry and properties can be set as arguments directly. Parameters: - **obj**: Another feature instance, an object with the \_\_geo_interface__ or a geojson dictionary o...
python
def add_feature(self, obj=None, geometry=None, properties=None): """ Adds a given feature. If obj isn't specified, geometry and properties can be set as arguments directly. Parameters: - **obj**: Another feature instance, an object with the \_\_geo_interface__ or a geojson dictionary o...
[ "def", "add_feature", "(", "self", ",", "obj", "=", "None", ",", "geometry", "=", "None", ",", "properties", "=", "None", ")", ":", "properties", "=", "properties", "or", "{", "}", "if", "isinstance", "(", "obj", ",", "Feature", ")", ":", "# instead of...
Adds a given feature. If obj isn't specified, geometry and properties can be set as arguments directly. Parameters: - **obj**: Another feature instance, an object with the \_\_geo_interface__ or a geojson dictionary of the Feature type. - **geometry** (optional): Anything that the Geometry ins...
[ "Adds", "a", "given", "feature", ".", "If", "obj", "isn", "t", "specified", "geometry", "and", "properties", "can", "be", "set", "as", "arguments", "directly", "." ]
train
https://github.com/karimbahgat/PyGeoj/blob/b0f4e5f6a2d8289526fc7ee64a7b48d7b9a622a5/pygeoj.py#L550-L568
karimbahgat/PyGeoj
pygeoj.py
GeojsonFile.define_crs
def define_crs(self, type, name=None, link=None, link_type=None): """ Defines the coordinate reference system for the geojson file. For link crs, only online urls are currenlty supported (no auxilliary crs files). Parameters: - **type**: The type of crs, either "name" o...
python
def define_crs(self, type, name=None, link=None, link_type=None): """ Defines the coordinate reference system for the geojson file. For link crs, only online urls are currenlty supported (no auxilliary crs files). Parameters: - **type**: The type of crs, either "name" o...
[ "def", "define_crs", "(", "self", ",", "type", ",", "name", "=", "None", ",", "link", "=", "None", ",", "link_type", "=", "None", ")", ":", "if", "not", "type", "in", "(", "\"name\"", ",", "\"link\"", ")", ":", "raise", "Exception", "(", "\"type must...
Defines the coordinate reference system for the geojson file. For link crs, only online urls are currenlty supported (no auxilliary crs files). Parameters: - **type**: The type of crs, either "name" or "link". - **name** (optional): The crs name as an OGC formatted crs string (...
[ "Defines", "the", "coordinate", "reference", "system", "for", "the", "geojson", "file", ".", "For", "link", "crs", "only", "online", "urls", "are", "currenlty", "supported", "(", "no", "auxilliary", "crs", "files", ")", "." ]
train
https://github.com/karimbahgat/PyGeoj/blob/b0f4e5f6a2d8289526fc7ee64a7b48d7b9a622a5/pygeoj.py#L629-L651
karimbahgat/PyGeoj
pygeoj.py
GeojsonFile.update_bbox
def update_bbox(self): """ Recalculates the bbox region attribute for the entire file. Useful after adding and/or removing features. No need to use this method just for saving, because saving automatically updates the bbox. """ xmins, ymins, xmaxs, ymaxs = zip(*...
python
def update_bbox(self): """ Recalculates the bbox region attribute for the entire file. Useful after adding and/or removing features. No need to use this method just for saving, because saving automatically updates the bbox. """ xmins, ymins, xmaxs, ymaxs = zip(*...
[ "def", "update_bbox", "(", "self", ")", ":", "xmins", ",", "ymins", ",", "xmaxs", ",", "ymaxs", "=", "zip", "(", "*", "(", "feat", ".", "geometry", ".", "bbox", "for", "feat", "in", "self", "if", "feat", ".", "geometry", ".", "type", "!=", "\"Null\...
Recalculates the bbox region attribute for the entire file. Useful after adding and/or removing features. No need to use this method just for saving, because saving automatically updates the bbox.
[ "Recalculates", "the", "bbox", "region", "attribute", "for", "the", "entire", "file", ".", "Useful", "after", "adding", "and", "/", "or", "removing", "features", "." ]
train
https://github.com/karimbahgat/PyGeoj/blob/b0f4e5f6a2d8289526fc7ee64a7b48d7b9a622a5/pygeoj.py#L653-L664
karimbahgat/PyGeoj
pygeoj.py
GeojsonFile.add_unique_id
def add_unique_id(self): """ Adds a unique id property to each feature. Raises: - An Exception if any of the features already have an "id" field. """ uid = 0 for feature in self._data["features"]: if feature["properties"...
python
def add_unique_id(self): """ Adds a unique id property to each feature. Raises: - An Exception if any of the features already have an "id" field. """ uid = 0 for feature in self._data["features"]: if feature["properties"...
[ "def", "add_unique_id", "(", "self", ")", ":", "uid", "=", "0", "for", "feature", "in", "self", ".", "_data", "[", "\"features\"", "]", ":", "if", "feature", "[", "\"properties\"", "]", ".", "get", "(", "\"id\"", ")", ":", "raise", "Exception", "(", ...
Adds a unique id property to each feature. Raises: - An Exception if any of the features already have an "id" field.
[ "Adds", "a", "unique", "id", "property", "to", "each", "feature", "." ]
train
https://github.com/karimbahgat/PyGeoj/blob/b0f4e5f6a2d8289526fc7ee64a7b48d7b9a622a5/pygeoj.py#L666-L681
karimbahgat/PyGeoj
pygeoj.py
GeojsonFile.add_all_bboxes
def add_all_bboxes(self): """ Calculates and adds a bbox attribute to the geojson entry of all feature geometries, updating any existing ones. """ for feature in self: if feature.geometry.type != "Null": feature.geometry._data["bbox"] = Feature(feature).geomet...
python
def add_all_bboxes(self): """ Calculates and adds a bbox attribute to the geojson entry of all feature geometries, updating any existing ones. """ for feature in self: if feature.geometry.type != "Null": feature.geometry._data["bbox"] = Feature(feature).geomet...
[ "def", "add_all_bboxes", "(", "self", ")", ":", "for", "feature", "in", "self", ":", "if", "feature", ".", "geometry", ".", "type", "!=", "\"Null\"", ":", "feature", ".", "geometry", ".", "_data", "[", "\"bbox\"", "]", "=", "Feature", "(", "feature", "...
Calculates and adds a bbox attribute to the geojson entry of all feature geometries, updating any existing ones.
[ "Calculates", "and", "adds", "a", "bbox", "attribute", "to", "the", "geojson", "entry", "of", "all", "feature", "geometries", "updating", "any", "existing", "ones", "." ]
train
https://github.com/karimbahgat/PyGeoj/blob/b0f4e5f6a2d8289526fc7ee64a7b48d7b9a622a5/pygeoj.py#L683-L689
karimbahgat/PyGeoj
pygeoj.py
GeojsonFile.save
def save(self, savepath, **kwargs): """ Saves the geojson instance to file. To save with a different text encoding use the 'encoding' argument. Parameters: - **savepath**: Filepath to save the file. """ self.update_bbox() tempfile = open(savepath,"w") ...
python
def save(self, savepath, **kwargs): """ Saves the geojson instance to file. To save with a different text encoding use the 'encoding' argument. Parameters: - **savepath**: Filepath to save the file. """ self.update_bbox() tempfile = open(savepath,"w") ...
[ "def", "save", "(", "self", ",", "savepath", ",", "*", "*", "kwargs", ")", ":", "self", ".", "update_bbox", "(", ")", "tempfile", "=", "open", "(", "savepath", ",", "\"w\"", ")", "json", ".", "dump", "(", "self", ".", "_data", ",", "tempfile", ",",...
Saves the geojson instance to file. To save with a different text encoding use the 'encoding' argument. Parameters: - **savepath**: Filepath to save the file.
[ "Saves", "the", "geojson", "instance", "to", "file", ".", "To", "save", "with", "a", "different", "text", "encoding", "use", "the", "encoding", "argument", "." ]
train
https://github.com/karimbahgat/PyGeoj/blob/b0f4e5f6a2d8289526fc7ee64a7b48d7b9a622a5/pygeoj.py#L691-L703
karimbahgat/PyGeoj
pygeoj.py
GeojsonFile._loadfilepath
def _loadfilepath(self, filepath, **kwargs): """This loads a geojson file into a geojson python dictionary using the json module. Note: to load with a different text encoding use the encoding argument. """ with open(filepath, "r") as f: data = json.load(f, **...
python
def _loadfilepath(self, filepath, **kwargs): """This loads a geojson file into a geojson python dictionary using the json module. Note: to load with a different text encoding use the encoding argument. """ with open(filepath, "r") as f: data = json.load(f, **...
[ "def", "_loadfilepath", "(", "self", ",", "filepath", ",", "*", "*", "kwargs", ")", ":", "with", "open", "(", "filepath", ",", "\"r\"", ")", "as", "f", ":", "data", "=", "json", ".", "load", "(", "f", ",", "*", "*", "kwargs", ")", "return", "data...
This loads a geojson file into a geojson python dictionary using the json module. Note: to load with a different text encoding use the encoding argument.
[ "This", "loads", "a", "geojson", "file", "into", "a", "geojson", "python", "dictionary", "using", "the", "json", "module", ".", "Note", ":", "to", "load", "with", "a", "different", "text", "encoding", "use", "the", "encoding", "argument", "." ]
train
https://github.com/karimbahgat/PyGeoj/blob/b0f4e5f6a2d8289526fc7ee64a7b48d7b9a622a5/pygeoj.py#L707-L715
karimbahgat/PyGeoj
pygeoj.py
GeojsonFile._prepdata
def _prepdata(self): """Adds potentially missing items to the geojson dictionary""" # if missing, compute and add bbox if not self._data.get("bbox"): self.update_bbox() # if missing, set crs to default crs (WGS84), see http://geojson.org/geojson-spec.html if...
python
def _prepdata(self): """Adds potentially missing items to the geojson dictionary""" # if missing, compute and add bbox if not self._data.get("bbox"): self.update_bbox() # if missing, set crs to default crs (WGS84), see http://geojson.org/geojson-spec.html if...
[ "def", "_prepdata", "(", "self", ")", ":", "# if missing, compute and add bbox", "if", "not", "self", ".", "_data", ".", "get", "(", "\"bbox\"", ")", ":", "self", ".", "update_bbox", "(", ")", "# if missing, set crs to default crs (WGS84), see http://geojson.org/geojson...
Adds potentially missing items to the geojson dictionary
[ "Adds", "potentially", "missing", "items", "to", "the", "geojson", "dictionary" ]
train
https://github.com/karimbahgat/PyGeoj/blob/b0f4e5f6a2d8289526fc7ee64a7b48d7b9a622a5/pygeoj.py#L717-L727
eddieantonio/perfection
perfection/getty.py
hash_parameters
def hash_parameters(keys, minimize=True, to_int=None): """ Calculates the parameters for a perfect hash. The result is returned as a HashInfo tuple which has the following fields: t The "table parameter". This is the minimum side length of the table used to create the hash. In practice, t...
python
def hash_parameters(keys, minimize=True, to_int=None): """ Calculates the parameters for a perfect hash. The result is returned as a HashInfo tuple which has the following fields: t The "table parameter". This is the minimum side length of the table used to create the hash. In practice, t...
[ "def", "hash_parameters", "(", "keys", ",", "minimize", "=", "True", ",", "to_int", "=", "None", ")", ":", "# If to_int is not assigned, simply use the identity function.", "if", "to_int", "is", "None", ":", "to_int", "=", "__identity", "key_to_original", "=", "{", ...
Calculates the parameters for a perfect hash. The result is returned as a HashInfo tuple which has the following fields: t The "table parameter". This is the minimum side length of the table used to create the hash. In practice, t**2 is the maximum size of the output hash. slots ...
[ "Calculates", "the", "parameters", "for", "a", "perfect", "hash", ".", "The", "result", "is", "returned", "as", "a", "HashInfo", "tuple", "which", "has", "the", "following", "fields", ":" ]
train
https://github.com/eddieantonio/perfection/blob/69b7a06b31a15bd9534c69d4bdcc2e48e8ddfc43/perfection/getty.py#L20-L107
eddieantonio/perfection
perfection/getty.py
place_items_in_square
def place_items_in_square(items, t): """ Returns a list of rows that are stored as a priority queue to be used with heapq functions. >>> place_items_in_square([1,5,7], 4) [(2, 1, [(1, 5), (3, 7)]), (3, 0, [(1, 1)])] >>> place_items_in_square([1,5,7], 3) [(2, 0, [(1, 1)]), (2, 1, [(2, 5)]), ...
python
def place_items_in_square(items, t): """ Returns a list of rows that are stored as a priority queue to be used with heapq functions. >>> place_items_in_square([1,5,7], 4) [(2, 1, [(1, 5), (3, 7)]), (3, 0, [(1, 1)])] >>> place_items_in_square([1,5,7], 3) [(2, 0, [(1, 1)]), (2, 1, [(2, 5)]), ...
[ "def", "place_items_in_square", "(", "items", ",", "t", ")", ":", "# A minheap (because that's all that heapq supports :/)", "# of the length of each row. Why this is important is because", "# we'll be popping the largest rows when figuring out row displacements.", "# Each item is a tuple of (...
Returns a list of rows that are stored as a priority queue to be used with heapq functions. >>> place_items_in_square([1,5,7], 4) [(2, 1, [(1, 5), (3, 7)]), (3, 0, [(1, 1)])] >>> place_items_in_square([1,5,7], 3) [(2, 0, [(1, 1)]), (2, 1, [(2, 5)]), (2, 2, [(1, 7)])]
[ "Returns", "a", "list", "of", "rows", "that", "are", "stored", "as", "a", "priority", "queue", "to", "be", "used", "with", "heapq", "functions", "." ]
train
https://github.com/eddieantonio/perfection/blob/69b7a06b31a15bd9534c69d4bdcc2e48e8ddfc43/perfection/getty.py#L118-L154
eddieantonio/perfection
perfection/getty.py
arrange_rows
def arrange_rows(row_queue, t): """ Takes a priority queue as generated by place_items_in_square(). Arranges the items from its conceptual square to one list. Returns both the resultant vector, plus the displacement vector, to be used in the final output hash function. >>> rows = [(2, 1, [(0, ...
python
def arrange_rows(row_queue, t): """ Takes a priority queue as generated by place_items_in_square(). Arranges the items from its conceptual square to one list. Returns both the resultant vector, plus the displacement vector, to be used in the final output hash function. >>> rows = [(2, 1, [(0, ...
[ "def", "arrange_rows", "(", "row_queue", ",", "t", ")", ":", "# Create a set of all of the unoccupied columns.", "max_columns", "=", "t", "**", "2", "cols", "=", "(", "(", "x", ",", "True", ")", "for", "x", "in", "range", "(", "max_columns", ")", ")", "uno...
Takes a priority queue as generated by place_items_in_square(). Arranges the items from its conceptual square to one list. Returns both the resultant vector, plus the displacement vector, to be used in the final output hash function. >>> rows = [(2, 1, [(0, 1), (1, 5)]), (3, 3, [(1, 7)])] >>> resu...
[ "Takes", "a", "priority", "queue", "as", "generated", "by", "place_items_in_square", "()", ".", "Arranges", "the", "items", "from", "its", "conceptual", "square", "to", "one", "list", ".", "Returns", "both", "the", "resultant", "vector", "plus", "the", "displa...
train
https://github.com/eddieantonio/perfection/blob/69b7a06b31a15bd9534c69d4bdcc2e48e8ddfc43/perfection/getty.py#L157-L202
eddieantonio/perfection
perfection/getty.py
find_first_fit
def find_first_fit(unoccupied_columns, row, row_length): """ Finds the first index that the row's items can fit. """ for free_col in unoccupied_columns: # The offset is that such that the first item goes in the free column. first_item_x = row[0][0] offset = free_col - first_item_...
python
def find_first_fit(unoccupied_columns, row, row_length): """ Finds the first index that the row's items can fit. """ for free_col in unoccupied_columns: # The offset is that such that the first item goes in the free column. first_item_x = row[0][0] offset = free_col - first_item_...
[ "def", "find_first_fit", "(", "unoccupied_columns", ",", "row", ",", "row_length", ")", ":", "for", "free_col", "in", "unoccupied_columns", ":", "# The offset is that such that the first item goes in the free column.", "first_item_x", "=", "row", "[", "0", "]", "[", "0"...
Finds the first index that the row's items can fit.
[ "Finds", "the", "first", "index", "that", "the", "row", "s", "items", "can", "fit", "." ]
train
https://github.com/eddieantonio/perfection/blob/69b7a06b31a15bd9534c69d4bdcc2e48e8ddfc43/perfection/getty.py#L205-L217
eddieantonio/perfection
perfection/getty.py
check_columns_fit
def check_columns_fit(unoccupied_columns, row, offset, row_length): """ Checks if all the occupied columns in the row fit in the indices given by free columns. >>> check_columns_fit({0,1,2,3}, [(0, True), (2, True)], 0, 4) True >>> check_columns_fit({0,2,3}, [(2, True), (3, True)], 0, 4) Tr...
python
def check_columns_fit(unoccupied_columns, row, offset, row_length): """ Checks if all the occupied columns in the row fit in the indices given by free columns. >>> check_columns_fit({0,1,2,3}, [(0, True), (2, True)], 0, 4) True >>> check_columns_fit({0,2,3}, [(2, True), (3, True)], 0, 4) Tr...
[ "def", "check_columns_fit", "(", "unoccupied_columns", ",", "row", ",", "offset", ",", "row_length", ")", ":", "for", "index", ",", "item", "in", "row", ":", "adjusted_index", "=", "(", "index", "+", "offset", ")", "%", "row_length", "# Check if the index is i...
Checks if all the occupied columns in the row fit in the indices given by free columns. >>> check_columns_fit({0,1,2,3}, [(0, True), (2, True)], 0, 4) True >>> check_columns_fit({0,2,3}, [(2, True), (3, True)], 0, 4) True >>> check_columns_fit({}, [(2, True), (3, True)], 0, 4) False >>>...
[ "Checks", "if", "all", "the", "occupied", "columns", "in", "the", "row", "fit", "in", "the", "indices", "given", "by", "free", "columns", "." ]
train
https://github.com/eddieantonio/perfection/blob/69b7a06b31a15bd9534c69d4bdcc2e48e8ddfc43/perfection/getty.py#L220-L244
eddieantonio/perfection
perfection/getty.py
print_square
def print_square(row_queue, t): """ Prints a row queue as its conceptual square array. """ occupied_rows = {y: row for _, y, row in row_queue} empty_row = ', '.join('...' for _ in range(t)) for y in range(t): print('|', end=' ') if y not in occupied_rows: print(empty...
python
def print_square(row_queue, t): """ Prints a row queue as its conceptual square array. """ occupied_rows = {y: row for _, y, row in row_queue} empty_row = ', '.join('...' for _ in range(t)) for y in range(t): print('|', end=' ') if y not in occupied_rows: print(empty...
[ "def", "print_square", "(", "row_queue", ",", "t", ")", ":", "occupied_rows", "=", "{", "y", ":", "row", "for", "_", ",", "y", ",", "row", "in", "row_queue", "}", "empty_row", "=", "', '", ".", "join", "(", "'...'", "for", "_", "in", "range", "(", ...
Prints a row queue as its conceptual square array.
[ "Prints", "a", "row", "queue", "as", "its", "conceptual", "square", "array", "." ]
train
https://github.com/eddieantonio/perfection/blob/69b7a06b31a15bd9534c69d4bdcc2e48e8ddfc43/perfection/getty.py#L247-L264
eddieantonio/perfection
perfection/getty.py
trim_nones_from_right
def trim_nones_from_right(xs): """ Returns the list without all the Nones at the right end. >>> trim_nones_from_right([1, 2, None, 4, None, 5, None, None]) [1, 2, None, 4, None, 5] """ # Find the first element that does not contain none. for i, item in enumerate(reversed(xs)): if i...
python
def trim_nones_from_right(xs): """ Returns the list without all the Nones at the right end. >>> trim_nones_from_right([1, 2, None, 4, None, 5, None, None]) [1, 2, None, 4, None, 5] """ # Find the first element that does not contain none. for i, item in enumerate(reversed(xs)): if i...
[ "def", "trim_nones_from_right", "(", "xs", ")", ":", "# Find the first element that does not contain none.", "for", "i", ",", "item", "in", "enumerate", "(", "reversed", "(", "xs", ")", ")", ":", "if", "item", "is", "not", "None", ":", "break", "return", "xs",...
Returns the list without all the Nones at the right end. >>> trim_nones_from_right([1, 2, None, 4, None, 5, None, None]) [1, 2, None, 4, None, 5]
[ "Returns", "the", "list", "without", "all", "the", "Nones", "at", "the", "right", "end", "." ]
train
https://github.com/eddieantonio/perfection/blob/69b7a06b31a15bd9534c69d4bdcc2e48e8ddfc43/perfection/getty.py#L267-L280
eddieantonio/perfection
perfection/getty.py
make_hash
def make_hash(keys, **kwargs): """ Creates a perfect hash function from the given keys. For a description of the keyword arguments see :py:func:`hash_parameters`. >>> l = (0, 3, 4, 7 ,10, 13, 15, 18, 19, 21, 22, 24, 26, 29, 30, 34) >>> hf = make_hash(l) >>> hf(19) 1 >>> hash_parameters(...
python
def make_hash(keys, **kwargs): """ Creates a perfect hash function from the given keys. For a description of the keyword arguments see :py:func:`hash_parameters`. >>> l = (0, 3, 4, 7 ,10, 13, 15, 18, 19, 21, 22, 24, 26, 29, 30, 34) >>> hf = make_hash(l) >>> hf(19) 1 >>> hash_parameters(...
[ "def", "make_hash", "(", "keys", ",", "*", "*", "kwargs", ")", ":", "params", "=", "hash_parameters", "(", "keys", ",", "*", "*", "kwargs", ")", "t", "=", "params", ".", "t", "r", "=", "params", ".", "r", "offset", "=", "params", ".", "offset", "...
Creates a perfect hash function from the given keys. For a description of the keyword arguments see :py:func:`hash_parameters`. >>> l = (0, 3, 4, 7 ,10, 13, 15, 18, 19, 21, 22, 24, 26, 29, 30, 34) >>> hf = make_hash(l) >>> hf(19) 1 >>> hash_parameters(l).slots[1] 19
[ "Creates", "a", "perfect", "hash", "function", "from", "the", "given", "keys", ".", "For", "a", "description", "of", "the", "keyword", "arguments", "see", ":", "py", ":", "func", ":", "hash_parameters", "." ]
train
https://github.com/eddieantonio/perfection/blob/69b7a06b31a15bd9534c69d4bdcc2e48e8ddfc43/perfection/getty.py#L283-L311
eddieantonio/perfection
perfection/getty.py
make_dict
def make_dict(name, keys, **kwargs): """ Creates a dictionary-like mapping class that uses perfect hashing. ``name`` is the proper class name of the returned class. See ``hash_parameters()`` for documentation on all arguments after ``name``. >>> MyDict = make_dict('MyDict', '+-<>[],.', to_int=o...
python
def make_dict(name, keys, **kwargs): """ Creates a dictionary-like mapping class that uses perfect hashing. ``name`` is the proper class name of the returned class. See ``hash_parameters()`` for documentation on all arguments after ``name``. >>> MyDict = make_dict('MyDict', '+-<>[],.', to_int=o...
[ "def", "make_dict", "(", "name", ",", "keys", ",", "*", "*", "kwargs", ")", ":", "hash_func", "=", "make_hash", "(", "keys", ",", "*", "*", "kwargs", ")", "slots", "=", "hash_func", ".", "slots", "# Create a docstring that at least describes where the class came...
Creates a dictionary-like mapping class that uses perfect hashing. ``name`` is the proper class name of the returned class. See ``hash_parameters()`` for documentation on all arguments after ``name``. >>> MyDict = make_dict('MyDict', '+-<>[],.', to_int=ord) >>> d = MyDict([('+', 1), ('-', 2)]) ...
[ "Creates", "a", "dictionary", "-", "like", "mapping", "class", "that", "uses", "perfect", "hashing", ".", "name", "is", "the", "proper", "class", "name", "of", "the", "returned", "class", ".", "See", "hash_parameters", "()", "for", "documentation", "on", "al...
train
https://github.com/eddieantonio/perfection/blob/69b7a06b31a15bd9534c69d4bdcc2e48e8ddfc43/perfection/getty.py#L314-L343
ajslater/picopt
picopt/timestamp.py
_get_timestamp
def _get_timestamp(dirname_full, remove): """ Get the timestamp from the timestamp file. Optionally mark it for removal if we're going to write another one. """ record_filename = os.path.join(dirname_full, RECORD_FILENAME) if not os.path.exists(record_filename): return None mtime ...
python
def _get_timestamp(dirname_full, remove): """ Get the timestamp from the timestamp file. Optionally mark it for removal if we're going to write another one. """ record_filename = os.path.join(dirname_full, RECORD_FILENAME) if not os.path.exists(record_filename): return None mtime ...
[ "def", "_get_timestamp", "(", "dirname_full", ",", "remove", ")", ":", "record_filename", "=", "os", ".", "path", ".", "join", "(", "dirname_full", ",", "RECORD_FILENAME", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "record_filename", ")", ":"...
Get the timestamp from the timestamp file. Optionally mark it for removal if we're going to write another one.
[ "Get", "the", "timestamp", "from", "the", "timestamp", "file", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/timestamp.py#L16-L32
ajslater/picopt
picopt/timestamp.py
_get_timestamp_cached
def _get_timestamp_cached(dirname_full, remove): """ Get the timestamp from the cache or fill the cache Much quicker than reading the same files over and over """ if dirname_full not in TIMESTAMP_CACHE: mtime = _get_timestamp(dirname_full, remove) TIMESTAMP_CACHE[dirname_full] = mtim...
python
def _get_timestamp_cached(dirname_full, remove): """ Get the timestamp from the cache or fill the cache Much quicker than reading the same files over and over """ if dirname_full not in TIMESTAMP_CACHE: mtime = _get_timestamp(dirname_full, remove) TIMESTAMP_CACHE[dirname_full] = mtim...
[ "def", "_get_timestamp_cached", "(", "dirname_full", ",", "remove", ")", ":", "if", "dirname_full", "not", "in", "TIMESTAMP_CACHE", ":", "mtime", "=", "_get_timestamp", "(", "dirname_full", ",", "remove", ")", "TIMESTAMP_CACHE", "[", "dirname_full", "]", "=", "m...
Get the timestamp from the cache or fill the cache Much quicker than reading the same files over and over
[ "Get", "the", "timestamp", "from", "the", "cache", "or", "fill", "the", "cache", "Much", "quicker", "than", "reading", "the", "same", "files", "over", "and", "over" ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/timestamp.py#L35-L43
ajslater/picopt
picopt/timestamp.py
_max_timestamps
def _max_timestamps(dirname_full, remove, compare_tstamp): """Compare a timestamp file to one passed in. Get the max.""" tstamp = _get_timestamp_cached(dirname_full, remove) return max_none((tstamp, compare_tstamp))
python
def _max_timestamps(dirname_full, remove, compare_tstamp): """Compare a timestamp file to one passed in. Get the max.""" tstamp = _get_timestamp_cached(dirname_full, remove) return max_none((tstamp, compare_tstamp))
[ "def", "_max_timestamps", "(", "dirname_full", ",", "remove", ",", "compare_tstamp", ")", ":", "tstamp", "=", "_get_timestamp_cached", "(", "dirname_full", ",", "remove", ")", "return", "max_none", "(", "(", "tstamp", ",", "compare_tstamp", ")", ")" ]
Compare a timestamp file to one passed in. Get the max.
[ "Compare", "a", "timestamp", "file", "to", "one", "passed", "in", ".", "Get", "the", "max", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/timestamp.py#L56-L59
ajslater/picopt
picopt/timestamp.py
_get_parent_timestamp
def _get_parent_timestamp(dirname, mtime): """ Get the timestamps up the directory tree. All the way to root. Because they affect every subdirectory. """ parent_pathname = os.path.dirname(dirname) # max between the parent timestamp the one passed in mtime = _max_timestamps(parent_pathname,...
python
def _get_parent_timestamp(dirname, mtime): """ Get the timestamps up the directory tree. All the way to root. Because they affect every subdirectory. """ parent_pathname = os.path.dirname(dirname) # max between the parent timestamp the one passed in mtime = _max_timestamps(parent_pathname,...
[ "def", "_get_parent_timestamp", "(", "dirname", ",", "mtime", ")", ":", "parent_pathname", "=", "os", ".", "path", ".", "dirname", "(", "dirname", ")", "# max between the parent timestamp the one passed in", "mtime", "=", "_max_timestamps", "(", "parent_pathname", ","...
Get the timestamps up the directory tree. All the way to root. Because they affect every subdirectory.
[ "Get", "the", "timestamps", "up", "the", "directory", "tree", ".", "All", "the", "way", "to", "root", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/timestamp.py#L62-L77
ajslater/picopt
picopt/timestamp.py
get_walk_after
def get_walk_after(filename, optimize_after=None): """ Figure out the which mtime to check against. If we have to look up the path return that. """ if Settings.optimize_after is not None: return Settings.optimize_after dirname = os.path.dirname(filename) if optimize_after is None: ...
python
def get_walk_after(filename, optimize_after=None): """ Figure out the which mtime to check against. If we have to look up the path return that. """ if Settings.optimize_after is not None: return Settings.optimize_after dirname = os.path.dirname(filename) if optimize_after is None: ...
[ "def", "get_walk_after", "(", "filename", ",", "optimize_after", "=", "None", ")", ":", "if", "Settings", ".", "optimize_after", "is", "not", "None", ":", "return", "Settings", ".", "optimize_after", "dirname", "=", "os", ".", "path", ".", "dirname", "(", ...
Figure out the which mtime to check against. If we have to look up the path return that.
[ "Figure", "out", "the", "which", "mtime", "to", "check", "against", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/timestamp.py#L80-L92
ajslater/picopt
picopt/timestamp.py
record_timestamp
def record_timestamp(pathname_full): """Record the timestamp of running in a dotfile.""" if Settings.test or Settings.list_only or not Settings.record_timestamp: return if not Settings.follow_symlinks and os.path.islink(pathname_full): if Settings.verbose: print('Not setting time...
python
def record_timestamp(pathname_full): """Record the timestamp of running in a dotfile.""" if Settings.test or Settings.list_only or not Settings.record_timestamp: return if not Settings.follow_symlinks and os.path.islink(pathname_full): if Settings.verbose: print('Not setting time...
[ "def", "record_timestamp", "(", "pathname_full", ")", ":", "if", "Settings", ".", "test", "or", "Settings", ".", "list_only", "or", "not", "Settings", ".", "record_timestamp", ":", "return", "if", "not", "Settings", ".", "follow_symlinks", "and", "os", ".", ...
Record the timestamp of running in a dotfile.
[ "Record", "the", "timestamp", "of", "running", "in", "a", "dotfile", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/timestamp.py#L95-L123
ajslater/picopt
picopt/walk.py
walk_comic_archive
def walk_comic_archive(filename_full, image_format, optimize_after): """ Optimize a comic archive. This is done mostly inline to use the master processes process pool for workers. And to avoid calling back up into walk from a dedicated module or format processor. It does mean that we block on uncom...
python
def walk_comic_archive(filename_full, image_format, optimize_after): """ Optimize a comic archive. This is done mostly inline to use the master processes process pool for workers. And to avoid calling back up into walk from a dedicated module or format processor. It does mean that we block on uncom...
[ "def", "walk_comic_archive", "(", "filename_full", ",", "image_format", ",", "optimize_after", ")", ":", "# uncompress archive", "tmp_dir", ",", "report_stats", "=", "comic", ".", "comic_archive_uncompress", "(", "filename_full", ",", "image_format", ")", "if", "tmp_d...
Optimize a comic archive. This is done mostly inline to use the master processes process pool for workers. And to avoid calling back up into walk from a dedicated module or format processor. It does mean that we block on uncompress and on waiting for the contents subprocesses to compress.
[ "Optimize", "a", "comic", "archive", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/walk.py#L16-L45