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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
datastore/datastore | datastore/core/basic.py | InterfaceMappingDatastore.get | def get(self, key):
'''Return the object in `service` named by `key` or None.
Args:
key: Key naming the object to retrieve.
Returns:
object or None
'''
key = self._service_key(key)
return self._service_ops['get'](key) | python | def get(self, key):
'''Return the object in `service` named by `key` or None.
Args:
key: Key naming the object to retrieve.
Returns:
object or None
'''
key = self._service_key(key)
return self._service_ops['get'](key) | [
"def",
"get",
"(",
"self",
",",
"key",
")",
":",
"key",
"=",
"self",
".",
"_service_key",
"(",
"key",
")",
"return",
"self",
".",
"_service_ops",
"[",
"'get'",
"]",
"(",
"key",
")"
] | Return the object in `service` named by `key` or None.
Args:
key: Key naming the object to retrieve.
Returns:
object or None | [
"Return",
"the",
"object",
"in",
"service",
"named",
"by",
"key",
"or",
"None",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/basic.py#L244-L254 | train | 24,500 |
datastore/datastore | datastore/core/basic.py | InterfaceMappingDatastore.put | def put(self, key, value):
'''Stores the object `value` named by `key` in `service`.
Args:
key: Key naming `value`.
value: the object to store.
'''
key = self._service_key(key)
self._service_ops['put'](key, value) | python | def put(self, key, value):
'''Stores the object `value` named by `key` in `service`.
Args:
key: Key naming `value`.
value: the object to store.
'''
key = self._service_key(key)
self._service_ops['put'](key, value) | [
"def",
"put",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"key",
"=",
"self",
".",
"_service_key",
"(",
"key",
")",
"self",
".",
"_service_ops",
"[",
"'put'",
"]",
"(",
"key",
",",
"value",
")"
] | Stores the object `value` named by `key` in `service`.
Args:
key: Key naming `value`.
value: the object to store. | [
"Stores",
"the",
"object",
"value",
"named",
"by",
"key",
"in",
"service",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/basic.py#L256-L264 | train | 24,501 |
datastore/datastore | datastore/core/basic.py | InterfaceMappingDatastore.delete | def delete(self, key):
'''Removes the object named by `key` in `service`.
Args:
key: Key naming the object to remove.
'''
key = self._service_key(key)
self._service_ops['delete'](key) | python | def delete(self, key):
'''Removes the object named by `key` in `service`.
Args:
key: Key naming the object to remove.
'''
key = self._service_key(key)
self._service_ops['delete'](key) | [
"def",
"delete",
"(",
"self",
",",
"key",
")",
":",
"key",
"=",
"self",
".",
"_service_key",
"(",
"key",
")",
"self",
".",
"_service_ops",
"[",
"'delete'",
"]",
"(",
"key",
")"
] | Removes the object named by `key` in `service`.
Args:
key: Key naming the object to remove. | [
"Removes",
"the",
"object",
"named",
"by",
"key",
"in",
"service",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/basic.py#L266-L273 | train | 24,502 |
datastore/datastore | datastore/core/basic.py | CacheShimDatastore.get | def get(self, key):
'''Return the object named by key or None if it does not exist.
CacheShimDatastore first checks its ``cache_datastore``.
'''
value = self.cache_datastore.get(key)
return value if value is not None else self.child_datastore.get(key) | python | def get(self, key):
'''Return the object named by key or None if it does not exist.
CacheShimDatastore first checks its ``cache_datastore``.
'''
value = self.cache_datastore.get(key)
return value if value is not None else self.child_datastore.get(key) | [
"def",
"get",
"(",
"self",
",",
"key",
")",
":",
"value",
"=",
"self",
".",
"cache_datastore",
".",
"get",
"(",
"key",
")",
"return",
"value",
"if",
"value",
"is",
"not",
"None",
"else",
"self",
".",
"child_datastore",
".",
"get",
"(",
"key",
")"
] | Return the object named by key or None if it does not exist.
CacheShimDatastore first checks its ``cache_datastore``. | [
"Return",
"the",
"object",
"named",
"by",
"key",
"or",
"None",
"if",
"it",
"does",
"not",
"exist",
".",
"CacheShimDatastore",
"first",
"checks",
"its",
"cache_datastore",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/basic.py#L377-L382 | train | 24,503 |
datastore/datastore | datastore/core/basic.py | CacheShimDatastore.put | def put(self, key, value):
'''Stores the object `value` named by `key`self.
Writes to both ``cache_datastore`` and ``child_datastore``.
'''
self.cache_datastore.put(key, value)
self.child_datastore.put(key, value) | python | def put(self, key, value):
'''Stores the object `value` named by `key`self.
Writes to both ``cache_datastore`` and ``child_datastore``.
'''
self.cache_datastore.put(key, value)
self.child_datastore.put(key, value) | [
"def",
"put",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"self",
".",
"cache_datastore",
".",
"put",
"(",
"key",
",",
"value",
")",
"self",
".",
"child_datastore",
".",
"put",
"(",
"key",
",",
"value",
")"
] | Stores the object `value` named by `key`self.
Writes to both ``cache_datastore`` and ``child_datastore``. | [
"Stores",
"the",
"object",
"value",
"named",
"by",
"key",
"self",
".",
"Writes",
"to",
"both",
"cache_datastore",
"and",
"child_datastore",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/basic.py#L384-L389 | train | 24,504 |
datastore/datastore | datastore/core/basic.py | CacheShimDatastore.delete | def delete(self, key):
'''Removes the object named by `key`.
Writes to both ``cache_datastore`` and ``child_datastore``.
'''
self.cache_datastore.delete(key)
self.child_datastore.delete(key) | python | def delete(self, key):
'''Removes the object named by `key`.
Writes to both ``cache_datastore`` and ``child_datastore``.
'''
self.cache_datastore.delete(key)
self.child_datastore.delete(key) | [
"def",
"delete",
"(",
"self",
",",
"key",
")",
":",
"self",
".",
"cache_datastore",
".",
"delete",
"(",
"key",
")",
"self",
".",
"child_datastore",
".",
"delete",
"(",
"key",
")"
] | Removes the object named by `key`.
Writes to both ``cache_datastore`` and ``child_datastore``. | [
"Removes",
"the",
"object",
"named",
"by",
"key",
".",
"Writes",
"to",
"both",
"cache_datastore",
"and",
"child_datastore",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/basic.py#L391-L396 | train | 24,505 |
datastore/datastore | datastore/core/basic.py | CacheShimDatastore.contains | def contains(self, key):
'''Returns whether the object named by `key` exists.
First checks ``cache_datastore``.
'''
return self.cache_datastore.contains(key) \
or self.child_datastore.contains(key) | python | def contains(self, key):
'''Returns whether the object named by `key` exists.
First checks ``cache_datastore``.
'''
return self.cache_datastore.contains(key) \
or self.child_datastore.contains(key) | [
"def",
"contains",
"(",
"self",
",",
"key",
")",
":",
"return",
"self",
".",
"cache_datastore",
".",
"contains",
"(",
"key",
")",
"or",
"self",
".",
"child_datastore",
".",
"contains",
"(",
"key",
")"
] | Returns whether the object named by `key` exists.
First checks ``cache_datastore``. | [
"Returns",
"whether",
"the",
"object",
"named",
"by",
"key",
"exists",
".",
"First",
"checks",
"cache_datastore",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/basic.py#L398-L403 | train | 24,506 |
datastore/datastore | datastore/core/basic.py | LoggingDatastore.get | def get(self, key):
'''Return the object named by key or None if it does not exist.
LoggingDatastore logs the access.
'''
self.logger.info('%s: get %s' % (self, key))
value = super(LoggingDatastore, self).get(key)
self.logger.debug('%s: %s' % (self, value))
return value | python | def get(self, key):
'''Return the object named by key or None if it does not exist.
LoggingDatastore logs the access.
'''
self.logger.info('%s: get %s' % (self, key))
value = super(LoggingDatastore, self).get(key)
self.logger.debug('%s: %s' % (self, value))
return value | [
"def",
"get",
"(",
"self",
",",
"key",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'%s: get %s'",
"%",
"(",
"self",
",",
"key",
")",
")",
"value",
"=",
"super",
"(",
"LoggingDatastore",
",",
"self",
")",
".",
"get",
"(",
"key",
")",
"self... | Return the object named by key or None if it does not exist.
LoggingDatastore logs the access. | [
"Return",
"the",
"object",
"named",
"by",
"key",
"or",
"None",
"if",
"it",
"does",
"not",
"exist",
".",
"LoggingDatastore",
"logs",
"the",
"access",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/basic.py#L420-L427 | train | 24,507 |
datastore/datastore | datastore/core/basic.py | LoggingDatastore.delete | def delete(self, key):
'''Removes the object named by `key`.
LoggingDatastore logs the access.
'''
self.logger.info('%s: delete %s' % (self, key))
super(LoggingDatastore, self).delete(key) | python | def delete(self, key):
'''Removes the object named by `key`.
LoggingDatastore logs the access.
'''
self.logger.info('%s: delete %s' % (self, key))
super(LoggingDatastore, self).delete(key) | [
"def",
"delete",
"(",
"self",
",",
"key",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'%s: delete %s'",
"%",
"(",
"self",
",",
"key",
")",
")",
"super",
"(",
"LoggingDatastore",
",",
"self",
")",
".",
"delete",
"(",
"key",
")"
] | Removes the object named by `key`.
LoggingDatastore logs the access. | [
"Removes",
"the",
"object",
"named",
"by",
"key",
".",
"LoggingDatastore",
"logs",
"the",
"access",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/basic.py#L437-L442 | train | 24,508 |
datastore/datastore | datastore/core/basic.py | LoggingDatastore.contains | def contains(self, key):
'''Returns whether the object named by `key` exists.
LoggingDatastore logs the access.
'''
self.logger.info('%s: contains %s' % (self, key))
return super(LoggingDatastore, self).contains(key) | python | def contains(self, key):
'''Returns whether the object named by `key` exists.
LoggingDatastore logs the access.
'''
self.logger.info('%s: contains %s' % (self, key))
return super(LoggingDatastore, self).contains(key) | [
"def",
"contains",
"(",
"self",
",",
"key",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'%s: contains %s'",
"%",
"(",
"self",
",",
"key",
")",
")",
"return",
"super",
"(",
"LoggingDatastore",
",",
"self",
")",
".",
"contains",
"(",
"key",
")"... | Returns whether the object named by `key` exists.
LoggingDatastore logs the access. | [
"Returns",
"whether",
"the",
"object",
"named",
"by",
"key",
"exists",
".",
"LoggingDatastore",
"logs",
"the",
"access",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/basic.py#L444-L449 | train | 24,509 |
datastore/datastore | datastore/core/basic.py | LoggingDatastore.query | def query(self, query):
'''Returns an iterable of objects matching criteria expressed in `query`.
LoggingDatastore logs the access.
'''
self.logger.info('%s: query %s' % (self, query))
return super(LoggingDatastore, self).query(query) | python | def query(self, query):
'''Returns an iterable of objects matching criteria expressed in `query`.
LoggingDatastore logs the access.
'''
self.logger.info('%s: query %s' % (self, query))
return super(LoggingDatastore, self).query(query) | [
"def",
"query",
"(",
"self",
",",
"query",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'%s: query %s'",
"%",
"(",
"self",
",",
"query",
")",
")",
"return",
"super",
"(",
"LoggingDatastore",
",",
"self",
")",
".",
"query",
"(",
"query",
")"
] | Returns an iterable of objects matching criteria expressed in `query`.
LoggingDatastore logs the access. | [
"Returns",
"an",
"iterable",
"of",
"objects",
"matching",
"criteria",
"expressed",
"in",
"query",
".",
"LoggingDatastore",
"logs",
"the",
"access",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/basic.py#L451-L456 | train | 24,510 |
datastore/datastore | datastore/core/basic.py | NestedPathDatastore.nestKey | def nestKey(self, key):
'''Returns a nested `key`.'''
nest = self.nest_keyfn(key)
# if depth * length > len(key.name), we need to pad.
mult = 1 + int(self.nest_depth * self.nest_length / len(nest))
nest = nest * mult
pref = Key(self.nestedPath(nest, self.nest_depth, self.nest_length))
return pref.child(key) | python | def nestKey(self, key):
'''Returns a nested `key`.'''
nest = self.nest_keyfn(key)
# if depth * length > len(key.name), we need to pad.
mult = 1 + int(self.nest_depth * self.nest_length / len(nest))
nest = nest * mult
pref = Key(self.nestedPath(nest, self.nest_depth, self.nest_length))
return pref.child(key) | [
"def",
"nestKey",
"(",
"self",
",",
"key",
")",
":",
"nest",
"=",
"self",
".",
"nest_keyfn",
"(",
"key",
")",
"# if depth * length > len(key.name), we need to pad.",
"mult",
"=",
"1",
"+",
"int",
"(",
"self",
".",
"nest_depth",
"*",
"self",
".",
"nest_length... | Returns a nested `key`. | [
"Returns",
"a",
"nested",
"key",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/basic.py#L643-L653 | train | 24,511 |
datastore/datastore | datastore/core/basic.py | SymlinkDatastore._link_for_value | def _link_for_value(self, value):
'''Returns the linked key if `value` is a link, or None.'''
try:
key = Key(value)
if key.name == self.sentinel:
return key.parent
except:
pass
return None | python | def _link_for_value(self, value):
'''Returns the linked key if `value` is a link, or None.'''
try:
key = Key(value)
if key.name == self.sentinel:
return key.parent
except:
pass
return None | [
"def",
"_link_for_value",
"(",
"self",
",",
"value",
")",
":",
"try",
":",
"key",
"=",
"Key",
"(",
"value",
")",
"if",
"key",
".",
"name",
"==",
"self",
".",
"sentinel",
":",
"return",
"key",
".",
"parent",
"except",
":",
"pass",
"return",
"None"
] | Returns the linked key if `value` is a link, or None. | [
"Returns",
"the",
"linked",
"key",
"if",
"value",
"is",
"a",
"link",
"or",
"None",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/basic.py#L728-L736 | train | 24,512 |
datastore/datastore | datastore/core/basic.py | SymlinkDatastore._follow_link | def _follow_link(self, value):
'''Returns given `value` or, if it is a symlink, the `value` it names.'''
seen_keys = set()
while True:
link_key = self._link_for_value(value)
if not link_key:
return value
assert link_key not in seen_keys, 'circular symlink reference'
seen_keys.add(link_key)
value = super(SymlinkDatastore, self).get(link_key) | python | def _follow_link(self, value):
'''Returns given `value` or, if it is a symlink, the `value` it names.'''
seen_keys = set()
while True:
link_key = self._link_for_value(value)
if not link_key:
return value
assert link_key not in seen_keys, 'circular symlink reference'
seen_keys.add(link_key)
value = super(SymlinkDatastore, self).get(link_key) | [
"def",
"_follow_link",
"(",
"self",
",",
"value",
")",
":",
"seen_keys",
"=",
"set",
"(",
")",
"while",
"True",
":",
"link_key",
"=",
"self",
".",
"_link_for_value",
"(",
"value",
")",
"if",
"not",
"link_key",
":",
"return",
"value",
"assert",
"link_key"... | Returns given `value` or, if it is a symlink, the `value` it names. | [
"Returns",
"given",
"value",
"or",
"if",
"it",
"is",
"a",
"symlink",
"the",
"value",
"it",
"names",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/basic.py#L739-L749 | train | 24,513 |
datastore/datastore | datastore/core/basic.py | SymlinkDatastore.link | def link(self, source_key, target_key):
'''Creates a symbolic link key pointing from `target_key` to `source_key`'''
link_value = self._link_value_for_key(source_key)
# put straight into the child, to avoid following previous links.
self.child_datastore.put(target_key, link_value)
# exercise the link. ensure there are no cycles.
self.get(target_key) | python | def link(self, source_key, target_key):
'''Creates a symbolic link key pointing from `target_key` to `source_key`'''
link_value = self._link_value_for_key(source_key)
# put straight into the child, to avoid following previous links.
self.child_datastore.put(target_key, link_value)
# exercise the link. ensure there are no cycles.
self.get(target_key) | [
"def",
"link",
"(",
"self",
",",
"source_key",
",",
"target_key",
")",
":",
"link_value",
"=",
"self",
".",
"_link_value_for_key",
"(",
"source_key",
")",
"# put straight into the child, to avoid following previous links.",
"self",
".",
"child_datastore",
".",
"put",
... | Creates a symbolic link key pointing from `target_key` to `source_key` | [
"Creates",
"a",
"symbolic",
"link",
"key",
"pointing",
"from",
"target_key",
"to",
"source_key"
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/basic.py#L757-L765 | train | 24,514 |
datastore/datastore | datastore/core/basic.py | SymlinkDatastore.get | def get(self, key):
'''Return the object named by `key. Follows links.'''
value = super(SymlinkDatastore, self).get(key)
return self._follow_link(value) | python | def get(self, key):
'''Return the object named by `key. Follows links.'''
value = super(SymlinkDatastore, self).get(key)
return self._follow_link(value) | [
"def",
"get",
"(",
"self",
",",
"key",
")",
":",
"value",
"=",
"super",
"(",
"SymlinkDatastore",
",",
"self",
")",
".",
"get",
"(",
"key",
")",
"return",
"self",
".",
"_follow_link",
"(",
"value",
")"
] | Return the object named by `key. Follows links. | [
"Return",
"the",
"object",
"named",
"by",
"key",
".",
"Follows",
"links",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/basic.py#L768-L771 | train | 24,515 |
datastore/datastore | datastore/core/basic.py | SymlinkDatastore.put | def put(self, key, value):
'''Stores the object named by `key`. Follows links.'''
# if value is a link, don't follow links
if self._link_for_value(value):
super(SymlinkDatastore, self).put(key, value)
return
# if `key` points to a symlink, need to follow it.
current_value = super(SymlinkDatastore, self).get(key)
link_key = self._link_for_value(current_value)
if link_key:
self.put(link_key, value) # self.put: could be another link.
else:
super(SymlinkDatastore, self).put(key, value) | python | def put(self, key, value):
'''Stores the object named by `key`. Follows links.'''
# if value is a link, don't follow links
if self._link_for_value(value):
super(SymlinkDatastore, self).put(key, value)
return
# if `key` points to a symlink, need to follow it.
current_value = super(SymlinkDatastore, self).get(key)
link_key = self._link_for_value(current_value)
if link_key:
self.put(link_key, value) # self.put: could be another link.
else:
super(SymlinkDatastore, self).put(key, value) | [
"def",
"put",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"# if value is a link, don't follow links",
"if",
"self",
".",
"_link_for_value",
"(",
"value",
")",
":",
"super",
"(",
"SymlinkDatastore",
",",
"self",
")",
".",
"put",
"(",
"key",
",",
"value... | Stores the object named by `key`. Follows links. | [
"Stores",
"the",
"object",
"named",
"by",
"key",
".",
"Follows",
"links",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/basic.py#L773-L786 | train | 24,516 |
datastore/datastore | datastore/core/basic.py | SymlinkDatastore.query | def query(self, query):
'''Returns objects matching criteria expressed in `query`. Follows links.'''
results = super(SymlinkDatastore, self).query(query)
return self._follow_link_gen(results) | python | def query(self, query):
'''Returns objects matching criteria expressed in `query`. Follows links.'''
results = super(SymlinkDatastore, self).query(query)
return self._follow_link_gen(results) | [
"def",
"query",
"(",
"self",
",",
"query",
")",
":",
"results",
"=",
"super",
"(",
"SymlinkDatastore",
",",
"self",
")",
".",
"query",
"(",
"query",
")",
"return",
"self",
".",
"_follow_link_gen",
"(",
"results",
")"
] | Returns objects matching criteria expressed in `query`. Follows links. | [
"Returns",
"objects",
"matching",
"criteria",
"expressed",
"in",
"query",
".",
"Follows",
"links",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/basic.py#L788-L791 | train | 24,517 |
datastore/datastore | datastore/core/basic.py | DirectoryDatastore.directory | def directory(self, dir_key):
'''Initializes directory at dir_key.'''
dir_items = self.get(dir_key)
if not isinstance(dir_items, list):
self.put(dir_key, []) | python | def directory(self, dir_key):
'''Initializes directory at dir_key.'''
dir_items = self.get(dir_key)
if not isinstance(dir_items, list):
self.put(dir_key, []) | [
"def",
"directory",
"(",
"self",
",",
"dir_key",
")",
":",
"dir_items",
"=",
"self",
".",
"get",
"(",
"dir_key",
")",
"if",
"not",
"isinstance",
"(",
"dir_items",
",",
"list",
")",
":",
"self",
".",
"put",
"(",
"dir_key",
",",
"[",
"]",
")"
] | Initializes directory at dir_key. | [
"Initializes",
"directory",
"at",
"dir_key",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/basic.py#L823-L827 | train | 24,518 |
datastore/datastore | datastore/core/basic.py | DirectoryDatastore.directoryAdd | def directoryAdd(self, dir_key, key):
'''Adds directory entry `key` to directory at `dir_key`.
If the directory `dir_key` does not exist, it is created.
'''
key = str(key)
dir_items = self.get(dir_key) or []
if key not in dir_items:
dir_items.append(key)
self.put(dir_key, dir_items) | python | def directoryAdd(self, dir_key, key):
'''Adds directory entry `key` to directory at `dir_key`.
If the directory `dir_key` does not exist, it is created.
'''
key = str(key)
dir_items = self.get(dir_key) or []
if key not in dir_items:
dir_items.append(key)
self.put(dir_key, dir_items) | [
"def",
"directoryAdd",
"(",
"self",
",",
"dir_key",
",",
"key",
")",
":",
"key",
"=",
"str",
"(",
"key",
")",
"dir_items",
"=",
"self",
".",
"get",
"(",
"dir_key",
")",
"or",
"[",
"]",
"if",
"key",
"not",
"in",
"dir_items",
":",
"dir_items",
".",
... | Adds directory entry `key` to directory at `dir_key`.
If the directory `dir_key` does not exist, it is created. | [
"Adds",
"directory",
"entry",
"key",
"to",
"directory",
"at",
"dir_key",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/basic.py#L840-L850 | train | 24,519 |
datastore/datastore | datastore/core/basic.py | DirectoryDatastore.directoryRemove | def directoryRemove(self, dir_key, key):
'''Removes directory entry `key` from directory at `dir_key`.
If either the directory `dir_key` or the directory entry `key` don't exist,
this method is a no-op.
'''
key = str(key)
dir_items = self.get(dir_key) or []
if key in dir_items:
dir_items = [k for k in dir_items if k != key]
self.put(dir_key, dir_items) | python | def directoryRemove(self, dir_key, key):
'''Removes directory entry `key` from directory at `dir_key`.
If either the directory `dir_key` or the directory entry `key` don't exist,
this method is a no-op.
'''
key = str(key)
dir_items = self.get(dir_key) or []
if key in dir_items:
dir_items = [k for k in dir_items if k != key]
self.put(dir_key, dir_items) | [
"def",
"directoryRemove",
"(",
"self",
",",
"dir_key",
",",
"key",
")",
":",
"key",
"=",
"str",
"(",
"key",
")",
"dir_items",
"=",
"self",
".",
"get",
"(",
"dir_key",
")",
"or",
"[",
"]",
"if",
"key",
"in",
"dir_items",
":",
"dir_items",
"=",
"[",
... | Removes directory entry `key` from directory at `dir_key`.
If either the directory `dir_key` or the directory entry `key` don't exist,
this method is a no-op. | [
"Removes",
"directory",
"entry",
"key",
"from",
"directory",
"at",
"dir_key",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/basic.py#L853-L864 | train | 24,520 |
datastore/datastore | datastore/core/basic.py | DirectoryTreeDatastore.put | def put(self, key, value):
'''Stores the object `value` named by `key`self.
DirectoryTreeDatastore stores a directory entry.
'''
super(DirectoryTreeDatastore, self).put(key, value)
str_key = str(key)
# ignore root
if str_key == '/':
return
# retrieve directory, to add entry
dir_key = key.parent.instance('directory')
directory = self.directory(dir_key)
# ensure key is in directory
if str_key not in directory:
directory.append(str_key)
super(DirectoryTreeDatastore, self).put(dir_key, directory) | python | def put(self, key, value):
'''Stores the object `value` named by `key`self.
DirectoryTreeDatastore stores a directory entry.
'''
super(DirectoryTreeDatastore, self).put(key, value)
str_key = str(key)
# ignore root
if str_key == '/':
return
# retrieve directory, to add entry
dir_key = key.parent.instance('directory')
directory = self.directory(dir_key)
# ensure key is in directory
if str_key not in directory:
directory.append(str_key)
super(DirectoryTreeDatastore, self).put(dir_key, directory) | [
"def",
"put",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"super",
"(",
"DirectoryTreeDatastore",
",",
"self",
")",
".",
"put",
"(",
"key",
",",
"value",
")",
"str_key",
"=",
"str",
"(",
"key",
")",
"# ignore root",
"if",
"str_key",
"==",
"'/'",... | Stores the object `value` named by `key`self.
DirectoryTreeDatastore stores a directory entry. | [
"Stores",
"the",
"object",
"value",
"named",
"by",
"key",
"self",
".",
"DirectoryTreeDatastore",
"stores",
"a",
"directory",
"entry",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/basic.py#L910-L929 | train | 24,521 |
datastore/datastore | datastore/core/basic.py | DirectoryTreeDatastore.delete | def delete(self, key):
'''Removes the object named by `key`.
DirectoryTreeDatastore removes the directory entry.
'''
super(DirectoryTreeDatastore, self).delete(key)
str_key = str(key)
# ignore root
if str_key == '/':
return
# retrieve directory, to remove entry
dir_key = key.parent.instance('directory')
directory = self.directory(dir_key)
# ensure key is not in directory
if directory and str_key in directory:
directory.remove(str_key)
if len(directory) > 0:
super(DirectoryTreeDatastore, self).put(dir_key, directory)
else:
super(DirectoryTreeDatastore, self).delete(dir_key) | python | def delete(self, key):
'''Removes the object named by `key`.
DirectoryTreeDatastore removes the directory entry.
'''
super(DirectoryTreeDatastore, self).delete(key)
str_key = str(key)
# ignore root
if str_key == '/':
return
# retrieve directory, to remove entry
dir_key = key.parent.instance('directory')
directory = self.directory(dir_key)
# ensure key is not in directory
if directory and str_key in directory:
directory.remove(str_key)
if len(directory) > 0:
super(DirectoryTreeDatastore, self).put(dir_key, directory)
else:
super(DirectoryTreeDatastore, self).delete(dir_key) | [
"def",
"delete",
"(",
"self",
",",
"key",
")",
":",
"super",
"(",
"DirectoryTreeDatastore",
",",
"self",
")",
".",
"delete",
"(",
"key",
")",
"str_key",
"=",
"str",
"(",
"key",
")",
"# ignore root",
"if",
"str_key",
"==",
"'/'",
":",
"return",
"# retri... | Removes the object named by `key`.
DirectoryTreeDatastore removes the directory entry. | [
"Removes",
"the",
"object",
"named",
"by",
"key",
".",
"DirectoryTreeDatastore",
"removes",
"the",
"directory",
"entry",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/basic.py#L932-L954 | train | 24,522 |
datastore/datastore | datastore/core/basic.py | DirectoryTreeDatastore.directory | def directory(self, key):
'''Retrieves directory entries for given key.'''
if key.name != 'directory':
key = key.instance('directory')
return self.get(key) or [] | python | def directory(self, key):
'''Retrieves directory entries for given key.'''
if key.name != 'directory':
key = key.instance('directory')
return self.get(key) or [] | [
"def",
"directory",
"(",
"self",
",",
"key",
")",
":",
"if",
"key",
".",
"name",
"!=",
"'directory'",
":",
"key",
"=",
"key",
".",
"instance",
"(",
"'directory'",
")",
"return",
"self",
".",
"get",
"(",
"key",
")",
"or",
"[",
"]"
] | Retrieves directory entries for given key. | [
"Retrieves",
"directory",
"entries",
"for",
"given",
"key",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/basic.py#L965-L969 | train | 24,523 |
datastore/datastore | datastore/core/basic.py | DirectoryTreeDatastore.directory_values_generator | def directory_values_generator(self, key):
'''Retrieve directory values for given key.'''
directory = self.directory(key)
for key in directory:
yield self.get(Key(key)) | python | def directory_values_generator(self, key):
'''Retrieve directory values for given key.'''
directory = self.directory(key)
for key in directory:
yield self.get(Key(key)) | [
"def",
"directory_values_generator",
"(",
"self",
",",
"key",
")",
":",
"directory",
"=",
"self",
".",
"directory",
"(",
"key",
")",
"for",
"key",
"in",
"directory",
":",
"yield",
"self",
".",
"get",
"(",
"Key",
"(",
"key",
")",
")"
] | Retrieve directory values for given key. | [
"Retrieve",
"directory",
"values",
"for",
"given",
"key",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/basic.py#L972-L976 | train | 24,524 |
datastore/datastore | datastore/core/basic.py | DatastoreCollection.appendDatastore | def appendDatastore(self, store):
'''Appends datastore `store` to this collection.'''
if not isinstance(store, Datastore):
raise TypeError("stores must be of type %s" % Datastore)
self._stores.append(store) | python | def appendDatastore(self, store):
'''Appends datastore `store` to this collection.'''
if not isinstance(store, Datastore):
raise TypeError("stores must be of type %s" % Datastore)
self._stores.append(store) | [
"def",
"appendDatastore",
"(",
"self",
",",
"store",
")",
":",
"if",
"not",
"isinstance",
"(",
"store",
",",
"Datastore",
")",
":",
"raise",
"TypeError",
"(",
"\"stores must be of type %s\"",
"%",
"Datastore",
")",
"self",
".",
"_stores",
".",
"append",
"(",... | Appends datastore `store` to this collection. | [
"Appends",
"datastore",
"store",
"to",
"this",
"collection",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/basic.py#L999-L1004 | train | 24,525 |
datastore/datastore | datastore/core/basic.py | DatastoreCollection.insertDatastore | def insertDatastore(self, index, store):
'''Inserts datastore `store` into this collection at `index`.'''
if not isinstance(store, Datastore):
raise TypeError("stores must be of type %s" % Datastore)
self._stores.insert(index, store) | python | def insertDatastore(self, index, store):
'''Inserts datastore `store` into this collection at `index`.'''
if not isinstance(store, Datastore):
raise TypeError("stores must be of type %s" % Datastore)
self._stores.insert(index, store) | [
"def",
"insertDatastore",
"(",
"self",
",",
"index",
",",
"store",
")",
":",
"if",
"not",
"isinstance",
"(",
"store",
",",
"Datastore",
")",
":",
"raise",
"TypeError",
"(",
"\"stores must be of type %s\"",
"%",
"Datastore",
")",
"self",
".",
"_stores",
".",
... | Inserts datastore `store` into this collection at `index`. | [
"Inserts",
"datastore",
"store",
"into",
"this",
"collection",
"at",
"index",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/basic.py#L1010-L1015 | train | 24,526 |
datastore/datastore | datastore/core/basic.py | TieredDatastore.get | def get(self, key):
'''Return the object named by key. Checks each datastore in order.'''
value = None
for store in self._stores:
value = store.get(key)
if value is not None:
break
# add model to lower stores only
if value is not None:
for store2 in self._stores:
if store == store2:
break
store2.put(key, value)
return value | python | def get(self, key):
'''Return the object named by key. Checks each datastore in order.'''
value = None
for store in self._stores:
value = store.get(key)
if value is not None:
break
# add model to lower stores only
if value is not None:
for store2 in self._stores:
if store == store2:
break
store2.put(key, value)
return value | [
"def",
"get",
"(",
"self",
",",
"key",
")",
":",
"value",
"=",
"None",
"for",
"store",
"in",
"self",
".",
"_stores",
":",
"value",
"=",
"store",
".",
"get",
"(",
"key",
")",
"if",
"value",
"is",
"not",
"None",
":",
"break",
"# add model to lower stor... | Return the object named by key. Checks each datastore in order. | [
"Return",
"the",
"object",
"named",
"by",
"key",
".",
"Checks",
"each",
"datastore",
"in",
"order",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/basic.py#L1039-L1054 | train | 24,527 |
datastore/datastore | datastore/core/basic.py | TieredDatastore.put | def put(self, key, value):
'''Stores the object in all underlying datastores.'''
for store in self._stores:
store.put(key, value) | python | def put(self, key, value):
'''Stores the object in all underlying datastores.'''
for store in self._stores:
store.put(key, value) | [
"def",
"put",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"for",
"store",
"in",
"self",
".",
"_stores",
":",
"store",
".",
"put",
"(",
"key",
",",
"value",
")"
] | Stores the object in all underlying datastores. | [
"Stores",
"the",
"object",
"in",
"all",
"underlying",
"datastores",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/basic.py#L1056-L1059 | train | 24,528 |
datastore/datastore | datastore/core/basic.py | TieredDatastore.contains | def contains(self, key):
'''Returns whether the object is in this datastore.'''
for store in self._stores:
if store.contains(key):
return True
return False | python | def contains(self, key):
'''Returns whether the object is in this datastore.'''
for store in self._stores:
if store.contains(key):
return True
return False | [
"def",
"contains",
"(",
"self",
",",
"key",
")",
":",
"for",
"store",
"in",
"self",
".",
"_stores",
":",
"if",
"store",
".",
"contains",
"(",
"key",
")",
":",
"return",
"True",
"return",
"False"
] | Returns whether the object is in this datastore. | [
"Returns",
"whether",
"the",
"object",
"is",
"in",
"this",
"datastore",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/basic.py#L1074-L1079 | train | 24,529 |
datastore/datastore | datastore/core/basic.py | ShardedDatastore.put | def put(self, key, value):
'''Stores the object to the corresponding datastore.'''
self.shardDatastore(key).put(key, value) | python | def put(self, key, value):
'''Stores the object to the corresponding datastore.'''
self.shardDatastore(key).put(key, value) | [
"def",
"put",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"self",
".",
"shardDatastore",
"(",
"key",
")",
".",
"put",
"(",
"key",
",",
"value",
")"
] | Stores the object to the corresponding datastore. | [
"Stores",
"the",
"object",
"to",
"the",
"corresponding",
"datastore",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/basic.py#L1120-L1122 | train | 24,530 |
datastore/datastore | datastore/core/basic.py | ShardedDatastore.shard_query_generator | def shard_query_generator(self, query):
'''A generator that queries each shard in sequence.'''
shard_query = query.copy()
for shard in self._stores:
# yield all items matching within this shard
cursor = shard.query(shard_query)
for item in cursor:
yield item
# update query with results of first query
shard_query.offset = max(shard_query.offset - cursor.skipped, 0)
if shard_query.limit:
shard_query.limit = max(shard_query.limit - cursor.returned, 0)
if shard_query.limit <= 0:
break | python | def shard_query_generator(self, query):
'''A generator that queries each shard in sequence.'''
shard_query = query.copy()
for shard in self._stores:
# yield all items matching within this shard
cursor = shard.query(shard_query)
for item in cursor:
yield item
# update query with results of first query
shard_query.offset = max(shard_query.offset - cursor.skipped, 0)
if shard_query.limit:
shard_query.limit = max(shard_query.limit - cursor.returned, 0)
if shard_query.limit <= 0:
break | [
"def",
"shard_query_generator",
"(",
"self",
",",
"query",
")",
":",
"shard_query",
"=",
"query",
".",
"copy",
"(",
")",
"for",
"shard",
"in",
"self",
".",
"_stores",
":",
"# yield all items matching within this shard",
"cursor",
"=",
"shard",
".",
"query",
"(... | A generator that queries each shard in sequence. | [
"A",
"generator",
"that",
"queries",
"each",
"shard",
"in",
"sequence",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/basic.py#L1138-L1154 | train | 24,531 |
datastore/datastore | datastore/core/serialize.py | monkey_patch_bson | def monkey_patch_bson(bson=None):
'''Patch bson in pymongo to use loads and dumps interface.'''
if not bson:
import bson
if not hasattr(bson, 'loads'):
bson.loads = lambda bsondoc: bson.BSON(bsondoc).decode()
if not hasattr(bson, 'dumps'):
bson.dumps = lambda document: bson.BSON.encode(document) | python | def monkey_patch_bson(bson=None):
'''Patch bson in pymongo to use loads and dumps interface.'''
if not bson:
import bson
if not hasattr(bson, 'loads'):
bson.loads = lambda bsondoc: bson.BSON(bsondoc).decode()
if not hasattr(bson, 'dumps'):
bson.dumps = lambda document: bson.BSON.encode(document) | [
"def",
"monkey_patch_bson",
"(",
"bson",
"=",
"None",
")",
":",
"if",
"not",
"bson",
":",
"import",
"bson",
"if",
"not",
"hasattr",
"(",
"bson",
",",
"'loads'",
")",
":",
"bson",
".",
"loads",
"=",
"lambda",
"bsondoc",
":",
"bson",
".",
"BSON",
"(",
... | Patch bson in pymongo to use loads and dumps interface. | [
"Patch",
"bson",
"in",
"pymongo",
"to",
"use",
"loads",
"and",
"dumps",
"interface",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/serialize.py#L112-L121 | train | 24,532 |
datastore/datastore | datastore/core/serialize.py | Stack.loads | def loads(self, value):
'''Returns deserialized `value`.'''
for serializer in reversed(self):
value = serializer.loads(value)
return value | python | def loads(self, value):
'''Returns deserialized `value`.'''
for serializer in reversed(self):
value = serializer.loads(value)
return value | [
"def",
"loads",
"(",
"self",
",",
"value",
")",
":",
"for",
"serializer",
"in",
"reversed",
"(",
"self",
")",
":",
"value",
"=",
"serializer",
".",
"loads",
"(",
"value",
")",
"return",
"value"
] | Returns deserialized `value`. | [
"Returns",
"deserialized",
"value",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/serialize.py#L64-L68 | train | 24,533 |
datastore/datastore | datastore/core/serialize.py | Stack.dumps | def dumps(self, value):
'''returns serialized `value`.'''
for serializer in self:
value = serializer.dumps(value)
return value | python | def dumps(self, value):
'''returns serialized `value`.'''
for serializer in self:
value = serializer.dumps(value)
return value | [
"def",
"dumps",
"(",
"self",
",",
"value",
")",
":",
"for",
"serializer",
"in",
"self",
":",
"value",
"=",
"serializer",
".",
"dumps",
"(",
"value",
")",
"return",
"value"
] | returns serialized `value`. | [
"returns",
"serialized",
"value",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/serialize.py#L70-L74 | train | 24,534 |
datastore/datastore | datastore/core/serialize.py | map_serializer.loads | def loads(cls, value):
'''Returns mapping type deserialized `value`.'''
if len(value) == 1 and cls.sentinel in value:
value = value[cls.sentinel]
return value | python | def loads(cls, value):
'''Returns mapping type deserialized `value`.'''
if len(value) == 1 and cls.sentinel in value:
value = value[cls.sentinel]
return value | [
"def",
"loads",
"(",
"cls",
",",
"value",
")",
":",
"if",
"len",
"(",
"value",
")",
"==",
"1",
"and",
"cls",
".",
"sentinel",
"in",
"value",
":",
"value",
"=",
"value",
"[",
"cls",
".",
"sentinel",
"]",
"return",
"value"
] | Returns mapping type deserialized `value`. | [
"Returns",
"mapping",
"type",
"deserialized",
"value",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/serialize.py#L84-L88 | train | 24,535 |
datastore/datastore | datastore/core/serialize.py | map_serializer.dumps | def dumps(cls, value):
'''returns mapping typed serialized `value`.'''
if not hasattr(value, '__getitem__') or not hasattr(value, 'iteritems'):
value = {cls.sentinel: value}
return value | python | def dumps(cls, value):
'''returns mapping typed serialized `value`.'''
if not hasattr(value, '__getitem__') or not hasattr(value, 'iteritems'):
value = {cls.sentinel: value}
return value | [
"def",
"dumps",
"(",
"cls",
",",
"value",
")",
":",
"if",
"not",
"hasattr",
"(",
"value",
",",
"'__getitem__'",
")",
"or",
"not",
"hasattr",
"(",
"value",
",",
"'iteritems'",
")",
":",
"value",
"=",
"{",
"cls",
".",
"sentinel",
":",
"value",
"}",
"... | returns mapping typed serialized `value`. | [
"returns",
"mapping",
"typed",
"serialized",
"value",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/serialize.py#L91-L95 | train | 24,536 |
datastore/datastore | datastore/core/serialize.py | SerializerShimDatastore.get | def get(self, key):
'''Return the object named by key or None if it does not exist.
Retrieves the value from the ``child_datastore``, and de-serializes
it on the way out.
Args:
key: Key naming the object to retrieve
Returns:
object or None
'''
''''''
value = self.child_datastore.get(key)
return self.deserializedValue(value) | python | def get(self, key):
'''Return the object named by key or None if it does not exist.
Retrieves the value from the ``child_datastore``, and de-serializes
it on the way out.
Args:
key: Key naming the object to retrieve
Returns:
object or None
'''
''''''
value = self.child_datastore.get(key)
return self.deserializedValue(value) | [
"def",
"get",
"(",
"self",
",",
"key",
")",
":",
"''''''",
"value",
"=",
"self",
".",
"child_datastore",
".",
"get",
"(",
"key",
")",
"return",
"self",
".",
"deserializedValue",
"(",
"value",
")"
] | Return the object named by key or None if it does not exist.
Retrieves the value from the ``child_datastore``, and de-serializes
it on the way out.
Args:
key: Key naming the object to retrieve
Returns:
object or None | [
"Return",
"the",
"object",
"named",
"by",
"key",
"or",
"None",
"if",
"it",
"does",
"not",
"exist",
".",
"Retrieves",
"the",
"value",
"from",
"the",
"child_datastore",
"and",
"de",
"-",
"serializes",
"it",
"on",
"the",
"way",
"out",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/serialize.py#L172-L186 | train | 24,537 |
datastore/datastore | datastore/core/serialize.py | SerializerShimDatastore.put | def put(self, key, value):
'''Stores the object `value` named by `key`.
Serializes values on the way in, and stores the serialized data into the
``child_datastore``.
Args:
key: Key naming `value`
value: the object to store.
'''
value = self.serializedValue(value)
self.child_datastore.put(key, value) | python | def put(self, key, value):
'''Stores the object `value` named by `key`.
Serializes values on the way in, and stores the serialized data into the
``child_datastore``.
Args:
key: Key naming `value`
value: the object to store.
'''
value = self.serializedValue(value)
self.child_datastore.put(key, value) | [
"def",
"put",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"value",
"=",
"self",
".",
"serializedValue",
"(",
"value",
")",
"self",
".",
"child_datastore",
".",
"put",
"(",
"key",
",",
"value",
")"
] | Stores the object `value` named by `key`.
Serializes values on the way in, and stores the serialized data into the
``child_datastore``.
Args:
key: Key naming `value`
value: the object to store. | [
"Stores",
"the",
"object",
"value",
"named",
"by",
"key",
".",
"Serializes",
"values",
"on",
"the",
"way",
"in",
"and",
"stores",
"the",
"serialized",
"data",
"into",
"the",
"child_datastore",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/serialize.py#L188-L199 | train | 24,538 |
datastore/datastore | datastore/core/query.py | _object_getattr | def _object_getattr(obj, field):
'''Attribute getter for the objects to operate on.
This function can be overridden in classes or instances of Query, Filter, and
Order. Thus, a custom function to extract values to attributes can be
specified, and the system can remain agnostic to the client's data model,
without loosing query power.
For example, the default implementation works with attributes and items::
def _object_getattr(obj, field):
# check whether this key is an attribute
if hasattr(obj, field):
value = getattr(obj, field)
# if not, perhaps it is an item (raw dicts, etc)
elif field in obj:
value = obj[field]
# return whatever we've got.
return value
Or consider a more complex, application-specific structure::
def _object_getattr(version, field):
if field in ['key', 'committed', 'created', 'hash']:
return getattr(version, field)
else:
return version.attributes[field]['value']
'''
# TODO: consider changing this to raise an exception if no value is found.
value = None
# check whether this key is an attribute
if hasattr(obj, field):
value = getattr(obj, field)
# if not, perhaps it is an item (raw dicts, etc)
elif field in obj:
value = obj[field]
# return whatever we've got.
return value | python | def _object_getattr(obj, field):
'''Attribute getter for the objects to operate on.
This function can be overridden in classes or instances of Query, Filter, and
Order. Thus, a custom function to extract values to attributes can be
specified, and the system can remain agnostic to the client's data model,
without loosing query power.
For example, the default implementation works with attributes and items::
def _object_getattr(obj, field):
# check whether this key is an attribute
if hasattr(obj, field):
value = getattr(obj, field)
# if not, perhaps it is an item (raw dicts, etc)
elif field in obj:
value = obj[field]
# return whatever we've got.
return value
Or consider a more complex, application-specific structure::
def _object_getattr(version, field):
if field in ['key', 'committed', 'created', 'hash']:
return getattr(version, field)
else:
return version.attributes[field]['value']
'''
# TODO: consider changing this to raise an exception if no value is found.
value = None
# check whether this key is an attribute
if hasattr(obj, field):
value = getattr(obj, field)
# if not, perhaps it is an item (raw dicts, etc)
elif field in obj:
value = obj[field]
# return whatever we've got.
return value | [
"def",
"_object_getattr",
"(",
"obj",
",",
"field",
")",
":",
"# TODO: consider changing this to raise an exception if no value is found.",
"value",
"=",
"None",
"# check whether this key is an attribute",
"if",
"hasattr",
"(",
"obj",
",",
"field",
")",
":",
"value",
"=",... | Attribute getter for the objects to operate on.
This function can be overridden in classes or instances of Query, Filter, and
Order. Thus, a custom function to extract values to attributes can be
specified, and the system can remain agnostic to the client's data model,
without loosing query power.
For example, the default implementation works with attributes and items::
def _object_getattr(obj, field):
# check whether this key is an attribute
if hasattr(obj, field):
value = getattr(obj, field)
# if not, perhaps it is an item (raw dicts, etc)
elif field in obj:
value = obj[field]
# return whatever we've got.
return value
Or consider a more complex, application-specific structure::
def _object_getattr(version, field):
if field in ['key', 'committed', 'created', 'hash']:
return getattr(version, field)
else:
return version.attributes[field]['value'] | [
"Attribute",
"getter",
"for",
"the",
"objects",
"to",
"operate",
"on",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/query.py#L5-L52 | train | 24,539 |
datastore/datastore | datastore/core/query.py | limit_gen | def limit_gen(limit, iterable):
'''A generator that applies a count `limit`.'''
limit = int(limit)
assert limit >= 0, 'negative limit'
for item in iterable:
if limit <= 0:
break
yield item
limit -= 1 | python | def limit_gen(limit, iterable):
'''A generator that applies a count `limit`.'''
limit = int(limit)
assert limit >= 0, 'negative limit'
for item in iterable:
if limit <= 0:
break
yield item
limit -= 1 | [
"def",
"limit_gen",
"(",
"limit",
",",
"iterable",
")",
":",
"limit",
"=",
"int",
"(",
"limit",
")",
"assert",
"limit",
">=",
"0",
",",
"'negative limit'",
"for",
"item",
"in",
"iterable",
":",
"if",
"limit",
"<=",
"0",
":",
"break",
"yield",
"item",
... | A generator that applies a count `limit`. | [
"A",
"generator",
"that",
"applies",
"a",
"count",
"limit",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/query.py#L57-L66 | train | 24,540 |
datastore/datastore | datastore/core/query.py | offset_gen | def offset_gen(offset, iterable, skip_signal=None):
'''A generator that applies an `offset`, skipping `offset` elements from
`iterable`. If skip_signal is a callable, it will be called with every
skipped element.
'''
offset = int(offset)
assert offset >= 0, 'negative offset'
for item in iterable:
if offset > 0:
offset -= 1
if callable(skip_signal):
skip_signal(item)
else:
yield item | python | def offset_gen(offset, iterable, skip_signal=None):
'''A generator that applies an `offset`, skipping `offset` elements from
`iterable`. If skip_signal is a callable, it will be called with every
skipped element.
'''
offset = int(offset)
assert offset >= 0, 'negative offset'
for item in iterable:
if offset > 0:
offset -= 1
if callable(skip_signal):
skip_signal(item)
else:
yield item | [
"def",
"offset_gen",
"(",
"offset",
",",
"iterable",
",",
"skip_signal",
"=",
"None",
")",
":",
"offset",
"=",
"int",
"(",
"offset",
")",
"assert",
"offset",
">=",
"0",
",",
"'negative offset'",
"for",
"item",
"in",
"iterable",
":",
"if",
"offset",
">",
... | A generator that applies an `offset`, skipping `offset` elements from
`iterable`. If skip_signal is a callable, it will be called with every
skipped element. | [
"A",
"generator",
"that",
"applies",
"an",
"offset",
"skipping",
"offset",
"elements",
"from",
"iterable",
".",
"If",
"skip_signal",
"is",
"a",
"callable",
"it",
"will",
"be",
"called",
"with",
"every",
"skipped",
"element",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/query.py#L69-L83 | train | 24,541 |
datastore/datastore | datastore/core/query.py | Filter.valuePasses | def valuePasses(self, value):
'''Returns whether this value passes this filter'''
return self._conditional_cmp[self.op](value, self.value) | python | def valuePasses(self, value):
'''Returns whether this value passes this filter'''
return self._conditional_cmp[self.op](value, self.value) | [
"def",
"valuePasses",
"(",
"self",
",",
"value",
")",
":",
"return",
"self",
".",
"_conditional_cmp",
"[",
"self",
".",
"op",
"]",
"(",
"value",
",",
"self",
".",
"value",
")"
] | Returns whether this value passes this filter | [
"Returns",
"whether",
"this",
"value",
"passes",
"this",
"filter"
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/query.py#L154-L156 | train | 24,542 |
datastore/datastore | datastore/core/query.py | Filter.filter | def filter(cls, filters, iterable):
'''Returns the elements in `iterable` that pass given `filters`'''
if isinstance(filters, Filter):
filters = [filters]
for filter in filters:
iterable = filter.generator(iterable)
return iterable | python | def filter(cls, filters, iterable):
'''Returns the elements in `iterable` that pass given `filters`'''
if isinstance(filters, Filter):
filters = [filters]
for filter in filters:
iterable = filter.generator(iterable)
return iterable | [
"def",
"filter",
"(",
"cls",
",",
"filters",
",",
"iterable",
")",
":",
"if",
"isinstance",
"(",
"filters",
",",
"Filter",
")",
":",
"filters",
"=",
"[",
"filters",
"]",
"for",
"filter",
"in",
"filters",
":",
"iterable",
"=",
"filter",
".",
"generator"... | Returns the elements in `iterable` that pass given `filters` | [
"Returns",
"the",
"elements",
"in",
"iterable",
"that",
"pass",
"given",
"filters"
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/query.py#L182-L190 | train | 24,543 |
datastore/datastore | datastore/core/query.py | Order.multipleOrderComparison | def multipleOrderComparison(cls, orders):
'''Returns a function that will compare two items according to `orders`'''
comparers = [ (o.keyfn, 1 if o.isAscending() else -1) for o in orders]
def cmpfn(a, b):
for keyfn, ascOrDesc in comparers:
comparison = cmp(keyfn(a), keyfn(b)) * ascOrDesc
if comparison is not 0:
return comparison
return 0
return cmpfn | python | def multipleOrderComparison(cls, orders):
'''Returns a function that will compare two items according to `orders`'''
comparers = [ (o.keyfn, 1 if o.isAscending() else -1) for o in orders]
def cmpfn(a, b):
for keyfn, ascOrDesc in comparers:
comparison = cmp(keyfn(a), keyfn(b)) * ascOrDesc
if comparison is not 0:
return comparison
return 0
return cmpfn | [
"def",
"multipleOrderComparison",
"(",
"cls",
",",
"orders",
")",
":",
"comparers",
"=",
"[",
"(",
"o",
".",
"keyfn",
",",
"1",
"if",
"o",
".",
"isAscending",
"(",
")",
"else",
"-",
"1",
")",
"for",
"o",
"in",
"orders",
"]",
"def",
"cmpfn",
"(",
... | Returns a function that will compare two items according to `orders` | [
"Returns",
"a",
"function",
"that",
"will",
"compare",
"two",
"items",
"according",
"to",
"orders"
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/query.py#L267-L278 | train | 24,544 |
datastore/datastore | datastore/core/query.py | Order.sorted | def sorted(cls, items, orders):
'''Returns the elements in `items` sorted according to `orders`'''
return sorted(items, cmp=cls.multipleOrderComparison(orders)) | python | def sorted(cls, items, orders):
'''Returns the elements in `items` sorted according to `orders`'''
return sorted(items, cmp=cls.multipleOrderComparison(orders)) | [
"def",
"sorted",
"(",
"cls",
",",
"items",
",",
"orders",
")",
":",
"return",
"sorted",
"(",
"items",
",",
"cmp",
"=",
"cls",
".",
"multipleOrderComparison",
"(",
"orders",
")",
")"
] | Returns the elements in `items` sorted according to `orders` | [
"Returns",
"the",
"elements",
"in",
"items",
"sorted",
"according",
"to",
"orders"
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/query.py#L281-L283 | train | 24,545 |
datastore/datastore | datastore/core/query.py | Query.order | def order(self, order):
'''Adds an Order to this query.
Args:
see :py:class:`Order <datastore.query.Order>` constructor
Returns self for JS-like method chaining::
query.order('+age').order('-home')
'''
order = order if isinstance(order, Order) else Order(order)
# ensure order gets attr values the same way the rest of the query does.
order.object_getattr = self.object_getattr
self.orders.append(order)
return self | python | def order(self, order):
'''Adds an Order to this query.
Args:
see :py:class:`Order <datastore.query.Order>` constructor
Returns self for JS-like method chaining::
query.order('+age').order('-home')
'''
order = order if isinstance(order, Order) else Order(order)
# ensure order gets attr values the same way the rest of the query does.
order.object_getattr = self.object_getattr
self.orders.append(order)
return self | [
"def",
"order",
"(",
"self",
",",
"order",
")",
":",
"order",
"=",
"order",
"if",
"isinstance",
"(",
"order",
",",
"Order",
")",
"else",
"Order",
"(",
"order",
")",
"# ensure order gets attr values the same way the rest of the query does.",
"order",
".",
"object_g... | Adds an Order to this query.
Args:
see :py:class:`Order <datastore.query.Order>` constructor
Returns self for JS-like method chaining::
query.order('+age').order('-home') | [
"Adds",
"an",
"Order",
"to",
"this",
"query",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/query.py#L365-L381 | train | 24,546 |
datastore/datastore | datastore/core/query.py | Query.filter | def filter(self, *args):
'''Adds a Filter to this query.
Args:
see :py:class:`Filter <datastore.query.Filter>` constructor
Returns self for JS-like method chaining::
query.filter('age', '>', 18).filter('sex', '=', 'Female')
'''
if len(args) == 1 and isinstance(args[0], Filter):
filter = args[0]
else:
filter = Filter(*args)
# ensure filter gets attr values the same way the rest of the query does.
filter.object_getattr = self.object_getattr
self.filters.append(filter)
return self | python | def filter(self, *args):
'''Adds a Filter to this query.
Args:
see :py:class:`Filter <datastore.query.Filter>` constructor
Returns self for JS-like method chaining::
query.filter('age', '>', 18).filter('sex', '=', 'Female')
'''
if len(args) == 1 and isinstance(args[0], Filter):
filter = args[0]
else:
filter = Filter(*args)
# ensure filter gets attr values the same way the rest of the query does.
filter.object_getattr = self.object_getattr
self.filters.append(filter)
return self | [
"def",
"filter",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"1",
"and",
"isinstance",
"(",
"args",
"[",
"0",
"]",
",",
"Filter",
")",
":",
"filter",
"=",
"args",
"[",
"0",
"]",
"else",
":",
"filter",
"=",
"F... | Adds a Filter to this query.
Args:
see :py:class:`Filter <datastore.query.Filter>` constructor
Returns self for JS-like method chaining::
query.filter('age', '>', 18).filter('sex', '=', 'Female') | [
"Adds",
"a",
"Filter",
"to",
"this",
"query",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/query.py#L384-L403 | train | 24,547 |
datastore/datastore | datastore/core/query.py | Query.copy | def copy(self):
'''Returns a copy of this query.'''
if self.object_getattr is Query.object_getattr:
other = Query(self.key)
else:
other = Query(self.key, object_getattr=self.object_getattr)
other.limit = self.limit
other.offset = self.offset
other.offset_key = self.offset_key
other.filters = self.filters
other.orders = self.orders
return other | python | def copy(self):
'''Returns a copy of this query.'''
if self.object_getattr is Query.object_getattr:
other = Query(self.key)
else:
other = Query(self.key, object_getattr=self.object_getattr)
other.limit = self.limit
other.offset = self.offset
other.offset_key = self.offset_key
other.filters = self.filters
other.orders = self.orders
return other | [
"def",
"copy",
"(",
"self",
")",
":",
"if",
"self",
".",
"object_getattr",
"is",
"Query",
".",
"object_getattr",
":",
"other",
"=",
"Query",
"(",
"self",
".",
"key",
")",
"else",
":",
"other",
"=",
"Query",
"(",
"self",
".",
"key",
",",
"object_getat... | Returns a copy of this query. | [
"Returns",
"a",
"copy",
"of",
"this",
"query",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/query.py#L412-L423 | train | 24,548 |
datastore/datastore | datastore/core/query.py | Query.dict | def dict(self):
'''Returns a dictionary representing this query.'''
d = dict()
d['key'] = str(self.key)
if self.limit is not None:
d['limit'] = self.limit
if self.offset > 0:
d['offset'] = self.offset
if self.offset_key:
d['offset_key'] = str(self.offset_key)
if len(self.filters) > 0:
d['filter'] = [[f.field, f.op, f.value] for f in self.filters]
if len(self.orders) > 0:
d['order'] = [str(o) for o in self.orders]
return d | python | def dict(self):
'''Returns a dictionary representing this query.'''
d = dict()
d['key'] = str(self.key)
if self.limit is not None:
d['limit'] = self.limit
if self.offset > 0:
d['offset'] = self.offset
if self.offset_key:
d['offset_key'] = str(self.offset_key)
if len(self.filters) > 0:
d['filter'] = [[f.field, f.op, f.value] for f in self.filters]
if len(self.orders) > 0:
d['order'] = [str(o) for o in self.orders]
return d | [
"def",
"dict",
"(",
"self",
")",
":",
"d",
"=",
"dict",
"(",
")",
"d",
"[",
"'key'",
"]",
"=",
"str",
"(",
"self",
".",
"key",
")",
"if",
"self",
".",
"limit",
"is",
"not",
"None",
":",
"d",
"[",
"'limit'",
"]",
"=",
"self",
".",
"limit",
"... | Returns a dictionary representing this query. | [
"Returns",
"a",
"dictionary",
"representing",
"this",
"query",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/query.py#L425-L441 | train | 24,549 |
datastore/datastore | datastore/core/query.py | Query.from_dict | def from_dict(cls, dictionary):
'''Constructs a query from a dictionary.'''
query = cls(Key(dictionary['key']))
for key, value in dictionary.items():
if key == 'order':
for order in value:
query.order(order)
elif key == 'filter':
for filter in value:
if not isinstance(filter, Filter):
filter = Filter(*filter)
query.filter(filter)
elif key in ['limit', 'offset', 'offset_key']:
setattr(query, key, value)
return query | python | def from_dict(cls, dictionary):
'''Constructs a query from a dictionary.'''
query = cls(Key(dictionary['key']))
for key, value in dictionary.items():
if key == 'order':
for order in value:
query.order(order)
elif key == 'filter':
for filter in value:
if not isinstance(filter, Filter):
filter = Filter(*filter)
query.filter(filter)
elif key in ['limit', 'offset', 'offset_key']:
setattr(query, key, value)
return query | [
"def",
"from_dict",
"(",
"cls",
",",
"dictionary",
")",
":",
"query",
"=",
"cls",
"(",
"Key",
"(",
"dictionary",
"[",
"'key'",
"]",
")",
")",
"for",
"key",
",",
"value",
"in",
"dictionary",
".",
"items",
"(",
")",
":",
"if",
"key",
"==",
"'order'",... | Constructs a query from a dictionary. | [
"Constructs",
"a",
"query",
"from",
"a",
"dictionary",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/query.py#L444-L462 | train | 24,550 |
datastore/datastore | datastore/core/query.py | Cursor.next | def next(self):
'''Iterator next. Build up count of returned elements during iteration.'''
# if iteration has not begun, begin it.
if not self._iterator:
self.__iter__()
next = self._iterator.next()
if next is not StopIteration:
self._returned_inc(next)
return next | python | def next(self):
'''Iterator next. Build up count of returned elements during iteration.'''
# if iteration has not begun, begin it.
if not self._iterator:
self.__iter__()
next = self._iterator.next()
if next is not StopIteration:
self._returned_inc(next)
return next | [
"def",
"next",
"(",
"self",
")",
":",
"# if iteration has not begun, begin it.",
"if",
"not",
"self",
".",
"_iterator",
":",
"self",
".",
"__iter__",
"(",
")",
"next",
"=",
"self",
".",
"_iterator",
".",
"next",
"(",
")",
"if",
"next",
"is",
"not",
"Stop... | Iterator next. Build up count of returned elements during iteration. | [
"Iterator",
"next",
".",
"Build",
"up",
"count",
"of",
"returned",
"elements",
"during",
"iteration",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/query.py#L499-L509 | train | 24,551 |
datastore/datastore | datastore/core/query.py | Cursor.apply_filter | def apply_filter(self):
'''Naively apply query filters.'''
self._ensure_modification_is_safe()
if len(self.query.filters) > 0:
self._iterable = Filter.filter(self.query.filters, self._iterable) | python | def apply_filter(self):
'''Naively apply query filters.'''
self._ensure_modification_is_safe()
if len(self.query.filters) > 0:
self._iterable = Filter.filter(self.query.filters, self._iterable) | [
"def",
"apply_filter",
"(",
"self",
")",
":",
"self",
".",
"_ensure_modification_is_safe",
"(",
")",
"if",
"len",
"(",
"self",
".",
"query",
".",
"filters",
")",
">",
"0",
":",
"self",
".",
"_iterable",
"=",
"Filter",
".",
"filter",
"(",
"self",
".",
... | Naively apply query filters. | [
"Naively",
"apply",
"query",
"filters",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/query.py#L528-L533 | train | 24,552 |
datastore/datastore | datastore/core/query.py | Cursor.apply_order | def apply_order(self):
'''Naively apply query orders.'''
self._ensure_modification_is_safe()
if len(self.query.orders) > 0:
self._iterable = Order.sorted(self._iterable, self.query.orders) | python | def apply_order(self):
'''Naively apply query orders.'''
self._ensure_modification_is_safe()
if len(self.query.orders) > 0:
self._iterable = Order.sorted(self._iterable, self.query.orders) | [
"def",
"apply_order",
"(",
"self",
")",
":",
"self",
".",
"_ensure_modification_is_safe",
"(",
")",
"if",
"len",
"(",
"self",
".",
"query",
".",
"orders",
")",
">",
"0",
":",
"self",
".",
"_iterable",
"=",
"Order",
".",
"sorted",
"(",
"self",
".",
"_... | Naively apply query orders. | [
"Naively",
"apply",
"query",
"orders",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/query.py#L535-L540 | train | 24,553 |
datastore/datastore | datastore/core/query.py | Cursor.apply_offset | def apply_offset(self):
'''Naively apply query offset.'''
self._ensure_modification_is_safe()
if self.query.offset != 0:
self._iterable = \
offset_gen(self.query.offset, self._iterable, self._skipped_inc) | python | def apply_offset(self):
'''Naively apply query offset.'''
self._ensure_modification_is_safe()
if self.query.offset != 0:
self._iterable = \
offset_gen(self.query.offset, self._iterable, self._skipped_inc) | [
"def",
"apply_offset",
"(",
"self",
")",
":",
"self",
".",
"_ensure_modification_is_safe",
"(",
")",
"if",
"self",
".",
"query",
".",
"offset",
"!=",
"0",
":",
"self",
".",
"_iterable",
"=",
"offset_gen",
"(",
"self",
".",
"query",
".",
"offset",
",",
... | Naively apply query offset. | [
"Naively",
"apply",
"query",
"offset",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/query.py#L543-L549 | train | 24,554 |
datastore/datastore | datastore/core/query.py | Cursor.apply_limit | def apply_limit(self):
'''Naively apply query limit.'''
self._ensure_modification_is_safe()
if self.query.limit is not None:
self._iterable = limit_gen(self.query.limit, self._iterable) | python | def apply_limit(self):
'''Naively apply query limit.'''
self._ensure_modification_is_safe()
if self.query.limit is not None:
self._iterable = limit_gen(self.query.limit, self._iterable) | [
"def",
"apply_limit",
"(",
"self",
")",
":",
"self",
".",
"_ensure_modification_is_safe",
"(",
")",
"if",
"self",
".",
"query",
".",
"limit",
"is",
"not",
"None",
":",
"self",
".",
"_iterable",
"=",
"limit_gen",
"(",
"self",
".",
"query",
".",
"limit",
... | Naively apply query limit. | [
"Naively",
"apply",
"query",
"limit",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/query.py#L552-L557 | train | 24,555 |
cockroachdb/cockroachdb-python | cockroachdb/sqlalchemy/transaction.py | run_transaction | def run_transaction(transactor, callback):
"""Run a transaction with retries.
``callback()`` will be called with one argument to execute the
transaction. ``callback`` may be called more than once; it should have
no side effects other than writes to the database on the given
connection. ``callback`` should not call ``commit()` or ``rollback()``;
these will be called automatically.
The ``transactor`` argument may be one of the following types:
* `sqlalchemy.engine.Connection`: the same connection is passed to the callback.
* `sqlalchemy.engine.Engine`: a connection is created and passed to the callback.
* `sqlalchemy.orm.sessionmaker`: a session is created and passed to the callback.
"""
if isinstance(transactor, sqlalchemy.engine.Connection):
return _txn_retry_loop(transactor, callback)
elif isinstance(transactor, sqlalchemy.engine.Engine):
with transactor.connect() as connection:
return _txn_retry_loop(connection, callback)
elif isinstance(transactor, sqlalchemy.orm.sessionmaker):
session = transactor(autocommit=True)
return _txn_retry_loop(session, callback)
else:
raise TypeError("don't know how to run a transaction on %s", type(transactor)) | python | def run_transaction(transactor, callback):
"""Run a transaction with retries.
``callback()`` will be called with one argument to execute the
transaction. ``callback`` may be called more than once; it should have
no side effects other than writes to the database on the given
connection. ``callback`` should not call ``commit()` or ``rollback()``;
these will be called automatically.
The ``transactor`` argument may be one of the following types:
* `sqlalchemy.engine.Connection`: the same connection is passed to the callback.
* `sqlalchemy.engine.Engine`: a connection is created and passed to the callback.
* `sqlalchemy.orm.sessionmaker`: a session is created and passed to the callback.
"""
if isinstance(transactor, sqlalchemy.engine.Connection):
return _txn_retry_loop(transactor, callback)
elif isinstance(transactor, sqlalchemy.engine.Engine):
with transactor.connect() as connection:
return _txn_retry_loop(connection, callback)
elif isinstance(transactor, sqlalchemy.orm.sessionmaker):
session = transactor(autocommit=True)
return _txn_retry_loop(session, callback)
else:
raise TypeError("don't know how to run a transaction on %s", type(transactor)) | [
"def",
"run_transaction",
"(",
"transactor",
",",
"callback",
")",
":",
"if",
"isinstance",
"(",
"transactor",
",",
"sqlalchemy",
".",
"engine",
".",
"Connection",
")",
":",
"return",
"_txn_retry_loop",
"(",
"transactor",
",",
"callback",
")",
"elif",
"isinsta... | Run a transaction with retries.
``callback()`` will be called with one argument to execute the
transaction. ``callback`` may be called more than once; it should have
no side effects other than writes to the database on the given
connection. ``callback`` should not call ``commit()` or ``rollback()``;
these will be called automatically.
The ``transactor`` argument may be one of the following types:
* `sqlalchemy.engine.Connection`: the same connection is passed to the callback.
* `sqlalchemy.engine.Engine`: a connection is created and passed to the callback.
* `sqlalchemy.orm.sessionmaker`: a session is created and passed to the callback. | [
"Run",
"a",
"transaction",
"with",
"retries",
"."
] | 5a23e5fb4dc4386828fd147155becba58f0a7c4f | https://github.com/cockroachdb/cockroachdb-python/blob/5a23e5fb4dc4386828fd147155becba58f0a7c4f/cockroachdb/sqlalchemy/transaction.py#L10-L33 | train | 24,556 |
cockroachdb/cockroachdb-python | cockroachdb/sqlalchemy/transaction.py | _txn_retry_loop | def _txn_retry_loop(conn, callback):
"""Inner transaction retry loop.
``conn`` may be either a Connection or a Session, but they both
have compatible ``begin()`` and ``begin_nested()`` methods.
"""
with conn.begin():
while True:
try:
with _NestedTransaction(conn):
ret = callback(conn)
return ret
except sqlalchemy.exc.DatabaseError as e:
if isinstance(e.orig, psycopg2.OperationalError):
if e.orig.pgcode == psycopg2.errorcodes.SERIALIZATION_FAILURE:
continue
raise | python | def _txn_retry_loop(conn, callback):
"""Inner transaction retry loop.
``conn`` may be either a Connection or a Session, but they both
have compatible ``begin()`` and ``begin_nested()`` methods.
"""
with conn.begin():
while True:
try:
with _NestedTransaction(conn):
ret = callback(conn)
return ret
except sqlalchemy.exc.DatabaseError as e:
if isinstance(e.orig, psycopg2.OperationalError):
if e.orig.pgcode == psycopg2.errorcodes.SERIALIZATION_FAILURE:
continue
raise | [
"def",
"_txn_retry_loop",
"(",
"conn",
",",
"callback",
")",
":",
"with",
"conn",
".",
"begin",
"(",
")",
":",
"while",
"True",
":",
"try",
":",
"with",
"_NestedTransaction",
"(",
"conn",
")",
":",
"ret",
"=",
"callback",
"(",
"conn",
")",
"return",
... | Inner transaction retry loop.
``conn`` may be either a Connection or a Session, but they both
have compatible ``begin()`` and ``begin_nested()`` methods. | [
"Inner",
"transaction",
"retry",
"loop",
"."
] | 5a23e5fb4dc4386828fd147155becba58f0a7c4f | https://github.com/cockroachdb/cockroachdb-python/blob/5a23e5fb4dc4386828fd147155becba58f0a7c4f/cockroachdb/sqlalchemy/transaction.py#L65-L81 | train | 24,557 |
pazz/urwidtrees | urwidtrees/tree.py | Tree._get | def _get(self, pos):
"""loads widget at given position; handling invalid arguments"""
res = None, None
if pos is not None:
try:
res = self[pos], pos
except (IndexError, KeyError):
pass
return res | python | def _get(self, pos):
"""loads widget at given position; handling invalid arguments"""
res = None, None
if pos is not None:
try:
res = self[pos], pos
except (IndexError, KeyError):
pass
return res | [
"def",
"_get",
"(",
"self",
",",
"pos",
")",
":",
"res",
"=",
"None",
",",
"None",
"if",
"pos",
"is",
"not",
"None",
":",
"try",
":",
"res",
"=",
"self",
"[",
"pos",
"]",
",",
"pos",
"except",
"(",
"IndexError",
",",
"KeyError",
")",
":",
"pass... | loads widget at given position; handling invalid arguments | [
"loads",
"widget",
"at",
"given",
"position",
";",
"handling",
"invalid",
"arguments"
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/tree.py#L32-L40 | train | 24,558 |
pazz/urwidtrees | urwidtrees/tree.py | Tree._next_of_kin | def _next_of_kin(self, pos):
"""
looks up the next sibling of the closest ancestor with not-None next
siblings.
"""
candidate = None
parent = self.parent_position(pos)
if parent is not None:
candidate = self.next_sibling_position(parent)
if candidate is None:
candidate = self._next_of_kin(parent)
return candidate | python | def _next_of_kin(self, pos):
"""
looks up the next sibling of the closest ancestor with not-None next
siblings.
"""
candidate = None
parent = self.parent_position(pos)
if parent is not None:
candidate = self.next_sibling_position(parent)
if candidate is None:
candidate = self._next_of_kin(parent)
return candidate | [
"def",
"_next_of_kin",
"(",
"self",
",",
"pos",
")",
":",
"candidate",
"=",
"None",
"parent",
"=",
"self",
".",
"parent_position",
"(",
"pos",
")",
"if",
"parent",
"is",
"not",
"None",
":",
"candidate",
"=",
"self",
".",
"next_sibling_position",
"(",
"pa... | looks up the next sibling of the closest ancestor with not-None next
siblings. | [
"looks",
"up",
"the",
"next",
"sibling",
"of",
"the",
"closest",
"ancestor",
"with",
"not",
"-",
"None",
"next",
"siblings",
"."
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/tree.py#L42-L53 | train | 24,559 |
pazz/urwidtrees | urwidtrees/tree.py | Tree._last_in_direction | def _last_in_direction(starting_pos, direction):
"""
move in the tree in given direction and return the last position.
:param starting_pos: position to start at
:param direction: callable that transforms a position into a position.
"""
cur_pos = None
next_pos = starting_pos
while next_pos is not None:
cur_pos = next_pos
next_pos = direction(cur_pos)
return cur_pos | python | def _last_in_direction(starting_pos, direction):
"""
move in the tree in given direction and return the last position.
:param starting_pos: position to start at
:param direction: callable that transforms a position into a position.
"""
cur_pos = None
next_pos = starting_pos
while next_pos is not None:
cur_pos = next_pos
next_pos = direction(cur_pos)
return cur_pos | [
"def",
"_last_in_direction",
"(",
"starting_pos",
",",
"direction",
")",
":",
"cur_pos",
"=",
"None",
"next_pos",
"=",
"starting_pos",
"while",
"next_pos",
"is",
"not",
"None",
":",
"cur_pos",
"=",
"next_pos",
"next_pos",
"=",
"direction",
"(",
"cur_pos",
")",... | move in the tree in given direction and return the last position.
:param starting_pos: position to start at
:param direction: callable that transforms a position into a position. | [
"move",
"in",
"the",
"tree",
"in",
"given",
"direction",
"and",
"return",
"the",
"last",
"position",
"."
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/tree.py#L56-L68 | train | 24,560 |
pazz/urwidtrees | urwidtrees/tree.py | Tree.depth | def depth(self, pos):
"""determine depth of node at pos"""
parent = self.parent_position(pos)
if parent is None:
return 0
else:
return self.depth(parent) + 1 | python | def depth(self, pos):
"""determine depth of node at pos"""
parent = self.parent_position(pos)
if parent is None:
return 0
else:
return self.depth(parent) + 1 | [
"def",
"depth",
"(",
"self",
",",
"pos",
")",
":",
"parent",
"=",
"self",
".",
"parent_position",
"(",
"pos",
")",
"if",
"parent",
"is",
"None",
":",
"return",
"0",
"else",
":",
"return",
"self",
".",
"depth",
"(",
"parent",
")",
"+",
"1"
] | determine depth of node at pos | [
"determine",
"depth",
"of",
"node",
"at",
"pos"
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/tree.py#L70-L76 | train | 24,561 |
pazz/urwidtrees | urwidtrees/tree.py | Tree.next_position | def next_position(self, pos):
"""returns the next position in depth-first order"""
candidate = None
if pos is not None:
candidate = self.first_child_position(pos)
if candidate is None:
candidate = self.next_sibling_position(pos)
if candidate is None:
candidate = self._next_of_kin(pos)
return candidate | python | def next_position(self, pos):
"""returns the next position in depth-first order"""
candidate = None
if pos is not None:
candidate = self.first_child_position(pos)
if candidate is None:
candidate = self.next_sibling_position(pos)
if candidate is None:
candidate = self._next_of_kin(pos)
return candidate | [
"def",
"next_position",
"(",
"self",
",",
"pos",
")",
":",
"candidate",
"=",
"None",
"if",
"pos",
"is",
"not",
"None",
":",
"candidate",
"=",
"self",
".",
"first_child_position",
"(",
"pos",
")",
"if",
"candidate",
"is",
"None",
":",
"candidate",
"=",
... | returns the next position in depth-first order | [
"returns",
"the",
"next",
"position",
"in",
"depth",
"-",
"first",
"order"
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/tree.py#L102-L111 | train | 24,562 |
pazz/urwidtrees | urwidtrees/tree.py | Tree.prev_position | def prev_position(self, pos):
"""returns the previous position in depth-first order"""
candidate = None
if pos is not None:
prevsib = self.prev_sibling_position(pos) # is None if first
if prevsib is not None:
candidate = self.last_decendant(prevsib)
else:
parent = self.parent_position(pos)
if parent is not None:
candidate = parent
return candidate | python | def prev_position(self, pos):
"""returns the previous position in depth-first order"""
candidate = None
if pos is not None:
prevsib = self.prev_sibling_position(pos) # is None if first
if prevsib is not None:
candidate = self.last_decendant(prevsib)
else:
parent = self.parent_position(pos)
if parent is not None:
candidate = parent
return candidate | [
"def",
"prev_position",
"(",
"self",
",",
"pos",
")",
":",
"candidate",
"=",
"None",
"if",
"pos",
"is",
"not",
"None",
":",
"prevsib",
"=",
"self",
".",
"prev_sibling_position",
"(",
"pos",
")",
"# is None if first",
"if",
"prevsib",
"is",
"not",
"None",
... | returns the previous position in depth-first order | [
"returns",
"the",
"previous",
"position",
"in",
"depth",
"-",
"first",
"order"
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/tree.py#L113-L124 | train | 24,563 |
pazz/urwidtrees | urwidtrees/tree.py | Tree.positions | def positions(self, reverse=False):
"""returns a generator that walks the positions of this tree in DFO"""
def Posgen(reverse):
if reverse:
lastrootsib = self.last_sibling_position(self.root)
current = self.last_decendant(lastrootsib)
while current is not None:
yield current
current = self.prev_position(current)
else:
current = self.root
while current is not None:
yield current
current = self.next_position(current)
return Posgen(reverse) | python | def positions(self, reverse=False):
"""returns a generator that walks the positions of this tree in DFO"""
def Posgen(reverse):
if reverse:
lastrootsib = self.last_sibling_position(self.root)
current = self.last_decendant(lastrootsib)
while current is not None:
yield current
current = self.prev_position(current)
else:
current = self.root
while current is not None:
yield current
current = self.next_position(current)
return Posgen(reverse) | [
"def",
"positions",
"(",
"self",
",",
"reverse",
"=",
"False",
")",
":",
"def",
"Posgen",
"(",
"reverse",
")",
":",
"if",
"reverse",
":",
"lastrootsib",
"=",
"self",
".",
"last_sibling_position",
"(",
"self",
".",
"root",
")",
"current",
"=",
"self",
"... | returns a generator that walks the positions of this tree in DFO | [
"returns",
"a",
"generator",
"that",
"walks",
"the",
"positions",
"of",
"this",
"tree",
"in",
"DFO"
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/tree.py#L126-L140 | train | 24,564 |
pazz/urwidtrees | urwidtrees/tree.py | SimpleTree._get_substructure | def _get_substructure(self, treelist, pos):
"""recursive helper to look up node-tuple for `pos` in `treelist`"""
subtree = None
if len(pos) > 1:
subtree = self._get_substructure(treelist[pos[0]][1], pos[1:])
else:
try:
subtree = treelist[pos[0]]
except (IndexError, TypeError):
pass
return subtree | python | def _get_substructure(self, treelist, pos):
"""recursive helper to look up node-tuple for `pos` in `treelist`"""
subtree = None
if len(pos) > 1:
subtree = self._get_substructure(treelist[pos[0]][1], pos[1:])
else:
try:
subtree = treelist[pos[0]]
except (IndexError, TypeError):
pass
return subtree | [
"def",
"_get_substructure",
"(",
"self",
",",
"treelist",
",",
"pos",
")",
":",
"subtree",
"=",
"None",
"if",
"len",
"(",
"pos",
")",
">",
"1",
":",
"subtree",
"=",
"self",
".",
"_get_substructure",
"(",
"treelist",
"[",
"pos",
"[",
"0",
"]",
"]",
... | recursive helper to look up node-tuple for `pos` in `treelist` | [
"recursive",
"helper",
"to",
"look",
"up",
"node",
"-",
"tuple",
"for",
"pos",
"in",
"treelist"
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/tree.py#L188-L198 | train | 24,565 |
pazz/urwidtrees | urwidtrees/tree.py | SimpleTree._get_node | def _get_node(self, treelist, pos):
"""
look up widget at `pos` of `treelist`; default to None if
nonexistent.
"""
node = None
if pos is not None:
subtree = self._get_substructure(treelist, pos)
if subtree is not None:
node = subtree[0]
return node | python | def _get_node(self, treelist, pos):
"""
look up widget at `pos` of `treelist`; default to None if
nonexistent.
"""
node = None
if pos is not None:
subtree = self._get_substructure(treelist, pos)
if subtree is not None:
node = subtree[0]
return node | [
"def",
"_get_node",
"(",
"self",
",",
"treelist",
",",
"pos",
")",
":",
"node",
"=",
"None",
"if",
"pos",
"is",
"not",
"None",
":",
"subtree",
"=",
"self",
".",
"_get_substructure",
"(",
"treelist",
",",
"pos",
")",
"if",
"subtree",
"is",
"not",
"Non... | look up widget at `pos` of `treelist`; default to None if
nonexistent. | [
"look",
"up",
"widget",
"at",
"pos",
"of",
"treelist",
";",
"default",
"to",
"None",
"if",
"nonexistent",
"."
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/tree.py#L200-L210 | train | 24,566 |
pazz/urwidtrees | urwidtrees/tree.py | SimpleTree._confirm_pos | def _confirm_pos(self, pos):
"""look up widget for pos and default to None"""
candidate = None
if self._get_node(self._treelist, pos) is not None:
candidate = pos
return candidate | python | def _confirm_pos(self, pos):
"""look up widget for pos and default to None"""
candidate = None
if self._get_node(self._treelist, pos) is not None:
candidate = pos
return candidate | [
"def",
"_confirm_pos",
"(",
"self",
",",
"pos",
")",
":",
"candidate",
"=",
"None",
"if",
"self",
".",
"_get_node",
"(",
"self",
".",
"_treelist",
",",
"pos",
")",
"is",
"not",
"None",
":",
"candidate",
"=",
"pos",
"return",
"candidate"
] | look up widget for pos and default to None | [
"look",
"up",
"widget",
"for",
"pos",
"and",
"default",
"to",
"None"
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/tree.py#L212-L217 | train | 24,567 |
pazz/urwidtrees | docs/examples/example4.filesystem.py | DirectoryTree._list_dir | def _list_dir(self, path):
"""returns absolute paths for all entries in a directory"""
try:
elements = [
os.path.join(path, x) for x in os.listdir(path)
] if os.path.isdir(path) else []
elements.sort()
except OSError:
elements = None
return elements | python | def _list_dir(self, path):
"""returns absolute paths for all entries in a directory"""
try:
elements = [
os.path.join(path, x) for x in os.listdir(path)
] if os.path.isdir(path) else []
elements.sort()
except OSError:
elements = None
return elements | [
"def",
"_list_dir",
"(",
"self",
",",
"path",
")",
":",
"try",
":",
"elements",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"x",
")",
"for",
"x",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
"]",
"if",
"os",
".",
"path",
".",... | returns absolute paths for all entries in a directory | [
"returns",
"absolute",
"paths",
"for",
"all",
"entries",
"in",
"a",
"directory"
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/docs/examples/example4.filesystem.py#L50-L59 | train | 24,568 |
pazz/urwidtrees | docs/examples/example4.filesystem.py | DirectoryTree._get_siblings | def _get_siblings(self, pos):
"""lists the parent directory of pos """
parent = self.parent_position(pos)
siblings = [pos]
if parent is not None:
siblings = self._list_dir(parent)
return siblings | python | def _get_siblings(self, pos):
"""lists the parent directory of pos """
parent = self.parent_position(pos)
siblings = [pos]
if parent is not None:
siblings = self._list_dir(parent)
return siblings | [
"def",
"_get_siblings",
"(",
"self",
",",
"pos",
")",
":",
"parent",
"=",
"self",
".",
"parent_position",
"(",
"pos",
")",
"siblings",
"=",
"[",
"pos",
"]",
"if",
"parent",
"is",
"not",
"None",
":",
"siblings",
"=",
"self",
".",
"_list_dir",
"(",
"pa... | lists the parent directory of pos | [
"lists",
"the",
"parent",
"directory",
"of",
"pos"
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/docs/examples/example4.filesystem.py#L61-L67 | train | 24,569 |
incuna/django-orderable | orderable/admin.py | OrderableAdmin.reorder_view | def reorder_view(self, request):
"""The 'reorder' admin view for this model."""
model = self.model
if not self.has_change_permission(request):
raise PermissionDenied
if request.method == "POST":
object_pks = request.POST.getlist('neworder[]')
model.objects.set_orders(object_pks)
return HttpResponse("OK") | python | def reorder_view(self, request):
"""The 'reorder' admin view for this model."""
model = self.model
if not self.has_change_permission(request):
raise PermissionDenied
if request.method == "POST":
object_pks = request.POST.getlist('neworder[]')
model.objects.set_orders(object_pks)
return HttpResponse("OK") | [
"def",
"reorder_view",
"(",
"self",
",",
"request",
")",
":",
"model",
"=",
"self",
".",
"model",
"if",
"not",
"self",
".",
"has_change_permission",
"(",
"request",
")",
":",
"raise",
"PermissionDenied",
"if",
"request",
".",
"method",
"==",
"\"POST\"",
":... | The 'reorder' admin view for this model. | [
"The",
"reorder",
"admin",
"view",
"for",
"this",
"model",
"."
] | 88da9c762ef0500725f95988c8f18d9b304e6951 | https://github.com/incuna/django-orderable/blob/88da9c762ef0500725f95988c8f18d9b304e6951/orderable/admin.py#L50-L61 | train | 24,570 |
pazz/urwidtrees | urwidtrees/decoration.py | CollapseMixin.is_collapsed | def is_collapsed(self, pos):
"""checks if given position is currently collapsed"""
collapsed = self._initially_collapsed(pos)
if pos in self._divergent_positions:
collapsed = not collapsed
return collapsed | python | def is_collapsed(self, pos):
"""checks if given position is currently collapsed"""
collapsed = self._initially_collapsed(pos)
if pos in self._divergent_positions:
collapsed = not collapsed
return collapsed | [
"def",
"is_collapsed",
"(",
"self",
",",
"pos",
")",
":",
"collapsed",
"=",
"self",
".",
"_initially_collapsed",
"(",
"pos",
")",
"if",
"pos",
"in",
"self",
".",
"_divergent_positions",
":",
"collapsed",
"=",
"not",
"collapsed",
"return",
"collapsed"
] | checks if given position is currently collapsed | [
"checks",
"if",
"given",
"position",
"is",
"currently",
"collapsed"
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/decoration.py#L76-L81 | train | 24,571 |
pazz/urwidtrees | urwidtrees/decoration.py | ArrowTree._construct_spacer | def _construct_spacer(self, pos, acc):
"""
build a spacer that occupies the horizontally indented space between
pos's parent and the root node. It will return a list of tuples to be
fed into a Columns widget.
"""
parent = self._tree.parent_position(pos)
if parent is not None:
grandparent = self._tree.parent_position(parent)
if self._indent > 0 and grandparent is not None:
parent_sib = self._tree.next_sibling_position(parent)
draw_vbar = parent_sib is not None and \
self._arrow_vbar_char is not None
space_width = self._indent - 1 * (draw_vbar) - self._childbar_offset
if space_width > 0:
void = urwid.AttrMap(urwid.SolidFill(' '), self._arrow_att)
acc.insert(0, ((space_width, void)))
if draw_vbar:
barw = urwid.SolidFill(self._arrow_vbar_char)
bar = urwid.AttrMap(barw, self._arrow_vbar_att or
self._arrow_att)
acc.insert(0, ((1, bar)))
return self._construct_spacer(parent, acc)
else:
return acc | python | def _construct_spacer(self, pos, acc):
"""
build a spacer that occupies the horizontally indented space between
pos's parent and the root node. It will return a list of tuples to be
fed into a Columns widget.
"""
parent = self._tree.parent_position(pos)
if parent is not None:
grandparent = self._tree.parent_position(parent)
if self._indent > 0 and grandparent is not None:
parent_sib = self._tree.next_sibling_position(parent)
draw_vbar = parent_sib is not None and \
self._arrow_vbar_char is not None
space_width = self._indent - 1 * (draw_vbar) - self._childbar_offset
if space_width > 0:
void = urwid.AttrMap(urwid.SolidFill(' '), self._arrow_att)
acc.insert(0, ((space_width, void)))
if draw_vbar:
barw = urwid.SolidFill(self._arrow_vbar_char)
bar = urwid.AttrMap(barw, self._arrow_vbar_att or
self._arrow_att)
acc.insert(0, ((1, bar)))
return self._construct_spacer(parent, acc)
else:
return acc | [
"def",
"_construct_spacer",
"(",
"self",
",",
"pos",
",",
"acc",
")",
":",
"parent",
"=",
"self",
".",
"_tree",
".",
"parent_position",
"(",
"pos",
")",
"if",
"parent",
"is",
"not",
"None",
":",
"grandparent",
"=",
"self",
".",
"_tree",
".",
"parent_po... | build a spacer that occupies the horizontally indented space between
pos's parent and the root node. It will return a list of tuples to be
fed into a Columns widget. | [
"build",
"a",
"spacer",
"that",
"occupies",
"the",
"horizontally",
"indented",
"space",
"between",
"pos",
"s",
"parent",
"and",
"the",
"root",
"node",
".",
"It",
"will",
"return",
"a",
"list",
"of",
"tuples",
"to",
"be",
"fed",
"into",
"a",
"Columns",
"w... | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/decoration.py#L329-L353 | train | 24,572 |
pazz/urwidtrees | urwidtrees/decoration.py | ArrowTree._construct_connector | def _construct_connector(self, pos):
"""
build widget to be used as "connector" bit between the vertical bar
between siblings and their respective horizontal bars leading to the
arrow tip
"""
# connector symbol, either L or |- shaped.
connectorw = None
connector = None
if self._tree.next_sibling_position(pos) is not None: # |- shaped
if self._arrow_connector_tchar is not None:
connectorw = urwid.Text(self._arrow_connector_tchar)
else: # L shaped
if self._arrow_connector_lchar is not None:
connectorw = urwid.Text(self._arrow_connector_lchar)
if connectorw is not None:
att = self._arrow_connector_att or self._arrow_att
connector = urwid.AttrMap(connectorw, att)
return connector | python | def _construct_connector(self, pos):
"""
build widget to be used as "connector" bit between the vertical bar
between siblings and their respective horizontal bars leading to the
arrow tip
"""
# connector symbol, either L or |- shaped.
connectorw = None
connector = None
if self._tree.next_sibling_position(pos) is not None: # |- shaped
if self._arrow_connector_tchar is not None:
connectorw = urwid.Text(self._arrow_connector_tchar)
else: # L shaped
if self._arrow_connector_lchar is not None:
connectorw = urwid.Text(self._arrow_connector_lchar)
if connectorw is not None:
att = self._arrow_connector_att or self._arrow_att
connector = urwid.AttrMap(connectorw, att)
return connector | [
"def",
"_construct_connector",
"(",
"self",
",",
"pos",
")",
":",
"# connector symbol, either L or |- shaped.",
"connectorw",
"=",
"None",
"connector",
"=",
"None",
"if",
"self",
".",
"_tree",
".",
"next_sibling_position",
"(",
"pos",
")",
"is",
"not",
"None",
"... | build widget to be used as "connector" bit between the vertical bar
between siblings and their respective horizontal bars leading to the
arrow tip | [
"build",
"widget",
"to",
"be",
"used",
"as",
"connector",
"bit",
"between",
"the",
"vertical",
"bar",
"between",
"siblings",
"and",
"their",
"respective",
"horizontal",
"bars",
"leading",
"to",
"the",
"arrow",
"tip"
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/decoration.py#L355-L373 | train | 24,573 |
pazz/urwidtrees | urwidtrees/decoration.py | ArrowTree._construct_first_indent | def _construct_first_indent(self, pos):
"""
build spacer to occupy the first indentation level from pos to the
left. This is separate as it adds arrowtip and sibling connector.
"""
cols = []
void = urwid.AttrMap(urwid.SolidFill(' '), self._arrow_att)
available_width = self._indent
if self._tree.depth(pos) > 0:
connector = self._construct_connector(pos)
if connector is not None:
width = connector.pack()[0]
if width > available_width:
raise NoSpaceError()
available_width -= width
if self._tree.next_sibling_position(pos) is not None:
barw = urwid.SolidFill(self._arrow_vbar_char)
below = urwid.AttrMap(barw, self._arrow_vbar_att or
self._arrow_att)
else:
below = void
# pile up connector and bar
spacer = urwid.Pile([('pack', connector), below])
cols.append((width, spacer))
#arrow tip
awidth, at = self._construct_arrow_tip(pos)
if at is not None:
if awidth > available_width:
raise NoSpaceError()
available_width -= awidth
at_spacer = urwid.Pile([('pack', at), void])
cols.append((awidth, at_spacer))
# bar between connector and arrow tip
if available_width > 0:
barw = urwid.SolidFill(self._arrow_hbar_char)
bar = urwid.AttrMap(
barw, self._arrow_hbar_att or self._arrow_att)
hb_spacer = urwid.Pile([(1, bar), void])
cols.insert(1, (available_width, hb_spacer))
return cols | python | def _construct_first_indent(self, pos):
"""
build spacer to occupy the first indentation level from pos to the
left. This is separate as it adds arrowtip and sibling connector.
"""
cols = []
void = urwid.AttrMap(urwid.SolidFill(' '), self._arrow_att)
available_width = self._indent
if self._tree.depth(pos) > 0:
connector = self._construct_connector(pos)
if connector is not None:
width = connector.pack()[0]
if width > available_width:
raise NoSpaceError()
available_width -= width
if self._tree.next_sibling_position(pos) is not None:
barw = urwid.SolidFill(self._arrow_vbar_char)
below = urwid.AttrMap(barw, self._arrow_vbar_att or
self._arrow_att)
else:
below = void
# pile up connector and bar
spacer = urwid.Pile([('pack', connector), below])
cols.append((width, spacer))
#arrow tip
awidth, at = self._construct_arrow_tip(pos)
if at is not None:
if awidth > available_width:
raise NoSpaceError()
available_width -= awidth
at_spacer = urwid.Pile([('pack', at), void])
cols.append((awidth, at_spacer))
# bar between connector and arrow tip
if available_width > 0:
barw = urwid.SolidFill(self._arrow_hbar_char)
bar = urwid.AttrMap(
barw, self._arrow_hbar_att or self._arrow_att)
hb_spacer = urwid.Pile([(1, bar), void])
cols.insert(1, (available_width, hb_spacer))
return cols | [
"def",
"_construct_first_indent",
"(",
"self",
",",
"pos",
")",
":",
"cols",
"=",
"[",
"]",
"void",
"=",
"urwid",
".",
"AttrMap",
"(",
"urwid",
".",
"SolidFill",
"(",
"' '",
")",
",",
"self",
".",
"_arrow_att",
")",
"available_width",
"=",
"self",
".",... | build spacer to occupy the first indentation level from pos to the
left. This is separate as it adds arrowtip and sibling connector. | [
"build",
"spacer",
"to",
"occupy",
"the",
"first",
"indentation",
"level",
"from",
"pos",
"to",
"the",
"left",
".",
"This",
"is",
"separate",
"as",
"it",
"adds",
"arrowtip",
"and",
"sibling",
"connector",
"."
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/decoration.py#L386-L428 | train | 24,574 |
pazz/urwidtrees | urwidtrees/widgets.py | TreeBox.collapse_focussed | def collapse_focussed(self):
"""
Collapse currently focussed position; works only if the underlying
tree allows it.
"""
if implementsCollapseAPI(self._tree):
w, focuspos = self.get_focus()
self._tree.collapse(focuspos)
self._walker.clear_cache()
self.refresh() | python | def collapse_focussed(self):
"""
Collapse currently focussed position; works only if the underlying
tree allows it.
"""
if implementsCollapseAPI(self._tree):
w, focuspos = self.get_focus()
self._tree.collapse(focuspos)
self._walker.clear_cache()
self.refresh() | [
"def",
"collapse_focussed",
"(",
"self",
")",
":",
"if",
"implementsCollapseAPI",
"(",
"self",
".",
"_tree",
")",
":",
"w",
",",
"focuspos",
"=",
"self",
".",
"get_focus",
"(",
")",
"self",
".",
"_tree",
".",
"collapse",
"(",
"focuspos",
")",
"self",
"... | Collapse currently focussed position; works only if the underlying
tree allows it. | [
"Collapse",
"currently",
"focussed",
"position",
";",
"works",
"only",
"if",
"the",
"underlying",
"tree",
"allows",
"it",
"."
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/widgets.py#L156-L165 | train | 24,575 |
pazz/urwidtrees | urwidtrees/widgets.py | TreeBox.expand_focussed | def expand_focussed(self):
"""
Expand currently focussed position; works only if the underlying
tree allows it.
"""
if implementsCollapseAPI(self._tree):
w, focuspos = self.get_focus()
self._tree.expand(focuspos)
self._walker.clear_cache()
self.refresh() | python | def expand_focussed(self):
"""
Expand currently focussed position; works only if the underlying
tree allows it.
"""
if implementsCollapseAPI(self._tree):
w, focuspos = self.get_focus()
self._tree.expand(focuspos)
self._walker.clear_cache()
self.refresh() | [
"def",
"expand_focussed",
"(",
"self",
")",
":",
"if",
"implementsCollapseAPI",
"(",
"self",
".",
"_tree",
")",
":",
"w",
",",
"focuspos",
"=",
"self",
".",
"get_focus",
"(",
")",
"self",
".",
"_tree",
".",
"expand",
"(",
"focuspos",
")",
"self",
".",
... | Expand currently focussed position; works only if the underlying
tree allows it. | [
"Expand",
"currently",
"focussed",
"position",
";",
"works",
"only",
"if",
"the",
"underlying",
"tree",
"allows",
"it",
"."
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/widgets.py#L167-L176 | train | 24,576 |
pazz/urwidtrees | urwidtrees/widgets.py | TreeBox.collapse_all | def collapse_all(self):
"""
Collapse all positions; works only if the underlying tree allows it.
"""
if implementsCollapseAPI(self._tree):
self._tree.collapse_all()
self.set_focus(self._tree.root)
self._walker.clear_cache()
self.refresh() | python | def collapse_all(self):
"""
Collapse all positions; works only if the underlying tree allows it.
"""
if implementsCollapseAPI(self._tree):
self._tree.collapse_all()
self.set_focus(self._tree.root)
self._walker.clear_cache()
self.refresh() | [
"def",
"collapse_all",
"(",
"self",
")",
":",
"if",
"implementsCollapseAPI",
"(",
"self",
".",
"_tree",
")",
":",
"self",
".",
"_tree",
".",
"collapse_all",
"(",
")",
"self",
".",
"set_focus",
"(",
"self",
".",
"_tree",
".",
"root",
")",
"self",
".",
... | Collapse all positions; works only if the underlying tree allows it. | [
"Collapse",
"all",
"positions",
";",
"works",
"only",
"if",
"the",
"underlying",
"tree",
"allows",
"it",
"."
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/widgets.py#L178-L186 | train | 24,577 |
pazz/urwidtrees | urwidtrees/widgets.py | TreeBox.expand_all | def expand_all(self):
"""
Expand all positions; works only if the underlying tree allows it.
"""
if implementsCollapseAPI(self._tree):
self._tree.expand_all()
self._walker.clear_cache()
self.refresh() | python | def expand_all(self):
"""
Expand all positions; works only if the underlying tree allows it.
"""
if implementsCollapseAPI(self._tree):
self._tree.expand_all()
self._walker.clear_cache()
self.refresh() | [
"def",
"expand_all",
"(",
"self",
")",
":",
"if",
"implementsCollapseAPI",
"(",
"self",
".",
"_tree",
")",
":",
"self",
".",
"_tree",
".",
"expand_all",
"(",
")",
"self",
".",
"_walker",
".",
"clear_cache",
"(",
")",
"self",
".",
"refresh",
"(",
")"
] | Expand all positions; works only if the underlying tree allows it. | [
"Expand",
"all",
"positions",
";",
"works",
"only",
"if",
"the",
"underlying",
"tree",
"allows",
"it",
"."
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/widgets.py#L188-L195 | train | 24,578 |
pazz/urwidtrees | urwidtrees/widgets.py | TreeBox.focus_parent | def focus_parent(self):
"""move focus to parent node of currently focussed one"""
w, focuspos = self.get_focus()
parent = self._tree.parent_position(focuspos)
if parent is not None:
self.set_focus(parent) | python | def focus_parent(self):
"""move focus to parent node of currently focussed one"""
w, focuspos = self.get_focus()
parent = self._tree.parent_position(focuspos)
if parent is not None:
self.set_focus(parent) | [
"def",
"focus_parent",
"(",
"self",
")",
":",
"w",
",",
"focuspos",
"=",
"self",
".",
"get_focus",
"(",
")",
"parent",
"=",
"self",
".",
"_tree",
".",
"parent_position",
"(",
"focuspos",
")",
"if",
"parent",
"is",
"not",
"None",
":",
"self",
".",
"se... | move focus to parent node of currently focussed one | [
"move",
"focus",
"to",
"parent",
"node",
"of",
"currently",
"focussed",
"one"
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/widgets.py#L198-L203 | train | 24,579 |
pazz/urwidtrees | urwidtrees/widgets.py | TreeBox.focus_first_child | def focus_first_child(self):
"""move focus to first child of currently focussed one"""
w, focuspos = self.get_focus()
child = self._tree.first_child_position(focuspos)
if child is not None:
self.set_focus(child) | python | def focus_first_child(self):
"""move focus to first child of currently focussed one"""
w, focuspos = self.get_focus()
child = self._tree.first_child_position(focuspos)
if child is not None:
self.set_focus(child) | [
"def",
"focus_first_child",
"(",
"self",
")",
":",
"w",
",",
"focuspos",
"=",
"self",
".",
"get_focus",
"(",
")",
"child",
"=",
"self",
".",
"_tree",
".",
"first_child_position",
"(",
"focuspos",
")",
"if",
"child",
"is",
"not",
"None",
":",
"self",
".... | move focus to first child of currently focussed one | [
"move",
"focus",
"to",
"first",
"child",
"of",
"currently",
"focussed",
"one"
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/widgets.py#L205-L210 | train | 24,580 |
pazz/urwidtrees | urwidtrees/widgets.py | TreeBox.focus_last_child | def focus_last_child(self):
"""move focus to last child of currently focussed one"""
w, focuspos = self.get_focus()
child = self._tree.last_child_position(focuspos)
if child is not None:
self.set_focus(child) | python | def focus_last_child(self):
"""move focus to last child of currently focussed one"""
w, focuspos = self.get_focus()
child = self._tree.last_child_position(focuspos)
if child is not None:
self.set_focus(child) | [
"def",
"focus_last_child",
"(",
"self",
")",
":",
"w",
",",
"focuspos",
"=",
"self",
".",
"get_focus",
"(",
")",
"child",
"=",
"self",
".",
"_tree",
".",
"last_child_position",
"(",
"focuspos",
")",
"if",
"child",
"is",
"not",
"None",
":",
"self",
".",... | move focus to last child of currently focussed one | [
"move",
"focus",
"to",
"last",
"child",
"of",
"currently",
"focussed",
"one"
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/widgets.py#L212-L217 | train | 24,581 |
pazz/urwidtrees | urwidtrees/widgets.py | TreeBox.focus_next_sibling | def focus_next_sibling(self):
"""move focus to next sibling of currently focussed one"""
w, focuspos = self.get_focus()
sib = self._tree.next_sibling_position(focuspos)
if sib is not None:
self.set_focus(sib) | python | def focus_next_sibling(self):
"""move focus to next sibling of currently focussed one"""
w, focuspos = self.get_focus()
sib = self._tree.next_sibling_position(focuspos)
if sib is not None:
self.set_focus(sib) | [
"def",
"focus_next_sibling",
"(",
"self",
")",
":",
"w",
",",
"focuspos",
"=",
"self",
".",
"get_focus",
"(",
")",
"sib",
"=",
"self",
".",
"_tree",
".",
"next_sibling_position",
"(",
"focuspos",
")",
"if",
"sib",
"is",
"not",
"None",
":",
"self",
".",... | move focus to next sibling of currently focussed one | [
"move",
"focus",
"to",
"next",
"sibling",
"of",
"currently",
"focussed",
"one"
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/widgets.py#L219-L224 | train | 24,582 |
pazz/urwidtrees | urwidtrees/widgets.py | TreeBox.focus_prev_sibling | def focus_prev_sibling(self):
"""move focus to previous sibling of currently focussed one"""
w, focuspos = self.get_focus()
sib = self._tree.prev_sibling_position(focuspos)
if sib is not None:
self.set_focus(sib) | python | def focus_prev_sibling(self):
"""move focus to previous sibling of currently focussed one"""
w, focuspos = self.get_focus()
sib = self._tree.prev_sibling_position(focuspos)
if sib is not None:
self.set_focus(sib) | [
"def",
"focus_prev_sibling",
"(",
"self",
")",
":",
"w",
",",
"focuspos",
"=",
"self",
".",
"get_focus",
"(",
")",
"sib",
"=",
"self",
".",
"_tree",
".",
"prev_sibling_position",
"(",
"focuspos",
")",
"if",
"sib",
"is",
"not",
"None",
":",
"self",
".",... | move focus to previous sibling of currently focussed one | [
"move",
"focus",
"to",
"previous",
"sibling",
"of",
"currently",
"focussed",
"one"
] | d1fa38ce4f37db00bdfc574b856023b5db4c7ead | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/urwidtrees/widgets.py#L226-L231 | train | 24,583 |
incuna/django-orderable | orderable/models.py | Orderable.get_unique_fields | def get_unique_fields(self):
"""List field names that are unique_together with `sort_order`."""
for unique_together in self._meta.unique_together:
if 'sort_order' in unique_together:
unique_fields = list(unique_together)
unique_fields.remove('sort_order')
return ['%s_id' % f for f in unique_fields]
return [] | python | def get_unique_fields(self):
"""List field names that are unique_together with `sort_order`."""
for unique_together in self._meta.unique_together:
if 'sort_order' in unique_together:
unique_fields = list(unique_together)
unique_fields.remove('sort_order')
return ['%s_id' % f for f in unique_fields]
return [] | [
"def",
"get_unique_fields",
"(",
"self",
")",
":",
"for",
"unique_together",
"in",
"self",
".",
"_meta",
".",
"unique_together",
":",
"if",
"'sort_order'",
"in",
"unique_together",
":",
"unique_fields",
"=",
"list",
"(",
"unique_together",
")",
"unique_fields",
... | List field names that are unique_together with `sort_order`. | [
"List",
"field",
"names",
"that",
"are",
"unique_together",
"with",
"sort_order",
"."
] | 88da9c762ef0500725f95988c8f18d9b304e6951 | https://github.com/incuna/django-orderable/blob/88da9c762ef0500725f95988c8f18d9b304e6951/orderable/models.py#L29-L36 | train | 24,584 |
incuna/django-orderable | orderable/models.py | Orderable._is_sort_order_unique_together_with_something | def _is_sort_order_unique_together_with_something(self):
"""
Is the sort_order field unique_together with something
"""
unique_together = self._meta.unique_together
for fields in unique_together:
if 'sort_order' in fields and len(fields) > 1:
return True
return False | python | def _is_sort_order_unique_together_with_something(self):
"""
Is the sort_order field unique_together with something
"""
unique_together = self._meta.unique_together
for fields in unique_together:
if 'sort_order' in fields and len(fields) > 1:
return True
return False | [
"def",
"_is_sort_order_unique_together_with_something",
"(",
"self",
")",
":",
"unique_together",
"=",
"self",
".",
"_meta",
".",
"unique_together",
"for",
"fields",
"in",
"unique_together",
":",
"if",
"'sort_order'",
"in",
"fields",
"and",
"len",
"(",
"fields",
"... | Is the sort_order field unique_together with something | [
"Is",
"the",
"sort_order",
"field",
"unique_together",
"with",
"something"
] | 88da9c762ef0500725f95988c8f18d9b304e6951 | https://github.com/incuna/django-orderable/blob/88da9c762ef0500725f95988c8f18d9b304e6951/orderable/models.py#L62-L70 | train | 24,585 |
incuna/django-orderable | orderable/models.py | Orderable._update | def _update(qs):
"""
Increment the sort_order in a queryset.
Handle IntegrityErrors caused by unique constraints.
"""
try:
with transaction.atomic():
qs.update(sort_order=models.F('sort_order') + 1)
except IntegrityError:
for obj in qs.order_by('-sort_order'):
qs.filter(pk=obj.pk).update(sort_order=models.F('sort_order') + 1) | python | def _update(qs):
"""
Increment the sort_order in a queryset.
Handle IntegrityErrors caused by unique constraints.
"""
try:
with transaction.atomic():
qs.update(sort_order=models.F('sort_order') + 1)
except IntegrityError:
for obj in qs.order_by('-sort_order'):
qs.filter(pk=obj.pk).update(sort_order=models.F('sort_order') + 1) | [
"def",
"_update",
"(",
"qs",
")",
":",
"try",
":",
"with",
"transaction",
".",
"atomic",
"(",
")",
":",
"qs",
".",
"update",
"(",
"sort_order",
"=",
"models",
".",
"F",
"(",
"'sort_order'",
")",
"+",
"1",
")",
"except",
"IntegrityError",
":",
"for",
... | Increment the sort_order in a queryset.
Handle IntegrityErrors caused by unique constraints. | [
"Increment",
"the",
"sort_order",
"in",
"a",
"queryset",
"."
] | 88da9c762ef0500725f95988c8f18d9b304e6951 | https://github.com/incuna/django-orderable/blob/88da9c762ef0500725f95988c8f18d9b304e6951/orderable/models.py#L73-L84 | train | 24,586 |
incuna/django-orderable | orderable/models.py | Orderable.save | def save(self, *args, **kwargs):
"""Keep the unique order in sync."""
objects = self.get_filtered_manager()
old_pos = getattr(self, '_original_sort_order', None)
new_pos = self.sort_order
if old_pos is None and self._unique_togethers_changed():
self.sort_order = None
new_pos = None
try:
with transaction.atomic():
self._save(objects, old_pos, new_pos)
except IntegrityError:
with transaction.atomic():
old_pos = objects.filter(pk=self.pk).values_list(
'sort_order', flat=True)[0]
self._save(objects, old_pos, new_pos)
# Call the "real" save() method.
super(Orderable, self).save(*args, **kwargs) | python | def save(self, *args, **kwargs):
"""Keep the unique order in sync."""
objects = self.get_filtered_manager()
old_pos = getattr(self, '_original_sort_order', None)
new_pos = self.sort_order
if old_pos is None and self._unique_togethers_changed():
self.sort_order = None
new_pos = None
try:
with transaction.atomic():
self._save(objects, old_pos, new_pos)
except IntegrityError:
with transaction.atomic():
old_pos = objects.filter(pk=self.pk).values_list(
'sort_order', flat=True)[0]
self._save(objects, old_pos, new_pos)
# Call the "real" save() method.
super(Orderable, self).save(*args, **kwargs) | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"objects",
"=",
"self",
".",
"get_filtered_manager",
"(",
")",
"old_pos",
"=",
"getattr",
"(",
"self",
",",
"'_original_sort_order'",
",",
"None",
")",
"new_pos",
"=",
"se... | Keep the unique order in sync. | [
"Keep",
"the",
"unique",
"order",
"in",
"sync",
"."
] | 88da9c762ef0500725f95988c8f18d9b304e6951 | https://github.com/incuna/django-orderable/blob/88da9c762ef0500725f95988c8f18d9b304e6951/orderable/models.py#L133-L153 | train | 24,587 |
incuna/django-orderable | orderable/querysets.py | OrderableQueryset.set_orders | def set_orders(self, object_pks):
"""
Perform a mass update of sort_orders across the full queryset.
Accepts a list, object_pks, of the intended order for the objects.
Works as follows:
- Compile a list of all sort orders in the queryset. Leave out anything that
isn't in the object_pks list - this deals with pagination and any
inconsistencies.
- Get the maximum among all model object sort orders. Update the queryset to add
it to all the existing sort order values. This lifts them 'out of the way' of
unique_together clashes when setting the intended sort orders.
- Set the sort order on each object. Use only sort_order values that the objects
had before calling this method, so they get rearranged in place.
Performs O(n) queries.
"""
objects_to_sort = self.filter(pk__in=object_pks)
max_value = self.model.objects.all().aggregate(
models.Max('sort_order')
)['sort_order__max']
# Call list() on the values right away, so they don't get affected by the
# update() later (since values_list() is lazy).
orders = list(objects_to_sort.values_list('sort_order', flat=True))
# Check there are no unrecognised entries in the object_pks list. If so,
# throw an error. We only have to check that they're the same length because
# orders is built using only entries in object_pks, and all the pks are unique,
# so if their lengths are the same, the elements must match up exactly.
if len(orders) != len(object_pks):
pks = set(objects_to_sort.values_list('pk', flat=True))
message = 'The following object_pks are not in this queryset: {}'.format(
[pk for pk in object_pks if pk not in pks]
)
raise TypeError(message)
with transaction.atomic():
objects_to_sort.update(sort_order=models.F('sort_order') + max_value)
for pk, order in zip(object_pks, orders):
# Use update() to save a query per item and dodge the insertion sort
# code in save().
self.filter(pk=pk).update(sort_order=order)
# Return the operated-on queryset for convenience.
return objects_to_sort | python | def set_orders(self, object_pks):
"""
Perform a mass update of sort_orders across the full queryset.
Accepts a list, object_pks, of the intended order for the objects.
Works as follows:
- Compile a list of all sort orders in the queryset. Leave out anything that
isn't in the object_pks list - this deals with pagination and any
inconsistencies.
- Get the maximum among all model object sort orders. Update the queryset to add
it to all the existing sort order values. This lifts them 'out of the way' of
unique_together clashes when setting the intended sort orders.
- Set the sort order on each object. Use only sort_order values that the objects
had before calling this method, so they get rearranged in place.
Performs O(n) queries.
"""
objects_to_sort = self.filter(pk__in=object_pks)
max_value = self.model.objects.all().aggregate(
models.Max('sort_order')
)['sort_order__max']
# Call list() on the values right away, so they don't get affected by the
# update() later (since values_list() is lazy).
orders = list(objects_to_sort.values_list('sort_order', flat=True))
# Check there are no unrecognised entries in the object_pks list. If so,
# throw an error. We only have to check that they're the same length because
# orders is built using only entries in object_pks, and all the pks are unique,
# so if their lengths are the same, the elements must match up exactly.
if len(orders) != len(object_pks):
pks = set(objects_to_sort.values_list('pk', flat=True))
message = 'The following object_pks are not in this queryset: {}'.format(
[pk for pk in object_pks if pk not in pks]
)
raise TypeError(message)
with transaction.atomic():
objects_to_sort.update(sort_order=models.F('sort_order') + max_value)
for pk, order in zip(object_pks, orders):
# Use update() to save a query per item and dodge the insertion sort
# code in save().
self.filter(pk=pk).update(sort_order=order)
# Return the operated-on queryset for convenience.
return objects_to_sort | [
"def",
"set_orders",
"(",
"self",
",",
"object_pks",
")",
":",
"objects_to_sort",
"=",
"self",
".",
"filter",
"(",
"pk__in",
"=",
"object_pks",
")",
"max_value",
"=",
"self",
".",
"model",
".",
"objects",
".",
"all",
"(",
")",
".",
"aggregate",
"(",
"m... | Perform a mass update of sort_orders across the full queryset.
Accepts a list, object_pks, of the intended order for the objects.
Works as follows:
- Compile a list of all sort orders in the queryset. Leave out anything that
isn't in the object_pks list - this deals with pagination and any
inconsistencies.
- Get the maximum among all model object sort orders. Update the queryset to add
it to all the existing sort order values. This lifts them 'out of the way' of
unique_together clashes when setting the intended sort orders.
- Set the sort order on each object. Use only sort_order values that the objects
had before calling this method, so they get rearranged in place.
Performs O(n) queries. | [
"Perform",
"a",
"mass",
"update",
"of",
"sort_orders",
"across",
"the",
"full",
"queryset",
".",
"Accepts",
"a",
"list",
"object_pks",
"of",
"the",
"intended",
"order",
"for",
"the",
"objects",
"."
] | 88da9c762ef0500725f95988c8f18d9b304e6951 | https://github.com/incuna/django-orderable/blob/88da9c762ef0500725f95988c8f18d9b304e6951/orderable/querysets.py#L18-L62 | train | 24,588 |
tatterdemalion/django-nece | nece/managers.py | TranslationQuerySet.order_by_json_path | def order_by_json_path(self, json_path, language_code=None, order='asc'):
"""
Orders a queryset by the value of the specified `json_path`.
More about the `#>>` operator and the `json_path` arg syntax:
https://www.postgresql.org/docs/current/static/functions-json.html
More about Raw SQL expressions:
https://docs.djangoproject.com/en/dev/ref/models/expressions/#raw-sql-expressions
Usage example:
MyModel.objects.language('en_us').filter(is_active=True).order_by_json_path('title')
"""
language_code = (language_code
or self._language_code
or self.get_language_key(language_code))
json_path = '{%s,%s}' % (language_code, json_path)
# Our jsonb field is named `translations`.
raw_sql_expression = RawSQL("translations#>>%s", (json_path,))
if order == 'desc':
raw_sql_expression = raw_sql_expression.desc()
return self.order_by(raw_sql_expression) | python | def order_by_json_path(self, json_path, language_code=None, order='asc'):
"""
Orders a queryset by the value of the specified `json_path`.
More about the `#>>` operator and the `json_path` arg syntax:
https://www.postgresql.org/docs/current/static/functions-json.html
More about Raw SQL expressions:
https://docs.djangoproject.com/en/dev/ref/models/expressions/#raw-sql-expressions
Usage example:
MyModel.objects.language('en_us').filter(is_active=True).order_by_json_path('title')
"""
language_code = (language_code
or self._language_code
or self.get_language_key(language_code))
json_path = '{%s,%s}' % (language_code, json_path)
# Our jsonb field is named `translations`.
raw_sql_expression = RawSQL("translations#>>%s", (json_path,))
if order == 'desc':
raw_sql_expression = raw_sql_expression.desc()
return self.order_by(raw_sql_expression) | [
"def",
"order_by_json_path",
"(",
"self",
",",
"json_path",
",",
"language_code",
"=",
"None",
",",
"order",
"=",
"'asc'",
")",
":",
"language_code",
"=",
"(",
"language_code",
"or",
"self",
".",
"_language_code",
"or",
"self",
".",
"get_language_key",
"(",
... | Orders a queryset by the value of the specified `json_path`.
More about the `#>>` operator and the `json_path` arg syntax:
https://www.postgresql.org/docs/current/static/functions-json.html
More about Raw SQL expressions:
https://docs.djangoproject.com/en/dev/ref/models/expressions/#raw-sql-expressions
Usage example:
MyModel.objects.language('en_us').filter(is_active=True).order_by_json_path('title') | [
"Orders",
"a",
"queryset",
"by",
"the",
"value",
"of",
"the",
"specified",
"json_path",
"."
] | 44a6f7a303270709b1a8877138b50ecc1e99074a | https://github.com/tatterdemalion/django-nece/blob/44a6f7a303270709b1a8877138b50ecc1e99074a/nece/managers.py#L64-L85 | train | 24,589 |
dcramer/django-ratings | djangoratings/managers.py | VoteQuerySet.delete | def delete(self, *args, **kwargs):
"""Handles updating the related `votes` and `score` fields attached to the model."""
# XXX: circular import
from fields import RatingField
qs = self.distinct().values_list('content_type', 'object_id').order_by('content_type')
to_update = []
for content_type, objects in itertools.groupby(qs, key=lambda x: x[0]):
model_class = ContentType.objects.get(pk=content_type).model_class()
if model_class:
to_update.extend(list(model_class.objects.filter(pk__in=list(objects)[0])))
retval = super(VoteQuerySet, self).delete(*args, **kwargs)
# TODO: this could be improved
for obj in to_update:
for field in getattr(obj, '_djangoratings', []):
getattr(obj, field.name)._update(commit=False)
obj.save()
return retval | python | def delete(self, *args, **kwargs):
"""Handles updating the related `votes` and `score` fields attached to the model."""
# XXX: circular import
from fields import RatingField
qs = self.distinct().values_list('content_type', 'object_id').order_by('content_type')
to_update = []
for content_type, objects in itertools.groupby(qs, key=lambda x: x[0]):
model_class = ContentType.objects.get(pk=content_type).model_class()
if model_class:
to_update.extend(list(model_class.objects.filter(pk__in=list(objects)[0])))
retval = super(VoteQuerySet, self).delete(*args, **kwargs)
# TODO: this could be improved
for obj in to_update:
for field in getattr(obj, '_djangoratings', []):
getattr(obj, field.name)._update(commit=False)
obj.save()
return retval | [
"def",
"delete",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# XXX: circular import",
"from",
"fields",
"import",
"RatingField",
"qs",
"=",
"self",
".",
"distinct",
"(",
")",
".",
"values_list",
"(",
"'content_type'",
",",
"'object_i... | Handles updating the related `votes` and `score` fields attached to the model. | [
"Handles",
"updating",
"the",
"related",
"votes",
"and",
"score",
"fields",
"attached",
"to",
"the",
"model",
"."
] | 4d00dedc920a4e32d650dc12d5f480c51fc6216c | https://github.com/dcramer/django-ratings/blob/4d00dedc920a4e32d650dc12d5f480c51fc6216c/djangoratings/managers.py#L8-L29 | train | 24,590 |
adafruit/Adafruit_CircuitPython_Motor | adafruit_motor/servo.py | _BaseServo.set_pulse_width_range | def set_pulse_width_range(self, min_pulse=750, max_pulse=2250):
"""Change min and max pulse widths."""
self._min_duty = int((min_pulse * self._pwm_out.frequency) / 1000000 * 0xffff)
max_duty = (max_pulse * self._pwm_out.frequency) / 1000000 * 0xffff
self._duty_range = int(max_duty - self._min_duty) | python | def set_pulse_width_range(self, min_pulse=750, max_pulse=2250):
"""Change min and max pulse widths."""
self._min_duty = int((min_pulse * self._pwm_out.frequency) / 1000000 * 0xffff)
max_duty = (max_pulse * self._pwm_out.frequency) / 1000000 * 0xffff
self._duty_range = int(max_duty - self._min_duty) | [
"def",
"set_pulse_width_range",
"(",
"self",
",",
"min_pulse",
"=",
"750",
",",
"max_pulse",
"=",
"2250",
")",
":",
"self",
".",
"_min_duty",
"=",
"int",
"(",
"(",
"min_pulse",
"*",
"self",
".",
"_pwm_out",
".",
"frequency",
")",
"/",
"1000000",
"*",
"... | Change min and max pulse widths. | [
"Change",
"min",
"and",
"max",
"pulse",
"widths",
"."
] | 98563ab65800aac6464f671c0d005df56ecaa6c6 | https://github.com/adafruit/Adafruit_CircuitPython_Motor/blob/98563ab65800aac6464f671c0d005df56ecaa6c6/adafruit_motor/servo.py#L47-L51 | train | 24,591 |
adafruit/Adafruit_CircuitPython_Motor | adafruit_motor/stepper.py | StepperMotor.onestep | def onestep(self, *, direction=FORWARD, style=SINGLE):
"""Performs one step of a particular style. The actual rotation amount will vary by style.
`SINGLE` and `DOUBLE` will normal cause a full step rotation. `INTERLEAVE` will normally
do a half step rotation. `MICROSTEP` will perform the smallest configured step.
When step styles are mixed, subsequent `SINGLE`, `DOUBLE` or `INTERLEAVE` steps may be
less than normal in order to align to the desired style's pattern.
:param int direction: Either `FORWARD` or `BACKWARD`
:param int style: `SINGLE`, `DOUBLE`, `INTERLEAVE`"""
# Adjust current steps based on the direction and type of step.
step_size = 0
if style == MICROSTEP:
step_size = 1
else:
half_step = self._microsteps // 2
full_step = self._microsteps
# Its possible the previous steps were MICROSTEPS so first align with the interleave
# pattern.
additional_microsteps = self._current_microstep % half_step
if additional_microsteps != 0:
# We set _current_microstep directly because our step size varies depending on the
# direction.
if direction == FORWARD:
self._current_microstep += half_step - additional_microsteps
else:
self._current_microstep -= additional_microsteps
step_size = 0
elif style == INTERLEAVE:
step_size = half_step
current_interleave = self._current_microstep // half_step
if ((style == SINGLE and current_interleave % 2 == 1) or
(style == DOUBLE and current_interleave % 2 == 0)):
step_size = half_step
elif style in (SINGLE, DOUBLE):
step_size = full_step
if direction == FORWARD:
self._current_microstep += step_size
else:
self._current_microstep -= step_size
# Now that we know our target microstep we can determine how to energize the four coils.
self._update_coils(microstepping=style == MICROSTEP)
return self._current_microstep | python | def onestep(self, *, direction=FORWARD, style=SINGLE):
"""Performs one step of a particular style. The actual rotation amount will vary by style.
`SINGLE` and `DOUBLE` will normal cause a full step rotation. `INTERLEAVE` will normally
do a half step rotation. `MICROSTEP` will perform the smallest configured step.
When step styles are mixed, subsequent `SINGLE`, `DOUBLE` or `INTERLEAVE` steps may be
less than normal in order to align to the desired style's pattern.
:param int direction: Either `FORWARD` or `BACKWARD`
:param int style: `SINGLE`, `DOUBLE`, `INTERLEAVE`"""
# Adjust current steps based on the direction and type of step.
step_size = 0
if style == MICROSTEP:
step_size = 1
else:
half_step = self._microsteps // 2
full_step = self._microsteps
# Its possible the previous steps were MICROSTEPS so first align with the interleave
# pattern.
additional_microsteps = self._current_microstep % half_step
if additional_microsteps != 0:
# We set _current_microstep directly because our step size varies depending on the
# direction.
if direction == FORWARD:
self._current_microstep += half_step - additional_microsteps
else:
self._current_microstep -= additional_microsteps
step_size = 0
elif style == INTERLEAVE:
step_size = half_step
current_interleave = self._current_microstep // half_step
if ((style == SINGLE and current_interleave % 2 == 1) or
(style == DOUBLE and current_interleave % 2 == 0)):
step_size = half_step
elif style in (SINGLE, DOUBLE):
step_size = full_step
if direction == FORWARD:
self._current_microstep += step_size
else:
self._current_microstep -= step_size
# Now that we know our target microstep we can determine how to energize the four coils.
self._update_coils(microstepping=style == MICROSTEP)
return self._current_microstep | [
"def",
"onestep",
"(",
"self",
",",
"*",
",",
"direction",
"=",
"FORWARD",
",",
"style",
"=",
"SINGLE",
")",
":",
"# Adjust current steps based on the direction and type of step.",
"step_size",
"=",
"0",
"if",
"style",
"==",
"MICROSTEP",
":",
"step_size",
"=",
"... | Performs one step of a particular style. The actual rotation amount will vary by style.
`SINGLE` and `DOUBLE` will normal cause a full step rotation. `INTERLEAVE` will normally
do a half step rotation. `MICROSTEP` will perform the smallest configured step.
When step styles are mixed, subsequent `SINGLE`, `DOUBLE` or `INTERLEAVE` steps may be
less than normal in order to align to the desired style's pattern.
:param int direction: Either `FORWARD` or `BACKWARD`
:param int style: `SINGLE`, `DOUBLE`, `INTERLEAVE` | [
"Performs",
"one",
"step",
"of",
"a",
"particular",
"style",
".",
"The",
"actual",
"rotation",
"amount",
"will",
"vary",
"by",
"style",
".",
"SINGLE",
"and",
"DOUBLE",
"will",
"normal",
"cause",
"a",
"full",
"step",
"rotation",
".",
"INTERLEAVE",
"will",
"... | 98563ab65800aac6464f671c0d005df56ecaa6c6 | https://github.com/adafruit/Adafruit_CircuitPython_Motor/blob/98563ab65800aac6464f671c0d005df56ecaa6c6/adafruit_motor/stepper.py#L116-L162 | train | 24,592 |
OCA/openupgradelib | openupgradelib/openupgrade_merge_records.py | merge_records | def merge_records(env, model_name, record_ids, target_record_id,
field_spec=None, method='orm', delete=True,
exclude_columns=None):
"""Merge several records into the target one.
NOTE: This should be executed in end migration scripts for assuring that
all the possible relations are loaded and changed. Tested on v10/v11.
:param env: Environment variable
:param model_name: Name of the model of the records to merge
:param record_ids: List of IDS of records that are going to be merged.
:param target_record_id: ID of the record where the rest records are going
to be merge in.
:param field_spec: Dictionary with field names as keys and forced operation
to perform as values. If a field is not present here, default operation
will be performed. See _adjust_merged_values_orm method doc for all the
available operators.
:param method: Specify how to perform operations. By default or specifying
'orm', operations will be performed with ORM, maybe slower, but safer, as
related and computed fields will be recomputed on changes, and all
constraints will be checked.
:param delete: If set, the source ids will be unlinked.
:exclude_columns: list of tuples (table, column) that will be ignored.
"""
if exclude_columns is None:
exclude_columns = []
if field_spec is None:
field_spec = {}
if isinstance(record_ids, list):
record_ids = tuple(record_ids)
args0 = (env, model_name, record_ids, target_record_id)
args = args0 + (exclude_columns, )
args2 = args0 + (field_spec, )
if target_record_id in record_ids:
raise Exception("You can't put the target record in the list or "
"records to be merged.")
# Check which records to be merged exist
record_ids = env[model_name].browse(record_ids).exists().ids
if not record_ids:
return
_change_generic(*args, method=method)
if method == 'orm':
_change_many2one_refs_orm(*args)
_change_many2many_refs_orm(*args)
_change_reference_refs_orm(*args)
_change_translations_orm(*args)
# TODO: serialized fields
with env.norecompute():
_adjust_merged_values_orm(*args2)
env[model_name].recompute()
if delete:
_delete_records_orm(env, model_name, record_ids, target_record_id)
else:
_change_foreign_key_refs(*args)
_change_reference_refs_sql(*args)
_change_translations_sql(*args)
# TODO: Adjust values of the merged records through SQL
if delete:
_delete_records_sql(env, model_name, record_ids, target_record_id) | python | def merge_records(env, model_name, record_ids, target_record_id,
field_spec=None, method='orm', delete=True,
exclude_columns=None):
"""Merge several records into the target one.
NOTE: This should be executed in end migration scripts for assuring that
all the possible relations are loaded and changed. Tested on v10/v11.
:param env: Environment variable
:param model_name: Name of the model of the records to merge
:param record_ids: List of IDS of records that are going to be merged.
:param target_record_id: ID of the record where the rest records are going
to be merge in.
:param field_spec: Dictionary with field names as keys and forced operation
to perform as values. If a field is not present here, default operation
will be performed. See _adjust_merged_values_orm method doc for all the
available operators.
:param method: Specify how to perform operations. By default or specifying
'orm', operations will be performed with ORM, maybe slower, but safer, as
related and computed fields will be recomputed on changes, and all
constraints will be checked.
:param delete: If set, the source ids will be unlinked.
:exclude_columns: list of tuples (table, column) that will be ignored.
"""
if exclude_columns is None:
exclude_columns = []
if field_spec is None:
field_spec = {}
if isinstance(record_ids, list):
record_ids = tuple(record_ids)
args0 = (env, model_name, record_ids, target_record_id)
args = args0 + (exclude_columns, )
args2 = args0 + (field_spec, )
if target_record_id in record_ids:
raise Exception("You can't put the target record in the list or "
"records to be merged.")
# Check which records to be merged exist
record_ids = env[model_name].browse(record_ids).exists().ids
if not record_ids:
return
_change_generic(*args, method=method)
if method == 'orm':
_change_many2one_refs_orm(*args)
_change_many2many_refs_orm(*args)
_change_reference_refs_orm(*args)
_change_translations_orm(*args)
# TODO: serialized fields
with env.norecompute():
_adjust_merged_values_orm(*args2)
env[model_name].recompute()
if delete:
_delete_records_orm(env, model_name, record_ids, target_record_id)
else:
_change_foreign_key_refs(*args)
_change_reference_refs_sql(*args)
_change_translations_sql(*args)
# TODO: Adjust values of the merged records through SQL
if delete:
_delete_records_sql(env, model_name, record_ids, target_record_id) | [
"def",
"merge_records",
"(",
"env",
",",
"model_name",
",",
"record_ids",
",",
"target_record_id",
",",
"field_spec",
"=",
"None",
",",
"method",
"=",
"'orm'",
",",
"delete",
"=",
"True",
",",
"exclude_columns",
"=",
"None",
")",
":",
"if",
"exclude_columns"... | Merge several records into the target one.
NOTE: This should be executed in end migration scripts for assuring that
all the possible relations are loaded and changed. Tested on v10/v11.
:param env: Environment variable
:param model_name: Name of the model of the records to merge
:param record_ids: List of IDS of records that are going to be merged.
:param target_record_id: ID of the record where the rest records are going
to be merge in.
:param field_spec: Dictionary with field names as keys and forced operation
to perform as values. If a field is not present here, default operation
will be performed. See _adjust_merged_values_orm method doc for all the
available operators.
:param method: Specify how to perform operations. By default or specifying
'orm', operations will be performed with ORM, maybe slower, but safer, as
related and computed fields will be recomputed on changes, and all
constraints will be checked.
:param delete: If set, the source ids will be unlinked.
:exclude_columns: list of tuples (table, column) that will be ignored. | [
"Merge",
"several",
"records",
"into",
"the",
"target",
"one",
"."
] | b220b6498075d62c1b64073cc934513a465cfd85 | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade_merge_records.py#L465-L523 | train | 24,593 |
OCA/openupgradelib | openupgradelib/openupgrade.py | allow_pgcodes | def allow_pgcodes(cr, *codes):
"""Context manager that will omit specified error codes.
E.g., suppose you expect a migration to produce unique constraint
violations and you want to ignore them. Then you could just do::
with allow_pgcodes(cr, psycopg2.errorcodes.UNIQUE_VIOLATION):
cr.execute("INSERT INTO me (name) SELECT name FROM you")
.. warning::
**All** sentences inside this context will be rolled back if **a single
error** is raised, so the above example would insert **nothing** if a
single row violates a unique constraint.
This would ignore duplicate files but insert the others::
cr.execute("SELECT name FROM you")
for row in cr.fetchall():
with allow_pgcodes(cr, psycopg2.errorcodes.UNIQUE_VIOLATION):
cr.execute("INSERT INTO me (name) VALUES (%s)", row[0])
:param *str codes:
Undefined amount of error codes found in :mod:`psycopg2.errorcodes`
that are allowed. Codes can have either 2 characters (indicating an
error class) or 5 (indicating a concrete error). Any other errors
will be raised.
"""
try:
with cr.savepoint():
with core.tools.mute_logger('odoo.sql_db'):
yield
except (ProgrammingError, IntegrityError) as error:
msg = "Code: {code}. Class: {class_}. Error: {error}.".format(
code=error.pgcode,
class_=errorcodes.lookup(error.pgcode[:2]),
error=errorcodes.lookup(error.pgcode))
if error.pgcode in codes or error.pgcode[:2] in codes:
logger.info(msg)
else:
logger.exception(msg)
raise | python | def allow_pgcodes(cr, *codes):
"""Context manager that will omit specified error codes.
E.g., suppose you expect a migration to produce unique constraint
violations and you want to ignore them. Then you could just do::
with allow_pgcodes(cr, psycopg2.errorcodes.UNIQUE_VIOLATION):
cr.execute("INSERT INTO me (name) SELECT name FROM you")
.. warning::
**All** sentences inside this context will be rolled back if **a single
error** is raised, so the above example would insert **nothing** if a
single row violates a unique constraint.
This would ignore duplicate files but insert the others::
cr.execute("SELECT name FROM you")
for row in cr.fetchall():
with allow_pgcodes(cr, psycopg2.errorcodes.UNIQUE_VIOLATION):
cr.execute("INSERT INTO me (name) VALUES (%s)", row[0])
:param *str codes:
Undefined amount of error codes found in :mod:`psycopg2.errorcodes`
that are allowed. Codes can have either 2 characters (indicating an
error class) or 5 (indicating a concrete error). Any other errors
will be raised.
"""
try:
with cr.savepoint():
with core.tools.mute_logger('odoo.sql_db'):
yield
except (ProgrammingError, IntegrityError) as error:
msg = "Code: {code}. Class: {class_}. Error: {error}.".format(
code=error.pgcode,
class_=errorcodes.lookup(error.pgcode[:2]),
error=errorcodes.lookup(error.pgcode))
if error.pgcode in codes or error.pgcode[:2] in codes:
logger.info(msg)
else:
logger.exception(msg)
raise | [
"def",
"allow_pgcodes",
"(",
"cr",
",",
"*",
"codes",
")",
":",
"try",
":",
"with",
"cr",
".",
"savepoint",
"(",
")",
":",
"with",
"core",
".",
"tools",
".",
"mute_logger",
"(",
"'odoo.sql_db'",
")",
":",
"yield",
"except",
"(",
"ProgrammingError",
","... | Context manager that will omit specified error codes.
E.g., suppose you expect a migration to produce unique constraint
violations and you want to ignore them. Then you could just do::
with allow_pgcodes(cr, psycopg2.errorcodes.UNIQUE_VIOLATION):
cr.execute("INSERT INTO me (name) SELECT name FROM you")
.. warning::
**All** sentences inside this context will be rolled back if **a single
error** is raised, so the above example would insert **nothing** if a
single row violates a unique constraint.
This would ignore duplicate files but insert the others::
cr.execute("SELECT name FROM you")
for row in cr.fetchall():
with allow_pgcodes(cr, psycopg2.errorcodes.UNIQUE_VIOLATION):
cr.execute("INSERT INTO me (name) VALUES (%s)", row[0])
:param *str codes:
Undefined amount of error codes found in :mod:`psycopg2.errorcodes`
that are allowed. Codes can have either 2 characters (indicating an
error class) or 5 (indicating a concrete error). Any other errors
will be raised. | [
"Context",
"manager",
"that",
"will",
"omit",
"specified",
"error",
"codes",
"."
] | b220b6498075d62c1b64073cc934513a465cfd85 | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade.py#L180-L220 | train | 24,594 |
OCA/openupgradelib | openupgradelib/openupgrade.py | check_values_selection_field | def check_values_selection_field(cr, table_name, field_name, allowed_values):
"""
check if the field selection 'field_name' of the table 'table_name'
has only the values 'allowed_values'.
If not return False and log an error.
If yes, return True.
.. versionadded:: 8.0
"""
res = True
cr.execute("SELECT %s, count(*) FROM %s GROUP BY %s;" %
(field_name, table_name, field_name))
for row in cr.fetchall():
if row[0] not in allowed_values:
logger.error(
"Invalid value '%s' in the table '%s' "
"for the field '%s'. (%s rows).",
row[0], table_name, field_name, row[1])
res = False
return res | python | def check_values_selection_field(cr, table_name, field_name, allowed_values):
"""
check if the field selection 'field_name' of the table 'table_name'
has only the values 'allowed_values'.
If not return False and log an error.
If yes, return True.
.. versionadded:: 8.0
"""
res = True
cr.execute("SELECT %s, count(*) FROM %s GROUP BY %s;" %
(field_name, table_name, field_name))
for row in cr.fetchall():
if row[0] not in allowed_values:
logger.error(
"Invalid value '%s' in the table '%s' "
"for the field '%s'. (%s rows).",
row[0], table_name, field_name, row[1])
res = False
return res | [
"def",
"check_values_selection_field",
"(",
"cr",
",",
"table_name",
",",
"field_name",
",",
"allowed_values",
")",
":",
"res",
"=",
"True",
"cr",
".",
"execute",
"(",
"\"SELECT %s, count(*) FROM %s GROUP BY %s;\"",
"%",
"(",
"field_name",
",",
"table_name",
",",
... | check if the field selection 'field_name' of the table 'table_name'
has only the values 'allowed_values'.
If not return False and log an error.
If yes, return True.
.. versionadded:: 8.0 | [
"check",
"if",
"the",
"field",
"selection",
"field_name",
"of",
"the",
"table",
"table_name",
"has",
"only",
"the",
"values",
"allowed_values",
".",
"If",
"not",
"return",
"False",
"and",
"log",
"an",
"error",
".",
"If",
"yes",
"return",
"True",
"."
] | b220b6498075d62c1b64073cc934513a465cfd85 | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade.py#L223-L242 | train | 24,595 |
OCA/openupgradelib | openupgradelib/openupgrade.py | load_data | def load_data(cr, module_name, filename, idref=None, mode='init'):
"""
Load an xml, csv or yml data file from your post script. The usual case for
this is the
occurrence of newly added essential or useful data in the module that is
marked with "noupdate='1'" and without "forcecreate='1'" so that it will
not be loaded by the usual upgrade mechanism. Leaving the 'mode' argument
to its default 'init' will load the data from your migration script.
Theoretically, you could simply load a stock file from the module, but be
careful not to reinitialize any data that could have been customized.
Preferably, select only the newly added items. Copy these to a file
in your migrations directory and load that file.
Leave it to the user to actually delete existing resources that are
marked with 'noupdate' (other named items will be deleted
automatically).
:param module_name: the name of the module
:param filename: the path to the filename, relative to the module \
directory.
:param idref: optional hash with ?id mapping cache?
:param mode:
one of 'init', 'update', 'demo', 'init_no_create'.
Always use 'init' for adding new items from files that are marked with
'noupdate'. Defaults to 'init'.
'init_no_create' is a hack to load data for records which have
forcecreate=False set. As those records won't be recreated during the
update, standard Odoo would recreate the record if it was deleted,
but this will fail in cases where there are required fields to be
filled which are not contained in the data file.
"""
if idref is None:
idref = {}
logger.info('%s: loading %s' % (module_name, filename))
_, ext = os.path.splitext(filename)
pathname = os.path.join(module_name, filename)
fp = tools.file_open(pathname)
try:
if ext == '.csv':
noupdate = True
tools.convert_csv_import(
cr, module_name, pathname, fp.read(), idref, mode, noupdate)
elif ext == '.yml':
yaml_import(cr, module_name, fp, None, idref=idref, mode=mode)
elif mode == 'init_no_create':
for fp2 in _get_existing_records(cr, fp, module_name):
tools.convert_xml_import(
cr, module_name, fp2, idref, mode='init',
)
else:
tools.convert_xml_import(cr, module_name, fp, idref, mode=mode)
finally:
fp.close() | python | def load_data(cr, module_name, filename, idref=None, mode='init'):
"""
Load an xml, csv or yml data file from your post script. The usual case for
this is the
occurrence of newly added essential or useful data in the module that is
marked with "noupdate='1'" and without "forcecreate='1'" so that it will
not be loaded by the usual upgrade mechanism. Leaving the 'mode' argument
to its default 'init' will load the data from your migration script.
Theoretically, you could simply load a stock file from the module, but be
careful not to reinitialize any data that could have been customized.
Preferably, select only the newly added items. Copy these to a file
in your migrations directory and load that file.
Leave it to the user to actually delete existing resources that are
marked with 'noupdate' (other named items will be deleted
automatically).
:param module_name: the name of the module
:param filename: the path to the filename, relative to the module \
directory.
:param idref: optional hash with ?id mapping cache?
:param mode:
one of 'init', 'update', 'demo', 'init_no_create'.
Always use 'init' for adding new items from files that are marked with
'noupdate'. Defaults to 'init'.
'init_no_create' is a hack to load data for records which have
forcecreate=False set. As those records won't be recreated during the
update, standard Odoo would recreate the record if it was deleted,
but this will fail in cases where there are required fields to be
filled which are not contained in the data file.
"""
if idref is None:
idref = {}
logger.info('%s: loading %s' % (module_name, filename))
_, ext = os.path.splitext(filename)
pathname = os.path.join(module_name, filename)
fp = tools.file_open(pathname)
try:
if ext == '.csv':
noupdate = True
tools.convert_csv_import(
cr, module_name, pathname, fp.read(), idref, mode, noupdate)
elif ext == '.yml':
yaml_import(cr, module_name, fp, None, idref=idref, mode=mode)
elif mode == 'init_no_create':
for fp2 in _get_existing_records(cr, fp, module_name):
tools.convert_xml_import(
cr, module_name, fp2, idref, mode='init',
)
else:
tools.convert_xml_import(cr, module_name, fp, idref, mode=mode)
finally:
fp.close() | [
"def",
"load_data",
"(",
"cr",
",",
"module_name",
",",
"filename",
",",
"idref",
"=",
"None",
",",
"mode",
"=",
"'init'",
")",
":",
"if",
"idref",
"is",
"None",
":",
"idref",
"=",
"{",
"}",
"logger",
".",
"info",
"(",
"'%s: loading %s'",
"%",
"(",
... | Load an xml, csv or yml data file from your post script. The usual case for
this is the
occurrence of newly added essential or useful data in the module that is
marked with "noupdate='1'" and without "forcecreate='1'" so that it will
not be loaded by the usual upgrade mechanism. Leaving the 'mode' argument
to its default 'init' will load the data from your migration script.
Theoretically, you could simply load a stock file from the module, but be
careful not to reinitialize any data that could have been customized.
Preferably, select only the newly added items. Copy these to a file
in your migrations directory and load that file.
Leave it to the user to actually delete existing resources that are
marked with 'noupdate' (other named items will be deleted
automatically).
:param module_name: the name of the module
:param filename: the path to the filename, relative to the module \
directory.
:param idref: optional hash with ?id mapping cache?
:param mode:
one of 'init', 'update', 'demo', 'init_no_create'.
Always use 'init' for adding new items from files that are marked with
'noupdate'. Defaults to 'init'.
'init_no_create' is a hack to load data for records which have
forcecreate=False set. As those records won't be recreated during the
update, standard Odoo would recreate the record if it was deleted,
but this will fail in cases where there are required fields to be
filled which are not contained in the data file. | [
"Load",
"an",
"xml",
"csv",
"or",
"yml",
"data",
"file",
"from",
"your",
"post",
"script",
".",
"The",
"usual",
"case",
"for",
"this",
"is",
"the",
"occurrence",
"of",
"newly",
"added",
"essential",
"or",
"useful",
"data",
"in",
"the",
"module",
"that",
... | b220b6498075d62c1b64073cc934513a465cfd85 | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade.py#L245-L300 | train | 24,596 |
OCA/openupgradelib | openupgradelib/openupgrade.py | _get_existing_records | def _get_existing_records(cr, fp, module_name):
"""yield file like objects per 'leaf' node in the xml file that exists.
This is for not trying to create a record with partial data in case the
record was removed in the database."""
def yield_element(node, path=None):
if node.tag not in ['openerp', 'odoo', 'data']:
if node.tag == 'record':
xmlid = node.attrib['id']
if '.' not in xmlid:
module = module_name
else:
module, xmlid = xmlid.split('.', 1)
cr.execute(
'select id from ir_model_data where module=%s and name=%s',
(module, xmlid)
)
if not cr.rowcount:
return
result = StringIO(etree.tostring(path, encoding='unicode'))
result.name = None
yield result
else:
for child in node:
for value in yield_element(
child,
etree.SubElement(path, node.tag, node.attrib)
if path else etree.Element(node.tag, node.attrib)
):
yield value
return yield_element(etree.parse(fp).getroot()) | python | def _get_existing_records(cr, fp, module_name):
"""yield file like objects per 'leaf' node in the xml file that exists.
This is for not trying to create a record with partial data in case the
record was removed in the database."""
def yield_element(node, path=None):
if node.tag not in ['openerp', 'odoo', 'data']:
if node.tag == 'record':
xmlid = node.attrib['id']
if '.' not in xmlid:
module = module_name
else:
module, xmlid = xmlid.split('.', 1)
cr.execute(
'select id from ir_model_data where module=%s and name=%s',
(module, xmlid)
)
if not cr.rowcount:
return
result = StringIO(etree.tostring(path, encoding='unicode'))
result.name = None
yield result
else:
for child in node:
for value in yield_element(
child,
etree.SubElement(path, node.tag, node.attrib)
if path else etree.Element(node.tag, node.attrib)
):
yield value
return yield_element(etree.parse(fp).getroot()) | [
"def",
"_get_existing_records",
"(",
"cr",
",",
"fp",
",",
"module_name",
")",
":",
"def",
"yield_element",
"(",
"node",
",",
"path",
"=",
"None",
")",
":",
"if",
"node",
".",
"tag",
"not",
"in",
"[",
"'openerp'",
",",
"'odoo'",
",",
"'data'",
"]",
"... | yield file like objects per 'leaf' node in the xml file that exists.
This is for not trying to create a record with partial data in case the
record was removed in the database. | [
"yield",
"file",
"like",
"objects",
"per",
"leaf",
"node",
"in",
"the",
"xml",
"file",
"that",
"exists",
".",
"This",
"is",
"for",
"not",
"trying",
"to",
"create",
"a",
"record",
"with",
"partial",
"data",
"in",
"case",
"the",
"record",
"was",
"removed",... | b220b6498075d62c1b64073cc934513a465cfd85 | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade.py#L303-L332 | train | 24,597 |
OCA/openupgradelib | openupgradelib/openupgrade.py | rename_columns | def rename_columns(cr, column_spec):
"""
Rename table columns. Typically called in the pre script.
:param column_spec: a hash with table keys, with lists of tuples as \
values. Tuples consist of (old_name, new_name). Use None for new_name \
to trigger a conversion of old_name using get_legacy_name()
"""
for table in column_spec.keys():
for (old, new) in column_spec[table]:
if new is None:
new = get_legacy_name(old)
logger.info("table %s, column %s: renaming to %s",
table, old, new)
cr.execute(
'ALTER TABLE "%s" RENAME "%s" TO "%s"' % (table, old, new,))
cr.execute('DROP INDEX IF EXISTS "%s_%s_index"' % (table, old)) | python | def rename_columns(cr, column_spec):
"""
Rename table columns. Typically called in the pre script.
:param column_spec: a hash with table keys, with lists of tuples as \
values. Tuples consist of (old_name, new_name). Use None for new_name \
to trigger a conversion of old_name using get_legacy_name()
"""
for table in column_spec.keys():
for (old, new) in column_spec[table]:
if new is None:
new = get_legacy_name(old)
logger.info("table %s, column %s: renaming to %s",
table, old, new)
cr.execute(
'ALTER TABLE "%s" RENAME "%s" TO "%s"' % (table, old, new,))
cr.execute('DROP INDEX IF EXISTS "%s_%s_index"' % (table, old)) | [
"def",
"rename_columns",
"(",
"cr",
",",
"column_spec",
")",
":",
"for",
"table",
"in",
"column_spec",
".",
"keys",
"(",
")",
":",
"for",
"(",
"old",
",",
"new",
")",
"in",
"column_spec",
"[",
"table",
"]",
":",
"if",
"new",
"is",
"None",
":",
"new... | Rename table columns. Typically called in the pre script.
:param column_spec: a hash with table keys, with lists of tuples as \
values. Tuples consist of (old_name, new_name). Use None for new_name \
to trigger a conversion of old_name using get_legacy_name() | [
"Rename",
"table",
"columns",
".",
"Typically",
"called",
"in",
"the",
"pre",
"script",
"."
] | b220b6498075d62c1b64073cc934513a465cfd85 | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade.py#L378-L394 | train | 24,598 |
OCA/openupgradelib | openupgradelib/openupgrade.py | rename_tables | def rename_tables(cr, table_spec):
"""
Rename tables. Typically called in the pre script.
This function also renames the id sequence if it exists and if it is
not modified in the same run.
:param table_spec: a list of tuples (old table name, new table name). Use \
None for new_name to trigger a conversion of old_name to the result of \
get_legacy_name()
"""
# Append id sequences
to_rename = [x[0] for x in table_spec]
for old, new in list(table_spec):
if new is None:
new = get_legacy_name(old)
if (table_exists(cr, old + '_id_seq') and
old + '_id_seq' not in to_rename):
table_spec.append((old + '_id_seq', new + '_id_seq'))
for (old, new) in table_spec:
if new is None:
new = get_legacy_name(old)
logger.info("table %s: renaming to %s",
old, new)
cr.execute('ALTER TABLE "%s" RENAME TO "%s"' % (old, new,)) | python | def rename_tables(cr, table_spec):
"""
Rename tables. Typically called in the pre script.
This function also renames the id sequence if it exists and if it is
not modified in the same run.
:param table_spec: a list of tuples (old table name, new table name). Use \
None for new_name to trigger a conversion of old_name to the result of \
get_legacy_name()
"""
# Append id sequences
to_rename = [x[0] for x in table_spec]
for old, new in list(table_spec):
if new is None:
new = get_legacy_name(old)
if (table_exists(cr, old + '_id_seq') and
old + '_id_seq' not in to_rename):
table_spec.append((old + '_id_seq', new + '_id_seq'))
for (old, new) in table_spec:
if new is None:
new = get_legacy_name(old)
logger.info("table %s: renaming to %s",
old, new)
cr.execute('ALTER TABLE "%s" RENAME TO "%s"' % (old, new,)) | [
"def",
"rename_tables",
"(",
"cr",
",",
"table_spec",
")",
":",
"# Append id sequences",
"to_rename",
"=",
"[",
"x",
"[",
"0",
"]",
"for",
"x",
"in",
"table_spec",
"]",
"for",
"old",
",",
"new",
"in",
"list",
"(",
"table_spec",
")",
":",
"if",
"new",
... | Rename tables. Typically called in the pre script.
This function also renames the id sequence if it exists and if it is
not modified in the same run.
:param table_spec: a list of tuples (old table name, new table name). Use \
None for new_name to trigger a conversion of old_name to the result of \
get_legacy_name() | [
"Rename",
"tables",
".",
"Typically",
"called",
"in",
"the",
"pre",
"script",
".",
"This",
"function",
"also",
"renames",
"the",
"id",
"sequence",
"if",
"it",
"exists",
"and",
"if",
"it",
"is",
"not",
"modified",
"in",
"the",
"same",
"run",
"."
] | b220b6498075d62c1b64073cc934513a465cfd85 | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade.py#L505-L528 | train | 24,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.