code stringlengths 1 18.2k |
|---|
def time(self): """Retrieve the current time from the redis server. :rtype: float :raises: :exc:`~tredis.exceptions.RedisError` """ def format_response(value): """Format a TIME response into a datetime.datetime :param list value: TIME response is a list of the number of seconds since the epoch and the number of micros ... |
def get_show_name(self): """ Get video show name from the website. It's located in the div with 'data-hover' attribute under the 'title' key. Returns: str: Video show name. """ div = self.soup.find('div', attrs={'data-hover': True}) data = json.loads(div['data-hover']) show_name = data.get('title') return show_name |
def mk_req(self, url, **kwargs): """ Helper function to create a tornado HTTPRequest object, kwargs get passed in to create the HTTPRequest object. See: http://tornado.readthedocs.org/en/latest/httpclient.html#request-objects """ req_url = self.base_url + url req_kwargs = kwargs req_kwargs['ca_certs'] = req_kwargs.get(... |
def mk_url(self, *args, **kwargs): """ Args get parameterized into base url: *(foo, bar, baz) -> /foo/bar/baz Kwargs get encoded and appended to base url: **{'hello':'world'} -> /foo/bar/baz?hello=world """ params = urlencode(kwargs) url = '/' + '/'.join([x for x in args if x]) if params: url += '?' + params return url |
def ping(self, callback=None, **kwargs): """ Ping request to check status of elasticsearch host """ self.client.fetch( self.mk_req('', method='HEAD', **kwargs), callback = callback ) |
def info(self, callback=None, **kwargs): """ Get the basic info from the current cluster. """ self.client.fetch( self.mk_req('', method='GET', **kwargs), callback = callback ) |
def create_doc(self, index, doc_type, body, doc_id = None, params = {}, callback = None, **kwargs ): """ Adds a typed JSON document in a specific index, making it searchable. Behind the scenes this method calls index(..., op_type='create') `<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-ind... |
the document :arg ttl: Expiration time for the document :arg version: Explicit version number for concurrency control :arg version_type: Specific version type """ method = 'PUT' if doc_id else 'POST' query_params = ('consistency', 'op_type', 'parent', 'refresh', 'replication', 'routing', 'timeout', 'timestamp', 'ttl', ... |
def scroll(self, scroll_id, params={}, callback=None, **kwargs): """ Scroll a search request created by specifying the scroll parameter. `<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-scroll.html>`_ :arg scroll_id: The scroll ID :arg scroll: Specify how long a consistent view of ... |
def clear_scroll(self, scroll_id = None, body = '', params = {}, callback = None, **kwargs ): """ Clear the scroll request created by specifying the scroll parameter to search. `<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-scroll.html>`_ :arg scroll_id: The scroll ID or a list o... |
def abort_benchmark(self, name=None, params={}, body='', callback=None, **kwargs): """ Aborts a running benchmark. `<http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/search-benchmark.html>`_ :arg name: A benchmark name """ url = self.mk_url(*['_bench', 'abort', name]) self.client.fetch( self.mk_req(... |
def list_benchmarks(self, index = None, doc_type = None, params = {}, cb = None, **kwargs ): """ View the progress of long-running benchmarks. `<http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/search-benchmark.html>`_ :arg index: A comma-separated list of index names; use `_all` or empty string to ... |
def put_script(self, lang, script_id, body, params={}, callback=None, **kwargs): """ Create a script in given language with specified ID. `<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/modules-scripting.html>`_ :arg lang: Script language :arg script_id: Script ID :arg body: The document :arg op... |
def put_template(self, temp_id, body, params={}, callback=None, **kwargs): """ Create a search template. `<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-template.html>`_ :arg temp_id: Template ID :arg body: The document """ url = self.mk_url(*['_search', 'template', temp_id]) self.client.... |
def delete_template(self, temp_id=None, params={}, callback=None, **kwargs): """ Delete a search template. `<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-template.html>`_ :arg temp_id: Template ID """ url = self.mk_url(*['_search', 'template', temp_id]) self.client.fetch( self.mk_req(url... |
def report(title='Unhandled Exception', exec_info=(), **kwargs): """ Create a technical server error response. The last three arguments are the values returned from sys.exc_info() and friends. :param title: Title of error email :type title: str :param exec_info: exc_info from traceback """ exc_type, exc_value, tb = exe... |
def get_traceback_data(self): """Return a dictionary containing traceback information.""" default_template_engine = None if default_template_engine is None: template_loaders = [] frames = self.get_traceback_frames() for i, frame in enumerate(frames): if 'vars' in frame: frame_vars = [] for k, v in frame['vars']: v = pf... |
'is_email': False, 'frames': frames, 'sys_executable': sys.executable, 'sys_version_info': '%d.%d.%d' % sys.version_info[0:3], 'sys_path': sys.path, } # Check whether exception info is available if self.exc_type: c['exception_type'] = self.exc_type.__name__ if self.exc_value: c['exception_value'] = self.exc_value if fr... |
def get_traceback_html(self, **kwargs): "Return HTML version of debug 500 HTTP error page." t = Template(TECHNICAL_500_TEMPLATE) c = self.get_traceback_data() c['kwargs'] = kwargs return t.render(Context(c)) |
def _get_lines_from_file(self, filename, lineno, context_lines, loader=None, module_name=None): """ Returns context_lines before and after lineno from file. Returns (pre_context_lineno, pre_context, context_line, post_context). """ source = None if loader is not None and hasattr(loader, "get_source"): try: source = loa... |
# (http://www.python.org/dev/peps/pep-0263/) match = re.search(br'coding[:=]\s*([-\w.]+)', line) if match: encoding = match.group(1).decode('ascii') break source = [six.text_type(sline, encoding, 'replace') for sline in source] lower_bound = max(0, lineno - context_lines) upper_bound = lineno + context_lines pre_contex... |
def get_traceback_frames(self): """Returns the traceback frames as a list""" frames = [] tb = self.tb while tb is not None: # Support for __traceback_hide__ which is used by a few libraries # to hide internal frames. if tb.tb_frame.f_locals.get('__traceback_hide__'): tb = tb.tb_next continue filename = tb.tb_frame.f_co... |
def format_exception(self): """ Return the same data as from traceback.format_exception. """ import traceback frames = self.get_traceback_frames() tb = [(f['filename'], f['lineno'], f['function'], f['context_line']) for f in frames] list = ['Traceback (most recent call last):\n'] list += traceback.format_list(tb) list ... |
def delete(self, *keys): """Removes the specified keys. A key is ignored if it does not exist. Returns :data:`True` if all keys are removed. .. note:: **Time complexity**: ``O(N)`` where ``N`` is the number of keys that will be removed. When a key to remove holds a value other than a string, the individual complexity f... |
def expire(self, key, timeout): """Set a timeout on key. After the timeout has expired, the key will automatically be deleted. A key with an associated timeout is often said to be volatile in Redis terminology. The timeout is cleared only when the key is removed using the :meth:`~tredis.RedisClient.delete` method or ov... |
turning the key back into a persistent key, using the :meth:`~tredis.RedisClient.persist` method. If a key is renamed with :meth:`~tredis.RedisClient.rename`, the associated time to live is transferred to the new key name. If a key is overwritten by :meth:`~tredis.RedisClient.rename`, like in the case of an existing ke... |
def expireat(self, key, timestamp): """:meth:`~tredis.RedisClient.expireat` has the same effect and semantic as :meth:`~tredis.RedisClient.expire`, but instead of specifying the number of seconds representing the TTL (time to live), it takes an absolute Unix timestamp (seconds since January 1, 1970). Please for the spe... |
def migrate(self, host, port, key, destination_db, timeout, copy=False, replace=False): """Atomically transfer a key from a source Redis instance to a destination Redis instance. On success the key is deleted from the original instance and is guaranteed to exist in the target instance. The command is atomic and blocks ... |
to migrate the key to :type host: bytes, str :param int port: The port to connect on :param key: The key to migrate :type key: bytes, str :param int destination_db: The database number to select :param int timeout: The maximum idle time in milliseconds :param bool copy: Do not remove the key from the local instance :pa... |
def move(self, key, db): """Move key from the currently selected database (see :meth:`~tredis.RedisClient.select`) to the specified destination database. When key already exists in the destination database, or it does not exist in the source database, it does nothing. It is possible to use :meth:`~tredis.RedisClient.mo... |
def pexpire(self, key, timeout): """This command works exactly like :meth:`~tredis.RedisClient.pexpire` but the time to live of the key is specified in milliseconds instead of seconds. .. note:: **Time complexity**: ``O(1)`` :param key: The key to set an expiration for :type key: :class:`str`, :class:`bytes` :param int... |
def pexpireat(self, key, timestamp): """:meth:`~tredis.RedisClient.pexpireat` has the same effect and semantic as :meth:`~tredis.RedisClient.expireat`, but the Unix time at which the key will expire is specified in milliseconds instead of seconds. .. note:: **Time complexity**: ``O(1)`` :param key: The key to set an ex... |
def rename(self, key, new_key): """Renames ``key`` to ``new_key``. It returns an error when the source and destination names are the same, or when ``key`` does not exist. If ``new_key`` already exists it is overwritten, when this happens :meth:`~tredis.RedisClient.rename` executes an implicit :meth:`~tredis.RedisClient... |
def restore(self, key, ttl, value, replace=False): """Create a key associated with a value that is obtained by deserializing the provided serialized value (obtained via :meth:`~tredis.RedisClient.dump`). If ``ttl`` is ``0`` the key is created without any expire, otherwise the specified expire time (in milliseconds) is ... |
``O(1)+O(1*M)`` where ``M`` is small, so simply ``O(1)``. However for sorted set values the complexity is ``O(N*M*log(N))`` because inserting values into sorted sets is ``O(log(N))``. :param key: The key to get the TTL for :type key: :class:`str`, :class:`bytes` :param int ttl: The number of seconds to set the timeout ... |
def scan(self, cursor=0, pattern=None, count=None): """The :meth:`~tredis.RedisClient.scan` command and the closely related commands :meth:`~tredis.RedisClient.sscan`, :meth:`~tredis.RedisClient.hscan` and :meth:`~tredis.RedisClient.zscan` are used in order to incrementally iterate over a collection of elements. - :met... |
is ``0``. For more information on :meth:`~tredis.RedisClient.scan`, visit the `Redis docs on scan <http://redis.io/commands/scan>`_. .. note:: **Time complexity**: ``O(1)`` for every call. ``O(N)`` for a complete iteration, including enough command calls for the cursor to return back to ``0``. ``N`` is the number of el... |
if pattern: command += [b'MATCH', pattern] if count: command += [b'COUNT', ascii(count).encode('ascii')] return self._execute(command, format_callback=format_response) |
def sort(self, key, by=None, external=None, offset=0, limit=None, order=None, alpha=False, store_as=None): """Returns or stores the elements contained in the list, set or sorted set at key. By default, sorting is numeric and elements are compared by their value interpreted as double precision floating point number. The... |
:type key: :class:`str`, :class:`bytes` :param by: The optional pattern for external sorting keys :type by: :class:`str`, :class:`bytes` :param external: Pattern or list of patterns to return external keys :type external: :class:`str`, :class:`bytes`, list :param int offset: The starting offset when using limit :param ... |
in external: command += [b'GET', entry] elif external: command += [b'GET', external] if limit: command += [ b'LIMIT', ascii(offset).encode('utf-8'), ascii(limit).encode('utf-8') ] if order: command.append(order) if alpha is True: command.append(b'ALPHA') if store_as: command += [b'STORE', store_as] return self._execute... |
def wait(self, num_slaves, timeout=0): """his command blocks the current client until all the previous write commands are successfully transferred and acknowledged by at least the specified number of slaves. If the timeout, specified in milliseconds, is reached, the command returns even if the specified number of slave... |
def enable_thread_profiling(profile_dir, exception_callback=None): """ Monkey-patch the threading.Thread class with our own ProfiledThread. Any subsequent imports of threading.Thread will reference ProfiledThread instead. """ global profiled_thread_enabled, Thread, Process if os.path.isdir(profile_dir): _Profiler.profi... |
def enable_thread_logging(exception_callback=None): """ Monkey-patch the threading.Thread class with our own LoggedThread. Any subsequent imports of threading.Thread will reference LoggedThread instead. """ global logged_thread_enabled, Thread LoggedThread.exception_callback = exception_callback Thread = threading.Thre... |
def image(request, obj_id): """Handles a request based on method and calls the appropriate function""" obj = Image.objects.get(pk=obj_id) if request.method == 'POST': return post(request, obj) elif request.method == 'PUT': getPutData(request) return put(request, obj) elif request.method == 'DELETE': getPutData(request)... |
def video(request, obj_id): """Handles a request based on method and calls the appropriate function""" obj = Video.objects.get(pk=obj_id) if request.method == 'POST': return post(request, obj) elif request.method == 'PUT': getPutData(request) return put(request, obj) elif request.method == 'DELETE': getPutData(request)... |
def parse_from_calc(self): """ Parses the datafolder, stores results. This parser for this simple code does simply store in the DB a node representing the file of forces in real space """ from aiida.common.exceptions import InvalidOperation from aiida.common import aiidalogger from aiida.backends.djsite.utils import ge... |
# output structure has_out_atoms = True if self._calc._output_aseatoms in list_of_files else False if has_out_atoms: out_atoms = ase.io.read( out_folder.get_abs_path( self._calc._output_aseatoms ) ) out_structure = StructureData().set_ase(out_atoms) # load the results dictionary json_outfile = out_folder.get_abs_path( ... |
(self._outstruc_name, structure_data) ) return successful,new_nodes_list |
def hset(self, key, field, value): """Sets `field` in the hash stored at `key` to `value`. If `key` does not exist, a new key holding a hash is created. If `field` already exists in the hash, it is overwritten. .. note:: **Time complexity**: always ``O(1)`` :param key: The key of the hash :type key: :class:`str`, :clas... |
def hgetall(self, key): """ Returns all fields and values of the has stored at `key`. The underlying redis `HGETALL`_ command returns an array of pairs. This method converts that to a Python :class:`dict`. It will return an empty :class:`dict` when the key is not found. .. note:: **Time complexity**: ``O(N)`` where ``N... |
def hmset(self, key, value_dict): """ Sets fields to values as in `value_dict` in the hash stored at `key`. Sets the specified fields to their respective values in the hash stored at `key`. This command overwrites any specified fields already existing in the hash. If `key` does not exist, a new key holding a hash is cr... |
def hmget(self, key, *fields): """ Returns the values associated with the specified `fields` in a hash. For every ``field`` that does not exist in the hash, :data:`None` is returned. Because a non-existing keys are treated as empty hashes, calling :meth:`hmget` against a non-existing key will return a list of :data:`No... |
def hdel(self, key, *fields): """ Remove the specified fields from the hash stored at `key`. Specified fields that do not exist within this hash are ignored. If `key` does not exist, it is treated as an empty hash and this command returns zero. :param key: The key of the hash :type key: :class:`str`, :class:`bytes` :pa... |
def hincrby(self, key, field, increment): """ Increments the number stored at `field` in the hash stored at `key`. If `key` does not exist, a new key holding a hash is created. If `field` does not exist the value is set to ``0`` before the operation is performed. The range of values supported is limited to 64-bit signe... |
def hincrbyfloat(self, key, field, increment): """ Increments the number stored at `field` in the hash stored at `key`. If the increment value is negative, the result is to have the hash field **decremented** instead of incremented. If the field does not exist, it is set to ``0`` before performing the operation. An err... |
:type increment: float :returns: the value at `field` after the increment occurs :rtype: float """ return self._execute( [b'HINCRBYFLOAT', key, field, increment], format_callback=float) |
def hsetnx(self, key, field, value): """ Sets `field` in the hash stored at `key` only if it does not exist. Sets `field` in the hash stored at `key` only if `field` does not yet exist. If `key` does not exist, a new key holding a hash is created. If `field` already exists, this operation has no effect. .. note:: *Time... |
key, field, value]) |
def create_snapshot(self, repository, snapshot, body, params={}, callback=None, **kwargs): """ Create a snapshot in repository `<http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/modules-snapshots.html>`_ :arg repository: A repository name :arg snapshot: A snapshot name :arg body: The snapshot defini... |
def verify_repository(self, repository, master_timeout = 10, timeout = 10, body = '', params = {}, callback = None, **kwargs ): """ Returns a list of nodes where repository was successfully verified or an error message if verification process failed. `<http://www.elasticsearch.org/guide/en/elasticsearch/reference/curre... |
def main(): # pylint: disable-msg=R0912,R0915 """Main.""" parser = optparse.OptionParser() parser.usage = textwrap.dedent("""\ %prog {--run|--install_key|--dump_config} [options] SSH command authenticator. Used to restrict which commands can be run via trusted SSH keys. """) group = optparse.OptionGroup( parser, 'Run M... |
dest='configdir', help='Path to authprogs configuration directory. ' 'Defaults to ~/.ssh/authprogs.d', metavar='DIR') group.add_option('--logfile', dest='logfile', help='Write logging info to this file. ' 'Defaults to no logging.', metavar='FILE') group.add_option('--debug', dest='debug', action='store_true', help='Wri... |
%s' % err) sys.exit(1) elif opts.run: ap.exec_command() sys.exit('authprogs command returned - should ' 'never happen.') else: parser.error('Not sure what to do. Consider --help') except SSHEnvironmentError as err: ap.log('SSHEnvironmentError "%s"\n%s\n' % ( err, traceback.format_exc())) sys.exit('authprogs: %s' % err)... |
def raise_and_log_error(self, error, message): """Raise error, including message and original traceback. error: the error to raise message: the user-facing error message """ self.log('raising %s, traceback %s\n' % (error, traceback.format_exc())) raise error(message) |
def get_client_ip(self): """Return the client IP from the environment.""" if self.client_ip: return self.client_ip try: client = os.environ.get('SSH_CONNECTION', os.environ.get('SSH_CLIENT')) self.client_ip = client.split()[0] self.logdebug('client_ip: %s\n' % self.client_ip) return self.client_ip except: raise SSHEnvi... |
def check_keyname(self, rule): """If a key name is specified, verify it is permitted.""" keynames = rule.get('keynames') if not keynames: self.logdebug('no keynames requirement.\n') return True if not isinstance(keynames, list): keynames = [keynames] if self.keyname in keynames: self.logdebug('keyname "%s" matches rule... |
def check_client_ip(self, rule): """If a client IP is specified, verify it is permitted.""" if not rule.get('from'): self.logdebug('no "from" requirement.\n') return True allow_from = rule.get('from') if not isinstance(allow_from, list): allow_from = [allow_from] client_ip = self.get_client_ip() if client_ip in allow_f... |
def get_merged_config(self): """Get merged config file. Returns an open StringIO containing the merged config file. """ if self.yamldocs: return loadfiles = [] if self.configfile: loadfiles.append(self.configfile) if self.configdir: # Gets list of all non-dotfile files from configdir. loadfiles.extend( [f for f in [os.... |
def load(self): """Load our config, log and raise on error.""" try: merged_configfile = self.get_merged_config() self.yamldocs = yaml.load(merged_configfile, Loader=Loader) # Strip out the top level 'None's we get from concatenation. # Functionally not required, but makes dumps cleaner. self.yamldocs = [x for x in self... |
def dump_config(self): """Pretty print the configuration dict to stdout.""" yaml_content = self.get_merged_config() print('YAML Configuration\n%s\n' % yaml_content.read()) try: self.load() print('Python Configuration\n%s\n' % pretty(self.yamldocs)) except ConfigError: sys.stderr.write( 'config parse error. try running ... |
def install_key_data(self, keydata, target): """Install the key data into the open file.""" target.seek(0) contents = target.read() ssh_opts = 'no-port-forwarding' if keydata in contents: raise InstallError('key data already in file - refusing ' 'to double-install.\n') command = '%s --run' % self.authprogs_binary if se... |
def install_key(self, keyfile, authorized_keys): """Install a key into the authorized_keys file.""" # Make the directory containing the authorized_keys # file, if it doesn't exist. (Typically ~/.ssh). # Ignore errors; we'll fail shortly if we can't # create the authkeys file. try: os.makedirs(os.path.dirname(authorized... |
def find_match_scp(self, rule): # pylint: disable-msg=R0911,R0912 """Handle scp commands.""" orig_list = [] orig_list.extend(self.original_command_list) binary = orig_list.pop(0) allowed_binaries = ['scp', '/usr/bin/scp'] if binary not in allowed_binaries: self.logdebug('skipping scp processing - binary "%s" ' 'not in ... |
'list %s\n' % (filepath, files)) return # Allow it! return {'command': self.original_command_list} |
def find_match_command(self, rule): """Return a matching (possibly munged) command, if found in rule.""" command_string = rule['command'] command_list = command_string.split() self.logdebug('comparing "%s" to "%s"\n' % (command_list, self.original_command_list)) if rule.get('allow_trailing_args'): self.logdebug('allow_... |
def find_match(self): """Load the config and find a matching rule. returns the results of find_match_command, a dict of the command and (in the future) other metadata. """ self.load() for yamldoc in self.yamldocs: self.logdebug('\nchecking rule """%s"""\n' % yamldoc) if not yamldoc: continue if not self.check_client_ip... |
def exec_command(self): """Glean the command to run and exec. On problems, sys.exit. This method should *never* return. """ if not self.original_command_string: raise SSHEnvironmentError('no SSH command found; ' 'interactive shell disallowed.') command_info = {'from': self.get_client_ip(), 'keyname': self.keyname, 'ssh... |
def _py2_crc16(value): """Calculate the CRC for the value in Python 2 :param str value: The value to return for the CRC Checksum :rtype: int """ crc = 0 for byte in value: crc = ((crc << 8) & 0xffff) ^ \ _CRC16_LOOKUP[((crc >> 8) ^ ord(byte)) & 0xff] return crc |
def _py3_crc16(value): """Calculate the CRC for the value in Python 3 :param bytes value: The value to return for the CRC Checksum :rtype: int """ crc = 0 for byte in value: crc = ((crc << 8) & 0xffff) ^ _CRC16_LOOKUP[((crc >> 8) ^ byte) & 0xff] return crc |
def validate_url(cls, url: str) -> Optional[Match[str]]: """Check if the Extractor can handle the given url.""" match = re.match(cls._VALID_URL, url) return match |
def get_info(self) -> dict: """Get information about the videos from YoutubeDL package.""" with suppress_stdout(): with youtube_dl.YoutubeDL() as ydl: info_dict = ydl.extract_info(self.url, download=False) return info_dict |
def update_entries(entries: Entries, data: dict) -> None: """Update each entry in the list with some data.""" # TODO: Is mutating the list okay, making copies is such a pain in the ass for entry in entries: entry.update(data) |
def get_extra_context(site, ctx): 'Returns extra data useful to the templates.' # XXX: clean this up from obsolete stuff ctx['site'] = site ctx['feeds'] = feeds = site.active_feeds.order_by('name') def get_mod_chk(k): mod, chk = ( (max(vals) if vals else None) for vals in ( filter(None, it.imap(op.attrgetter(k), feeds)... |
def get_posts_tags(subscribers, object_list, feed, tag_name): '''Adds a qtags property in every post object in a page. Use "qtags" instead of "tags" in templates to avoid unnecesary DB hits.''' tagd = dict() user_obj = None tag_obj = None tags = models.Tag.objects.extra( select=dict(post_id='{0}.{1}'.format( *it.imap( ... |
user_obj, tag_obj |
def get_page(site, page=1, **criterias): 'Returns a paginator object and a requested page from it.' global _since_formats_vary if 'since' in criterias: since = criterias['since'] if since in _since_offsets: since = datetime.today() - timedelta(_since_offsets[since]) else: if _since_formats_vary: for fmt, substs in it.p... |
= Paginator(posts, site.posts_per_page) try: return paginator.page(page) except InvalidPage: raise Http404 |
def page_context(request, site, **criterias): 'Returns the context dictionary for a page view.' try: page = int(request.GET.get('page', 1)) except ValueError: page = 1 feed, tag = criterias.get('feed'), criterias.get('tag') if feed: try: feed = models.Feed.objects.get(pk=feed) except ObjectDoesNotExist: raise Http404 p... |
raise Http404 site_proc_tags = site.processing_tags.strip() if site_proc_tags != 'none': site_proc_tags = filter( None, map(op.methodcaller('strip'), site.processing_tags.split(',')) ) # XXX: database hit that can be cached for site_feed, posts in it.groupby(page.object_list, key=op.attrgetter('feed')): proc = site_fee... |
for n in xrange(-10, 11)) ), ## DEPRECATED: # Totally misnamed and inconsistent b/w user/user_obj, # use "feed" and "subscribers" instead. user_id = feed and feed.id, user = user_obj, # Legacy flat pagination context, use "p" instead. is_paginated = page.paginator.num_pages > 1, results_per_page = site.posts_per_page, ... |
def bitcount(self, key, start=None, end=None): """Count the number of set bits (population counting) in a string. By default all the bytes contained in the string are examined. It is possible to specify the counting operation only in an interval passing the additional arguments start and end. Like for the :meth:`~tredi... |
The end position to evaluate in the string :rtype: int :raises: :exc:`~tredis.exceptions.RedisError`, :exc:`ValueError` """ command = [b'BITCOUNT', key] if start is not None and end is None: raise ValueError('Can not specify start without an end') elif start is None and end is not None: raise ValueError('Can not specif... |
def bitop(self, operation, dest_key, *keys): """Perform a bitwise operation between multiple keys (containing string values) and store the result in the destination key. The values for operation can be one of: - ``b'AND'`` - ``b'OR'`` - ``b'XOR'`` - ``b'NOT'`` - :data:`tredis.BITOP_AND` or ``b'&'`` - :data:`tredis.BITO... |
of the longest string. The same holds true for non-existent keys, that are considered as a stream of zero bytes up to the length of the longest string. .. versionadded:: 0.2.0 .. note:: **Time complexity**: ``O(N)`` :param bytes operation: The operation to perform :param dest_key: The key to store the bitwise operation... |
ValueError('NOT can only be used with 1 key') if operation in _BITOPTS.keys(): operation = _BITOPTS[operation] return self._execute([b'BITOP', operation, dest_key] + list(keys)) |
def bitpos(self, key, bit, start=None, end=None): """Return the position of the first bit set to ``1`` or ``0`` in a string. The position is returned, thinking of the string as an array of bits from left to right, where the first byte's most significant bit is at position 0, the second byte's most significant bit is at... |
differences as explained later). The range is interpreted as a range of bytes and not a range of bits, so ``start=0`` and ``end=2`` means to look at the first three bytes. Note that bit positions are returned always as absolute values starting from bit zero even when start and end are used to specify a range. Like for ... |
or ``0``) :param int start: The start position to evaluate in the string :param int end: The end position to evaluate in the string :returns: The position of the first bit set to ``1`` or ``0`` :rtype: int :raises: :exc:`~tredis.exceptions.RedisError`, :exc:`ValueError` """ if 0 < bit > 1: raise ValueError('bit must be... |
def decrby(self, key, decrement): """Decrements the number stored at key by decrement. If the key does not exist, it is set to 0 before performing the operation. An error is returned if the key contains a value of the wrong type or contains a string that can not be represented as integer. This operation is limited to 6... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.