code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
result = self._traverse_command(command, *args, **kwargs) if self.indexable: self.deindex([result]) return result
def _pop(self, command, *args, **kwargs)
Shortcut for commands that pop a value from the field, returning it while removing it. The returned value will be deindexed
8.21854
6.088498
1.349847
assert self.indexable, "Field not indexable" assert not only_index or self.has_index(only_index), "Invalid index" if only_index: only_index = only_index if isclass(only_index) else only_index.__class__ if values is None: values = self.proxy_get() ...
def index(self, values=None, only_index=None)
Index all values stored in the field, or only given ones if any.
3.481656
3.267701
1.065476
if self.indexable: keys = [] if args: if len(args) % 2 != 0: raise RedisError("ZADD requires an equal number of " "values and scores") keys.extend(args[1::2]) keys.extend(kwargs)...
def _call_zadd(self, command, *args, **kwargs)
We do the same computation of the zadd method of StrictRedis to keep keys to index them (instead of indexing the whole set) Members (value/score) can be passed: - in *args, with score followed by the value, 0+ times (to respect the redis order) - in **kwargs, with v...
5.44267
4.779146
1.138837
if self.indexable: self.index([value]) return self._traverse_command(command, value, *args, **kwargs)
def _call_zincrby(self, command, value, *args, **kwargs)
This command update a score of a given value. But it can be a new value of the sorted set, so we index it.
7.709527
6.905241
1.116475
values_callback = kwargs.pop('values_callback', None) pieces = [] if args: if len(args) % 2 != 0: raise RedisError("ZADD requires an equal number of " "values and scores") pieces.extend(args) for pair in ...
def coerce_zadd_args(*args, **kwargs)
Take arguments attended by a zadd call, named or not, and return a flat list that can be used. A callback can be called with all "values" (as *args) if defined as the `values_callback` named argument. Real values will then be the result of this callback.
2.842298
2.744905
1.035481
result = self._traverse_command(command, *args, **kwargs) if self.indexable and result: self.index(args) return result
def _pushx(self, command, *args, **kwargs)
Helper for lpushx and rpushx, that only index the new values if the list existed when the command was called
8.42481
6.741946
1.249611
if not count: if self.indexable: self.deindex([value]) return self._traverse_command(command, count, value, *args, **kwargs) else: return self._reset(command, count, value, *args, **kwargs)
def _call_lrem(self, command, count, value, *args, **kwargs)
If count is 0, we remove all elements equal to value, so we know we have nothing to index, and this value to deindex. In other case, we don't know how much elements will remain in the list, so we have to do a full deindex/reindex. So do it carefuly.
5.054095
3.941858
1.282161
if self.indexable: old_value = self.lindex(index) self.deindex([old_value]) result = self._traverse_command(command, index, value, *args, **kwargs) if self.indexable: self.index([value]) return result
def _call_lset(self, command, index, value, *args, **kwargs)
Before setting the new value, get the previous one to deindex it. Then call the command and index the new value, if exists
3.785218
3.049822
1.241128
assert self.indexable, "Field not indexable" assert not only_index or self.has_index(only_index), "Invalid index" if only_index: only_index = only_index if isclass(only_index) else only_index.__class__ if values is None: values = self.proxy_get() ...
def deindex(self, values=None, only_index=None)
Deal with dicts and field names.
3.144522
3.026723
1.03892
try: hashkey = self.key except DoesNotExist: return False else: return self.connection.hexists(hashkey, key)
def hexists(self, key)
Call the hexists command to check if the redis hash key exists for the current field
6.168079
6.354075
0.970728
args = list(args) args.insert(0, self.name) return super(InstanceHashField, self)._traverse_command(name, *args, **kwargs)
def _traverse_command(self, name, *args, **kwargs)
Add key AND the hash field to the args, and call the Redis command.
4.643461
3.147063
1.47549
try: key = self.key except DoesNotExist: return False else: return self.connection.hexists(key, self.name)
def hexists(self)
Call the hexists command to check if the redis hash key exists for the current field
5.240947
5.713683
0.917262
if value is None: raise ValueError('The pk for %s is not "auto-increment", you must fill it' % self._model.__name__) value = self.normalize(value) # Check that this pk does not already exist if self.exists(value): raise Unique...
def _validate(self, value)
Validate that a given new pk to set is always set, and return it. The returned value should be normalized, and will be used without check.
8.096136
6.271317
1.290979
try: if not value: value = self.get() except (AttributeError, DoesNotExist): # If the instance is deleted, the _pk attribute doesn't exist # anymore. So we catch the AttributeError to return False (this pk # field doesn't exist any...
def exists(self, value=None)
Return True if the given pk value exists for the given class. If no value is given, we use the value of the current field, which is the value of the "_pk" attribute of its instance.
8.543279
7.2285
1.181888
# Deny updating of an already set pk if self._set: raise ValueError('A primary key cannot be updated') # Validate and return the value to be used as a pk value = self._validate(value) # Tell the model the pk is now set self._instance._set_pk(value) ...
def set(self, value)
Override the default setter to check uniqueness, deny updating, and add the new pk to the model's collection. The value is not saved as a field in redis, because we don't need this. On an instance, we have the _pk attribute with the pk value, and when we ask for a collection, we get some...
7.787574
6.163207
1.263559
if not hasattr(self, '_instance'): raise ImplementationError("Impossible to get the PK of an unbound field") if not hasattr(self._instance, '_pk'): raise DoesNotExist("The current object doesn't exists anymore") if not self._instance._pk: self.set(va...
def get(self)
We do not call the default getter as we have the value cached in the instance in its _pk attribute
7.256673
5.686667
1.276085
if value is not None: raise ValueError('The pk for %s is "auto-increment", you must not fill it' % self._model.__name__) key = self._instance.make_key(self._model._name, 'max_pk') return self.normalize(self.connection.incr(key))
def _validate(self, value)
Validate that a given new pk to set is always set to None, then return a new pk
12.279375
9.492284
1.293617
if not self.field.lockable: return if self.already_locked_by_model: self.sub_lock_mode = True return self.already_locked_by_model = True super(FieldLock, self).acquire(*args, **kwargs)
def acquire(self, *args, **kwargs)
Really acquire the lock only if it's not a sub-lock. Then save the sub-lock status.
5.297026
4.534743
1.168098
if not self.field.lockable: return if self.sub_lock_mode: return super(FieldLock, self).release(*args, **kwargs) self.already_locked_by_model = self.sub_lock_mode = False
def release(self, *args, **kwargs)
Really release the lock only if it's not a sub-lock. Then save the sub-lock status and mark the model as unlocked.
6.496936
4.845118
1.340924
data = client.recv(1028) if data == b'': return False client.sendall(b'SERVER: ' + data) print(threading.active_count()) return True
def handle_readable(client)
Return True: The client is re-registered to the selector object. Return False: The server disconnects the client.
4.537253
3.792718
1.196307
attrs = {} if index_classes: attrs['index_classes'] = index_classes klass = type(str(name or cls.__name__), (cls, ), attrs) # let the ``configure`` method manage some fields configure_attrs = {} if key is not None: configure_attrs['key'...
def compose(cls, index_classes, key=None, transform=None, name=None)
Create a new class with the given index classes Parameters ----------- index_classes: list The list of index classes to be used in the multi-index class to create name: str The name of the new multi-index class. If not set, it will be the same as the ...
3.064147
3.704944
0.827043
for index in self._indexes: if index.can_handle_suffix(suffix): return True return False
def can_handle_suffix(self, suffix)
Tell if one of the managed indexes can be used for the given filter prefix For parameters, see BaseIndex.can_handle_suffix
4.569533
3.019083
1.51355
updated_args = list(args) if transform: updated_args[-1] = self.transform_value(updated_args[-1]) if self.key: updated_args.insert(-1, self.key) return updated_args
def prepare_args(self, args, transform=True)
Prepare args to be used by a sub-index Parameters ---------- args: list The while list of arguments passed to add, check_uniqueness, get_filtered_keys... transform: bool If ``True``, the last entry in `args`, ie the value, will be transformed. Else it...
3.555113
3.2101
1.107477
self.get_unique_index().check_uniqueness(*self.prepare_args(args, transform=False))
def check_uniqueness(self, *args)
For a unique index, check if the given args are not used twice For the parameters, seen BaseIndex.check_uniqueness
12.660506
9.482966
1.335079
check_uniqueness = kwargs.pop('check_uniqueness', False) args = self.prepare_args(args) for index in self._indexes: index.add(*args, check_uniqueness=check_uniqueness and index.handle_uniqueness, **kwargs) if check_uniqueness and index.handle_uniqueness: ...
def add(self, *args, **kwargs)
Add the instance tied to the field to all the indexes For the parameters, seen BaseIndex.add
3.772371
3.43466
1.098325
args = self.prepare_args(args) for index in self._indexes: index.remove(*args)
def remove(self, *args)
Remove the instance tied to the field from all the indexes For the parameters, seen BaseIndex.remove
7.89753
5.319763
1.484564
args = self.prepare_args(args, transform=False) for index in self._indexes: if index.can_handle_suffix(suffix): return index.get_filtered_keys(suffix, *args, **kwargs)
def get_filtered_keys(self, suffix, *args, **kwargs)
Returns the index keys to be used by the collection for the given args For the parameters, see BaseIndex.get_filtered_keys
4.550635
3.868104
1.176451
keys = set() for index in self._indexes: keys.update(index.get_all_storage_keys()) return keys
def get_all_storage_keys(self)
Returns the keys to be removed by `clear` in aggressive mode For the parameters, see BaseIndex.get_all_storage_keys
4.400014
3.477975
1.265108
attrs = {} for key in ('prefix', 'handle_uniqueness', 'key'): if key in kwargs: attrs[key] = kwargs.pop(key) if 'transform' in kwargs: attrs['transform'] = staticmethod(kwargs.pop('transform')) name = kwargs.pop('name', None) i...
def configure(cls, **kwargs)
Create a new index class with the given info This allow to avoid creating a new class when only few changes are to be made Parameters ---------- kwargs: dict prefix: str The string part to use in the collection, before the normal suffix. ...
4.135853
3.341858
1.237591
try: return self.remove_prefix(suffix) in self.handled_suffixes except IndexError: return False
def can_handle_suffix(self, suffix)
Tell if the current index can be used for the given filter suffix Parameters ---------- suffix: str The filter suffix we want to check. Must not includes the "__" part. Returns ------- bool ``True`` if the index can handle this suffix, ``False`` ...
6.580639
7.471805
0.88073
if transform: value = self.transform_value(value) return str(self.field.from_python(value))
def normalize_value(self, value, transform=True)
Prepare the given value to be stored in the index It first calls ``transform_value`` if ``transform`` is ``True``, then calls the ``from_python`` method of the field, then cast the result to a str. Parameters ---------- value: any The value to normalize ...
4.769965
4.453642
1.071026
if not self.transform: return value try: # we store a staticmethod but we accept a method taking `self` and `value` return self.transform(self, value) except TypeError as e: if 'argument' in str(e): # try to limit only to arguments error...
def transform_value(self, value)
Convert the value to be stored. This does nothing by default but subclasses can change this. Then the index will be able to filter on the transformed value. For example if the transform capitalizes some text, the filter would be ``myfield__capitalized__eq='FOO'``
8.875141
9.475201
0.936671
if not cls.prefix: return suffix if cls.prefix == suffix: return None return (suffix or '').split(cls.prefix + '__')[1] or None
def remove_prefix(cls, suffix)
Remove the class prefix from the suffix The collection pass the full suffix used in the filters to the index. But to know if it is valid, we have to remove the prefix to get the real suffix, for example to check if the suffix is handled by the index. Parameters ----------- ...
7.668992
6.405989
1.19716
try: if not bool(self.model): return False except AttributeError: return False else: try: return not bool(self.instance) except AttributeError: return True
def attached_to_model(self)
Tells if the current index is the one attached to the model field, not instance field
3.942676
3.12036
1.263532
# to avoid using self set that may be updated during the process indexed_values = set(self._indexed_values) deindexed_values = set(self._deindexed_values) for args in indexed_values: self.remove(*args) for args in deindexed_values: self.add(*arg...
def _rollback(self)
Restore the index in its previous state This uses values that were indexed/deindexed since the last call to `_reset_cache`. This is used when an error is encountered while updating a value, to return to the previous state
6.595459
5.419781
1.216924
pks = list(set(pks)) if len(pks) > 1: # this may not happen ! raise UniquenessError( "Multiple values indexed for unique field %s.%s: %s" % ( self.model.__name__, self.field.name, pks ) ) elif len(pk...
def assert_pks_uniqueness(self, pks, exclude, value)
Check uniqueness of pks Parameters ----------- pks: iterable The pks to check for uniqueness. If more than one different, it will raise. If only one and different than `exclude`, it will raise too. exclude: str The pk that we accept to be ...
3.424159
3.591248
0.953473
assert self.attached_to_model, \ '`clear` can only be called on an index attached to the model field' if aggressive: keys = self.get_all_storage_keys() with self.model.database.pipeline(transaction=False) as pipe: for key in keys: ...
def clear(self, chunk_size=1000, aggressive=False)
Will deindex all the value for the current field Parameters ---------- chunk_size: int Default to 1000, it's the number of instances to load at once if not in aggressive mode. aggressive: bool Default to ``False``. When ``False``, the actual collection of instanc...
5.02484
4.916294
1.022079
assert self.attached_to_model, \ '`rebuild` can only be called on an index attached to the model field' self.clear(chunk_size=chunk_size, aggressive=aggressive_clear) start = 0 while True: instances = self.model.collection().sort().instances(skip_exist_...
def rebuild(self, chunk_size=1000, aggressive_clear=False)
Rebuild the whole index for this field. Parameters ---------- chunk_size: int Default to 1000, it's the number of instances to load at once. aggressive_clear: bool Will be passed to the `aggressive` argument of the `clear` method. If `False`, all valu...
5.676243
5.938792
0.955791
accepted_key_types = kwargs.get('accepted_key_types', None) if accepted_key_types and 'set' not in accepted_key_types: raise ImplementationError( '%s can only return keys of type "set"' % self.__class__.__name__ ) # special "in" case: we get n ...
def get_filtered_keys(self, suffix, *args, **kwargs)
Return the set used by the index for the given "value" (`args`) For the parameters, see ``BaseIndex.get_filtered_keys``
5.188839
5.157237
1.006128
args = list(args) value = args.pop() parts = [ self.model._name, self.field.name, ] + args if self.prefix: parts.append(self.prefix) if self.key: parts.append(self.key) normalized_value = self.normalize...
def get_storage_key(self, *args, **kwargs)
Return the redis key where to store the index for the given "value" (`args`) For this index, we store all PKs having the same value for a field in the same set. Key has this form: model-name:field-name:sub-field-name:normalized-value The ':sub-field-name part' is repeated for each entry...
3.735392
3.161855
1.181393
parts1 = [ self.model._name, self.field.name, ] parts2 = parts1 + ['*'] # for indexes taking args, like for hashfields if self.prefix: parts1.append(self.prefix) parts2.append(self.prefix) if self.key: part...
def get_all_storage_keys(self)
Returns the keys to be removed by `clear` in aggressive mode For the parameters, see BaseIndex.get_all_storage_keys
3.790011
3.470929
1.09193
if not self.field.unique: return key = kwargs.get('key', None) if key is None: key = self.get_storage_key(*args) # Lets check if the index key already exist for another instance pk = self.instance.pk.get() pks = list(self.connection.sme...
def check_uniqueness(self, *args, **kwargs)
Check if the given "value" (via `args`) is unique or not. Parameters ---------- kwargs: dict key: str When given, it will be used instead of calling ``get_storage_key`` for the given args MUST be passed as a keyword argument F...
5.891636
5.115969
1.151617
check_uniqueness = kwargs.get('check_uniqueness', True) key = self.get_storage_key(*args) if self.field.unique and check_uniqueness: self.check_uniqueness(key=key, *args) # Do index => create a key to be able to retrieve parent pk with # current field valu...
def add(self, *args, **kwargs)
Add the instance tied to the field for the given "value" (via `args`) to the index For the parameters, see ``BaseIndex.add``
7.000576
6.633857
1.05528
key = self.get_storage_key(*args) pk = self.instance.pk.get() logger.debug("removing %s from index %s" % (pk, key)) self.connection.srem(key, pk) self._deindexed_values.add(tuple(args))
def remove(self, *args)
Remove the instance tied to the field for the given "value" (via `args`) from the index For the parameters, see ``BaseIndex.remove``
6.770764
5.521595
1.226233
args = list(args) args.pop() # final value, not needed for the storage key parts = [ self.model._name, self.field.name, ] + args if self.prefix: parts.append(self.prefix) if self.key: parts.append(self.key) ...
def get_storage_key(self, *args)
Return the redis key where to store the index for the given "value" (`args`) For this index, we store all PKs having for a field in the same sorted-set. Key has this form: model-name:field-name:sub-field-name:index-key-name The ':sub-field-name part' is repeated for each entry in *args ...
4.771832
4.663574
1.023214
if not self.field.unique: return try: pk = self.instance.pk.get() except AttributeError: pk = None key = self.get_storage_key(*args) value = list(args)[-1] pks = self.get_pks_for_filter(key, 'eq', self.normalize_value(value)...
def check_uniqueness(self, *args, **kwargs)
Check if the given "value" (via `args`) is unique or not. For the parameters, see ``BaseIndex.check_uniqueness``
5.289775
4.860458
1.088329
check_uniqueness = kwargs.get('check_uniqueness', True) if self.field.unique and check_uniqueness: self.check_uniqueness(*args) key = self.get_storage_key(*args) args = list(args) value = args[-1] pk = self.instance.pk.get() logger.debug(...
def add(self, *args, **kwargs)
Add the instance tied to the field for the given "value" (via `args`) to the index For the parameters, see ``BaseIndex.add`` Notes ----- This method calls the ``store`` method that should be overridden in subclasses to store in the index sorted-set key
4.825469
4.127231
1.169178
key = self.get_storage_key(*args) args = list(args) value = args[-1] pk = self.instance.pk.get() logger.debug("removing %s from index %s" % (pk, key)) self.unstore(key, pk, self.prepare_value_for_storage(value, pk)) self._deindexed_values.add(tuple(arg...
def remove(self, *args)
Remove the instance tied to the field for the given "value" (via `args`) from the index For the parameters, see ``BaseIndex.remove`` Notes ----- This method calls the ``unstore`` method that should be overridden in subclasses to remove data from the index sorted-set key
6.860341
5.198575
1.319658
self.model.database.call_script( # be sure to use the script dict at the class level # to avoid registering it many times script_dict=self.__class__.lua_filter_script, keys=[key, tmp_key], args=[key_type, start, end, exclude] + list(args) ...
def call_script(self, key, tmp_key, key_type, start, end, exclude, *args)
Call the lua scripts with given keys and args Parameters ----------- key: str The key of the index sorted-set tmp_key: str The final temporary key where to store the filtered primary keys key_type: str The type of temporary key to use, either ...
7.820889
6.616089
1.182102
accepted_key_types = kwargs.get('accepted_key_types', None) if accepted_key_types\ and 'set' not in accepted_key_types and 'zset' not in accepted_key_types: raise ImplementationError( '%s can only return keys of type "set" or "zset"' % self.__class_...
def get_filtered_keys(self, suffix, *args, **kwargs)
Returns the index key for the given args "value" (`args`) Parameters ---------- kwargs: dict use_lua: bool Default to ``True``, if scripting is supported. If ``True``, the process of reading from the sorted-set, extracting the primary ...
3.59727
3.350327
1.073707
value = super(TextRangeIndex, self).prepare_value_for_storage(value, pk) return self.separator.join([value, str(pk)])
def prepare_value_for_storage(self, value, pk)
Prepare the value to be stored in the zset We'll store the value and pk concatenated. For the parameters, see BaseRangeIndex.prepare_value_for_storage
5.064326
4.008569
1.263375
parts = string.split(self.separator) pk = parts.pop() return self.separator.join(parts), pk
def _extract_value_from_storage(self, string)
Taking a string that was a member of the zset, extract the value and pk Parameters ---------- string: str The member extracted from the sorted set Returns ------- tuple Tuple with the value and the pk, extracted from the string
6.411662
5.536434
1.158085
assert filter_type in self.handled_suffixes start = '-' end = '+' exclude = None if filter_type in (None, 'eq'): # we include the separator to only get the members with the exact value start = u'[%s%s' % (value, self.separator) end ...
def get_boundaries(self, filter_type, value)
Compute the boundaries to pass to zrangebylex depending of the filter type The third return value, ``exclude`` is ``None`` except for the filters `lt` and `gt` because we cannot explicitly exclude it when querying the sorted-set For the parameters, see BaseRangeIndex.store No...
3.528354
3.1717
1.112449
start, end, exclude = self.get_boundaries(filter_type, value) members = self.connection.zrangebylex(key, start, end) if exclude is not None: # special case where we don't want the exact given value, but we cannot # exclude it from the sorted set directly ...
def get_pks_for_filter(self, key, filter_type, value)
Extract the pks from the zset key for the given type and value For the parameters, see BaseRangeIndex.get_pks_for_filter
4.507831
4.164938
1.082329
args = list(args) args.append(self.separator) super(TextRangeIndex, self).call_script( key, tmp_key, key_type, start, end, exclude, *args )
def call_script(self, key, tmp_key, key_type, start, end, exclude, *args)
Call the lua scripts with given keys and args We add the separator to the arguments to be passed to the script For the parameters, see BaseRangeIndex.call_script
3.780282
2.644697
1.429382
if transform: value = self.transform_value(value) try: return float(value) except (ValueError, TypeError): if self.raise_if_not_float: raise ValueError('Invalid value %s for field %s.%s' % ( value, self.model.__name...
def normalize_value(self, value, transform=True)
Prepare the given value to be stored in the index For the parameters, see BaseIndex.normalize_value Raises ------ ValueError If ``raise_if_not_float`` is True and the value cannot be casted to a float.
2.93816
3.030839
0.969421
self.connection.zadd(key, value, pk)
def store(self, key, pk, value)
Store the value/pk in the sorted set index For the parameters, see BaseRangeIndex.store We simple store the pk as a member of the sorted set with the value being the score
10.29074
7.123819
1.444554
self.connection.zrem(key, pk)
def unstore(self, key, pk, value)
Remove the value/pk from the sorted set index For the parameters, see BaseRangeIndex.store We simple remove the pk as a member from the sorted set
10.460335
9.024276
1.159133
assert filter_type in self.handled_suffixes start = '-inf' end = '+inf' exclude = None if filter_type in (None, 'eq'): # only one score start = end = value elif filter_type == 'gt': start = '(%s' % value elif filte...
def get_boundaries(self, filter_type, value)
Compute the boundaries to pass to the sorted-set command depending of the filter type The third return value, ``exclude`` is always ``None`` because we can easily restrict the score to filter on in the sorted-set. For the parameters, see BaseRangeIndex.store Notes ----- ...
3.630821
3.046667
1.191735
start, end, __ = self.get_boundaries(filter_type, value) # we have nothing to exclude return self.connection.zrangebyscore(key, start, end)
def get_pks_for_filter(self, key, filter_type, value)
Extract the pks from the zset key for the given type and value For the parameters, see BaseRangeIndex.get_pks_for_filter
7.944291
6.50366
1.221511
for i in range(repeat): if print_counter: print i+1, print 'Hello, %s!' % name
def hello_command(name, print_counter=False, repeat=10)
Print nice greetings.
3.259645
2.925961
1.114043
self.logger.info("scene_command: Group %s Command %s", self.group_id, command) command_url = self.hub.hub_url + '/0?' + command + self.group_id + "=I=0" return self.hub.post_direct_command(command_url)
def scene_command(self, command)
Wrapper to send posted scene command and get response
7.743172
6.708746
1.154191
self.logger.info("enter_unlink_mode Group %s", self.group_id) self.scene_command('0A') # should send http://0.0.0.0/0?0A01=I=0 ## TODO check return status status = self.hub.get_buffer_status() return status
def enter_unlink_mode(self)
Enter unlinking mode for a group
14.734048
13.14317
1.121042
self.logger.info("cancel_link_unlink_mode") self.scene_command('08') # should send http://0.0.0.0/0?08=I=0 ## TODO check return status status = self.hub.get_buffer_status() return status
def cancel_link_unlink_mode(self)
Cancel linking or unlinking mode
14.205089
13.247166
1.072312
if self.cls.database.support_scripting(): self.cls.database.call_script( # be sure to use the script dict at the class level # to avoid registering it many times script_dict=self.__class__.scripts['list_to_set'], keys=[list_key...
def _list_to_set(self, list_key, set_key)
Store all content of the given ListField in a redis set. Use scripting if available to avoid retrieving all values locally from the list before sending them back to the set
5.582141
4.266912
1.308239
old_sort_limits_and_len_mode = None if self._sort_limits is None else self._sort_limits.copy(), self._len_mode old_sorts = None if self._sort is None else self._sort.copy(),\ None if self._sort_by_sortedset is None else self._sort_by_sortedset.copy() try: ...
def _collection(self)
Effectively retrieve data according to lazy_collection. If we have a stored collection, without any result, return an empty list
4.181309
3.960644
1.055714
if self.stored_key and not self.stored_key_exists(): raise DoesNotExist('This collection is based on a previous one, ' 'stored at a key that does not exist anymore.') conn = self.cls.get_connection() all_sets = set() tmp_keys = set()...
def _prepare_sets(self, sets)
The original "_prepare_sets" method simple return the list of sets in _lazy_collection, know to be all keys of redis sets. As the new "intersect" method can accept different types of "set", we have to handle them because we must return only keys of redis sets.
3.69415
3.581127
1.031561
sets_ = set() for set_ in sets: if isinstance(set_, (list, set)): set_ = tuple(set_) elif isinstance(set_, MultiValuesField) and not getattr(set_, '_instance', None): raise ValueError('%s passed to "intersect" must be bound' ...
def intersect(self, *sets)
Add a list of sets to the existing list of sets to check. Returns self for chaining. Each "set" represent a list of pk, the final goal is to return only pks matching the intersection of all sets. A "set" can be: - a string: considered as the name of a redis set, sorted set or lis...
6.260181
5.054235
1.238601
if self._has_sortedsets: self.cls.get_connection().zinterstore(final_set, list(sets)) else: final_set = super(ExtendedCollectionManager, self)._combine_sets(sets, final_set) return final_set
def _combine_sets(self, sets, final_set)
Given a list of set, combine them to create the final set that will be used to make the final redis call. If we have a least a sorted set, use zinterstore insted of sunionstore
6.848561
4.480146
1.528647
conn = self.cls.get_connection() # we have a sorted set without need to sort, use zrange if self._has_sortedsets and sort_options is None: return conn.zrange(final_set, 0, -1) # we have a stored collection, without other filter, and no need to # sort, use ...
def _final_redis_call(self, final_set, sort_options)
The final redis call to obtain the values to return from the "final_set" with some sort options. IIf we have at leaset a sorted set and if we don't have any sort options, call zrange on the final set wich is the result of a call to zinterstore.
5.772892
5.471664
1.055052
conn = self.cls.get_connection() # we have a sorted set without need to sort, use zcard if self._has_sortedsets: return conn.zcard(final_set) # we have a stored collection, without other filter, use llen elif self.stored_key and not self._lazy_collection['s...
def _collection_length(self, final_set)
Return the length of the final collection, directly asking redis for the count without calling sort
9.145238
8.288855
1.103317
self._sort_by_sortedset = None is_sortedset = False if parameters.get('by_score'): if parameters.get('by'): raise ValueError("You can't use `by` and `by_score` in the same " "call to `sort`.") by = parameters.get('...
def sort(self, **parameters)
Enhance the default sort method to accept a new parameter "by_score", to use instead of "by" if you want to sort by the score of a sorted set. You must pass to "by_sort" the key of a redis sorted set (or a sortedSetField attached to an instance)
4.24279
3.553822
1.193867
conn = self.cls.get_connection() default = '' if alpha else '-inf' if values is None: # no values given, we get scores from the whole sorted set result = conn.zrange(key, start=0, end=-1, withscores=True) values = list(islice(chain.from_iterable(resul...
def _zset_to_keys(self, key, values=None, alpha=False)
Convert a redis sorted set to a list of keys, to be used by sort. Each key is on the following format, for each value in the sorted set: ramdom_string:value-in-the-sorted-set => score-of-the-value The random string is the same for all keys. If values is not None, only these values fr...
3.739242
3.604787
1.037299
# create the keys base_tmp_key, tmp_keys = self._zset_to_keys( key=self._sort_by_sortedset['by'], values=values, ) # ask to sort on our new keys sort_options['by'] = '%s:*...
def _prepare_sort_by_score(self, values, sort_options)
Create the key to sort on the sorted set references in self._sort_by_sortedset and adapte sort options
5.133434
4.35681
1.178255
# if we want a result sorted by a score, and if we have a full result # (no slice), we can do it know, by creating keys for each values with # the sorted set score, and sort on them if self._sort_by_sortedset_after and (len(results) > 1 or self._values): conn = self....
def _prepare_results(self, results)
Sort results by score if not done before (faster, if we have no values to retrieve, or slice)
7.43382
6.739129
1.103083
result = zip(*([iter(collection)] * len(self._values['fields']['names']))) if self._values['mode'] == 'dicts': result = (dict(zip(self._values['fields']['names'], a_result)) for a_result in result) return result
def _to_values(self, collection)
Regroup values in tuples or dicts for each "instance". Exemple: Given this result from redis: ['id1', 'name1', 'id2', 'name2'] tuples: [('id1', 'name1'), ('id2', 'name2')] dicts: [{'id': 'id1', 'name': 'name1'}, {'id': 'id2', 'name': 'name2'}]
5.348921
4.309895
1.241079
return self._sort_by_sortedset and self._sort_limits and (not self._lazy_collection['pks'] or self._want_score_value)
def _sort_by_sortedset_before(self)
Return True if we have to sort by set and do the stuff *before* asking redis for the sort
25.828127
19.814325
1.303508
return self._sort_by_sortedset and not self._sort_limits and (not self._lazy_collection['pks'] or self._want_score_value)
def _sort_by_sortedset_after(self)
Return True if we have to sort by set and do the stuff *after* asking redis for the sort
24.300661
19.000883
1.278923
sort_options = super(ExtendedCollectionManager, self)._prepare_sort_options(has_pk) if self._values: # if we asked for values, we have to use the redis 'sort' # command, which is able to return other fields. if not sort_options: sort_options ...
def _prepare_sort_options(self, has_pk)
Prepare sort options for _values attributes. If we manager sort by score after getting the result, we do not want to get values from the first sort call, but only from the last one, after converting results in zset into keys
4.131384
3.731421
1.107188
if self._lazy_collection['intersects']: # if the intersect method was called, we had new sets to intersect # to the global set of sets. # And it there is no real filters, we had the set of the whole # collection because we cannot be sure that entries in "...
def _get_final_set(self, sets, pk, sort_options)
Add intersects fo sets and call parent's _get_final_set. If we have to sort by sorted score, and we have a slice, we have to convert the whole sorted set to keys now.
9.07966
8.111493
1.119357
string_filters = filters.copy() for key, value in filters.items(): is_extended = False if isinstance(value, RedisField): # we will fetch the value when running the collection if (not isinstance(value, SingleValueField) ...
def _add_filters(self, **filters)
In addition to the normal _add_filters, this one accept RedisField objects on the right part of a filter. The value will be fetched from redis when calling the collection. The filter value can also be a model instance, in which case its PK will be fetched when calling the collection, too...
4.602507
3.985178
1.154906
pk = super(ExtendedCollectionManager, self)._get_pk() if pk is not None and isinstance(pk, RawFilter): # We have a RedisModel and we want its pk, or a RedisField # (single value) and we want its value if isinstance(pk.value, RedisModel): pk =...
def _get_pk(self)
Override the default _get_pk method to retrieve the real pk value if we have a SingleValueField or a RedisModel instead of a real PK value
5.754771
4.542969
1.266742
try: sorted_score_pos = fields.index(SORTED_SCORE) except: sorted_score_pos = None else: fields = list(fields) fields.pop(sorted_score_pos) final_fields = {'names': [], 'keys': []} for field_name in fields: if ...
def _coerce_fields_parameters(self, fields)
Used by values and values_list to get the list of fields to use in the redis sort command to retrieve fields. The result is a dict with two lists: - 'names', with wanted field names - 'keys', with keys to use in the sort command When sorting by score, we allow to retrieve the...
2.926787
2.474039
1.183
old_sort_limits_and_len_mode = None if self._sort_limits is None else self._sort_limits.copy(), self._len_mode try: self._store = True # save sort and values options sort_options = None if self._sort is not None: sort_options = se...
def store(self, key=None, ttl=DEFAULT_STORE_TTL)
Will call the collection and store the result in Redis, and return a new collection based on this stored result. Note that only primary keys are stored, ie calls to values/values_list are ignored when storing result. But choices about instances/values_list are transmited to the new colle...
5.651349
4.915184
1.149774
# only one stored key allowed if self.stored_key: raise ValueError('This collection is already based on a stored one') # prepare the collection self.stored_key = key self.intersect(_StoredCollection(self.cls.get_connection(), key)) self.sort(by='noso...
def from_stored(self, key)
Set the current collection as based on a stored one. The key argument is the key off the stored collection.
12.032698
10.522049
1.14357
if not fields: fields = self._get_simple_fields() fields = self._coerce_fields_parameters(fields) self._instances = False self._values = {'fields': fields, 'mode': 'dicts'} return self
def values(self, *fields)
Ask the collection to return a list of dict of given fields for each instance found in the collection. If no fields are given, all "simple value" fields are used.
7.940937
7.103231
1.117933
flat = kwargs.pop('flat', False) if kwargs: raise ValueError('Unexpected keyword arguments for the values method: %s' % list(kwargs)) if not fields: fields = self._get_simple_fields() if flat and len(fields) > 1: ...
def values_list(self, *fields, **kwargs)
Ask the collection to return a list of tuples of given fields (in the given order) for each instance found in the collection. If 'flat=True' is passed, the resulting list will be flat, ie without tuple. It's a valid kwarg only if only one field is given. If no fields are given, all "simp...
4.39476
4.007265
1.096698
# set requested time range based on given parameters starttime_mjd = d['starttime_mjd'] timeskip = d['inttime']*d['nskip'] starttime = qa.getvalue(qa.convert(qa.time(qa.quantity(starttime_mjd+timeskip/(24.*60*60),'d'),form=['ymd'], prec=9)[0], 's'))[0] stoptime = qa.getvalue(qa.convert(qa.time...
def readiterinit(d)
Prepare to read data with ms.iter*
4.301506
4.259319
1.009905
da = ms.getdata([d['datacol'],'axis_info','u','v','w','flag','data_desc_id'], ifraxis=True) good = n.where((da['data_desc_id']) == d['spwlist'][0])[0] # take first spw time0 = da['axis_info']['time_axis']['MJDseconds'][good] data0 = n.transpose(da[...
def readiter(d)
Read iteration of size iterint
3.489731
3.498455
0.997506
# set requested time range based on given parameters starttime = qa.getvalue(qa.convert(qa.time(qa.quantity(d['segmenttimes'][segment,0],'d'),form=['ymd'], prec=9)[0], 's'))[0] stoptime = qa.getvalue(qa.convert(qa.time(qa.quantity(d['segmenttimes'][segment,1],'d'),form=['ymd'], prec=9)[0], 's'))[0] ...
def readsegment(d, segment)
Prepare to read segment of data
3.335406
3.33045
1.001488
if namespace is None: namespace = inspect.currentframe().f_back.f_globals elif type(namespace) is types.ModuleType: namespace = namespace.__dict__ if args is None: args = sys.argv if len(args) < 2 or args[1] in ('-h', '--help'): print_help(namespace, comman...
def autocmds(namespace=None, args=None, command_suffix='_command', add_dry_run_option=True, add_verbosity_option=True)
Parse and run commands. Will search ``namespace`` for functions that end with ``command_suffix``. :param namespace: the namespace/module to search for commands :param args: the arguments for the command parser. defaults to :data:`sys.argv` :param command_suffix: function name suffix th...
2.083609
2.118602
0.983483
param_re = re.compile(r, re.MULTILINE|re.VERBOSE) params = {} for match in param_re.finditer(doc): parts = match.groupdict() body_lines = parts['body'].strip().split('\n') params[parts['param']] = ' '.join(s.strip() for s in body_lines) return ...
def parse_rst_params(doc)
Parse a reStructuredText docstring and return a dictionary with parameter names and descriptions. >>> doc = ''' ... :param foo: foo parameter ... foo parameter ... ... :param bar: bar parameter ... :param baz: baz parameter ... baz parameter ... baz parameter...
3.349389
3.795641
0.88243
tokens = language.split('-') if len(tokens) == 1: return tokens[0] return "%s_%s" % (tokens[0], tokens[1].upper())
def language_to_locale(language)
Converts django's `LANGUAGE_CODE` settings to a proper locale code.
2.628413
2.400481
1.094953
if func is None: # returns a decorator fun = FunctionMaker(caller) first_arg = inspect.getargspec(caller)[0][0] src = 'def %s(%s): return _call_(caller, %s)' % ( caller.__name__, first_arg, first_arg) return fun.make(src, dict(caller=caller, _call_=decorator), ...
def decorator(caller, func=None)
decorator(caller) converts a caller function into a decorator; decorator(caller, func) decorates a function using a caller.
3.90554
3.858927
1.012079
logger.info('Working directory: {0}'.format(os.getcwd())) logger.info('Run on {0}'.format(asctime())) try: fileroot = os.environ['fileroot'] logger.info('Setting fileroot to {0} from environment variable.\n'.format(fileroot)) candsfile = 'cands_{0}_merge.pkl'.format(fileroot) ...
def initializenb()
Find input files and log initialization info
2.879116
2.798078
1.028962
data = readdata(mergepkl) circleinds = calcinds(data, thresh, ignoret) crossinds = calcinds(data, -1*thresh, ignoret) edgeinds = calcinds(data, thresh_link, ignoret) workdir = os.path.dirname(mergepkl) fileroot = os.path.basename(mergepkl).rstrip('_merge.pkl').lstrip('cands_') logger...
def plot_interactive(mergepkl, noisepkl=None, thresh=6.0, thresh_link=7.0, ignoret=None, savehtml=True, url_path='plots')
Backwards compatible function for making interactive candidate summary plot
4.063939
4.105458
0.989887
fields = ['dm', 'time', 'sizes', 'colors', 'snrs', 'key'] if not circleinds: circleinds = range(len(data['snrs'])) # set ranges datalen = len(data['dm']) inds = circleinds + crossinds + edgeinds dm = [data['dm'][i] for i in inds] dm_min = min(min(dm), max(dm)/1.2) dm_max = max(ma...
def plotdmt(data, circleinds=[], crossinds=[], edgeinds=[], url_path=None, fileroot=None, tools="hover,tap,pan,box_select,wheel_zoom,reset", plot_width=950, plot_height=500)
Make a light-weight dm-time figure
2.471073
2.475354
0.998271
fields = ['l1', 'm1', 'sizes', 'colors', 'snrs', 'key'] if not circleinds: circleinds = range(len(data['snrs'])) # set ranges datalen = len(data['dm']) inds = circleinds + crossinds + edgeinds l1 = [data['l1'][i] for i in inds] l1_min = min(l1) l1_max = max(l1) m1 = [data['m1...
def plotloc(data, circleinds=[], crossinds=[], edgeinds=[], url_path=None, fileroot=None, tools="hover,tap,pan,box_select,wheel_zoom,reset", plot_width=450, plot_height=400)
Make a light-weight loc figure
2.126895
2.143074
0.992451
fields = ['imkur', 'specstd', 'sizes', 'colors', 'snrs', 'key'] if not circleinds: circleinds = range(len(data['snrs'])) # set ranges datalen = len(data['dm']) inds = circleinds + crossinds + edgeinds specstd = [data['specstd'][i] for i in inds] specstd_min = min(specstd) specstd...
def plotstat(data, circleinds=None, crossinds=None, edgeinds=None, url_path=None, fileroot=None, tools="hover,tap,pan,box_select,wheel_zoom,reset", plot_width=450, plot_height=400)
Make a light-weight stat figure
2.290477
2.308558
0.992168
fields = ['zs', 'sizes', 'colors', 'abssnr', 'key', 'snrs'] if not circleinds: circleinds = range(len(data['snrs'])) source = ColumnDataSource(data = dict({(key, tuple([value[i] for i in circleinds if i not in edgeinds])) for (key, value) in data.iteritems...
def plotnorm(data, circleinds=[], crossinds=[], edgeinds=[], url_path=None, fileroot=None, tools="hover,tap,pan,box_select,wheel_zoom,reset", plot_width=450, plot_height=400)
Make a light-weight norm figure
2.347143
2.347876
0.999688