repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
martinmcbride/pysound | pysound/soundfile.py | save | def save(params, filename, source):
'''
Write a sequence of samples as a WAV file
Currently a 16 bit mono file
'''
writer = wave.open(filename, 'wb');
# Set the WAV file parameters, currently default values
writer.setnchannels(1)
writer.setsampwidth(2)
writer.setframerate(params.sample_rate)
data_out = array.array('h')
for x in source:
data_out.append(int(x * 32766))
writer.writeframes(data_out.tostring())
writer.close() | python | def save(params, filename, source):
'''
Write a sequence of samples as a WAV file
Currently a 16 bit mono file
'''
writer = wave.open(filename, 'wb');
# Set the WAV file parameters, currently default values
writer.setnchannels(1)
writer.setsampwidth(2)
writer.setframerate(params.sample_rate)
data_out = array.array('h')
for x in source:
data_out.append(int(x * 32766))
writer.writeframes(data_out.tostring())
writer.close() | [
"def",
"save",
"(",
"params",
",",
"filename",
",",
"source",
")",
":",
"writer",
"=",
"wave",
".",
"open",
"(",
"filename",
",",
"'wb'",
")",
"# Set the WAV file parameters, currently default values",
"writer",
".",
"setnchannels",
"(",
"1",
")",
"writer",
".... | Write a sequence of samples as a WAV file
Currently a 16 bit mono file | [
"Write",
"a",
"sequence",
"of",
"samples",
"as",
"a",
"WAV",
"file",
"Currently",
"a",
"16",
"bit",
"mono",
"file"
] | 253c8f712ad475318350e5a8ba21f6fefd7a3de2 | https://github.com/martinmcbride/pysound/blob/253c8f712ad475318350e5a8ba21f6fefd7a3de2/pysound/soundfile.py#L9-L23 | train | 47,100 |
deep-compute/deeputil | deeputil/priority_dict.py | PriorityDict.smallest | def smallest(self):
"""Return the item with the lowest priority.
Raises IndexError if the object is empty.
"""
heap = self._heap
v, k = heap[0]
while k not in self or self[k] != v:
heappop(heap)
v, k = heap[0]
return k | python | def smallest(self):
"""Return the item with the lowest priority.
Raises IndexError if the object is empty.
"""
heap = self._heap
v, k = heap[0]
while k not in self or self[k] != v:
heappop(heap)
v, k = heap[0]
return k | [
"def",
"smallest",
"(",
"self",
")",
":",
"heap",
"=",
"self",
".",
"_heap",
"v",
",",
"k",
"=",
"heap",
"[",
"0",
"]",
"while",
"k",
"not",
"in",
"self",
"or",
"self",
"[",
"k",
"]",
"!=",
"v",
":",
"heappop",
"(",
"heap",
")",
"v",
",",
"... | Return the item with the lowest priority.
Raises IndexError if the object is empty. | [
"Return",
"the",
"item",
"with",
"the",
"lowest",
"priority",
"."
] | 9af5702bc3fd990688bf2aed16c20fa104be66df | https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/priority_dict.py#L76-L88 | train | 47,101 |
deep-compute/deeputil | deeputil/priority_dict.py | PriorityDict.pop_smallest | def pop_smallest(self):
"""Return the item with the lowest priority and remove it.
Raises IndexError if the object is empty.
"""
heap = self._heap
v, k = heappop(heap)
while k not in self or self[k] != v:
v, k = heappop(heap)
del self[k]
return k | python | def pop_smallest(self):
"""Return the item with the lowest priority and remove it.
Raises IndexError if the object is empty.
"""
heap = self._heap
v, k = heappop(heap)
while k not in self or self[k] != v:
v, k = heappop(heap)
del self[k]
return k | [
"def",
"pop_smallest",
"(",
"self",
")",
":",
"heap",
"=",
"self",
".",
"_heap",
"v",
",",
"k",
"=",
"heappop",
"(",
"heap",
")",
"while",
"k",
"not",
"in",
"self",
"or",
"self",
"[",
"k",
"]",
"!=",
"v",
":",
"v",
",",
"k",
"=",
"heappop",
"... | Return the item with the lowest priority and remove it.
Raises IndexError if the object is empty. | [
"Return",
"the",
"item",
"with",
"the",
"lowest",
"priority",
"and",
"remove",
"it",
"."
] | 9af5702bc3fd990688bf2aed16c20fa104be66df | https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/priority_dict.py#L90-L101 | train | 47,102 |
proteanhq/protean | src/protean/utils/query.py | RegisterLookupMixin.get_lookups | def get_lookups(cls):
"""Fetch all Lookups"""
class_lookups = [parent.__dict__.get('class_lookups', {}) for parent in inspect.getmro(cls)]
return cls.merge_dicts(class_lookups) | python | def get_lookups(cls):
"""Fetch all Lookups"""
class_lookups = [parent.__dict__.get('class_lookups', {}) for parent in inspect.getmro(cls)]
return cls.merge_dicts(class_lookups) | [
"def",
"get_lookups",
"(",
"cls",
")",
":",
"class_lookups",
"=",
"[",
"parent",
".",
"__dict__",
".",
"get",
"(",
"'class_lookups'",
",",
"{",
"}",
")",
"for",
"parent",
"in",
"inspect",
".",
"getmro",
"(",
"cls",
")",
"]",
"return",
"cls",
".",
"me... | Fetch all Lookups | [
"Fetch",
"all",
"Lookups"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/utils/query.py#L22-L25 | train | 47,103 |
proteanhq/protean | src/protean/utils/query.py | RegisterLookupMixin.get_lookup | def get_lookup(self, lookup_name):
"""Fetch Lookup by name"""
from protean.core.repository import BaseLookup
lookup = self._get_lookup(lookup_name)
# If unable to find Lookup, or if Lookup is the wrong class, raise Error
if lookup is None or (lookup is not None and not issubclass(lookup, BaseLookup)):
raise NotImplementedError
return lookup | python | def get_lookup(self, lookup_name):
"""Fetch Lookup by name"""
from protean.core.repository import BaseLookup
lookup = self._get_lookup(lookup_name)
# If unable to find Lookup, or if Lookup is the wrong class, raise Error
if lookup is None or (lookup is not None and not issubclass(lookup, BaseLookup)):
raise NotImplementedError
return lookup | [
"def",
"get_lookup",
"(",
"self",
",",
"lookup_name",
")",
":",
"from",
"protean",
".",
"core",
".",
"repository",
"import",
"BaseLookup",
"lookup",
"=",
"self",
".",
"_get_lookup",
"(",
"lookup_name",
")",
"# If unable to find Lookup, or if Lookup is the wrong class,... | Fetch Lookup by name | [
"Fetch",
"Lookup",
"by",
"name"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/utils/query.py#L27-L36 | train | 47,104 |
proteanhq/protean | src/protean/utils/query.py | RegisterLookupMixin.register_lookup | def register_lookup(cls, lookup, lookup_name=None):
"""Register a Lookup to a class"""
if lookup_name is None:
lookup_name = lookup.lookup_name
if 'class_lookups' not in cls.__dict__:
cls.class_lookups = {}
cls.class_lookups[lookup_name] = lookup
cls._clear_cached_lookups()
return lookup | python | def register_lookup(cls, lookup, lookup_name=None):
"""Register a Lookup to a class"""
if lookup_name is None:
lookup_name = lookup.lookup_name
if 'class_lookups' not in cls.__dict__:
cls.class_lookups = {}
cls.class_lookups[lookup_name] = lookup
cls._clear_cached_lookups()
return lookup | [
"def",
"register_lookup",
"(",
"cls",
",",
"lookup",
",",
"lookup_name",
"=",
"None",
")",
":",
"if",
"lookup_name",
"is",
"None",
":",
"lookup_name",
"=",
"lookup",
".",
"lookup_name",
"if",
"'class_lookups'",
"not",
"in",
"cls",
".",
"__dict__",
":",
"cl... | Register a Lookup to a class | [
"Register",
"a",
"Lookup",
"to",
"a",
"class"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/utils/query.py#L55-L65 | train | 47,105 |
proteanhq/protean | src/protean/utils/query.py | RegisterLookupMixin._unregister_lookup | def _unregister_lookup(cls, lookup, lookup_name=None):
"""
Remove given lookup from cls lookups. For use in tests only as it's
not thread-safe.
"""
if lookup_name is None:
lookup_name = lookup.lookup_name
del cls.class_lookups[lookup_name] | python | def _unregister_lookup(cls, lookup, lookup_name=None):
"""
Remove given lookup from cls lookups. For use in tests only as it's
not thread-safe.
"""
if lookup_name is None:
lookup_name = lookup.lookup_name
del cls.class_lookups[lookup_name] | [
"def",
"_unregister_lookup",
"(",
"cls",
",",
"lookup",
",",
"lookup_name",
"=",
"None",
")",
":",
"if",
"lookup_name",
"is",
"None",
":",
"lookup_name",
"=",
"lookup",
".",
"lookup_name",
"del",
"cls",
".",
"class_lookups",
"[",
"lookup_name",
"]"
] | Remove given lookup from cls lookups. For use in tests only as it's
not thread-safe. | [
"Remove",
"given",
"lookup",
"from",
"cls",
"lookups",
".",
"For",
"use",
"in",
"tests",
"only",
"as",
"it",
"s",
"not",
"thread",
"-",
"safe",
"."
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/utils/query.py#L68-L75 | train | 47,106 |
proteanhq/protean | src/protean/utils/query.py | Q.deconstruct | def deconstruct(self):
"""Deconstruct a Q Object"""
path = '%s.%s' % (self.__class__.__module__, self.__class__.__name__)
args, kwargs = (), {}
if len(self.children) == 1 and not isinstance(self.children[0], Q):
child = self.children[0]
kwargs = {child[0]: child[1]}
else:
args = tuple(self.children)
if self.connector != self.default:
kwargs = {'_connector': self.connector}
if self.negated:
kwargs['_negated'] = True
return path, args, kwargs | python | def deconstruct(self):
"""Deconstruct a Q Object"""
path = '%s.%s' % (self.__class__.__module__, self.__class__.__name__)
args, kwargs = (), {}
if len(self.children) == 1 and not isinstance(self.children[0], Q):
child = self.children[0]
kwargs = {child[0]: child[1]}
else:
args = tuple(self.children)
if self.connector != self.default:
kwargs = {'_connector': self.connector}
if self.negated:
kwargs['_negated'] = True
return path, args, kwargs | [
"def",
"deconstruct",
"(",
"self",
")",
":",
"path",
"=",
"'%s.%s'",
"%",
"(",
"self",
".",
"__class__",
".",
"__module__",
",",
"self",
".",
"__class__",
".",
"__name__",
")",
"args",
",",
"kwargs",
"=",
"(",
")",
",",
"{",
"}",
"if",
"len",
"(",
... | Deconstruct a Q Object | [
"Deconstruct",
"a",
"Q",
"Object"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/utils/query.py#L238-L252 | train | 47,107 |
proteanhq/protean | src/protean/context.py | Context.set_context | def set_context(self, data):
"""Load Context with data"""
for key in data:
setattr(self.local_context, key, data[key]) | python | def set_context(self, data):
"""Load Context with data"""
for key in data:
setattr(self.local_context, key, data[key]) | [
"def",
"set_context",
"(",
"self",
",",
"data",
")",
":",
"for",
"key",
"in",
"data",
":",
"setattr",
"(",
"self",
".",
"local_context",
",",
"key",
",",
"data",
"[",
"key",
"]",
")"
] | Load Context with data | [
"Load",
"Context",
"with",
"data"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/context.py#L27-L30 | train | 47,108 |
proteanhq/protean | src/protean/core/field/association.py | _ReferenceField._reset_values | def _reset_values(self, instance):
"""Reset all associated values and clean up dictionary items"""
self.value = None
self.reference.value = None
instance.__dict__.pop(self.field_name, None)
instance.__dict__.pop(self.reference.field_name, None)
self.reference.delete_cached_value(instance) | python | def _reset_values(self, instance):
"""Reset all associated values and clean up dictionary items"""
self.value = None
self.reference.value = None
instance.__dict__.pop(self.field_name, None)
instance.__dict__.pop(self.reference.field_name, None)
self.reference.delete_cached_value(instance) | [
"def",
"_reset_values",
"(",
"self",
",",
"instance",
")",
":",
"self",
".",
"value",
"=",
"None",
"self",
".",
"reference",
".",
"value",
"=",
"None",
"instance",
".",
"__dict__",
".",
"pop",
"(",
"self",
".",
"field_name",
",",
"None",
")",
"instance... | Reset all associated values and clean up dictionary items | [
"Reset",
"all",
"associated",
"values",
"and",
"clean",
"up",
"dictionary",
"items"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/field/association.py#L41-L47 | train | 47,109 |
proteanhq/protean | src/protean/core/field/association.py | Reference.to_cls | def to_cls(self):
"""Property to retrieve to_cls as an entity when possible"""
# Checks if ``to_cls`` is a string
# If it is, checks if the entity is imported and available
# If it is, register the class
try:
if isinstance(self._to_cls, str):
self._to_cls = fetch_entity_cls_from_registry(self._to_cls)
except AssertionError:
# Preserve ``to_cls`` as a string and we will hook up the entity later
pass
return self._to_cls | python | def to_cls(self):
"""Property to retrieve to_cls as an entity when possible"""
# Checks if ``to_cls`` is a string
# If it is, checks if the entity is imported and available
# If it is, register the class
try:
if isinstance(self._to_cls, str):
self._to_cls = fetch_entity_cls_from_registry(self._to_cls)
except AssertionError:
# Preserve ``to_cls`` as a string and we will hook up the entity later
pass
return self._to_cls | [
"def",
"to_cls",
"(",
"self",
")",
":",
"# Checks if ``to_cls`` is a string",
"# If it is, checks if the entity is imported and available",
"# If it is, register the class",
"try",
":",
"if",
"isinstance",
"(",
"self",
".",
"_to_cls",
",",
"str",
")",
":",
"self",
"."... | Property to retrieve to_cls as an entity when possible | [
"Property",
"to",
"retrieve",
"to_cls",
"as",
"an",
"entity",
"when",
"possible"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/field/association.py#L68-L80 | train | 47,110 |
proteanhq/protean | src/protean/core/field/association.py | Reference.linked_attribute | def linked_attribute(self):
"""Choose the Linkage attribute between `via` and designated `id_field` of the target class
This method is initially called from `__set_name__()` -> `get_attribute_name()`
at which point, the `to_cls` has not been initialized properly. We simply default
the linked attribute to 'id' in that case.
Eventually, when setting value the first time, the `to_cls` entity is initialized
and the attribute name is reset correctly.
"""
if isinstance(self.to_cls, str):
return 'id'
else:
return self.via or self.to_cls.meta_.id_field.attribute_name | python | def linked_attribute(self):
"""Choose the Linkage attribute between `via` and designated `id_field` of the target class
This method is initially called from `__set_name__()` -> `get_attribute_name()`
at which point, the `to_cls` has not been initialized properly. We simply default
the linked attribute to 'id' in that case.
Eventually, when setting value the first time, the `to_cls` entity is initialized
and the attribute name is reset correctly.
"""
if isinstance(self.to_cls, str):
return 'id'
else:
return self.via or self.to_cls.meta_.id_field.attribute_name | [
"def",
"linked_attribute",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"to_cls",
",",
"str",
")",
":",
"return",
"'id'",
"else",
":",
"return",
"self",
".",
"via",
"or",
"self",
".",
"to_cls",
".",
"meta_",
".",
"id_field",
".",
"att... | Choose the Linkage attribute between `via` and designated `id_field` of the target class
This method is initially called from `__set_name__()` -> `get_attribute_name()`
at which point, the `to_cls` has not been initialized properly. We simply default
the linked attribute to 'id' in that case.
Eventually, when setting value the first time, the `to_cls` entity is initialized
and the attribute name is reset correctly. | [
"Choose",
"the",
"Linkage",
"attribute",
"between",
"via",
"and",
"designated",
"id_field",
"of",
"the",
"target",
"class"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/field/association.py#L95-L108 | train | 47,111 |
proteanhq/protean | src/protean/core/field/association.py | Association._linked_attribute | def _linked_attribute(self, owner):
"""Choose the Linkage attribute between `via` and own entity's `id_field`
FIXME Explore converting this method into an attribute, and treating it
uniformly at `association` level.
"""
return self.via or (utils.inflection.underscore(owner.__name__) + '_id') | python | def _linked_attribute(self, owner):
"""Choose the Linkage attribute between `via` and own entity's `id_field`
FIXME Explore converting this method into an attribute, and treating it
uniformly at `association` level.
"""
return self.via or (utils.inflection.underscore(owner.__name__) + '_id') | [
"def",
"_linked_attribute",
"(",
"self",
",",
"owner",
")",
":",
"return",
"self",
".",
"via",
"or",
"(",
"utils",
".",
"inflection",
".",
"underscore",
"(",
"owner",
".",
"__name__",
")",
"+",
"'_id'",
")"
] | Choose the Linkage attribute between `via` and own entity's `id_field`
FIXME Explore converting this method into an attribute, and treating it
uniformly at `association` level. | [
"Choose",
"the",
"Linkage",
"attribute",
"between",
"via",
"and",
"own",
"entity",
"s",
"id_field"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/field/association.py#L211-L217 | train | 47,112 |
proteanhq/protean | src/protean/core/field/association.py | HasMany._fetch_objects | def _fetch_objects(self, key, value):
"""Fetch Multiple linked objects"""
return self.to_cls.query.filter(**{key: value}) | python | def _fetch_objects(self, key, value):
"""Fetch Multiple linked objects"""
return self.to_cls.query.filter(**{key: value}) | [
"def",
"_fetch_objects",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"return",
"self",
".",
"to_cls",
".",
"query",
".",
"filter",
"(",
"*",
"*",
"{",
"key",
":",
"value",
"}",
")"
] | Fetch Multiple linked objects | [
"Fetch",
"Multiple",
"linked",
"objects"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/field/association.py#L290-L292 | train | 47,113 |
proteanhq/protean | src/protean/core/entity.py | EntityBase._load_fields | def _load_fields(new_class, attrs):
"""Load field items into Class.
This method sets up the primary attribute of an association.
If Child class has defined an attribute so `parent = field.Reference(Parent)`, then `parent`
is set up in this method, while `parent_id` is set up in `_set_up_reference_fields()`.
"""
for attr_name, attr_obj in attrs.items():
if isinstance(attr_obj, (Field, Reference)):
setattr(new_class, attr_name, attr_obj)
new_class.meta_.declared_fields[attr_name] = attr_obj | python | def _load_fields(new_class, attrs):
"""Load field items into Class.
This method sets up the primary attribute of an association.
If Child class has defined an attribute so `parent = field.Reference(Parent)`, then `parent`
is set up in this method, while `parent_id` is set up in `_set_up_reference_fields()`.
"""
for attr_name, attr_obj in attrs.items():
if isinstance(attr_obj, (Field, Reference)):
setattr(new_class, attr_name, attr_obj)
new_class.meta_.declared_fields[attr_name] = attr_obj | [
"def",
"_load_fields",
"(",
"new_class",
",",
"attrs",
")",
":",
"for",
"attr_name",
",",
"attr_obj",
"in",
"attrs",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"attr_obj",
",",
"(",
"Field",
",",
"Reference",
")",
")",
":",
"setattr",
"(",
... | Load field items into Class.
This method sets up the primary attribute of an association.
If Child class has defined an attribute so `parent = field.Reference(Parent)`, then `parent`
is set up in this method, while `parent_id` is set up in `_set_up_reference_fields()`. | [
"Load",
"field",
"items",
"into",
"Class",
"."
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/entity.py#L99-L109 | train | 47,114 |
proteanhq/protean | src/protean/core/entity.py | EntityBase._set_up_reference_fields | def _set_up_reference_fields(new_class):
"""Walk through relation fields and setup shadow attributes"""
if new_class.meta_.declared_fields:
for _, field in new_class.meta_.declared_fields.items():
if isinstance(field, Reference):
shadow_field_name, shadow_field = field.get_shadow_field()
setattr(new_class, shadow_field_name, shadow_field)
shadow_field.__set_name__(new_class, shadow_field_name) | python | def _set_up_reference_fields(new_class):
"""Walk through relation fields and setup shadow attributes"""
if new_class.meta_.declared_fields:
for _, field in new_class.meta_.declared_fields.items():
if isinstance(field, Reference):
shadow_field_name, shadow_field = field.get_shadow_field()
setattr(new_class, shadow_field_name, shadow_field)
shadow_field.__set_name__(new_class, shadow_field_name) | [
"def",
"_set_up_reference_fields",
"(",
"new_class",
")",
":",
"if",
"new_class",
".",
"meta_",
".",
"declared_fields",
":",
"for",
"_",
",",
"field",
"in",
"new_class",
".",
"meta_",
".",
"declared_fields",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
... | Walk through relation fields and setup shadow attributes | [
"Walk",
"through",
"relation",
"fields",
"and",
"setup",
"shadow",
"attributes"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/entity.py#L111-L118 | train | 47,115 |
proteanhq/protean | src/protean/core/entity.py | EntityBase._set_id_field | def _set_id_field(new_class):
"""Lookup the id field for this entity and assign"""
# FIXME What does it mean when there are no declared fields?
# Does it translate to an abstract entity?
if new_class.meta_.declared_fields:
try:
new_class.meta_.id_field = next(
field for _, field in new_class.meta_.declared_fields.items()
if field.identifier)
except StopIteration:
# If no id field is declared then create one
new_class._create_id_field() | python | def _set_id_field(new_class):
"""Lookup the id field for this entity and assign"""
# FIXME What does it mean when there are no declared fields?
# Does it translate to an abstract entity?
if new_class.meta_.declared_fields:
try:
new_class.meta_.id_field = next(
field for _, field in new_class.meta_.declared_fields.items()
if field.identifier)
except StopIteration:
# If no id field is declared then create one
new_class._create_id_field() | [
"def",
"_set_id_field",
"(",
"new_class",
")",
":",
"# FIXME What does it mean when there are no declared fields?",
"# Does it translate to an abstract entity?",
"if",
"new_class",
".",
"meta_",
".",
"declared_fields",
":",
"try",
":",
"new_class",
".",
"meta_",
".",
"id_... | Lookup the id field for this entity and assign | [
"Lookup",
"the",
"id",
"field",
"for",
"this",
"entity",
"and",
"assign"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/entity.py#L120-L131 | train | 47,116 |
proteanhq/protean | src/protean/core/entity.py | EntityBase._create_id_field | def _create_id_field(new_class):
"""Create and return a default ID field that is Auto generated"""
id_field = Auto(identifier=True)
setattr(new_class, 'id', id_field)
id_field.__set_name__(new_class, 'id')
# Ensure ID field is updated properly in Meta attribute
new_class.meta_.declared_fields['id'] = id_field
new_class.meta_.id_field = id_field | python | def _create_id_field(new_class):
"""Create and return a default ID field that is Auto generated"""
id_field = Auto(identifier=True)
setattr(new_class, 'id', id_field)
id_field.__set_name__(new_class, 'id')
# Ensure ID field is updated properly in Meta attribute
new_class.meta_.declared_fields['id'] = id_field
new_class.meta_.id_field = id_field | [
"def",
"_create_id_field",
"(",
"new_class",
")",
":",
"id_field",
"=",
"Auto",
"(",
"identifier",
"=",
"True",
")",
"setattr",
"(",
"new_class",
",",
"'id'",
",",
"id_field",
")",
"id_field",
".",
"__set_name__",
"(",
"new_class",
",",
"'id'",
")",
"# Ens... | Create and return a default ID field that is Auto generated | [
"Create",
"and",
"return",
"a",
"default",
"ID",
"field",
"that",
"is",
"Auto",
"generated"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/entity.py#L133-L142 | train | 47,117 |
proteanhq/protean | src/protean/core/entity.py | EntityBase._load_attributes | def _load_attributes(new_class):
"""Load list of attributes from declared fields"""
for field_name, field_obj in new_class.meta_.declared_fields.items():
new_class.meta_.attributes[field_obj.get_attribute_name()] = field_obj | python | def _load_attributes(new_class):
"""Load list of attributes from declared fields"""
for field_name, field_obj in new_class.meta_.declared_fields.items():
new_class.meta_.attributes[field_obj.get_attribute_name()] = field_obj | [
"def",
"_load_attributes",
"(",
"new_class",
")",
":",
"for",
"field_name",
",",
"field_obj",
"in",
"new_class",
".",
"meta_",
".",
"declared_fields",
".",
"items",
"(",
")",
":",
"new_class",
".",
"meta_",
".",
"attributes",
"[",
"field_obj",
".",
"get_attr... | Load list of attributes from declared fields | [
"Load",
"list",
"of",
"attributes",
"from",
"declared",
"fields"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/entity.py#L144-L147 | train | 47,118 |
proteanhq/protean | src/protean/core/entity.py | EntityMeta.unique_fields | def unique_fields(self):
""" Return the unique fields for this entity """
return [(field_name, field_obj)
for field_name, field_obj in self.declared_fields.items()
if field_obj.unique] | python | def unique_fields(self):
""" Return the unique fields for this entity """
return [(field_name, field_obj)
for field_name, field_obj in self.declared_fields.items()
if field_obj.unique] | [
"def",
"unique_fields",
"(",
"self",
")",
":",
"return",
"[",
"(",
"field_name",
",",
"field_obj",
")",
"for",
"field_name",
",",
"field_obj",
"in",
"self",
".",
"declared_fields",
".",
"items",
"(",
")",
"if",
"field_obj",
".",
"unique",
"]"
] | Return the unique fields for this entity | [
"Return",
"the",
"unique",
"fields",
"for",
"this",
"entity"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/entity.py#L189-L193 | train | 47,119 |
proteanhq/protean | src/protean/core/entity.py | Entity._update_data | def _update_data(self, *data_dict, **kwargs):
"""
A private method to process and update entity values correctly.
:param data: A dictionary of values to be updated for the entity
:param kwargs: keyword arguments with key-value pairs to be updated
"""
# Load each of the fields given in the data dictionary
self.errors = {}
for data in data_dict:
if not isinstance(data, dict):
raise AssertionError(
f'Positional argument "{data}" passed must be a dict.'
f'This argument serves as a template for loading common '
f'values.'
)
for field_name, val in data.items():
setattr(self, field_name, val)
# Now load against the keyword arguments
for field_name, val in kwargs.items():
setattr(self, field_name, val)
# Raise any errors found during update
if self.errors:
raise ValidationError(self.errors) | python | def _update_data(self, *data_dict, **kwargs):
"""
A private method to process and update entity values correctly.
:param data: A dictionary of values to be updated for the entity
:param kwargs: keyword arguments with key-value pairs to be updated
"""
# Load each of the fields given in the data dictionary
self.errors = {}
for data in data_dict:
if not isinstance(data, dict):
raise AssertionError(
f'Positional argument "{data}" passed must be a dict.'
f'This argument serves as a template for loading common '
f'values.'
)
for field_name, val in data.items():
setattr(self, field_name, val)
# Now load against the keyword arguments
for field_name, val in kwargs.items():
setattr(self, field_name, val)
# Raise any errors found during update
if self.errors:
raise ValidationError(self.errors) | [
"def",
"_update_data",
"(",
"self",
",",
"*",
"data_dict",
",",
"*",
"*",
"kwargs",
")",
":",
"# Load each of the fields given in the data dictionary",
"self",
".",
"errors",
"=",
"{",
"}",
"for",
"data",
"in",
"data_dict",
":",
"if",
"not",
"isinstance",
"(",... | A private method to process and update entity values correctly.
:param data: A dictionary of values to be updated for the entity
:param kwargs: keyword arguments with key-value pairs to be updated | [
"A",
"private",
"method",
"to",
"process",
"and",
"update",
"entity",
"values",
"correctly",
"."
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/entity.py#L324-L351 | train | 47,120 |
proteanhq/protean | src/protean/core/entity.py | Entity.to_dict | def to_dict(self):
""" Return entity data as a dictionary """
return {field_name: getattr(self, field_name, None)
for field_name in self.meta_.declared_fields} | python | def to_dict(self):
""" Return entity data as a dictionary """
return {field_name: getattr(self, field_name, None)
for field_name in self.meta_.declared_fields} | [
"def",
"to_dict",
"(",
"self",
")",
":",
"return",
"{",
"field_name",
":",
"getattr",
"(",
"self",
",",
"field_name",
",",
"None",
")",
"for",
"field_name",
"in",
"self",
".",
"meta_",
".",
"declared_fields",
"}"
] | Return entity data as a dictionary | [
"Return",
"entity",
"data",
"as",
"a",
"dictionary"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/entity.py#L353-L356 | train | 47,121 |
proteanhq/protean | src/protean/core/entity.py | Entity.clone | def clone(self):
"""Deepclone the entity, but reset state"""
clone_copy = copy.deepcopy(self)
clone_copy.state_ = EntityState()
return clone_copy | python | def clone(self):
"""Deepclone the entity, but reset state"""
clone_copy = copy.deepcopy(self)
clone_copy.state_ = EntityState()
return clone_copy | [
"def",
"clone",
"(",
"self",
")",
":",
"clone_copy",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
")",
"clone_copy",
".",
"state_",
"=",
"EntityState",
"(",
")",
"return",
"clone_copy"
] | Deepclone the entity, but reset state | [
"Deepclone",
"the",
"entity",
"but",
"reset",
"state"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/entity.py#L358-L363 | train | 47,122 |
proteanhq/protean | src/protean/core/entity.py | Entity.get | def get(cls, identifier: Any) -> 'Entity':
"""Get a specific Record from the Repository
:param identifier: id of the record to be fetched from the repository.
"""
logger.debug(f'Lookup `{cls.__name__}` object with identifier {identifier}')
# Get the ID field for the entity
filters = {
cls.meta_.id_field.field_name: identifier
}
# Find this item in the repository or raise Error
results = cls.query.filter(**filters).limit(1).all()
if not results:
raise ObjectNotFoundError(
f'`{cls.__name__}` object with identifier {identifier} '
f'does not exist.')
# Return the first result
return results.first | python | def get(cls, identifier: Any) -> 'Entity':
"""Get a specific Record from the Repository
:param identifier: id of the record to be fetched from the repository.
"""
logger.debug(f'Lookup `{cls.__name__}` object with identifier {identifier}')
# Get the ID field for the entity
filters = {
cls.meta_.id_field.field_name: identifier
}
# Find this item in the repository or raise Error
results = cls.query.filter(**filters).limit(1).all()
if not results:
raise ObjectNotFoundError(
f'`{cls.__name__}` object with identifier {identifier} '
f'does not exist.')
# Return the first result
return results.first | [
"def",
"get",
"(",
"cls",
",",
"identifier",
":",
"Any",
")",
"->",
"'Entity'",
":",
"logger",
".",
"debug",
"(",
"f'Lookup `{cls.__name__}` object with identifier {identifier}'",
")",
"# Get the ID field for the entity",
"filters",
"=",
"{",
"cls",
".",
"meta_",
".... | Get a specific Record from the Repository
:param identifier: id of the record to be fetched from the repository. | [
"Get",
"a",
"specific",
"Record",
"from",
"the",
"Repository"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/entity.py#L370-L389 | train | 47,123 |
proteanhq/protean | src/protean/core/entity.py | Entity.reload | def reload(self) -> None:
"""Reload Entity from the repository"""
if not self.state_.is_persisted or self.state_.is_changed:
raise InvalidStateError(f'`{self.__class__.__name__}` object is in invalid state')
# Retrieve the entity's ID by the configured Identifier field
identifier = getattr(self, self.meta_.id_field.field_name)
logger.debug(f'Lookup `{self.__class__.__name__}` object with '
f'identifier {self.meta_.id_field}')
# Fetch the entity data from db by its identifier
db_value = self.get(identifier)
# Update own data from fetched entity data
# This allows us to ``dog.reload()`` instead of ``dog = dog.reload()``
self._update_data(db_value.to_dict()) | python | def reload(self) -> None:
"""Reload Entity from the repository"""
if not self.state_.is_persisted or self.state_.is_changed:
raise InvalidStateError(f'`{self.__class__.__name__}` object is in invalid state')
# Retrieve the entity's ID by the configured Identifier field
identifier = getattr(self, self.meta_.id_field.field_name)
logger.debug(f'Lookup `{self.__class__.__name__}` object with '
f'identifier {self.meta_.id_field}')
# Fetch the entity data from db by its identifier
db_value = self.get(identifier)
# Update own data from fetched entity data
# This allows us to ``dog.reload()`` instead of ``dog = dog.reload()``
self._update_data(db_value.to_dict()) | [
"def",
"reload",
"(",
"self",
")",
"->",
"None",
":",
"if",
"not",
"self",
".",
"state_",
".",
"is_persisted",
"or",
"self",
".",
"state_",
".",
"is_changed",
":",
"raise",
"InvalidStateError",
"(",
"f'`{self.__class__.__name__}` object is in invalid state'",
")",... | Reload Entity from the repository | [
"Reload",
"Entity",
"from",
"the",
"repository"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/entity.py#L391-L406 | train | 47,124 |
proteanhq/protean | src/protean/core/entity.py | Entity.find_by | def find_by(cls, **kwargs) -> 'Entity':
"""Find a specific entity record that matches one or more criteria.
:param kwargs: named arguments consisting of attr_name and attr_value pairs to search on
"""
logger.debug(f'Lookup `{cls.__name__}` object with values '
f'{kwargs}')
# Find this item in the repository or raise Error
results = cls.query.filter(**kwargs).limit(1).all()
if not results:
raise ObjectNotFoundError(
f'`{cls.__name__}` object with values {[item for item in kwargs.items()]} '
f'does not exist.')
# Return the first result
return results.first | python | def find_by(cls, **kwargs) -> 'Entity':
"""Find a specific entity record that matches one or more criteria.
:param kwargs: named arguments consisting of attr_name and attr_value pairs to search on
"""
logger.debug(f'Lookup `{cls.__name__}` object with values '
f'{kwargs}')
# Find this item in the repository or raise Error
results = cls.query.filter(**kwargs).limit(1).all()
if not results:
raise ObjectNotFoundError(
f'`{cls.__name__}` object with values {[item for item in kwargs.items()]} '
f'does not exist.')
# Return the first result
return results.first | [
"def",
"find_by",
"(",
"cls",
",",
"*",
"*",
"kwargs",
")",
"->",
"'Entity'",
":",
"logger",
".",
"debug",
"(",
"f'Lookup `{cls.__name__}` object with values '",
"f'{kwargs}'",
")",
"# Find this item in the repository or raise Error",
"results",
"=",
"cls",
".",
"quer... | Find a specific entity record that matches one or more criteria.
:param kwargs: named arguments consisting of attr_name and attr_value pairs to search on | [
"Find",
"a",
"specific",
"entity",
"record",
"that",
"matches",
"one",
"or",
"more",
"criteria",
"."
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/entity.py#L409-L426 | train | 47,125 |
proteanhq/protean | src/protean/core/entity.py | Entity.exists | def exists(cls, excludes_, **filters):
""" Return `True` if objects matching the provided filters and excludes
exist if not return false.
Calls the `filter` method by default, but can be overridden for better and
quicker implementations that may be supported by a database.
:param excludes_: entities without this combination of field name and
values will be returned
"""
results = cls.query.filter(**filters).exclude(**excludes_)
return bool(results) | python | def exists(cls, excludes_, **filters):
""" Return `True` if objects matching the provided filters and excludes
exist if not return false.
Calls the `filter` method by default, but can be overridden for better and
quicker implementations that may be supported by a database.
:param excludes_: entities without this combination of field name and
values will be returned
"""
results = cls.query.filter(**filters).exclude(**excludes_)
return bool(results) | [
"def",
"exists",
"(",
"cls",
",",
"excludes_",
",",
"*",
"*",
"filters",
")",
":",
"results",
"=",
"cls",
".",
"query",
".",
"filter",
"(",
"*",
"*",
"filters",
")",
".",
"exclude",
"(",
"*",
"*",
"excludes_",
")",
"return",
"bool",
"(",
"results",... | Return `True` if objects matching the provided filters and excludes
exist if not return false.
Calls the `filter` method by default, but can be overridden for better and
quicker implementations that may be supported by a database.
:param excludes_: entities without this combination of field name and
values will be returned | [
"Return",
"True",
"if",
"objects",
"matching",
"the",
"provided",
"filters",
"and",
"excludes",
"exist",
"if",
"not",
"return",
"false",
"."
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/entity.py#L429-L440 | train | 47,126 |
proteanhq/protean | src/protean/core/entity.py | Entity.create | def create(cls, *args, **kwargs) -> 'Entity':
"""Create a new record in the repository.
Also performs unique validations before creating the entity
:param args: positional arguments for the entity
:param kwargs: keyword arguments for the entity
"""
logger.debug(
f'Creating new `{cls.__name__}` object using data {kwargs}')
model_cls = repo_factory.get_model(cls)
repository = repo_factory.get_repository(cls)
try:
# Build the entity from the input arguments
# Raises validation errors, if any, at this point
entity = cls(*args, **kwargs)
# Do unique checks, create this object and return it
entity._validate_unique()
# Perform Pre-Save Actions
entity.pre_save()
# Build the model object and create it
model_obj = repository.create(model_cls.from_entity(entity))
# Update the auto fields of the entity
for field_name, field_obj in entity.meta_.declared_fields.items():
if isinstance(field_obj, Auto):
if isinstance(model_obj, dict):
field_val = model_obj[field_name]
else:
field_val = getattr(model_obj, field_name)
setattr(entity, field_name, field_val)
# Set Entity status to saved
entity.state_.mark_saved()
# Perform Post-Save Actions
entity.post_save()
return entity
except ValidationError:
# FIXME Log Exception
raise | python | def create(cls, *args, **kwargs) -> 'Entity':
"""Create a new record in the repository.
Also performs unique validations before creating the entity
:param args: positional arguments for the entity
:param kwargs: keyword arguments for the entity
"""
logger.debug(
f'Creating new `{cls.__name__}` object using data {kwargs}')
model_cls = repo_factory.get_model(cls)
repository = repo_factory.get_repository(cls)
try:
# Build the entity from the input arguments
# Raises validation errors, if any, at this point
entity = cls(*args, **kwargs)
# Do unique checks, create this object and return it
entity._validate_unique()
# Perform Pre-Save Actions
entity.pre_save()
# Build the model object and create it
model_obj = repository.create(model_cls.from_entity(entity))
# Update the auto fields of the entity
for field_name, field_obj in entity.meta_.declared_fields.items():
if isinstance(field_obj, Auto):
if isinstance(model_obj, dict):
field_val = model_obj[field_name]
else:
field_val = getattr(model_obj, field_name)
setattr(entity, field_name, field_val)
# Set Entity status to saved
entity.state_.mark_saved()
# Perform Post-Save Actions
entity.post_save()
return entity
except ValidationError:
# FIXME Log Exception
raise | [
"def",
"create",
"(",
"cls",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"->",
"'Entity'",
":",
"logger",
".",
"debug",
"(",
"f'Creating new `{cls.__name__}` object using data {kwargs}'",
")",
"model_cls",
"=",
"repo_factory",
".",
"get_model",
"(",
"cls",
... | Create a new record in the repository.
Also performs unique validations before creating the entity
:param args: positional arguments for the entity
:param kwargs: keyword arguments for the entity | [
"Create",
"a",
"new",
"record",
"in",
"the",
"repository",
"."
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/entity.py#L443-L489 | train | 47,127 |
proteanhq/protean | src/protean/core/entity.py | Entity.save | def save(self):
"""Save a new Entity into repository.
Performs unique validations before creating the entity.
"""
logger.debug(
f'Saving `{self.__class__.__name__}` object')
# Fetch Model class and connected repository from Repository Factory
model_cls = repo_factory.get_model(self.__class__)
repository = repo_factory.get_repository(self.__class__)
try:
# Do unique checks, update the record and return the Entity
self._validate_unique(create=False)
# Perform Pre-Save Actions
self.pre_save()
# Build the model object and create it
model_obj = repository.create(model_cls.from_entity(self))
# Update the auto fields of the entity
for field_name, field_obj in self.meta_.declared_fields.items():
if isinstance(field_obj, Auto):
if isinstance(model_obj, dict):
field_val = model_obj[field_name]
else:
field_val = getattr(model_obj, field_name)
setattr(self, field_name, field_val)
# Set Entity status to saved
self.state_.mark_saved()
# Perform Post-Save Actions
self.post_save()
return self
except Exception:
# FIXME Log Exception
raise | python | def save(self):
"""Save a new Entity into repository.
Performs unique validations before creating the entity.
"""
logger.debug(
f'Saving `{self.__class__.__name__}` object')
# Fetch Model class and connected repository from Repository Factory
model_cls = repo_factory.get_model(self.__class__)
repository = repo_factory.get_repository(self.__class__)
try:
# Do unique checks, update the record and return the Entity
self._validate_unique(create=False)
# Perform Pre-Save Actions
self.pre_save()
# Build the model object and create it
model_obj = repository.create(model_cls.from_entity(self))
# Update the auto fields of the entity
for field_name, field_obj in self.meta_.declared_fields.items():
if isinstance(field_obj, Auto):
if isinstance(model_obj, dict):
field_val = model_obj[field_name]
else:
field_val = getattr(model_obj, field_name)
setattr(self, field_name, field_val)
# Set Entity status to saved
self.state_.mark_saved()
# Perform Post-Save Actions
self.post_save()
return self
except Exception:
# FIXME Log Exception
raise | [
"def",
"save",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"f'Saving `{self.__class__.__name__}` object'",
")",
"# Fetch Model class and connected repository from Repository Factory",
"model_cls",
"=",
"repo_factory",
".",
"get_model",
"(",
"self",
".",
"__class__",... | Save a new Entity into repository.
Performs unique validations before creating the entity. | [
"Save",
"a",
"new",
"Entity",
"into",
"repository",
"."
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/entity.py#L491-L531 | train | 47,128 |
proteanhq/protean | src/protean/core/entity.py | Entity.update | def update(self, *data, **kwargs) -> 'Entity':
"""Update a Record in the repository.
Also performs unique validations before creating the entity.
Supports both dictionary and keyword argument updates to the entity::
dog.update({'age': 10})
dog.update(age=10)
:param data: Dictionary of values to be updated for the entity
:param kwargs: keyword arguments with key-value pairs to be updated
"""
logger.debug(f'Updating existing `{self.__class__.__name__}` object with id {self.id}')
# Fetch Model class and connected repository from Repository Factory
model_cls = repo_factory.get_model(self.__class__)
repository = repo_factory.get_repository(self.__class__)
try:
# Update entity's data attributes
self._update_data(*data, **kwargs)
# Do unique checks, update the record and return the Entity
self._validate_unique(create=False)
# Perform Pre-Save Actions
self.pre_save()
repository.update(model_cls.from_entity(self))
# Set Entity status to saved
self.state_.mark_saved()
# Perform Post-Save Actions
self.post_save()
return self
except Exception:
# FIXME Log Exception
raise | python | def update(self, *data, **kwargs) -> 'Entity':
"""Update a Record in the repository.
Also performs unique validations before creating the entity.
Supports both dictionary and keyword argument updates to the entity::
dog.update({'age': 10})
dog.update(age=10)
:param data: Dictionary of values to be updated for the entity
:param kwargs: keyword arguments with key-value pairs to be updated
"""
logger.debug(f'Updating existing `{self.__class__.__name__}` object with id {self.id}')
# Fetch Model class and connected repository from Repository Factory
model_cls = repo_factory.get_model(self.__class__)
repository = repo_factory.get_repository(self.__class__)
try:
# Update entity's data attributes
self._update_data(*data, **kwargs)
# Do unique checks, update the record and return the Entity
self._validate_unique(create=False)
# Perform Pre-Save Actions
self.pre_save()
repository.update(model_cls.from_entity(self))
# Set Entity status to saved
self.state_.mark_saved()
# Perform Post-Save Actions
self.post_save()
return self
except Exception:
# FIXME Log Exception
raise | [
"def",
"update",
"(",
"self",
",",
"*",
"data",
",",
"*",
"*",
"kwargs",
")",
"->",
"'Entity'",
":",
"logger",
".",
"debug",
"(",
"f'Updating existing `{self.__class__.__name__}` object with id {self.id}'",
")",
"# Fetch Model class and connected repository from Repository ... | Update a Record in the repository.
Also performs unique validations before creating the entity.
Supports both dictionary and keyword argument updates to the entity::
dog.update({'age': 10})
dog.update(age=10)
:param data: Dictionary of values to be updated for the entity
:param kwargs: keyword arguments with key-value pairs to be updated | [
"Update",
"a",
"Record",
"in",
"the",
"repository",
"."
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/entity.py#L533-L574 | train | 47,129 |
proteanhq/protean | src/protean/core/entity.py | Entity._validate_unique | def _validate_unique(self, create=True):
""" Validate the unique constraints for the entity """
# Build the filters from the unique constraints
filters, excludes = {}, {}
for field_name, field_obj in self.meta_.unique_fields:
lookup_value = getattr(self, field_name, None)
# Ignore empty lookup values
if lookup_value in Field.empty_values:
continue
# Ignore identifiers on updates
if not create and field_obj.identifier:
excludes[field_name] = lookup_value
continue
filters[field_name] = lookup_value
# Lookup the objects by the filters and raise error on results
for filter_key, lookup_value in filters.items():
if self.exists(excludes, **{filter_key: lookup_value}):
field_obj = self.meta_.declared_fields[filter_key]
field_obj.fail('unique',
entity_name=self.__class__.__name__,
field_name=filter_key) | python | def _validate_unique(self, create=True):
""" Validate the unique constraints for the entity """
# Build the filters from the unique constraints
filters, excludes = {}, {}
for field_name, field_obj in self.meta_.unique_fields:
lookup_value = getattr(self, field_name, None)
# Ignore empty lookup values
if lookup_value in Field.empty_values:
continue
# Ignore identifiers on updates
if not create and field_obj.identifier:
excludes[field_name] = lookup_value
continue
filters[field_name] = lookup_value
# Lookup the objects by the filters and raise error on results
for filter_key, lookup_value in filters.items():
if self.exists(excludes, **{filter_key: lookup_value}):
field_obj = self.meta_.declared_fields[filter_key]
field_obj.fail('unique',
entity_name=self.__class__.__name__,
field_name=filter_key) | [
"def",
"_validate_unique",
"(",
"self",
",",
"create",
"=",
"True",
")",
":",
"# Build the filters from the unique constraints",
"filters",
",",
"excludes",
"=",
"{",
"}",
",",
"{",
"}",
"for",
"field_name",
",",
"field_obj",
"in",
"self",
".",
"meta_",
".",
... | Validate the unique constraints for the entity | [
"Validate",
"the",
"unique",
"constraints",
"for",
"the",
"entity"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/entity.py#L576-L598 | train | 47,130 |
proteanhq/protean | src/protean/core/entity.py | Entity.delete | def delete(self):
"""Delete a Record from the Repository
will perform callbacks and run validations before deletion.
Throws ObjectNotFoundError if the object was not found in the repository.
"""
# Fetch Model class and connected repository from Repository Factory
model_cls = repo_factory.get_model(self.__class__)
repository = repo_factory.get_repository(self.__class__)
try:
if not self.state_.is_destroyed:
# Update entity's data attributes
repository.delete(model_cls.from_entity(self))
# Set Entity status to saved
self.state_.mark_destroyed()
return self
except Exception:
# FIXME Log Exception
raise | python | def delete(self):
"""Delete a Record from the Repository
will perform callbacks and run validations before deletion.
Throws ObjectNotFoundError if the object was not found in the repository.
"""
# Fetch Model class and connected repository from Repository Factory
model_cls = repo_factory.get_model(self.__class__)
repository = repo_factory.get_repository(self.__class__)
try:
if not self.state_.is_destroyed:
# Update entity's data attributes
repository.delete(model_cls.from_entity(self))
# Set Entity status to saved
self.state_.mark_destroyed()
return self
except Exception:
# FIXME Log Exception
raise | [
"def",
"delete",
"(",
"self",
")",
":",
"# Fetch Model class and connected repository from Repository Factory",
"model_cls",
"=",
"repo_factory",
".",
"get_model",
"(",
"self",
".",
"__class__",
")",
"repository",
"=",
"repo_factory",
".",
"get_repository",
"(",
"self",... | Delete a Record from the Repository
will perform callbacks and run validations before deletion.
Throws ObjectNotFoundError if the object was not found in the repository. | [
"Delete",
"a",
"Record",
"from",
"the",
"Repository"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/entity.py#L600-L622 | train | 47,131 |
proteanhq/protean | src/protean/services/email/message.py | EmailMessage.message | def message(self):
""" Convert the message to a mime compliant email string """
return '\n'.join(
[self.from_email, str(self.to), self.subject, self.body]) | python | def message(self):
""" Convert the message to a mime compliant email string """
return '\n'.join(
[self.from_email, str(self.to), self.subject, self.body]) | [
"def",
"message",
"(",
"self",
")",
":",
"return",
"'\\n'",
".",
"join",
"(",
"[",
"self",
".",
"from_email",
",",
"str",
"(",
"self",
".",
"to",
")",
",",
"self",
".",
"subject",
",",
"self",
".",
"body",
"]",
")"
] | Convert the message to a mime compliant email string | [
"Convert",
"the",
"message",
"to",
"a",
"mime",
"compliant",
"email",
"string"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/services/email/message.py#L44-L47 | train | 47,132 |
proteanhq/protean | src/protean/services/email/message.py | EmailMessage.get_connection | def get_connection(self, fail_silently=False):
"""Retrieve connection to send email"""
from protean.services.email import get_connection
if not self.connection:
self.connection = get_connection(fail_silently=fail_silently)
return self.connection | python | def get_connection(self, fail_silently=False):
"""Retrieve connection to send email"""
from protean.services.email import get_connection
if not self.connection:
self.connection = get_connection(fail_silently=fail_silently)
return self.connection | [
"def",
"get_connection",
"(",
"self",
",",
"fail_silently",
"=",
"False",
")",
":",
"from",
"protean",
".",
"services",
".",
"email",
"import",
"get_connection",
"if",
"not",
"self",
".",
"connection",
":",
"self",
".",
"connection",
"=",
"get_connection",
"... | Retrieve connection to send email | [
"Retrieve",
"connection",
"to",
"send",
"email"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/services/email/message.py#L56-L63 | train | 47,133 |
wasp/waspy | waspy/router.py | Router.prefix | def prefix(self, prefix):
"""
Adds a prefix to routes contained within.
"""
original_prefix = self._prefix
self._prefix += prefix
yield self
self._prefix = original_prefix | python | def prefix(self, prefix):
"""
Adds a prefix to routes contained within.
"""
original_prefix = self._prefix
self._prefix += prefix
yield self
self._prefix = original_prefix | [
"def",
"prefix",
"(",
"self",
",",
"prefix",
")",
":",
"original_prefix",
"=",
"self",
".",
"_prefix",
"self",
".",
"_prefix",
"+=",
"prefix",
"yield",
"self",
"self",
".",
"_prefix",
"=",
"original_prefix"
] | Adds a prefix to routes contained within. | [
"Adds",
"a",
"prefix",
"to",
"routes",
"contained",
"within",
"."
] | 31cc352f300a089f9607d7f13d93591d4c69d5ec | https://github.com/wasp/waspy/blob/31cc352f300a089f9607d7f13d93591d4c69d5ec/waspy/router.py#L239-L246 | train | 47,134 |
proteanhq/protean | src/protean/core/exceptions.py | ValidationError.normalized_messages | def normalized_messages(self, no_field_name='_entity'):
"""Return all the error messages as a dictionary"""
if isinstance(self.messages, dict):
return self.messages
if not self.field_names:
return {no_field_name: self.messages}
return dict((name, self.messages) for name in self.field_names) | python | def normalized_messages(self, no_field_name='_entity'):
"""Return all the error messages as a dictionary"""
if isinstance(self.messages, dict):
return self.messages
if not self.field_names:
return {no_field_name: self.messages}
return dict((name, self.messages) for name in self.field_names) | [
"def",
"normalized_messages",
"(",
"self",
",",
"no_field_name",
"=",
"'_entity'",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"messages",
",",
"dict",
")",
":",
"return",
"self",
".",
"messages",
"if",
"not",
"self",
".",
"field_names",
":",
"return",... | Return all the error messages as a dictionary | [
"Return",
"all",
"the",
"error",
"messages",
"as",
"a",
"dictionary"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/exceptions.py#L52-L59 | train | 47,135 |
deep-compute/deeputil | deeputil/misc.py | generate_random_string | def generate_random_string(length=6):
'''
Returns a random string of a specified length.
>>> len(generate_random_string(length=25))
25
Test randomness. Try N times and observe no duplicaton
>>> N = 100
>>> len(set(generate_random_string(10) for i in range(N))) == N
True
'''
n = int(length / 2 + 1)
x = binascii.hexlify(os.urandom(n))
s = x[:length]
return s.decode('utf-8') | python | def generate_random_string(length=6):
'''
Returns a random string of a specified length.
>>> len(generate_random_string(length=25))
25
Test randomness. Try N times and observe no duplicaton
>>> N = 100
>>> len(set(generate_random_string(10) for i in range(N))) == N
True
'''
n = int(length / 2 + 1)
x = binascii.hexlify(os.urandom(n))
s = x[:length]
return s.decode('utf-8') | [
"def",
"generate_random_string",
"(",
"length",
"=",
"6",
")",
":",
"n",
"=",
"int",
"(",
"length",
"/",
"2",
"+",
"1",
")",
"x",
"=",
"binascii",
".",
"hexlify",
"(",
"os",
".",
"urandom",
"(",
"n",
")",
")",
"s",
"=",
"x",
"[",
":",
"length",... | Returns a random string of a specified length.
>>> len(generate_random_string(length=25))
25
Test randomness. Try N times and observe no duplicaton
>>> N = 100
>>> len(set(generate_random_string(10) for i in range(N))) == N
True | [
"Returns",
"a",
"random",
"string",
"of",
"a",
"specified",
"length",
"."
] | 9af5702bc3fd990688bf2aed16c20fa104be66df | https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/misc.py#L16-L31 | train | 47,136 |
deep-compute/deeputil | deeputil/misc.py | get_datetime | def get_datetime(epoch):
'''
get datetime from an epoch timestamp
>>> get_datetime(1432188772)
datetime.datetime(2015, 5, 21, 6, 12, 52)
'''
t = time.gmtime(epoch)
dt = datetime.datetime(*t[:6])
return dt | python | def get_datetime(epoch):
'''
get datetime from an epoch timestamp
>>> get_datetime(1432188772)
datetime.datetime(2015, 5, 21, 6, 12, 52)
'''
t = time.gmtime(epoch)
dt = datetime.datetime(*t[:6])
return dt | [
"def",
"get_datetime",
"(",
"epoch",
")",
":",
"t",
"=",
"time",
".",
"gmtime",
"(",
"epoch",
")",
"dt",
"=",
"datetime",
".",
"datetime",
"(",
"*",
"t",
"[",
":",
"6",
"]",
")",
"return",
"dt"
] | get datetime from an epoch timestamp
>>> get_datetime(1432188772)
datetime.datetime(2015, 5, 21, 6, 12, 52) | [
"get",
"datetime",
"from",
"an",
"epoch",
"timestamp"
] | 9af5702bc3fd990688bf2aed16c20fa104be66df | https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/misc.py#L48-L59 | train | 47,137 |
deep-compute/deeputil | deeputil/misc.py | xcode | def xcode(text, encoding='utf8', mode='ignore'):
'''
Converts unicode encoding to str
>>> xcode(b'hello')
b'hello'
>>> xcode('hello')
b'hello'
'''
return text.encode(encoding, mode) if isinstance(text, str) else text | python | def xcode(text, encoding='utf8', mode='ignore'):
'''
Converts unicode encoding to str
>>> xcode(b'hello')
b'hello'
>>> xcode('hello')
b'hello'
'''
return text.encode(encoding, mode) if isinstance(text, str) else text | [
"def",
"xcode",
"(",
"text",
",",
"encoding",
"=",
"'utf8'",
",",
"mode",
"=",
"'ignore'",
")",
":",
"return",
"text",
".",
"encode",
"(",
"encoding",
",",
"mode",
")",
"if",
"isinstance",
"(",
"text",
",",
"str",
")",
"else",
"text"
] | Converts unicode encoding to str
>>> xcode(b'hello')
b'hello'
>>> xcode('hello')
b'hello' | [
"Converts",
"unicode",
"encoding",
"to",
"str"
] | 9af5702bc3fd990688bf2aed16c20fa104be66df | https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/misc.py#L93-L102 | train | 47,138 |
deep-compute/deeputil | deeputil/misc.py | flatten_dict | def flatten_dict(d,
parent_key='', sep='.',
ignore_under_prefixed=True,
mark_value=True):
'''
Flattens a nested dictionary
>>> from pprint import pprint
>>> d = {"a": {"b": {"c": 1, "b": 2, "__d": 'ignore', "_e": "mark"} } }
>>> fd = flatten_dict(d)
>>> pprint(fd)
{'a.b._e': "'mark'", 'a.b.b': 2, 'a.b.c': 1}
'''
items = {}
for k in d:
if ignore_under_prefixed and k.startswith('__'): continue
v = d[k]
if mark_value and k.startswith('_') and not k.startswith('__'):
v = MarkValue(repr(v))
new_key = sep.join((parent_key, k)) if parent_key else k
if isinstance(v, collections.MutableMapping):
items.update(flatten_dict(v, new_key, sep=sep,
ignore_under_prefixed=True,
mark_value=True)
)
else:
items[new_key] = v
return items | python | def flatten_dict(d,
parent_key='', sep='.',
ignore_under_prefixed=True,
mark_value=True):
'''
Flattens a nested dictionary
>>> from pprint import pprint
>>> d = {"a": {"b": {"c": 1, "b": 2, "__d": 'ignore', "_e": "mark"} } }
>>> fd = flatten_dict(d)
>>> pprint(fd)
{'a.b._e': "'mark'", 'a.b.b': 2, 'a.b.c': 1}
'''
items = {}
for k in d:
if ignore_under_prefixed and k.startswith('__'): continue
v = d[k]
if mark_value and k.startswith('_') and not k.startswith('__'):
v = MarkValue(repr(v))
new_key = sep.join((parent_key, k)) if parent_key else k
if isinstance(v, collections.MutableMapping):
items.update(flatten_dict(v, new_key, sep=sep,
ignore_under_prefixed=True,
mark_value=True)
)
else:
items[new_key] = v
return items | [
"def",
"flatten_dict",
"(",
"d",
",",
"parent_key",
"=",
"''",
",",
"sep",
"=",
"'.'",
",",
"ignore_under_prefixed",
"=",
"True",
",",
"mark_value",
"=",
"True",
")",
":",
"items",
"=",
"{",
"}",
"for",
"k",
"in",
"d",
":",
"if",
"ignore_under_prefixed... | Flattens a nested dictionary
>>> from pprint import pprint
>>> d = {"a": {"b": {"c": 1, "b": 2, "__d": 'ignore', "_e": "mark"} } }
>>> fd = flatten_dict(d)
>>> pprint(fd)
{'a.b._e': "'mark'", 'a.b.b': 2, 'a.b.c': 1} | [
"Flattens",
"a",
"nested",
"dictionary"
] | 9af5702bc3fd990688bf2aed16c20fa104be66df | https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/misc.py#L192-L221 | train | 47,139 |
deep-compute/deeputil | deeputil/misc.py | set_file_limits | def set_file_limits(n):
'''
Set the limit on number of file descriptors
that this process can open.
'''
try:
resource.setrlimit(resource.RLIMIT_NOFILE, (n, n))
return True
except ValueError:
return False | python | def set_file_limits(n):
'''
Set the limit on number of file descriptors
that this process can open.
'''
try:
resource.setrlimit(resource.RLIMIT_NOFILE, (n, n))
return True
except ValueError:
return False | [
"def",
"set_file_limits",
"(",
"n",
")",
":",
"try",
":",
"resource",
".",
"setrlimit",
"(",
"resource",
".",
"RLIMIT_NOFILE",
",",
"(",
"n",
",",
"n",
")",
")",
"return",
"True",
"except",
"ValueError",
":",
"return",
"False"
] | Set the limit on number of file descriptors
that this process can open. | [
"Set",
"the",
"limit",
"on",
"number",
"of",
"file",
"descriptors",
"that",
"this",
"process",
"can",
"open",
"."
] | 9af5702bc3fd990688bf2aed16c20fa104be66df | https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/misc.py#L473-L484 | train | 47,140 |
deep-compute/deeputil | deeputil/misc.py | load_object | def load_object(imp_path):
'''
Given a python import path, load the object
For dynamic imports in a program
>>> isdir = load_object('os.path.isdir')
>>> isdir('/tmp')
True
>>> num = load_object('numbers.Number')
>>> isinstance('x', num)
False
>>> isinstance(777, num)
True
'''
module_name, obj_name = imp_path.split('.', 1)
module = __import__(module_name)
obj = attrgetter(obj_name)(module)
return obj | python | def load_object(imp_path):
'''
Given a python import path, load the object
For dynamic imports in a program
>>> isdir = load_object('os.path.isdir')
>>> isdir('/tmp')
True
>>> num = load_object('numbers.Number')
>>> isinstance('x', num)
False
>>> isinstance(777, num)
True
'''
module_name, obj_name = imp_path.split('.', 1)
module = __import__(module_name)
obj = attrgetter(obj_name)(module)
return obj | [
"def",
"load_object",
"(",
"imp_path",
")",
":",
"module_name",
",",
"obj_name",
"=",
"imp_path",
".",
"split",
"(",
"'.'",
",",
"1",
")",
"module",
"=",
"__import__",
"(",
"module_name",
")",
"obj",
"=",
"attrgetter",
"(",
"obj_name",
")",
"(",
"module"... | Given a python import path, load the object
For dynamic imports in a program
>>> isdir = load_object('os.path.isdir')
>>> isdir('/tmp')
True
>>> num = load_object('numbers.Number')
>>> isinstance('x', num)
False
>>> isinstance(777, num)
True | [
"Given",
"a",
"python",
"import",
"path",
"load",
"the",
"object",
"For",
"dynamic",
"imports",
"in",
"a",
"program"
] | 9af5702bc3fd990688bf2aed16c20fa104be66df | https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/misc.py#L592-L611 | train | 47,141 |
proteanhq/protean | src/protean/core/field/base.py | Field.fail | def fail(self, key, **kwargs):
"""A helper method that simply raises a `ValidationError`.
"""
try:
msg = self.error_messages[key]
except KeyError:
class_name = self.__class__.__name__
msg = MISSING_ERROR_MESSAGE.format(class_name=class_name,
key=key)
raise AssertionError(msg)
if isinstance(msg, str):
msg = msg.format(**kwargs)
raise exceptions.ValidationError(msg, self.field_name) | python | def fail(self, key, **kwargs):
"""A helper method that simply raises a `ValidationError`.
"""
try:
msg = self.error_messages[key]
except KeyError:
class_name = self.__class__.__name__
msg = MISSING_ERROR_MESSAGE.format(class_name=class_name,
key=key)
raise AssertionError(msg)
if isinstance(msg, str):
msg = msg.format(**kwargs)
raise exceptions.ValidationError(msg, self.field_name) | [
"def",
"fail",
"(",
"self",
",",
"key",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"msg",
"=",
"self",
".",
"error_messages",
"[",
"key",
"]",
"except",
"KeyError",
":",
"class_name",
"=",
"self",
".",
"__class__",
".",
"__name__",
"msg",
"=",
... | A helper method that simply raises a `ValidationError`. | [
"A",
"helper",
"method",
"that",
"simply",
"raises",
"a",
"ValidationError",
"."
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/field/base.py#L118-L130 | train | 47,142 |
proteanhq/protean | src/protean/core/field/base.py | Field._load | def _load(self, value: Any):
"""
Load the value for the field, run validators and return the value.
Subclasses can override this to provide custom load logic.
:param value: value of the field
"""
if value in self.empty_values:
# If a default has been set for the field return it
if self.default is not None:
default = self.default
value = default() if callable(default) else default
return value
# If no default is set and this field is required
elif self.required:
self.fail('required')
# In all other cases just return `None` as we do not want to
# run validations against an empty value
else:
return None
# If choices exist then validate that value is be one of the choices
if self.choices:
value_list = value
if not isinstance(value, (list, tuple)):
value_list = [value]
for v in value_list:
if v not in self.choice_dict:
self.fail(
'invalid_choice', value=v,
choices=list(self.choice_dict))
# Cast and Validate the value for this Field
value = self._cast_to_type(value)
# Call the rest of the validators defined for this Field
self._run_validators(value)
return value | python | def _load(self, value: Any):
"""
Load the value for the field, run validators and return the value.
Subclasses can override this to provide custom load logic.
:param value: value of the field
"""
if value in self.empty_values:
# If a default has been set for the field return it
if self.default is not None:
default = self.default
value = default() if callable(default) else default
return value
# If no default is set and this field is required
elif self.required:
self.fail('required')
# In all other cases just return `None` as we do not want to
# run validations against an empty value
else:
return None
# If choices exist then validate that value is be one of the choices
if self.choices:
value_list = value
if not isinstance(value, (list, tuple)):
value_list = [value]
for v in value_list:
if v not in self.choice_dict:
self.fail(
'invalid_choice', value=v,
choices=list(self.choice_dict))
# Cast and Validate the value for this Field
value = self._cast_to_type(value)
# Call the rest of the validators defined for this Field
self._run_validators(value)
return value | [
"def",
"_load",
"(",
"self",
",",
"value",
":",
"Any",
")",
":",
"if",
"value",
"in",
"self",
".",
"empty_values",
":",
"# If a default has been set for the field return it",
"if",
"self",
".",
"default",
"is",
"not",
"None",
":",
"default",
"=",
"self",
"."... | Load the value for the field, run validators and return the value.
Subclasses can override this to provide custom load logic.
:param value: value of the field | [
"Load",
"the",
"value",
"for",
"the",
"field",
"run",
"validators",
"and",
"return",
"the",
"value",
".",
"Subclasses",
"can",
"override",
"this",
"to",
"provide",
"custom",
"load",
"logic",
"."
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/field/base.py#L169-L211 | train | 47,143 |
proteanhq/protean | src/protean/core/provider/base.py | BaseProvider._extract_lookup | def _extract_lookup(self, key):
"""Extract lookup method based on key name format"""
parts = key.split('__')
# 'exact' is the default lookup if there was no explicit comparison op in `key`
# Assume there is only one `__` in the key.
# FIXME Change for child attribute query support
op = 'exact' if len(parts) == 1 else parts[1]
# Construct and assign the lookup class as a filter criteria
return parts[0], self.get_lookup(op) | python | def _extract_lookup(self, key):
"""Extract lookup method based on key name format"""
parts = key.split('__')
# 'exact' is the default lookup if there was no explicit comparison op in `key`
# Assume there is only one `__` in the key.
# FIXME Change for child attribute query support
op = 'exact' if len(parts) == 1 else parts[1]
# Construct and assign the lookup class as a filter criteria
return parts[0], self.get_lookup(op) | [
"def",
"_extract_lookup",
"(",
"self",
",",
"key",
")",
":",
"parts",
"=",
"key",
".",
"split",
"(",
"'__'",
")",
"# 'exact' is the default lookup if there was no explicit comparison op in `key`",
"# Assume there is only one `__` in the key.",
"# FIXME Change for child attrib... | Extract lookup method based on key name format | [
"Extract",
"lookup",
"method",
"based",
"on",
"key",
"name",
"format"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/provider/base.py#L21-L30 | train | 47,144 |
tadashi-aikawa/jumeaux | jumeaux/addons/log2reqs/json.py | Executor.exec | def exec(self, payload: Log2ReqsAddOnPayload) -> TList[Request]:
"""Transform from json to Request
Exception:
ValueError: If path does not exist.
"""
try:
return Request.from_jsonf_to_list(payload.file, encoding=self.config.encoding)
except TypeError as e:
raise ValueError(e) | python | def exec(self, payload: Log2ReqsAddOnPayload) -> TList[Request]:
"""Transform from json to Request
Exception:
ValueError: If path does not exist.
"""
try:
return Request.from_jsonf_to_list(payload.file, encoding=self.config.encoding)
except TypeError as e:
raise ValueError(e) | [
"def",
"exec",
"(",
"self",
",",
"payload",
":",
"Log2ReqsAddOnPayload",
")",
"->",
"TList",
"[",
"Request",
"]",
":",
"try",
":",
"return",
"Request",
".",
"from_jsonf_to_list",
"(",
"payload",
".",
"file",
",",
"encoding",
"=",
"self",
".",
"config",
"... | Transform from json to Request
Exception:
ValueError: If path does not exist. | [
"Transform",
"from",
"json",
"to",
"Request"
] | 23389bde3e9b27b3a646d99289f8b5ced411f6f0 | https://github.com/tadashi-aikawa/jumeaux/blob/23389bde3e9b27b3a646d99289f8b5ced411f6f0/jumeaux/addons/log2reqs/json.py#L18-L27 | train | 47,145 |
proteanhq/protean | src/protean/core/cache/base.py | BaseCache.get_backend_expiry | def get_backend_expiry(self, expiry=DEFAULT_EXPIRY):
"""
Return the expiry value usable by this backend based upon the provided
timeout.
"""
if expiry == DEFAULT_EXPIRY:
expiry = self.default_expiry
elif expiry == 0:
# avoid time.time() related precision issues
expiry = -1
return None if expiry is None else time.time() + expiry | python | def get_backend_expiry(self, expiry=DEFAULT_EXPIRY):
"""
Return the expiry value usable by this backend based upon the provided
timeout.
"""
if expiry == DEFAULT_EXPIRY:
expiry = self.default_expiry
elif expiry == 0:
# avoid time.time() related precision issues
expiry = -1
return None if expiry is None else time.time() + expiry | [
"def",
"get_backend_expiry",
"(",
"self",
",",
"expiry",
"=",
"DEFAULT_EXPIRY",
")",
":",
"if",
"expiry",
"==",
"DEFAULT_EXPIRY",
":",
"expiry",
"=",
"self",
".",
"default_expiry",
"elif",
"expiry",
"==",
"0",
":",
"# avoid time.time() related precision issues",
"... | Return the expiry value usable by this backend based upon the provided
timeout. | [
"Return",
"the",
"expiry",
"value",
"usable",
"by",
"this",
"backend",
"based",
"upon",
"the",
"provided",
"timeout",
"."
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/cache/base.py#L21-L31 | train | 47,146 |
proteanhq/protean | src/protean/core/cache/base.py | BaseCache.incr | def incr(self, key, delta=1):
"""
Add delta to value in the cache. If the key does not exist, raise a
ValueError exception.
"""
value = self.get(key)
if value is None:
raise ValueError("Key '%s' not found" % key)
new_value = value + delta
self.set(key, new_value)
return new_value | python | def incr(self, key, delta=1):
"""
Add delta to value in the cache. If the key does not exist, raise a
ValueError exception.
"""
value = self.get(key)
if value is None:
raise ValueError("Key '%s' not found" % key)
new_value = value + delta
self.set(key, new_value)
return new_value | [
"def",
"incr",
"(",
"self",
",",
"key",
",",
"delta",
"=",
"1",
")",
":",
"value",
"=",
"self",
".",
"get",
"(",
"key",
")",
"if",
"value",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Key '%s' not found\"",
"%",
"key",
")",
"new_value",
"=",
... | Add delta to value in the cache. If the key does not exist, raise a
ValueError exception. | [
"Add",
"delta",
"to",
"value",
"in",
"the",
"cache",
".",
"If",
"the",
"key",
"does",
"not",
"exist",
"raise",
"a",
"ValueError",
"exception",
"."
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/cache/base.py#L103-L113 | train | 47,147 |
proteanhq/protean | src/protean/core/provider/__init__.py | Providers._initialize_providers | def _initialize_providers(self):
"""Read config file and initialize providers"""
configured_providers = active_config.DATABASES
provider_objects = {}
if not isinstance(configured_providers, dict) or configured_providers == {}:
raise ConfigurationError(
"'DATABASES' config must be a dict and at least one "
"provider must be defined")
if 'default' not in configured_providers:
raise ConfigurationError(
"You must define a 'default' provider")
for provider_name, conn_info in configured_providers.items():
provider_full_path = conn_info['PROVIDER']
provider_module, provider_class = provider_full_path.rsplit('.', maxsplit=1)
provider_cls = getattr(importlib.import_module(provider_module), provider_class)
provider_objects[provider_name] = provider_cls(conn_info)
return provider_objects | python | def _initialize_providers(self):
"""Read config file and initialize providers"""
configured_providers = active_config.DATABASES
provider_objects = {}
if not isinstance(configured_providers, dict) or configured_providers == {}:
raise ConfigurationError(
"'DATABASES' config must be a dict and at least one "
"provider must be defined")
if 'default' not in configured_providers:
raise ConfigurationError(
"You must define a 'default' provider")
for provider_name, conn_info in configured_providers.items():
provider_full_path = conn_info['PROVIDER']
provider_module, provider_class = provider_full_path.rsplit('.', maxsplit=1)
provider_cls = getattr(importlib.import_module(provider_module), provider_class)
provider_objects[provider_name] = provider_cls(conn_info)
return provider_objects | [
"def",
"_initialize_providers",
"(",
"self",
")",
":",
"configured_providers",
"=",
"active_config",
".",
"DATABASES",
"provider_objects",
"=",
"{",
"}",
"if",
"not",
"isinstance",
"(",
"configured_providers",
",",
"dict",
")",
"or",
"configured_providers",
"==",
... | Read config file and initialize providers | [
"Read",
"config",
"file",
"and",
"initialize",
"providers"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/provider/__init__.py#L14-L35 | train | 47,148 |
proteanhq/protean | src/protean/core/provider/__init__.py | Providers.get_provider | def get_provider(self, provider_name='default'):
"""Fetch provider with the name specified in Configuration file"""
try:
if self._providers is None:
self._providers = self._initialize_providers()
return self._providers[provider_name]
except KeyError:
raise AssertionError(f'No Provider registered with name {provider_name}') | python | def get_provider(self, provider_name='default'):
"""Fetch provider with the name specified in Configuration file"""
try:
if self._providers is None:
self._providers = self._initialize_providers()
return self._providers[provider_name]
except KeyError:
raise AssertionError(f'No Provider registered with name {provider_name}') | [
"def",
"get_provider",
"(",
"self",
",",
"provider_name",
"=",
"'default'",
")",
":",
"try",
":",
"if",
"self",
".",
"_providers",
"is",
"None",
":",
"self",
".",
"_providers",
"=",
"self",
".",
"_initialize_providers",
"(",
")",
"return",
"self",
".",
"... | Fetch provider with the name specified in Configuration file | [
"Fetch",
"provider",
"with",
"the",
"name",
"specified",
"in",
"Configuration",
"file"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/provider/__init__.py#L37-L44 | train | 47,149 |
proteanhq/protean | src/protean/core/provider/__init__.py | Providers.get_connection | def get_connection(self, provider_name='default'):
"""Fetch connection from Provider"""
try:
return self._providers[provider_name].get_connection()
except KeyError:
raise AssertionError(f'No Provider registered with name {provider_name}') | python | def get_connection(self, provider_name='default'):
"""Fetch connection from Provider"""
try:
return self._providers[provider_name].get_connection()
except KeyError:
raise AssertionError(f'No Provider registered with name {provider_name}') | [
"def",
"get_connection",
"(",
"self",
",",
"provider_name",
"=",
"'default'",
")",
":",
"try",
":",
"return",
"self",
".",
"_providers",
"[",
"provider_name",
"]",
".",
"get_connection",
"(",
")",
"except",
"KeyError",
":",
"raise",
"AssertionError",
"(",
"f... | Fetch connection from Provider | [
"Fetch",
"connection",
"from",
"Provider"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/provider/__init__.py#L46-L51 | train | 47,150 |
proteanhq/protean | src/protean/conf/__init__.py | Config.update_defaults | def update_defaults(self, ext_config):
""" Update the default settings for an extension from an object"""
for setting in dir(ext_config):
if setting.isupper() and not hasattr(self, setting):
setattr(self, setting, getattr(ext_config, setting)) | python | def update_defaults(self, ext_config):
""" Update the default settings for an extension from an object"""
for setting in dir(ext_config):
if setting.isupper() and not hasattr(self, setting):
setattr(self, setting, getattr(ext_config, setting)) | [
"def",
"update_defaults",
"(",
"self",
",",
"ext_config",
")",
":",
"for",
"setting",
"in",
"dir",
"(",
"ext_config",
")",
":",
"if",
"setting",
".",
"isupper",
"(",
")",
"and",
"not",
"hasattr",
"(",
"self",
",",
"setting",
")",
":",
"setattr",
"(",
... | Update the default settings for an extension from an object | [
"Update",
"the",
"default",
"settings",
"for",
"an",
"extension",
"from",
"an",
"object"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/conf/__init__.py#L59-L63 | train | 47,151 |
proteanhq/protean | src/protean/core/field/utils.py | fetch_entity_cls_from_registry | def fetch_entity_cls_from_registry(entity):
"""Util Method to fetch an Entity class from an entity's name"""
# Defensive check to ensure we only process if `to_cls` is a string
if isinstance(entity, str):
try:
return repo_factory.get_entity(entity)
except AssertionError:
# Entity has not been registered (yet)
# FIXME print a helpful debug message
raise
else:
return entity | python | def fetch_entity_cls_from_registry(entity):
"""Util Method to fetch an Entity class from an entity's name"""
# Defensive check to ensure we only process if `to_cls` is a string
if isinstance(entity, str):
try:
return repo_factory.get_entity(entity)
except AssertionError:
# Entity has not been registered (yet)
# FIXME print a helpful debug message
raise
else:
return entity | [
"def",
"fetch_entity_cls_from_registry",
"(",
"entity",
")",
":",
"# Defensive check to ensure we only process if `to_cls` is a string",
"if",
"isinstance",
"(",
"entity",
",",
"str",
")",
":",
"try",
":",
"return",
"repo_factory",
".",
"get_entity",
"(",
"entity",
")",... | Util Method to fetch an Entity class from an entity's name | [
"Util",
"Method",
"to",
"fetch",
"an",
"Entity",
"class",
"from",
"an",
"entity",
"s",
"name"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/field/utils.py#L5-L16 | train | 47,152 |
proteanhq/protean | src/protean/core/repository/factory.py | RepositoryFactory._find_entity_in_records_by_class_name | def _find_entity_in_records_by_class_name(self, entity_name):
"""Fetch by Entity Name in values"""
records = {
key: value for (key, value)
in self._registry.items()
if value.name == entity_name
}
# If more than one record was found, we are dealing with the case of
# an Entity name present in multiple places (packages or plugins). Throw an error
# and ask for a fully qualified Entity name to be specified
if len(records) > 1:
raise ConfigurationError(
f'Entity with name {entity_name} has been registered twice. '
f'Please use fully qualified Entity name to specify the exact Entity.')
elif len(records) == 1:
return next(iter(records.values()))
else:
raise AssertionError(f'No Entity registered with name {entity_name}') | python | def _find_entity_in_records_by_class_name(self, entity_name):
"""Fetch by Entity Name in values"""
records = {
key: value for (key, value)
in self._registry.items()
if value.name == entity_name
}
# If more than one record was found, we are dealing with the case of
# an Entity name present in multiple places (packages or plugins). Throw an error
# and ask for a fully qualified Entity name to be specified
if len(records) > 1:
raise ConfigurationError(
f'Entity with name {entity_name} has been registered twice. '
f'Please use fully qualified Entity name to specify the exact Entity.')
elif len(records) == 1:
return next(iter(records.values()))
else:
raise AssertionError(f'No Entity registered with name {entity_name}') | [
"def",
"_find_entity_in_records_by_class_name",
"(",
"self",
",",
"entity_name",
")",
":",
"records",
"=",
"{",
"key",
":",
"value",
"for",
"(",
"key",
",",
"value",
")",
"in",
"self",
".",
"_registry",
".",
"items",
"(",
")",
"if",
"value",
".",
"name",... | Fetch by Entity Name in values | [
"Fetch",
"by",
"Entity",
"Name",
"in",
"values"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/repository/factory.py#L66-L83 | train | 47,153 |
proteanhq/protean | src/protean/core/repository/factory.py | RepositoryFactory._get_entity_by_class | def _get_entity_by_class(self, entity_cls):
"""Fetch Entity record with Entity class details"""
entity_qualname = fully_qualified_name(entity_cls)
if entity_qualname in self._registry:
return self._registry[entity_qualname]
else:
return self._find_entity_in_records_by_class_name(entity_cls.__name__) | python | def _get_entity_by_class(self, entity_cls):
"""Fetch Entity record with Entity class details"""
entity_qualname = fully_qualified_name(entity_cls)
if entity_qualname in self._registry:
return self._registry[entity_qualname]
else:
return self._find_entity_in_records_by_class_name(entity_cls.__name__) | [
"def",
"_get_entity_by_class",
"(",
"self",
",",
"entity_cls",
")",
":",
"entity_qualname",
"=",
"fully_qualified_name",
"(",
"entity_cls",
")",
"if",
"entity_qualname",
"in",
"self",
".",
"_registry",
":",
"return",
"self",
".",
"_registry",
"[",
"entity_qualname... | Fetch Entity record with Entity class details | [
"Fetch",
"Entity",
"record",
"with",
"Entity",
"class",
"details"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/repository/factory.py#L85-L91 | train | 47,154 |
proteanhq/protean | src/protean/core/repository/factory.py | RepositoryFactory._get_entity_by_name | def _get_entity_by_name(self, entity_name):
"""Fetch Entity record with an Entity name"""
if entity_name in self._registry:
return self._registry[entity_name]
else:
return self._find_entity_in_records_by_class_name(entity_name) | python | def _get_entity_by_name(self, entity_name):
"""Fetch Entity record with an Entity name"""
if entity_name in self._registry:
return self._registry[entity_name]
else:
return self._find_entity_in_records_by_class_name(entity_name) | [
"def",
"_get_entity_by_name",
"(",
"self",
",",
"entity_name",
")",
":",
"if",
"entity_name",
"in",
"self",
".",
"_registry",
":",
"return",
"self",
".",
"_registry",
"[",
"entity_name",
"]",
"else",
":",
"return",
"self",
".",
"_find_entity_in_records_by_class_... | Fetch Entity record with an Entity name | [
"Fetch",
"Entity",
"record",
"with",
"an",
"Entity",
"name"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/repository/factory.py#L93-L98 | train | 47,155 |
proteanhq/protean | src/protean/core/repository/factory.py | RepositoryFactory._validate_entity_cls | def _validate_entity_cls(self, entity_cls):
"""Validate that Entity is a valid class"""
# Import here to avoid cyclic dependency
from protean.core.entity import Entity
if not issubclass(entity_cls, Entity):
raise AssertionError(
f'Entity {entity_cls.__name__} must be subclass of `Entity`')
if entity_cls.meta_.abstract is True:
raise NotSupportedError(
f'{entity_cls.__name__} class has been marked abstract'
f' and cannot be instantiated') | python | def _validate_entity_cls(self, entity_cls):
"""Validate that Entity is a valid class"""
# Import here to avoid cyclic dependency
from protean.core.entity import Entity
if not issubclass(entity_cls, Entity):
raise AssertionError(
f'Entity {entity_cls.__name__} must be subclass of `Entity`')
if entity_cls.meta_.abstract is True:
raise NotSupportedError(
f'{entity_cls.__name__} class has been marked abstract'
f' and cannot be instantiated') | [
"def",
"_validate_entity_cls",
"(",
"self",
",",
"entity_cls",
")",
":",
"# Import here to avoid cyclic dependency",
"from",
"protean",
".",
"core",
".",
"entity",
"import",
"Entity",
"if",
"not",
"issubclass",
"(",
"entity_cls",
",",
"Entity",
")",
":",
"raise",
... | Validate that Entity is a valid class | [
"Validate",
"that",
"Entity",
"is",
"a",
"valid",
"class"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/repository/factory.py#L100-L112 | train | 47,156 |
proteanhq/protean | src/protean/core/repository/factory.py | RepositoryFactory.get_model | def get_model(self, entity_cls):
"""Retrieve Model class connected to Entity"""
entity_record = self._get_entity_by_class(entity_cls)
model_cls = None
if entity_record.model_cls:
model_cls = entity_record.model_cls
else:
# We should ask the Provider to give a fully baked model the first time
# that has been initialized properly for this entity
provider = self.get_provider(entity_record.provider_name)
baked_model_cls = provider.get_model(entity_record.entity_cls)
# Record for future reference
new_entity_record = entity_record._replace(model_cls=baked_model_cls)
self._registry[entity_record.qualname] = new_entity_record
model_cls = baked_model_cls
return model_cls | python | def get_model(self, entity_cls):
"""Retrieve Model class connected to Entity"""
entity_record = self._get_entity_by_class(entity_cls)
model_cls = None
if entity_record.model_cls:
model_cls = entity_record.model_cls
else:
# We should ask the Provider to give a fully baked model the first time
# that has been initialized properly for this entity
provider = self.get_provider(entity_record.provider_name)
baked_model_cls = provider.get_model(entity_record.entity_cls)
# Record for future reference
new_entity_record = entity_record._replace(model_cls=baked_model_cls)
self._registry[entity_record.qualname] = new_entity_record
model_cls = baked_model_cls
return model_cls | [
"def",
"get_model",
"(",
"self",
",",
"entity_cls",
")",
":",
"entity_record",
"=",
"self",
".",
"_get_entity_by_class",
"(",
"entity_cls",
")",
"model_cls",
"=",
"None",
"if",
"entity_record",
".",
"model_cls",
":",
"model_cls",
"=",
"entity_record",
".",
"mo... | Retrieve Model class connected to Entity | [
"Retrieve",
"Model",
"class",
"connected",
"to",
"Entity"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/repository/factory.py#L114-L133 | train | 47,157 |
proteanhq/protean | src/protean/core/repository/factory.py | RepositoryFactory.get_repository | def get_repository(self, entity_cls):
"""Retrieve a Repository for the Model with a live connection"""
entity_record = self._get_entity_by_class(entity_cls)
provider = self.get_provider(entity_record.provider_name)
return provider.get_repository(entity_record.entity_cls) | python | def get_repository(self, entity_cls):
"""Retrieve a Repository for the Model with a live connection"""
entity_record = self._get_entity_by_class(entity_cls)
provider = self.get_provider(entity_record.provider_name)
return provider.get_repository(entity_record.entity_cls) | [
"def",
"get_repository",
"(",
"self",
",",
"entity_cls",
")",
":",
"entity_record",
"=",
"self",
".",
"_get_entity_by_class",
"(",
"entity_cls",
")",
"provider",
"=",
"self",
".",
"get_provider",
"(",
"entity_record",
".",
"provider_name",
")",
"return",
"provid... | Retrieve a Repository for the Model with a live connection | [
"Retrieve",
"a",
"Repository",
"for",
"the",
"Model",
"with",
"a",
"live",
"connection"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/repository/factory.py#L143-L148 | train | 47,158 |
Danielhiversen/pymill | mill/__init__.py | set_heater_values | async def set_heater_values(heater_data, heater):
"""Set heater values from heater data"""
heater.current_temp = heater_data.get('currentTemp')
heater.device_status = heater_data.get('deviceStatus')
heater.available = heater.device_status == 0
heater.name = heater_data.get('deviceName')
heater.fan_status = heater_data.get('fanStatus')
heater.is_holiday = heater_data.get('isHoliday')
# Room assigned devices don't report canChangeTemp
# in selectDevice response.
if heater.room is None:
heater.can_change_temp = heater_data.get('canChangeTemp')
# Independent devices report their target temperature via
# holidayTemp value. But isHoliday is still set to 0.
# Room assigned devices may have set "Control Device individually"
# which effectively set their isHoliday value to 1.
# In this mode they behave similar to independent devices
# reporting their target temperature also via holidayTemp.
if heater.independent_device or heater.is_holiday == 1:
heater.set_temp = heater_data.get('holidayTemp')
elif heater.room is not None:
if heater.room.current_mode == 1:
heater.set_temp = heater.room.comfort_temp
elif heater.room.current_mode == 2:
heater.set_temp = heater.room.sleep_temp
elif heater.room.current_mode == 3:
heater.set_temp = heater.room.away_temp
heater.power_status = heater_data.get('powerStatus')
heater.tibber_control = heater_data.get('tibberControl')
heater.open_window = heater_data.get('open_window',
heater_data.get('open')
)
heater.is_heating = heater_data.get('heatStatus',
heater_data.get('heaterFlag')
)
try:
heater.sub_domain = int(float(heater_data.get('subDomain',
heater_data.get('subDomainId',
heater.sub_domain)
)))
except ValueError:
pass | python | async def set_heater_values(heater_data, heater):
"""Set heater values from heater data"""
heater.current_temp = heater_data.get('currentTemp')
heater.device_status = heater_data.get('deviceStatus')
heater.available = heater.device_status == 0
heater.name = heater_data.get('deviceName')
heater.fan_status = heater_data.get('fanStatus')
heater.is_holiday = heater_data.get('isHoliday')
# Room assigned devices don't report canChangeTemp
# in selectDevice response.
if heater.room is None:
heater.can_change_temp = heater_data.get('canChangeTemp')
# Independent devices report their target temperature via
# holidayTemp value. But isHoliday is still set to 0.
# Room assigned devices may have set "Control Device individually"
# which effectively set their isHoliday value to 1.
# In this mode they behave similar to independent devices
# reporting their target temperature also via holidayTemp.
if heater.independent_device or heater.is_holiday == 1:
heater.set_temp = heater_data.get('holidayTemp')
elif heater.room is not None:
if heater.room.current_mode == 1:
heater.set_temp = heater.room.comfort_temp
elif heater.room.current_mode == 2:
heater.set_temp = heater.room.sleep_temp
elif heater.room.current_mode == 3:
heater.set_temp = heater.room.away_temp
heater.power_status = heater_data.get('powerStatus')
heater.tibber_control = heater_data.get('tibberControl')
heater.open_window = heater_data.get('open_window',
heater_data.get('open')
)
heater.is_heating = heater_data.get('heatStatus',
heater_data.get('heaterFlag')
)
try:
heater.sub_domain = int(float(heater_data.get('subDomain',
heater_data.get('subDomainId',
heater.sub_domain)
)))
except ValueError:
pass | [
"async",
"def",
"set_heater_values",
"(",
"heater_data",
",",
"heater",
")",
":",
"heater",
".",
"current_temp",
"=",
"heater_data",
".",
"get",
"(",
"'currentTemp'",
")",
"heater",
".",
"device_status",
"=",
"heater_data",
".",
"get",
"(",
"'deviceStatus'",
"... | Set heater values from heater data | [
"Set",
"heater",
"values",
"from",
"heater",
"data"
] | f091385914b53682012d0948c549beb4a5a96794 | https://github.com/Danielhiversen/pymill/blob/f091385914b53682012d0948c549beb4a5a96794/mill/__init__.py#L445-L488 | train | 47,159 |
Danielhiversen/pymill | mill/__init__.py | Mill.connect | async def connect(self, retry=2):
"""Connect to Mill."""
# pylint: disable=too-many-return-statements
url = API_ENDPOINT_1 + 'login'
headers = {
"Content-Type": "application/x-zc-object",
"Connection": "Keep-Alive",
"X-Zc-Major-Domain": "seanywell",
"X-Zc-Msg-Name": "millService",
"X-Zc-Sub-Domain": "milltype",
"X-Zc-Seq-Id": "1",
"X-Zc-Version": "1",
}
payload = {"account": self._username,
"password": self._password}
try:
with async_timeout.timeout(self._timeout):
resp = await self.websession.post(url,
data=json.dumps(payload),
headers=headers)
except (asyncio.TimeoutError, aiohttp.ClientError):
if retry < 1:
_LOGGER.error("Error connecting to Mill", exc_info=True)
return False
return await self.connect(retry - 1)
result = await resp.text()
if '"errorCode":3504' in result:
_LOGGER.error('Wrong password')
return False
if '"errorCode":3501' in result:
_LOGGER.error('Account does not exist')
return False
data = json.loads(result)
token = data.get('token')
if token is None:
_LOGGER.error('No token')
return False
user_id = data.get('userId')
if user_id is None:
_LOGGER.error('No user id')
return False
self._token = token
self._user_id = user_id
return True | python | async def connect(self, retry=2):
"""Connect to Mill."""
# pylint: disable=too-many-return-statements
url = API_ENDPOINT_1 + 'login'
headers = {
"Content-Type": "application/x-zc-object",
"Connection": "Keep-Alive",
"X-Zc-Major-Domain": "seanywell",
"X-Zc-Msg-Name": "millService",
"X-Zc-Sub-Domain": "milltype",
"X-Zc-Seq-Id": "1",
"X-Zc-Version": "1",
}
payload = {"account": self._username,
"password": self._password}
try:
with async_timeout.timeout(self._timeout):
resp = await self.websession.post(url,
data=json.dumps(payload),
headers=headers)
except (asyncio.TimeoutError, aiohttp.ClientError):
if retry < 1:
_LOGGER.error("Error connecting to Mill", exc_info=True)
return False
return await self.connect(retry - 1)
result = await resp.text()
if '"errorCode":3504' in result:
_LOGGER.error('Wrong password')
return False
if '"errorCode":3501' in result:
_LOGGER.error('Account does not exist')
return False
data = json.loads(result)
token = data.get('token')
if token is None:
_LOGGER.error('No token')
return False
user_id = data.get('userId')
if user_id is None:
_LOGGER.error('No user id')
return False
self._token = token
self._user_id = user_id
return True | [
"async",
"def",
"connect",
"(",
"self",
",",
"retry",
"=",
"2",
")",
":",
"# pylint: disable=too-many-return-statements",
"url",
"=",
"API_ENDPOINT_1",
"+",
"'login'",
"headers",
"=",
"{",
"\"Content-Type\"",
":",
"\"application/x-zc-object\"",
",",
"\"Connection\"",
... | Connect to Mill. | [
"Connect",
"to",
"Mill",
"."
] | f091385914b53682012d0948c549beb4a5a96794 | https://github.com/Danielhiversen/pymill/blob/f091385914b53682012d0948c549beb4a5a96794/mill/__init__.py#L52-L100 | train | 47,160 |
Danielhiversen/pymill | mill/__init__.py | Mill.set_room_temperatures_by_name | async def set_room_temperatures_by_name(self, room_name, sleep_temp=None,
comfort_temp=None, away_temp=None):
"""Set room temps by name."""
if sleep_temp is None and comfort_temp is None and away_temp is None:
return
for room_id, _room in self.rooms.items():
if _room.name == room_name:
await self.set_room_temperatures(room_id, sleep_temp,
comfort_temp, away_temp)
return
_LOGGER.error("Could not find a room with name %s", room_name) | python | async def set_room_temperatures_by_name(self, room_name, sleep_temp=None,
comfort_temp=None, away_temp=None):
"""Set room temps by name."""
if sleep_temp is None and comfort_temp is None and away_temp is None:
return
for room_id, _room in self.rooms.items():
if _room.name == room_name:
await self.set_room_temperatures(room_id, sleep_temp,
comfort_temp, away_temp)
return
_LOGGER.error("Could not find a room with name %s", room_name) | [
"async",
"def",
"set_room_temperatures_by_name",
"(",
"self",
",",
"room_name",
",",
"sleep_temp",
"=",
"None",
",",
"comfort_temp",
"=",
"None",
",",
"away_temp",
"=",
"None",
")",
":",
"if",
"sleep_temp",
"is",
"None",
"and",
"comfort_temp",
"is",
"None",
... | Set room temps by name. | [
"Set",
"room",
"temps",
"by",
"name",
"."
] | f091385914b53682012d0948c549beb4a5a96794 | https://github.com/Danielhiversen/pymill/blob/f091385914b53682012d0948c549beb4a5a96794/mill/__init__.py#L249-L259 | train | 47,161 |
Danielhiversen/pymill | mill/__init__.py | Mill.set_room_temperatures | async def set_room_temperatures(self, room_id, sleep_temp=None,
comfort_temp=None, away_temp=None):
"""Set room temps."""
if sleep_temp is None and comfort_temp is None and away_temp is None:
return
room = self.rooms.get(room_id)
if room is None:
_LOGGER.error("No such device")
return
room.sleep_temp = sleep_temp if sleep_temp else room.sleep_temp
room.away_temp = away_temp if away_temp else room.away_temp
room.comfort_temp = comfort_temp if comfort_temp else room.comfort_temp
payload = {"roomId": room_id,
"sleepTemp": room.sleep_temp,
"comfortTemp": room.comfort_temp,
"awayTemp": room.away_temp,
"homeType": 0}
await self.request("changeRoomModeTempInfo", payload)
self.rooms[room_id] = room | python | async def set_room_temperatures(self, room_id, sleep_temp=None,
comfort_temp=None, away_temp=None):
"""Set room temps."""
if sleep_temp is None and comfort_temp is None and away_temp is None:
return
room = self.rooms.get(room_id)
if room is None:
_LOGGER.error("No such device")
return
room.sleep_temp = sleep_temp if sleep_temp else room.sleep_temp
room.away_temp = away_temp if away_temp else room.away_temp
room.comfort_temp = comfort_temp if comfort_temp else room.comfort_temp
payload = {"roomId": room_id,
"sleepTemp": room.sleep_temp,
"comfortTemp": room.comfort_temp,
"awayTemp": room.away_temp,
"homeType": 0}
await self.request("changeRoomModeTempInfo", payload)
self.rooms[room_id] = room | [
"async",
"def",
"set_room_temperatures",
"(",
"self",
",",
"room_id",
",",
"sleep_temp",
"=",
"None",
",",
"comfort_temp",
"=",
"None",
",",
"away_temp",
"=",
"None",
")",
":",
"if",
"sleep_temp",
"is",
"None",
"and",
"comfort_temp",
"is",
"None",
"and",
"... | Set room temps. | [
"Set",
"room",
"temps",
"."
] | f091385914b53682012d0948c549beb4a5a96794 | https://github.com/Danielhiversen/pymill/blob/f091385914b53682012d0948c549beb4a5a96794/mill/__init__.py#L261-L279 | train | 47,162 |
Danielhiversen/pymill | mill/__init__.py | Mill.throttle_update_heaters | async def throttle_update_heaters(self):
"""Throttle update device."""
if (self._throttle_time is not None
and dt.datetime.now() - self._throttle_time < MIN_TIME_BETWEEN_UPDATES):
return
self._throttle_time = dt.datetime.now()
await self.update_heaters() | python | async def throttle_update_heaters(self):
"""Throttle update device."""
if (self._throttle_time is not None
and dt.datetime.now() - self._throttle_time < MIN_TIME_BETWEEN_UPDATES):
return
self._throttle_time = dt.datetime.now()
await self.update_heaters() | [
"async",
"def",
"throttle_update_heaters",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"_throttle_time",
"is",
"not",
"None",
"and",
"dt",
".",
"datetime",
".",
"now",
"(",
")",
"-",
"self",
".",
"_throttle_time",
"<",
"MIN_TIME_BETWEEN_UPDATES",
")",
"... | Throttle update device. | [
"Throttle",
"update",
"device",
"."
] | f091385914b53682012d0948c549beb4a5a96794 | https://github.com/Danielhiversen/pymill/blob/f091385914b53682012d0948c549beb4a5a96794/mill/__init__.py#L316-L322 | train | 47,163 |
Danielhiversen/pymill | mill/__init__.py | Mill.throttle_update_all_heaters | async def throttle_update_all_heaters(self):
"""Throttle update all devices and rooms."""
if (self._throttle_all_time is not None
and dt.datetime.now() - self._throttle_all_time
< MIN_TIME_BETWEEN_UPDATES):
return
self._throttle_all_time = dt.datetime.now()
await self.find_all_heaters() | python | async def throttle_update_all_heaters(self):
"""Throttle update all devices and rooms."""
if (self._throttle_all_time is not None
and dt.datetime.now() - self._throttle_all_time
< MIN_TIME_BETWEEN_UPDATES):
return
self._throttle_all_time = dt.datetime.now()
await self.find_all_heaters() | [
"async",
"def",
"throttle_update_all_heaters",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"_throttle_all_time",
"is",
"not",
"None",
"and",
"dt",
".",
"datetime",
".",
"now",
"(",
")",
"-",
"self",
".",
"_throttle_all_time",
"<",
"MIN_TIME_BETWEEN_UPDATES"... | Throttle update all devices and rooms. | [
"Throttle",
"update",
"all",
"devices",
"and",
"rooms",
"."
] | f091385914b53682012d0948c549beb4a5a96794 | https://github.com/Danielhiversen/pymill/blob/f091385914b53682012d0948c549beb4a5a96794/mill/__init__.py#L324-L331 | train | 47,164 |
Danielhiversen/pymill | mill/__init__.py | Mill.set_heater_temp | async def set_heater_temp(self, device_id, set_temp):
"""Set heater temp."""
payload = {"homeType": 0,
"timeZoneNum": "+02:00",
"deviceId": device_id,
"value": int(set_temp),
"key": "holidayTemp"}
await self.request("changeDeviceInfo", payload) | python | async def set_heater_temp(self, device_id, set_temp):
"""Set heater temp."""
payload = {"homeType": 0,
"timeZoneNum": "+02:00",
"deviceId": device_id,
"value": int(set_temp),
"key": "holidayTemp"}
await self.request("changeDeviceInfo", payload) | [
"async",
"def",
"set_heater_temp",
"(",
"self",
",",
"device_id",
",",
"set_temp",
")",
":",
"payload",
"=",
"{",
"\"homeType\"",
":",
"0",
",",
"\"timeZoneNum\"",
":",
"\"+02:00\"",
",",
"\"deviceId\"",
":",
"device_id",
",",
"\"value\"",
":",
"int",
"(",
... | Set heater temp. | [
"Set",
"heater",
"temp",
"."
] | f091385914b53682012d0948c549beb4a5a96794 | https://github.com/Danielhiversen/pymill/blob/f091385914b53682012d0948c549beb4a5a96794/mill/__init__.py#L375-L382 | train | 47,165 |
proteanhq/protean | src/protean/core/queryset.py | QuerySet._clone | def _clone(self):
"""
Return a copy of the current QuerySet.
"""
clone = self.__class__(self._entity_cls, criteria=self._criteria,
offset=self._offset, limit=self._limit,
order_by=self._order_by)
return clone | python | def _clone(self):
"""
Return a copy of the current QuerySet.
"""
clone = self.__class__(self._entity_cls, criteria=self._criteria,
offset=self._offset, limit=self._limit,
order_by=self._order_by)
return clone | [
"def",
"_clone",
"(",
"self",
")",
":",
"clone",
"=",
"self",
".",
"__class__",
"(",
"self",
".",
"_entity_cls",
",",
"criteria",
"=",
"self",
".",
"_criteria",
",",
"offset",
"=",
"self",
".",
"_offset",
",",
"limit",
"=",
"self",
".",
"_limit",
","... | Return a copy of the current QuerySet. | [
"Return",
"a",
"copy",
"of",
"the",
"current",
"QuerySet",
"."
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/queryset.py#L58-L65 | train | 47,166 |
proteanhq/protean | src/protean/core/queryset.py | QuerySet._add_q | def _add_q(self, q_object):
"""Add a Q-object to the current filter."""
self._criteria = self._criteria._combine(q_object, q_object.connector) | python | def _add_q(self, q_object):
"""Add a Q-object to the current filter."""
self._criteria = self._criteria._combine(q_object, q_object.connector) | [
"def",
"_add_q",
"(",
"self",
",",
"q_object",
")",
":",
"self",
".",
"_criteria",
"=",
"self",
".",
"_criteria",
".",
"_combine",
"(",
"q_object",
",",
"q_object",
".",
"connector",
")"
] | Add a Q-object to the current filter. | [
"Add",
"a",
"Q",
"-",
"object",
"to",
"the",
"current",
"filter",
"."
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/queryset.py#L67-L69 | train | 47,167 |
proteanhq/protean | src/protean/core/queryset.py | QuerySet.limit | def limit(self, limit):
"""Limit number of records"""
clone = self._clone()
if isinstance(limit, int):
clone._limit = limit
return clone | python | def limit(self, limit):
"""Limit number of records"""
clone = self._clone()
if isinstance(limit, int):
clone._limit = limit
return clone | [
"def",
"limit",
"(",
"self",
",",
"limit",
")",
":",
"clone",
"=",
"self",
".",
"_clone",
"(",
")",
"if",
"isinstance",
"(",
"limit",
",",
"int",
")",
":",
"clone",
".",
"_limit",
"=",
"limit",
"return",
"clone"
] | Limit number of records | [
"Limit",
"number",
"of",
"records"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/queryset.py#L93-L100 | train | 47,168 |
proteanhq/protean | src/protean/core/queryset.py | QuerySet.offset | def offset(self, offset):
"""Fetch results after `offset` value"""
clone = self._clone()
if isinstance(offset, int):
clone._offset = offset
return clone | python | def offset(self, offset):
"""Fetch results after `offset` value"""
clone = self._clone()
if isinstance(offset, int):
clone._offset = offset
return clone | [
"def",
"offset",
"(",
"self",
",",
"offset",
")",
":",
"clone",
"=",
"self",
".",
"_clone",
"(",
")",
"if",
"isinstance",
"(",
"offset",
",",
"int",
")",
":",
"clone",
".",
"_offset",
"=",
"offset",
"return",
"clone"
] | Fetch results after `offset` value | [
"Fetch",
"results",
"after",
"offset",
"value"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/queryset.py#L102-L109 | train | 47,169 |
proteanhq/protean | src/protean/core/queryset.py | QuerySet.order_by | def order_by(self, order_by: Union[set, str]):
"""Update order_by setting for filter set"""
clone = self._clone()
if isinstance(order_by, str):
order_by = {order_by}
clone._order_by = clone._order_by.union(order_by)
return clone | python | def order_by(self, order_by: Union[set, str]):
"""Update order_by setting for filter set"""
clone = self._clone()
if isinstance(order_by, str):
order_by = {order_by}
clone._order_by = clone._order_by.union(order_by)
return clone | [
"def",
"order_by",
"(",
"self",
",",
"order_by",
":",
"Union",
"[",
"set",
",",
"str",
"]",
")",
":",
"clone",
"=",
"self",
".",
"_clone",
"(",
")",
"if",
"isinstance",
"(",
"order_by",
",",
"str",
")",
":",
"order_by",
"=",
"{",
"order_by",
"}",
... | Update order_by setting for filter set | [
"Update",
"order_by",
"setting",
"for",
"filter",
"set"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/queryset.py#L111-L119 | train | 47,170 |
proteanhq/protean | src/protean/core/queryset.py | QuerySet.all | def all(self):
"""Primary method to fetch data based on filters
Also trigged when the QuerySet is evaluated by calling one of the following methods:
* len()
* bool()
* list()
* Iteration
* Slicing
"""
logger.debug(f'Query `{self.__class__.__name__}` objects with filters {self}')
# Destroy any cached results
self._result_cache = None
# Fetch Model class and connected repository from Repository Factory
model_cls = repo_factory.get_model(self._entity_cls)
repository = repo_factory.get_repository(self._entity_cls)
# order_by clause must be list of keys
order_by = self._entity_cls.meta_.order_by if not self._order_by else self._order_by
# Call the read method of the repository
results = repository.filter(self._criteria, self._offset, self._limit, order_by)
# Convert the returned results to entity and return it
entity_items = []
for item in results.items:
entity = model_cls.to_entity(item)
entity.state_.mark_retrieved()
entity_items.append(entity)
results.items = entity_items
# Cache results
self._result_cache = results
return results | python | def all(self):
"""Primary method to fetch data based on filters
Also trigged when the QuerySet is evaluated by calling one of the following methods:
* len()
* bool()
* list()
* Iteration
* Slicing
"""
logger.debug(f'Query `{self.__class__.__name__}` objects with filters {self}')
# Destroy any cached results
self._result_cache = None
# Fetch Model class and connected repository from Repository Factory
model_cls = repo_factory.get_model(self._entity_cls)
repository = repo_factory.get_repository(self._entity_cls)
# order_by clause must be list of keys
order_by = self._entity_cls.meta_.order_by if not self._order_by else self._order_by
# Call the read method of the repository
results = repository.filter(self._criteria, self._offset, self._limit, order_by)
# Convert the returned results to entity and return it
entity_items = []
for item in results.items:
entity = model_cls.to_entity(item)
entity.state_.mark_retrieved()
entity_items.append(entity)
results.items = entity_items
# Cache results
self._result_cache = results
return results | [
"def",
"all",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"f'Query `{self.__class__.__name__}` objects with filters {self}'",
")",
"# Destroy any cached results",
"self",
".",
"_result_cache",
"=",
"None",
"# Fetch Model class and connected repository from Repository Fact... | Primary method to fetch data based on filters
Also trigged when the QuerySet is evaluated by calling one of the following methods:
* len()
* bool()
* list()
* Iteration
* Slicing | [
"Primary",
"method",
"to",
"fetch",
"data",
"based",
"on",
"filters"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/queryset.py#L121-L157 | train | 47,171 |
proteanhq/protean | src/protean/core/queryset.py | QuerySet.raw | def raw(self, query: Any, data: Any = None):
"""Runs raw query directly on the database and returns Entity objects
Note that this method will raise an exception if the returned objects
are not of the Entity type.
`query` is not checked for correctness or validity, and any errors thrown by the plugin or
database are passed as-is. Data passed will be transferred as-is to the plugin.
All other query options like `order_by`, `offset` and `limit` are ignored for this action.
"""
logger.debug(f'Query `{self.__class__.__name__}` objects with raw query {query}')
# Destroy any cached results
self._result_cache = None
# Fetch Model class and connected repository from Repository Factory
model_cls = repo_factory.get_model(self._entity_cls)
repository = repo_factory.get_repository(self._entity_cls)
try:
# Call the raw method of the repository
results = repository.raw(query, data)
# Convert the returned results to entity and return it
entity_items = []
for item in results.items:
entity = model_cls.to_entity(item)
entity.state_.mark_retrieved()
entity_items.append(entity)
results.items = entity_items
# Cache results
self._result_cache = results
except Exception:
# FIXME Log Exception
raise
return results | python | def raw(self, query: Any, data: Any = None):
"""Runs raw query directly on the database and returns Entity objects
Note that this method will raise an exception if the returned objects
are not of the Entity type.
`query` is not checked for correctness or validity, and any errors thrown by the plugin or
database are passed as-is. Data passed will be transferred as-is to the plugin.
All other query options like `order_by`, `offset` and `limit` are ignored for this action.
"""
logger.debug(f'Query `{self.__class__.__name__}` objects with raw query {query}')
# Destroy any cached results
self._result_cache = None
# Fetch Model class and connected repository from Repository Factory
model_cls = repo_factory.get_model(self._entity_cls)
repository = repo_factory.get_repository(self._entity_cls)
try:
# Call the raw method of the repository
results = repository.raw(query, data)
# Convert the returned results to entity and return it
entity_items = []
for item in results.items:
entity = model_cls.to_entity(item)
entity.state_.mark_retrieved()
entity_items.append(entity)
results.items = entity_items
# Cache results
self._result_cache = results
except Exception:
# FIXME Log Exception
raise
return results | [
"def",
"raw",
"(",
"self",
",",
"query",
":",
"Any",
",",
"data",
":",
"Any",
"=",
"None",
")",
":",
"logger",
".",
"debug",
"(",
"f'Query `{self.__class__.__name__}` objects with raw query {query}'",
")",
"# Destroy any cached results",
"self",
".",
"_result_cache"... | Runs raw query directly on the database and returns Entity objects
Note that this method will raise an exception if the returned objects
are not of the Entity type.
`query` is not checked for correctness or validity, and any errors thrown by the plugin or
database are passed as-is. Data passed will be transferred as-is to the plugin.
All other query options like `order_by`, `offset` and `limit` are ignored for this action. | [
"Runs",
"raw",
"query",
"directly",
"on",
"the",
"database",
"and",
"returns",
"Entity",
"objects"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/queryset.py#L181-L219 | train | 47,172 |
proteanhq/protean | src/protean/core/queryset.py | QuerySet.delete | def delete(self):
"""Deletes matching objects from the Repository
Does not throw error if no objects are matched.
Returns the number of objects matched (which may not be equal to the number of objects
deleted if objects rows already have the new value).
"""
# Fetch Model class and connected repository from Repository Factory
deleted_item_count = 0
try:
items = self.all()
for item in items:
item.delete()
deleted_item_count += 1
except Exception:
# FIXME Log Exception
raise
return deleted_item_count | python | def delete(self):
"""Deletes matching objects from the Repository
Does not throw error if no objects are matched.
Returns the number of objects matched (which may not be equal to the number of objects
deleted if objects rows already have the new value).
"""
# Fetch Model class and connected repository from Repository Factory
deleted_item_count = 0
try:
items = self.all()
for item in items:
item.delete()
deleted_item_count += 1
except Exception:
# FIXME Log Exception
raise
return deleted_item_count | [
"def",
"delete",
"(",
"self",
")",
":",
"# Fetch Model class and connected repository from Repository Factory",
"deleted_item_count",
"=",
"0",
"try",
":",
"items",
"=",
"self",
".",
"all",
"(",
")",
"for",
"item",
"in",
"items",
":",
"item",
".",
"delete",
"(",... | Deletes matching objects from the Repository
Does not throw error if no objects are matched.
Returns the number of objects matched (which may not be equal to the number of objects
deleted if objects rows already have the new value). | [
"Deletes",
"matching",
"objects",
"from",
"the",
"Repository"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/queryset.py#L221-L241 | train | 47,173 |
proteanhq/protean | src/protean/core/queryset.py | QuerySet.delete_all | def delete_all(self, *args, **kwargs):
"""Deletes objects that match a set of conditions supplied.
This method forwards filters directly to the repository. It does not instantiate entities and
it does not trigger Entity callbacks or validations.
Returns the number of objects matched and deleted.
"""
deleted_item_count = 0
repository = repo_factory.get_repository(self._entity_cls)
try:
deleted_item_count = repository.delete_all(self._criteria)
except Exception:
# FIXME Log Exception
raise
return deleted_item_count | python | def delete_all(self, *args, **kwargs):
"""Deletes objects that match a set of conditions supplied.
This method forwards filters directly to the repository. It does not instantiate entities and
it does not trigger Entity callbacks or validations.
Returns the number of objects matched and deleted.
"""
deleted_item_count = 0
repository = repo_factory.get_repository(self._entity_cls)
try:
deleted_item_count = repository.delete_all(self._criteria)
except Exception:
# FIXME Log Exception
raise
return deleted_item_count | [
"def",
"delete_all",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"deleted_item_count",
"=",
"0",
"repository",
"=",
"repo_factory",
".",
"get_repository",
"(",
"self",
".",
"_entity_cls",
")",
"try",
":",
"deleted_item_count",
"=",
"r... | Deletes objects that match a set of conditions supplied.
This method forwards filters directly to the repository. It does not instantiate entities and
it does not trigger Entity callbacks or validations.
Returns the number of objects matched and deleted. | [
"Deletes",
"objects",
"that",
"match",
"a",
"set",
"of",
"conditions",
"supplied",
"."
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/queryset.py#L266-L282 | train | 47,174 |
proteanhq/protean | src/protean/core/queryset.py | QuerySet.total | def total(self):
"""Return the total number of records"""
if self._result_cache:
return self._result_cache.total
return self.all().total | python | def total(self):
"""Return the total number of records"""
if self._result_cache:
return self._result_cache.total
return self.all().total | [
"def",
"total",
"(",
"self",
")",
":",
"if",
"self",
".",
"_result_cache",
":",
"return",
"self",
".",
"_result_cache",
".",
"total",
"return",
"self",
".",
"all",
"(",
")",
".",
"total"
] | Return the total number of records | [
"Return",
"the",
"total",
"number",
"of",
"records"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/queryset.py#L328-L333 | train | 47,175 |
proteanhq/protean | src/protean/core/queryset.py | QuerySet.items | def items(self):
"""Return result values"""
if self._result_cache:
return self._result_cache.items
return self.all().items | python | def items(self):
"""Return result values"""
if self._result_cache:
return self._result_cache.items
return self.all().items | [
"def",
"items",
"(",
"self",
")",
":",
"if",
"self",
".",
"_result_cache",
":",
"return",
"self",
".",
"_result_cache",
".",
"items",
"return",
"self",
".",
"all",
"(",
")",
".",
"items"
] | Return result values | [
"Return",
"result",
"values"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/queryset.py#L336-L341 | train | 47,176 |
proteanhq/protean | src/protean/core/queryset.py | QuerySet.first | def first(self):
"""Return the first result"""
if self._result_cache:
return self._result_cache.first
return self.all().first | python | def first(self):
"""Return the first result"""
if self._result_cache:
return self._result_cache.first
return self.all().first | [
"def",
"first",
"(",
"self",
")",
":",
"if",
"self",
".",
"_result_cache",
":",
"return",
"self",
".",
"_result_cache",
".",
"first",
"return",
"self",
".",
"all",
"(",
")",
".",
"first"
] | Return the first result | [
"Return",
"the",
"first",
"result"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/queryset.py#L344-L349 | train | 47,177 |
proteanhq/protean | src/protean/core/queryset.py | QuerySet.has_next | def has_next(self):
"""Return True if there are more values present"""
if self._result_cache:
return self._result_cache.has_next
return self.all().has_next | python | def has_next(self):
"""Return True if there are more values present"""
if self._result_cache:
return self._result_cache.has_next
return self.all().has_next | [
"def",
"has_next",
"(",
"self",
")",
":",
"if",
"self",
".",
"_result_cache",
":",
"return",
"self",
".",
"_result_cache",
".",
"has_next",
"return",
"self",
".",
"all",
"(",
")",
".",
"has_next"
] | Return True if there are more values present | [
"Return",
"True",
"if",
"there",
"are",
"more",
"values",
"present"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/queryset.py#L352-L357 | train | 47,178 |
proteanhq/protean | src/protean/core/queryset.py | QuerySet.has_prev | def has_prev(self):
"""Return True if there are previous values present"""
if self._result_cache:
return self._result_cache.has_prev
return self.all().has_prev | python | def has_prev(self):
"""Return True if there are previous values present"""
if self._result_cache:
return self._result_cache.has_prev
return self.all().has_prev | [
"def",
"has_prev",
"(",
"self",
")",
":",
"if",
"self",
".",
"_result_cache",
":",
"return",
"self",
".",
"_result_cache",
".",
"has_prev",
"return",
"self",
".",
"all",
"(",
")",
".",
"has_prev"
] | Return True if there are previous values present | [
"Return",
"True",
"if",
"there",
"are",
"previous",
"values",
"present"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/queryset.py#L360-L365 | train | 47,179 |
proteanhq/protean | src/protean/core/transport/response.py | ResponseFailure.value | def value(self):
"""Utility method to retrieve Response Object information"""
# Set the code to the status value
if isinstance(self.code, Status):
code = self.code.value
else:
code = self.code
return {'code': code, 'errors': self.errors} | python | def value(self):
"""Utility method to retrieve Response Object information"""
# Set the code to the status value
if isinstance(self.code, Status):
code = self.code.value
else:
code = self.code
return {'code': code, 'errors': self.errors} | [
"def",
"value",
"(",
"self",
")",
":",
"# Set the code to the status value",
"if",
"isinstance",
"(",
"self",
".",
"code",
",",
"Status",
")",
":",
"code",
"=",
"self",
".",
"code",
".",
"value",
"else",
":",
"code",
"=",
"self",
".",
"code",
"return",
... | Utility method to retrieve Response Object information | [
"Utility",
"method",
"to",
"retrieve",
"Response",
"Object",
"information"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/transport/response.py#L62-L69 | train | 47,180 |
proteanhq/protean | src/protean/core/transport/response.py | ResponseFailure.build_response | def build_response(cls, code=Status.SYSTEM_ERROR, errors=None):
"""Utility method to build a new Resource Error object.
Can be used to build all kinds of error messages.
"""
errors = [errors] if not isinstance(errors, list) else errors
return cls(code, errors) | python | def build_response(cls, code=Status.SYSTEM_ERROR, errors=None):
"""Utility method to build a new Resource Error object.
Can be used to build all kinds of error messages.
"""
errors = [errors] if not isinstance(errors, list) else errors
return cls(code, errors) | [
"def",
"build_response",
"(",
"cls",
",",
"code",
"=",
"Status",
".",
"SYSTEM_ERROR",
",",
"errors",
"=",
"None",
")",
":",
"errors",
"=",
"[",
"errors",
"]",
"if",
"not",
"isinstance",
"(",
"errors",
",",
"list",
")",
"else",
"errors",
"return",
"cls"... | Utility method to build a new Resource Error object.
Can be used to build all kinds of error messages. | [
"Utility",
"method",
"to",
"build",
"a",
"new",
"Resource",
"Error",
"object",
".",
"Can",
"be",
"used",
"to",
"build",
"all",
"kinds",
"of",
"error",
"messages",
"."
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/transport/response.py#L72-L77 | train | 47,181 |
proteanhq/protean | src/protean/core/transport/response.py | ResponseFailure.build_from_invalid_request | def build_from_invalid_request(cls, invalid_request_object):
"""Utility method to build a new Error object from parameters.
Typically used to build HTTP 422 error response."""
errors = [{err['parameter']: err['message']} for err in invalid_request_object.errors]
return cls.build_response(Status.UNPROCESSABLE_ENTITY, errors) | python | def build_from_invalid_request(cls, invalid_request_object):
"""Utility method to build a new Error object from parameters.
Typically used to build HTTP 422 error response."""
errors = [{err['parameter']: err['message']} for err in invalid_request_object.errors]
return cls.build_response(Status.UNPROCESSABLE_ENTITY, errors) | [
"def",
"build_from_invalid_request",
"(",
"cls",
",",
"invalid_request_object",
")",
":",
"errors",
"=",
"[",
"{",
"err",
"[",
"'parameter'",
"]",
":",
"err",
"[",
"'message'",
"]",
"}",
"for",
"err",
"in",
"invalid_request_object",
".",
"errors",
"]",
"retu... | Utility method to build a new Error object from parameters.
Typically used to build HTTP 422 error response. | [
"Utility",
"method",
"to",
"build",
"a",
"new",
"Error",
"object",
"from",
"parameters",
".",
"Typically",
"used",
"to",
"build",
"HTTP",
"422",
"error",
"response",
"."
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/transport/response.py#L80-L84 | train | 47,182 |
proteanhq/protean | src/protean/core/transport/response.py | ResponseFailure.build_not_found | def build_not_found(cls, errors=None):
"""Utility method to build a HTTP 404 Resource Error response"""
errors = [errors] if not isinstance(errors, list) else errors
return cls(Status.NOT_FOUND, errors) | python | def build_not_found(cls, errors=None):
"""Utility method to build a HTTP 404 Resource Error response"""
errors = [errors] if not isinstance(errors, list) else errors
return cls(Status.NOT_FOUND, errors) | [
"def",
"build_not_found",
"(",
"cls",
",",
"errors",
"=",
"None",
")",
":",
"errors",
"=",
"[",
"errors",
"]",
"if",
"not",
"isinstance",
"(",
"errors",
",",
"list",
")",
"else",
"errors",
"return",
"cls",
"(",
"Status",
".",
"NOT_FOUND",
",",
"errors"... | Utility method to build a HTTP 404 Resource Error response | [
"Utility",
"method",
"to",
"build",
"a",
"HTTP",
"404",
"Resource",
"Error",
"response"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/transport/response.py#L87-L90 | train | 47,183 |
proteanhq/protean | src/protean/core/transport/response.py | ResponseFailure.build_system_error | def build_system_error(cls, errors=None):
"""Utility method to build a HTTP 500 System Error response"""
errors = [errors] if not isinstance(errors, list) else errors
return cls(Status.SYSTEM_ERROR, errors) | python | def build_system_error(cls, errors=None):
"""Utility method to build a HTTP 500 System Error response"""
errors = [errors] if not isinstance(errors, list) else errors
return cls(Status.SYSTEM_ERROR, errors) | [
"def",
"build_system_error",
"(",
"cls",
",",
"errors",
"=",
"None",
")",
":",
"errors",
"=",
"[",
"errors",
"]",
"if",
"not",
"isinstance",
"(",
"errors",
",",
"list",
")",
"else",
"errors",
"return",
"cls",
"(",
"Status",
".",
"SYSTEM_ERROR",
",",
"e... | Utility method to build a HTTP 500 System Error response | [
"Utility",
"method",
"to",
"build",
"a",
"HTTP",
"500",
"System",
"Error",
"response"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/transport/response.py#L93-L96 | train | 47,184 |
proteanhq/protean | src/protean/core/transport/response.py | ResponseFailure.build_parameters_error | def build_parameters_error(cls, errors=None):
"""Utility method to build a HTTP 400 Parameter Error response"""
errors = [errors] if not isinstance(errors, list) else errors
return cls(Status.PARAMETERS_ERROR, errors) | python | def build_parameters_error(cls, errors=None):
"""Utility method to build a HTTP 400 Parameter Error response"""
errors = [errors] if not isinstance(errors, list) else errors
return cls(Status.PARAMETERS_ERROR, errors) | [
"def",
"build_parameters_error",
"(",
"cls",
",",
"errors",
"=",
"None",
")",
":",
"errors",
"=",
"[",
"errors",
"]",
"if",
"not",
"isinstance",
"(",
"errors",
",",
"list",
")",
"else",
"errors",
"return",
"cls",
"(",
"Status",
".",
"PARAMETERS_ERROR",
"... | Utility method to build a HTTP 400 Parameter Error response | [
"Utility",
"method",
"to",
"build",
"a",
"HTTP",
"400",
"Parameter",
"Error",
"response"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/transport/response.py#L99-L102 | train | 47,185 |
proteanhq/protean | src/protean/core/transport/response.py | ResponseFailure.build_unprocessable_error | def build_unprocessable_error(cls, errors=None):
"""Utility method to build a HTTP 422 Parameter Error object"""
errors = [errors] if not isinstance(errors, list) else errors
return cls(Status.UNPROCESSABLE_ENTITY, errors) | python | def build_unprocessable_error(cls, errors=None):
"""Utility method to build a HTTP 422 Parameter Error object"""
errors = [errors] if not isinstance(errors, list) else errors
return cls(Status.UNPROCESSABLE_ENTITY, errors) | [
"def",
"build_unprocessable_error",
"(",
"cls",
",",
"errors",
"=",
"None",
")",
":",
"errors",
"=",
"[",
"errors",
"]",
"if",
"not",
"isinstance",
"(",
"errors",
",",
"list",
")",
"else",
"errors",
"return",
"cls",
"(",
"Status",
".",
"UNPROCESSABLE_ENTIT... | Utility method to build a HTTP 422 Parameter Error object | [
"Utility",
"method",
"to",
"build",
"a",
"HTTP",
"422",
"Parameter",
"Error",
"object"
] | 0e29873f4aa634aa93cc08ed675dd749c7ed4b0f | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/transport/response.py#L105-L108 | train | 47,186 |
heroku/salesforce-oauth-request | salesforce_oauth_request/utils.py | oauth_flow | def oauth_flow(s, oauth_url, username=None, password=None, sandbox=False):
"""s should be a requests session"""
r = s.get(oauth_url)
if r.status_code >= 300:
raise RuntimeError(r.text)
params = urlparse.parse_qs(urlparse.urlparse(r.url).query)
data = {"un":username,
"width":2560,
"height":1440,
"hasRememberUn":True,
"startURL":params['startURL'],
"loginURL":"",
"loginType":6,
"useSecure":True,
"local":"",
"lt":"OAUTH",
"qs":"r=https%3A%2F%2Flocalhost%3A8443%2Fsalesforce%2F21",
"locale":"",
"oauth_token":"",
"oauth_callback":"",
"login":"",
"serverid":"",
"display":"popup",
"username":username,
"pw":password,
"Login":""}
base = "https://login.salesforce.com" if not sandbox else "https://test.salesforce.com"
r2 = s.post(base, data)
m = re.search("window.location.href\s*='(.[^']+)'", r2.text)
assert m is not None, "Couldn't find location.href expression in page %s (Username or password is wrong)" % r2.url
u3 = "https://" + urlparse.urlparse(r2.url).hostname + m.group(1)
r3 = s.get(u3)
m = re.search("window.location.href\s*='(.[^']+)'", r3.text)
assert m is not None, "Couldn't find location.href expression in page %s:\n%s" % (r3.url, r3.text)
return m.group(1) | python | def oauth_flow(s, oauth_url, username=None, password=None, sandbox=False):
"""s should be a requests session"""
r = s.get(oauth_url)
if r.status_code >= 300:
raise RuntimeError(r.text)
params = urlparse.parse_qs(urlparse.urlparse(r.url).query)
data = {"un":username,
"width":2560,
"height":1440,
"hasRememberUn":True,
"startURL":params['startURL'],
"loginURL":"",
"loginType":6,
"useSecure":True,
"local":"",
"lt":"OAUTH",
"qs":"r=https%3A%2F%2Flocalhost%3A8443%2Fsalesforce%2F21",
"locale":"",
"oauth_token":"",
"oauth_callback":"",
"login":"",
"serverid":"",
"display":"popup",
"username":username,
"pw":password,
"Login":""}
base = "https://login.salesforce.com" if not sandbox else "https://test.salesforce.com"
r2 = s.post(base, data)
m = re.search("window.location.href\s*='(.[^']+)'", r2.text)
assert m is not None, "Couldn't find location.href expression in page %s (Username or password is wrong)" % r2.url
u3 = "https://" + urlparse.urlparse(r2.url).hostname + m.group(1)
r3 = s.get(u3)
m = re.search("window.location.href\s*='(.[^']+)'", r3.text)
assert m is not None, "Couldn't find location.href expression in page %s:\n%s" % (r3.url, r3.text)
return m.group(1) | [
"def",
"oauth_flow",
"(",
"s",
",",
"oauth_url",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"sandbox",
"=",
"False",
")",
":",
"r",
"=",
"s",
".",
"get",
"(",
"oauth_url",
")",
"if",
"r",
".",
"status_code",
">=",
"300",
":",
... | s should be a requests session | [
"s",
"should",
"be",
"a",
"requests",
"session"
] | 16d4aa57f5bc00912d466a532c3f1d946d186da6 | https://github.com/heroku/salesforce-oauth-request/blob/16d4aa57f5bc00912d466a532c3f1d946d186da6/salesforce_oauth_request/utils.py#L113-L154 | train | 47,187 |
MainRo/cyclotron-py | cyclotron/router.py | make_crossroad_router | def make_crossroad_router(source, drain=False):
''' legacy crossroad implementation. deprecated
'''
sink_observer = None
def on_sink_subscribe(observer):
nonlocal sink_observer
sink_observer = observer
def dispose():
nonlocal sink_observer
sink_observer = None
return dispose
def route_crossroad(request):
def on_response_subscribe(observer):
def on_next_source(i):
if type(i) is cyclotron.Drain:
observer.on_completed()
else:
observer.on_next(i)
source_disposable = source.subscribe(
on_next=on_next_source,
on_error=lambda e: observer.on_error(e),
on_completed=lambda: observer.on_completed()
)
def on_next_request(i):
if sink_observer is not None:
sink_observer.on_next(i)
def on_request_completed():
if sink_observer is not None:
if drain is True:
sink_observer.on_next(cyclotron.Drain())
else:
sink_observer.on_completed()
request_disposable = request.subscribe(
on_next=on_next_request,
on_error=observer.on_error,
on_completed=on_request_completed
)
def dispose():
source_disposable.dispose()
request_disposable.dispose()
return dispose
return Observable.create(on_response_subscribe)
return Observable.create(on_sink_subscribe), route_crossroad | python | def make_crossroad_router(source, drain=False):
''' legacy crossroad implementation. deprecated
'''
sink_observer = None
def on_sink_subscribe(observer):
nonlocal sink_observer
sink_observer = observer
def dispose():
nonlocal sink_observer
sink_observer = None
return dispose
def route_crossroad(request):
def on_response_subscribe(observer):
def on_next_source(i):
if type(i) is cyclotron.Drain:
observer.on_completed()
else:
observer.on_next(i)
source_disposable = source.subscribe(
on_next=on_next_source,
on_error=lambda e: observer.on_error(e),
on_completed=lambda: observer.on_completed()
)
def on_next_request(i):
if sink_observer is not None:
sink_observer.on_next(i)
def on_request_completed():
if sink_observer is not None:
if drain is True:
sink_observer.on_next(cyclotron.Drain())
else:
sink_observer.on_completed()
request_disposable = request.subscribe(
on_next=on_next_request,
on_error=observer.on_error,
on_completed=on_request_completed
)
def dispose():
source_disposable.dispose()
request_disposable.dispose()
return dispose
return Observable.create(on_response_subscribe)
return Observable.create(on_sink_subscribe), route_crossroad | [
"def",
"make_crossroad_router",
"(",
"source",
",",
"drain",
"=",
"False",
")",
":",
"sink_observer",
"=",
"None",
"def",
"on_sink_subscribe",
"(",
"observer",
")",
":",
"nonlocal",
"sink_observer",
"sink_observer",
"=",
"observer",
"def",
"dispose",
"(",
")",
... | legacy crossroad implementation. deprecated | [
"legacy",
"crossroad",
"implementation",
".",
"deprecated"
] | 4530f65173aa4b9e27c3d4a2f5d33900fc19f754 | https://github.com/MainRo/cyclotron-py/blob/4530f65173aa4b9e27c3d4a2f5d33900fc19f754/cyclotron/router.py#L5-L59 | train | 47,188 |
MainRo/cyclotron-py | cyclotron/router.py | make_error_router | def make_error_router():
""" Creates an error router
An error router takes a higher order observable a input and returns two
observables: One containing the flattened items of the input observable
and another one containing the flattened errors of the input observable.
.. image:: ../docs/asset/error_router.png
:scale: 60%
:align: center
Returns
-------
error_observable: observable
An observable emitting errors remapped.
route_error: function
A lettable function routing errors and taking three parameters:
* source: Observable (higher order). Observable with errors to route.
* error_map: function. Function used to map errors before routing them.
* source_map: function. A function used to select the observable from each item is source.
Examples
--------
>>> sink, route_error = make_error_router()
my_observable.let(route_error, error_map=lambda e: e)
"""
sink_observer = None
def on_subscribe(observer):
nonlocal sink_observer
sink_observer = observer
def dispose():
nonlocal sink_observer
sink_observer = None
return dispose
def route_error(obs, convert):
""" Handles error raised by obs observable
catches any error raised by obs, maps it to anther object with the
convert function, and emits in on the error observer.
"""
def catch_error(e):
sink_observer.on_next(convert(e))
return Observable.empty()
return obs.catch_exception(catch_error)
def catch_or_flat_map(source, error_map, source_map=lambda i: i):
return source.flat_map(lambda i: route_error(source_map(i), error_map))
return Observable.create(on_subscribe), catch_or_flat_map | python | def make_error_router():
""" Creates an error router
An error router takes a higher order observable a input and returns two
observables: One containing the flattened items of the input observable
and another one containing the flattened errors of the input observable.
.. image:: ../docs/asset/error_router.png
:scale: 60%
:align: center
Returns
-------
error_observable: observable
An observable emitting errors remapped.
route_error: function
A lettable function routing errors and taking three parameters:
* source: Observable (higher order). Observable with errors to route.
* error_map: function. Function used to map errors before routing them.
* source_map: function. A function used to select the observable from each item is source.
Examples
--------
>>> sink, route_error = make_error_router()
my_observable.let(route_error, error_map=lambda e: e)
"""
sink_observer = None
def on_subscribe(observer):
nonlocal sink_observer
sink_observer = observer
def dispose():
nonlocal sink_observer
sink_observer = None
return dispose
def route_error(obs, convert):
""" Handles error raised by obs observable
catches any error raised by obs, maps it to anther object with the
convert function, and emits in on the error observer.
"""
def catch_error(e):
sink_observer.on_next(convert(e))
return Observable.empty()
return obs.catch_exception(catch_error)
def catch_or_flat_map(source, error_map, source_map=lambda i: i):
return source.flat_map(lambda i: route_error(source_map(i), error_map))
return Observable.create(on_subscribe), catch_or_flat_map | [
"def",
"make_error_router",
"(",
")",
":",
"sink_observer",
"=",
"None",
"def",
"on_subscribe",
"(",
"observer",
")",
":",
"nonlocal",
"sink_observer",
"sink_observer",
"=",
"observer",
"def",
"dispose",
"(",
")",
":",
"nonlocal",
"sink_observer",
"sink_observer",... | Creates an error router
An error router takes a higher order observable a input and returns two
observables: One containing the flattened items of the input observable
and another one containing the flattened errors of the input observable.
.. image:: ../docs/asset/error_router.png
:scale: 60%
:align: center
Returns
-------
error_observable: observable
An observable emitting errors remapped.
route_error: function
A lettable function routing errors and taking three parameters:
* source: Observable (higher order). Observable with errors to route.
* error_map: function. Function used to map errors before routing them.
* source_map: function. A function used to select the observable from each item is source.
Examples
--------
>>> sink, route_error = make_error_router()
my_observable.let(route_error, error_map=lambda e: e) | [
"Creates",
"an",
"error",
"router"
] | 4530f65173aa4b9e27c3d4a2f5d33900fc19f754 | https://github.com/MainRo/cyclotron-py/blob/4530f65173aa4b9e27c3d4a2f5d33900fc19f754/cyclotron/router.py#L145-L202 | train | 47,189 |
moonso/loqusdb | loqusdb/plugins/mongo/adapter.py | MongoAdapter.wipe_db | def wipe_db(self):
"""Wipe the whole database"""
logger.warning("Wiping the whole database")
self.client.drop_database(self.db_name)
logger.debug("Database wiped") | python | def wipe_db(self):
"""Wipe the whole database"""
logger.warning("Wiping the whole database")
self.client.drop_database(self.db_name)
logger.debug("Database wiped") | [
"def",
"wipe_db",
"(",
"self",
")",
":",
"logger",
".",
"warning",
"(",
"\"Wiping the whole database\"",
")",
"self",
".",
"client",
".",
"drop_database",
"(",
"self",
".",
"db_name",
")",
"logger",
".",
"debug",
"(",
"\"Database wiped\"",
")"
] | Wipe the whole database | [
"Wipe",
"the",
"whole",
"database"
] | 792dcd0d461aff5adc703c49eebf58964913a513 | https://github.com/moonso/loqusdb/blob/792dcd0d461aff5adc703c49eebf58964913a513/loqusdb/plugins/mongo/adapter.py#L17-L21 | train | 47,190 |
moonso/loqusdb | loqusdb/plugins/mongo/adapter.py | MongoAdapter.check_indexes | def check_indexes(self):
"""Check if the indexes exists"""
for collection_name in INDEXES:
existing_indexes = self.indexes(collection_name)
indexes = INDEXES[collection_name]
for index in indexes:
index_name = index.document.get('name')
if not index_name in existing_indexes:
logger.warning("Index {0} missing. Run command `loqusdb index`".format(index_name))
return
logger.info("All indexes exists") | python | def check_indexes(self):
"""Check if the indexes exists"""
for collection_name in INDEXES:
existing_indexes = self.indexes(collection_name)
indexes = INDEXES[collection_name]
for index in indexes:
index_name = index.document.get('name')
if not index_name in existing_indexes:
logger.warning("Index {0} missing. Run command `loqusdb index`".format(index_name))
return
logger.info("All indexes exists") | [
"def",
"check_indexes",
"(",
"self",
")",
":",
"for",
"collection_name",
"in",
"INDEXES",
":",
"existing_indexes",
"=",
"self",
".",
"indexes",
"(",
"collection_name",
")",
"indexes",
"=",
"INDEXES",
"[",
"collection_name",
"]",
"for",
"index",
"in",
"indexes"... | Check if the indexes exists | [
"Check",
"if",
"the",
"indexes",
"exists"
] | 792dcd0d461aff5adc703c49eebf58964913a513 | https://github.com/moonso/loqusdb/blob/792dcd0d461aff5adc703c49eebf58964913a513/loqusdb/plugins/mongo/adapter.py#L43-L53 | train | 47,191 |
moonso/loqusdb | loqusdb/plugins/mongo/adapter.py | MongoAdapter.ensure_indexes | def ensure_indexes(self):
"""Update the indexes"""
for collection_name in INDEXES:
existing_indexes = self.indexes(collection_name)
indexes = INDEXES[collection_name]
for index in indexes:
index_name = index.document.get('name')
if index_name in existing_indexes:
logger.debug("Index exists: %s" % index_name)
self.db[collection_name].drop_index(index_name)
logger.info("creating indexes for collection {0}: {1}".format(
collection_name,
', '.join([index.document.get('name') for index in indexes]),
)
)
self.db[collection_name].create_indexes(indexes) | python | def ensure_indexes(self):
"""Update the indexes"""
for collection_name in INDEXES:
existing_indexes = self.indexes(collection_name)
indexes = INDEXES[collection_name]
for index in indexes:
index_name = index.document.get('name')
if index_name in existing_indexes:
logger.debug("Index exists: %s" % index_name)
self.db[collection_name].drop_index(index_name)
logger.info("creating indexes for collection {0}: {1}".format(
collection_name,
', '.join([index.document.get('name') for index in indexes]),
)
)
self.db[collection_name].create_indexes(indexes) | [
"def",
"ensure_indexes",
"(",
"self",
")",
":",
"for",
"collection_name",
"in",
"INDEXES",
":",
"existing_indexes",
"=",
"self",
".",
"indexes",
"(",
"collection_name",
")",
"indexes",
"=",
"INDEXES",
"[",
"collection_name",
"]",
"for",
"index",
"in",
"indexes... | Update the indexes | [
"Update",
"the",
"indexes"
] | 792dcd0d461aff5adc703c49eebf58964913a513 | https://github.com/moonso/loqusdb/blob/792dcd0d461aff5adc703c49eebf58964913a513/loqusdb/plugins/mongo/adapter.py#L55-L70 | train | 47,192 |
yjzhang/uncurl_python | uncurl/state_estimation.py | _create_m_objective | def _create_m_objective(w, X):
"""
Creates an objective function and its derivative for M, given W and X
Args:
w (array): clusters x cells
X (array): genes x cells
"""
clusters, cells = w.shape
genes = X.shape[0]
w_sum = w.sum(1)
def objective(m):
m = m.reshape((X.shape[0], w.shape[0]))
d = m.dot(w)+eps
temp = X/d
w2 = w.dot(temp.T)
deriv = w_sum - w2.T
return np.sum(d - X*np.log(d))/genes, deriv.flatten()/genes
return objective | python | def _create_m_objective(w, X):
"""
Creates an objective function and its derivative for M, given W and X
Args:
w (array): clusters x cells
X (array): genes x cells
"""
clusters, cells = w.shape
genes = X.shape[0]
w_sum = w.sum(1)
def objective(m):
m = m.reshape((X.shape[0], w.shape[0]))
d = m.dot(w)+eps
temp = X/d
w2 = w.dot(temp.T)
deriv = w_sum - w2.T
return np.sum(d - X*np.log(d))/genes, deriv.flatten()/genes
return objective | [
"def",
"_create_m_objective",
"(",
"w",
",",
"X",
")",
":",
"clusters",
",",
"cells",
"=",
"w",
".",
"shape",
"genes",
"=",
"X",
".",
"shape",
"[",
"0",
"]",
"w_sum",
"=",
"w",
".",
"sum",
"(",
"1",
")",
"def",
"objective",
"(",
"m",
")",
":",
... | Creates an objective function and its derivative for M, given W and X
Args:
w (array): clusters x cells
X (array): genes x cells | [
"Creates",
"an",
"objective",
"function",
"and",
"its",
"derivative",
"for",
"M",
"given",
"W",
"and",
"X"
] | 55c58ca5670f87699d3bd5752fdfa4baa07724dd | https://github.com/yjzhang/uncurl_python/blob/55c58ca5670f87699d3bd5752fdfa4baa07724dd/uncurl/state_estimation.py#L50-L68 | train | 47,193 |
yjzhang/uncurl_python | uncurl/state_estimation.py | initialize_from_assignments | def initialize_from_assignments(assignments, k, max_assign_weight=0.75):
"""
Creates a weight initialization matrix from Poisson clustering assignments.
Args:
assignments (array): 1D array of integers, of length cells
k (int): number of states/clusters
max_assign_weight (float, optional): between 0 and 1 - how much weight to assign to the highest cluster. Default: 0.75
Returns:
init_W (array): k x cells
"""
cells = len(assignments)
init_W = np.zeros((k, cells))
for i, a in enumerate(assignments):
# entirely arbitrary... maybe it would be better to scale
# the weights based on k?
init_W[a, i] = max_assign_weight
for a2 in range(k):
if a2!=a:
init_W[a2, i] = (1-max_assign_weight)/(k-1)
return init_W/init_W.sum(0) | python | def initialize_from_assignments(assignments, k, max_assign_weight=0.75):
"""
Creates a weight initialization matrix from Poisson clustering assignments.
Args:
assignments (array): 1D array of integers, of length cells
k (int): number of states/clusters
max_assign_weight (float, optional): between 0 and 1 - how much weight to assign to the highest cluster. Default: 0.75
Returns:
init_W (array): k x cells
"""
cells = len(assignments)
init_W = np.zeros((k, cells))
for i, a in enumerate(assignments):
# entirely arbitrary... maybe it would be better to scale
# the weights based on k?
init_W[a, i] = max_assign_weight
for a2 in range(k):
if a2!=a:
init_W[a2, i] = (1-max_assign_weight)/(k-1)
return init_W/init_W.sum(0) | [
"def",
"initialize_from_assignments",
"(",
"assignments",
",",
"k",
",",
"max_assign_weight",
"=",
"0.75",
")",
":",
"cells",
"=",
"len",
"(",
"assignments",
")",
"init_W",
"=",
"np",
".",
"zeros",
"(",
"(",
"k",
",",
"cells",
")",
")",
"for",
"i",
","... | Creates a weight initialization matrix from Poisson clustering assignments.
Args:
assignments (array): 1D array of integers, of length cells
k (int): number of states/clusters
max_assign_weight (float, optional): between 0 and 1 - how much weight to assign to the highest cluster. Default: 0.75
Returns:
init_W (array): k x cells | [
"Creates",
"a",
"weight",
"initialization",
"matrix",
"from",
"Poisson",
"clustering",
"assignments",
"."
] | 55c58ca5670f87699d3bd5752fdfa4baa07724dd | https://github.com/yjzhang/uncurl_python/blob/55c58ca5670f87699d3bd5752fdfa4baa07724dd/uncurl/state_estimation.py#L70-L91 | train | 47,194 |
yjzhang/uncurl_python | uncurl/state_estimation.py | initialize_means | def initialize_means(data, clusters, k):
"""
Initializes the M matrix given the data and a set of cluster labels.
Cluster centers are set to the mean of each cluster.
Args:
data (array): genes x cells
clusters (array): 1d array of ints (0...k-1)
k (int): number of clusters
"""
init_w = np.zeros((data.shape[0], k))
if sparse.issparse(data):
for i in range(k):
if data[:,clusters==i].shape[1]==0:
point = np.random.randint(0, data.shape[1])
init_w[:,i] = data[:,point].toarray().flatten()
else:
# memory usage might be a problem here?
init_w[:,i] = np.array(data[:,clusters==i].mean(1)).flatten() + eps
else:
for i in range(k):
if data[:,clusters==i].shape[1]==0:
point = np.random.randint(0, data.shape[1])
init_w[:,i] = data[:,point].flatten()
else:
init_w[:,i] = data[:,clusters==i].mean(1) + eps
return init_w | python | def initialize_means(data, clusters, k):
"""
Initializes the M matrix given the data and a set of cluster labels.
Cluster centers are set to the mean of each cluster.
Args:
data (array): genes x cells
clusters (array): 1d array of ints (0...k-1)
k (int): number of clusters
"""
init_w = np.zeros((data.shape[0], k))
if sparse.issparse(data):
for i in range(k):
if data[:,clusters==i].shape[1]==0:
point = np.random.randint(0, data.shape[1])
init_w[:,i] = data[:,point].toarray().flatten()
else:
# memory usage might be a problem here?
init_w[:,i] = np.array(data[:,clusters==i].mean(1)).flatten() + eps
else:
for i in range(k):
if data[:,clusters==i].shape[1]==0:
point = np.random.randint(0, data.shape[1])
init_w[:,i] = data[:,point].flatten()
else:
init_w[:,i] = data[:,clusters==i].mean(1) + eps
return init_w | [
"def",
"initialize_means",
"(",
"data",
",",
"clusters",
",",
"k",
")",
":",
"init_w",
"=",
"np",
".",
"zeros",
"(",
"(",
"data",
".",
"shape",
"[",
"0",
"]",
",",
"k",
")",
")",
"if",
"sparse",
".",
"issparse",
"(",
"data",
")",
":",
"for",
"i... | Initializes the M matrix given the data and a set of cluster labels.
Cluster centers are set to the mean of each cluster.
Args:
data (array): genes x cells
clusters (array): 1d array of ints (0...k-1)
k (int): number of clusters | [
"Initializes",
"the",
"M",
"matrix",
"given",
"the",
"data",
"and",
"a",
"set",
"of",
"cluster",
"labels",
".",
"Cluster",
"centers",
"are",
"set",
"to",
"the",
"mean",
"of",
"each",
"cluster",
"."
] | 55c58ca5670f87699d3bd5752fdfa4baa07724dd | https://github.com/yjzhang/uncurl_python/blob/55c58ca5670f87699d3bd5752fdfa4baa07724dd/uncurl/state_estimation.py#L93-L119 | train | 47,195 |
yjzhang/uncurl_python | uncurl/state_estimation.py | initialize_weights_nn | def initialize_weights_nn(data, means, lognorm=True):
"""
Initializes the weights with a nearest-neighbor approach using the means.
"""
# TODO
genes, cells = data.shape
k = means.shape[1]
if lognorm:
data = log1p(cell_normalize(data))
for i in range(cells):
for j in range(k):
pass | python | def initialize_weights_nn(data, means, lognorm=True):
"""
Initializes the weights with a nearest-neighbor approach using the means.
"""
# TODO
genes, cells = data.shape
k = means.shape[1]
if lognorm:
data = log1p(cell_normalize(data))
for i in range(cells):
for j in range(k):
pass | [
"def",
"initialize_weights_nn",
"(",
"data",
",",
"means",
",",
"lognorm",
"=",
"True",
")",
":",
"# TODO",
"genes",
",",
"cells",
"=",
"data",
".",
"shape",
"k",
"=",
"means",
".",
"shape",
"[",
"1",
"]",
"if",
"lognorm",
":",
"data",
"=",
"log1p",
... | Initializes the weights with a nearest-neighbor approach using the means. | [
"Initializes",
"the",
"weights",
"with",
"a",
"nearest",
"-",
"neighbor",
"approach",
"using",
"the",
"means",
"."
] | 55c58ca5670f87699d3bd5752fdfa4baa07724dd | https://github.com/yjzhang/uncurl_python/blob/55c58ca5670f87699d3bd5752fdfa4baa07724dd/uncurl/state_estimation.py#L121-L132 | train | 47,196 |
yjzhang/uncurl_python | uncurl/state_estimation.py | initialize_means_weights | def initialize_means_weights(data, clusters, init_means=None, init_weights=None, initialization='tsvd', max_assign_weight=0.75):
"""
Generates initial means and weights for state estimation.
"""
genes, cells = data.shape
if init_means is None:
if init_weights is not None:
if len(init_weights.shape)==1:
means = initialize_means(data, init_weights, clusters)
else:
means = initialize_means(data, init_weights.argmax(0),
clusters, max_assign_weight=max_assign_weight)
elif initialization=='cluster':
assignments, means = poisson_cluster(data, clusters)
if init_weights is None:
init_weights = initialize_from_assignments(assignments, clusters,
max_assign_weight=max_assign_weight)
elif initialization=='kmpp':
means, assignments = kmeans_pp(data, clusters)
elif initialization=='km':
km = KMeans(clusters)
assignments = km.fit_predict(log1p(cell_normalize(data)).T)
init_weights = initialize_from_assignments(assignments, clusters,
max_assign_weight)
means = initialize_means(data, assignments, clusters)
elif initialization=='tsvd':
n_components = min(50, genes-1)
#tsvd = TruncatedSVD(min(50, genes-1))
km = KMeans(clusters)
# remove dependence on sklearn tsvd b/c it has a bug that
# prevents it from working properly on long inputs
# if num elements > 2**31
#data_reduced = tsvd.fit_transform(log1p(cell_normalize(data)).T)
U, Sigma, VT = randomized_svd(log1p(cell_normalize(data)).T,
n_components)
data_reduced = U*Sigma
assignments = km.fit_predict(data_reduced)
init_weights = initialize_from_assignments(assignments, clusters,
max_assign_weight)
means = initialize_means(data, assignments, clusters)
elif initialization == 'random' or initialization == 'rand':
# choose k random cells and set means to those
selected_cells = np.random.choice(range(cells), size=clusters,
replace=False)
means = data[:, selected_cells]
if sparse.issparse(means):
means = means.toarray()
else:
means = init_means.copy()
means = means.astype(float)
if init_weights is None:
if init_means is not None:
if initialization == 'cluster':
assignments, means = poisson_cluster(data, clusters,
init=init_means, max_iters=1)
w_init = initialize_from_assignments(assignments, clusters,
max_assign_weight)
elif initialization == 'km':
km = KMeans(clusters, init=log1p(init_means.T), max_iter=1)
assignments = km.fit_predict(log1p(cell_normalize(data)).T)
w_init = initialize_from_assignments(assignments, clusters,
max_assign_weight)
else:
w_init = np.random.random((clusters, cells))
w_init = w_init/w_init.sum(0)
else:
w_init = np.random.random((clusters, cells))
w_init = w_init/w_init.sum(0)
else:
if len(init_weights.shape)==1:
init_weights = initialize_from_assignments(init_weights, clusters,
max_assign_weight)
w_init = init_weights.copy()
return means, w_init | python | def initialize_means_weights(data, clusters, init_means=None, init_weights=None, initialization='tsvd', max_assign_weight=0.75):
"""
Generates initial means and weights for state estimation.
"""
genes, cells = data.shape
if init_means is None:
if init_weights is not None:
if len(init_weights.shape)==1:
means = initialize_means(data, init_weights, clusters)
else:
means = initialize_means(data, init_weights.argmax(0),
clusters, max_assign_weight=max_assign_weight)
elif initialization=='cluster':
assignments, means = poisson_cluster(data, clusters)
if init_weights is None:
init_weights = initialize_from_assignments(assignments, clusters,
max_assign_weight=max_assign_weight)
elif initialization=='kmpp':
means, assignments = kmeans_pp(data, clusters)
elif initialization=='km':
km = KMeans(clusters)
assignments = km.fit_predict(log1p(cell_normalize(data)).T)
init_weights = initialize_from_assignments(assignments, clusters,
max_assign_weight)
means = initialize_means(data, assignments, clusters)
elif initialization=='tsvd':
n_components = min(50, genes-1)
#tsvd = TruncatedSVD(min(50, genes-1))
km = KMeans(clusters)
# remove dependence on sklearn tsvd b/c it has a bug that
# prevents it from working properly on long inputs
# if num elements > 2**31
#data_reduced = tsvd.fit_transform(log1p(cell_normalize(data)).T)
U, Sigma, VT = randomized_svd(log1p(cell_normalize(data)).T,
n_components)
data_reduced = U*Sigma
assignments = km.fit_predict(data_reduced)
init_weights = initialize_from_assignments(assignments, clusters,
max_assign_weight)
means = initialize_means(data, assignments, clusters)
elif initialization == 'random' or initialization == 'rand':
# choose k random cells and set means to those
selected_cells = np.random.choice(range(cells), size=clusters,
replace=False)
means = data[:, selected_cells]
if sparse.issparse(means):
means = means.toarray()
else:
means = init_means.copy()
means = means.astype(float)
if init_weights is None:
if init_means is not None:
if initialization == 'cluster':
assignments, means = poisson_cluster(data, clusters,
init=init_means, max_iters=1)
w_init = initialize_from_assignments(assignments, clusters,
max_assign_weight)
elif initialization == 'km':
km = KMeans(clusters, init=log1p(init_means.T), max_iter=1)
assignments = km.fit_predict(log1p(cell_normalize(data)).T)
w_init = initialize_from_assignments(assignments, clusters,
max_assign_weight)
else:
w_init = np.random.random((clusters, cells))
w_init = w_init/w_init.sum(0)
else:
w_init = np.random.random((clusters, cells))
w_init = w_init/w_init.sum(0)
else:
if len(init_weights.shape)==1:
init_weights = initialize_from_assignments(init_weights, clusters,
max_assign_weight)
w_init = init_weights.copy()
return means, w_init | [
"def",
"initialize_means_weights",
"(",
"data",
",",
"clusters",
",",
"init_means",
"=",
"None",
",",
"init_weights",
"=",
"None",
",",
"initialization",
"=",
"'tsvd'",
",",
"max_assign_weight",
"=",
"0.75",
")",
":",
"genes",
",",
"cells",
"=",
"data",
".",... | Generates initial means and weights for state estimation. | [
"Generates",
"initial",
"means",
"and",
"weights",
"for",
"state",
"estimation",
"."
] | 55c58ca5670f87699d3bd5752fdfa4baa07724dd | https://github.com/yjzhang/uncurl_python/blob/55c58ca5670f87699d3bd5752fdfa4baa07724dd/uncurl/state_estimation.py#L170-L243 | train | 47,197 |
yjzhang/uncurl_python | uncurl/state_estimation.py | update_m | def update_m(data, old_M, old_W, selected_genes, disp=False, inner_max_iters=100, parallel=True, threads=4, write_progress_file=None, tol=0.0, regularization=0.0, **kwargs):
"""
This returns a new M matrix that contains all genes, given an M that was
created from running state estimation with a subset of genes.
Args:
data (sparse matrix or dense array): data matrix of shape (genes, cells), containing all genes
old_M (array): shape is (selected_genes, k)
old_W (array): shape is (k, cells)
selected_genes (list): list of selected gene indices
Rest of the args are as in poisson_estimate_state
Returns:
new_M: array of shape (all_genes, k)
"""
genes, cells = data.shape
k = old_M.shape[1]
non_selected_genes = [x for x in range(genes) if x not in set(selected_genes)]
# 1. initialize new M
new_M = np.zeros((genes, k))
new_M[selected_genes, :] = old_M
# TODO: how to initialize rest of genes?
# data*w?
if disp:
print('computing initial guess for M by data*W.T')
new_M_non_selected = data[non_selected_genes, :] * sparse.csc_matrix(old_W.T)
new_M[non_selected_genes, :] = new_M_non_selected.toarray()
X = data.astype(float)
XT = X.T
is_sparse = False
if sparse.issparse(X):
is_sparse = True
update_fn = sparse_nolips_update_w
# convert to csc
X = sparse.csc_matrix(X)
XT = sparse.csc_matrix(XT)
if parallel:
update_fn = parallel_sparse_nolips_update_w
Xsum = np.asarray(X.sum(0)).flatten()
Xsum_m = np.asarray(X.sum(1)).flatten()
# L-BFGS-B won't work right now for sparse matrices
method = 'NoLips'
objective_fn = _call_sparse_obj
else:
objective_fn = objective
update_fn = nolips_update_w
Xsum = X.sum(0)
Xsum_m = X.sum(1)
# If method is NoLips, converting to a sparse matrix
# will always improve the performance (?) and never lower accuracy...
# will almost always improve performance?
# if sparsity is below 40%?
if method == 'NoLips':
is_sparse = True
X = sparse.csc_matrix(X)
XT = sparse.csc_matrix(XT)
update_fn = sparse_nolips_update_w
if parallel:
update_fn = parallel_sparse_nolips_update_w
objective_fn = _call_sparse_obj
if disp:
print('starting estimating M')
new_M = _estimate_w(XT, new_M.T, old_W.T, Xsum_m, update_fn, objective_fn, is_sparse, parallel, threads, method, tol, disp, inner_max_iters, 'M', regularization)
if write_progress_file is not None:
progress = open(write_progress_file, 'w')
progress.write('0')
progress.close()
return new_M.T | python | def update_m(data, old_M, old_W, selected_genes, disp=False, inner_max_iters=100, parallel=True, threads=4, write_progress_file=None, tol=0.0, regularization=0.0, **kwargs):
"""
This returns a new M matrix that contains all genes, given an M that was
created from running state estimation with a subset of genes.
Args:
data (sparse matrix or dense array): data matrix of shape (genes, cells), containing all genes
old_M (array): shape is (selected_genes, k)
old_W (array): shape is (k, cells)
selected_genes (list): list of selected gene indices
Rest of the args are as in poisson_estimate_state
Returns:
new_M: array of shape (all_genes, k)
"""
genes, cells = data.shape
k = old_M.shape[1]
non_selected_genes = [x for x in range(genes) if x not in set(selected_genes)]
# 1. initialize new M
new_M = np.zeros((genes, k))
new_M[selected_genes, :] = old_M
# TODO: how to initialize rest of genes?
# data*w?
if disp:
print('computing initial guess for M by data*W.T')
new_M_non_selected = data[non_selected_genes, :] * sparse.csc_matrix(old_W.T)
new_M[non_selected_genes, :] = new_M_non_selected.toarray()
X = data.astype(float)
XT = X.T
is_sparse = False
if sparse.issparse(X):
is_sparse = True
update_fn = sparse_nolips_update_w
# convert to csc
X = sparse.csc_matrix(X)
XT = sparse.csc_matrix(XT)
if parallel:
update_fn = parallel_sparse_nolips_update_w
Xsum = np.asarray(X.sum(0)).flatten()
Xsum_m = np.asarray(X.sum(1)).flatten()
# L-BFGS-B won't work right now for sparse matrices
method = 'NoLips'
objective_fn = _call_sparse_obj
else:
objective_fn = objective
update_fn = nolips_update_w
Xsum = X.sum(0)
Xsum_m = X.sum(1)
# If method is NoLips, converting to a sparse matrix
# will always improve the performance (?) and never lower accuracy...
# will almost always improve performance?
# if sparsity is below 40%?
if method == 'NoLips':
is_sparse = True
X = sparse.csc_matrix(X)
XT = sparse.csc_matrix(XT)
update_fn = sparse_nolips_update_w
if parallel:
update_fn = parallel_sparse_nolips_update_w
objective_fn = _call_sparse_obj
if disp:
print('starting estimating M')
new_M = _estimate_w(XT, new_M.T, old_W.T, Xsum_m, update_fn, objective_fn, is_sparse, parallel, threads, method, tol, disp, inner_max_iters, 'M', regularization)
if write_progress_file is not None:
progress = open(write_progress_file, 'w')
progress.write('0')
progress.close()
return new_M.T | [
"def",
"update_m",
"(",
"data",
",",
"old_M",
",",
"old_W",
",",
"selected_genes",
",",
"disp",
"=",
"False",
",",
"inner_max_iters",
"=",
"100",
",",
"parallel",
"=",
"True",
",",
"threads",
"=",
"4",
",",
"write_progress_file",
"=",
"None",
",",
"tol",... | This returns a new M matrix that contains all genes, given an M that was
created from running state estimation with a subset of genes.
Args:
data (sparse matrix or dense array): data matrix of shape (genes, cells), containing all genes
old_M (array): shape is (selected_genes, k)
old_W (array): shape is (k, cells)
selected_genes (list): list of selected gene indices
Rest of the args are as in poisson_estimate_state
Returns:
new_M: array of shape (all_genes, k) | [
"This",
"returns",
"a",
"new",
"M",
"matrix",
"that",
"contains",
"all",
"genes",
"given",
"an",
"M",
"that",
"was",
"created",
"from",
"running",
"state",
"estimation",
"with",
"a",
"subset",
"of",
"genes",
"."
] | 55c58ca5670f87699d3bd5752fdfa4baa07724dd | https://github.com/yjzhang/uncurl_python/blob/55c58ca5670f87699d3bd5752fdfa4baa07724dd/uncurl/state_estimation.py#L353-L420 | train | 47,198 |
markperdue/pyvesync | home_assistant/custom_components/__init__.py | setup | def setup(hass, config):
"""Set up the VeSync component."""
from pyvesync.vesync import VeSync
conf = config[DOMAIN]
manager = VeSync(conf.get(CONF_USERNAME), conf.get(CONF_PASSWORD),
time_zone=conf.get(CONF_TIME_ZONE))
if not manager.login():
_LOGGER.error("Unable to login to VeSync")
return
manager.update()
hass.data[DOMAIN] = {
'manager': manager
}
discovery.load_platform(hass, 'switch', DOMAIN, {}, config)
return True | python | def setup(hass, config):
"""Set up the VeSync component."""
from pyvesync.vesync import VeSync
conf = config[DOMAIN]
manager = VeSync(conf.get(CONF_USERNAME), conf.get(CONF_PASSWORD),
time_zone=conf.get(CONF_TIME_ZONE))
if not manager.login():
_LOGGER.error("Unable to login to VeSync")
return
manager.update()
hass.data[DOMAIN] = {
'manager': manager
}
discovery.load_platform(hass, 'switch', DOMAIN, {}, config)
return True | [
"def",
"setup",
"(",
"hass",
",",
"config",
")",
":",
"from",
"pyvesync",
".",
"vesync",
"import",
"VeSync",
"conf",
"=",
"config",
"[",
"DOMAIN",
"]",
"manager",
"=",
"VeSync",
"(",
"conf",
".",
"get",
"(",
"CONF_USERNAME",
")",
",",
"conf",
".",
"g... | Set up the VeSync component. | [
"Set",
"up",
"the",
"VeSync",
"component",
"."
] | 7552dd1a6dd5ebc452acf78e33fd8f6e721e8cfc | https://github.com/markperdue/pyvesync/blob/7552dd1a6dd5ebc452acf78e33fd8f6e721e8cfc/home_assistant/custom_components/__init__.py#L22-L43 | train | 47,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.