code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
rep = '' for host in self.hosts.keys(): attrs = self.hosts[host] rep = rep + 'machine ' + host + '\n\tlogin ' + str(attrs[0]) + '\n' if attrs[1]: rep = rep + 'account ' + str(attrs[1]) rep = rep + '\tpassword ' + str(attrs[2]) + '\n' for macro in self.macros.keys(): rep = rep + 'macdef ' + macro + '\n' for line in self.macros[macro]: rep = rep + line rep = rep + '\n' return rep
def dump_netrc(self)
Dump the class data in the format of a .netrc file.
2.404738
2.306977
1.042376
client = obj['client'] if delete: client.delete_heartbeat(delete) else: try: heartbeat = client.heartbeat(origin=origin, tags=tags, timeout=timeout, customer=customer) except Exception as e: click.echo('ERROR: {}'.format(e)) sys.exit(1) click.echo(heartbeat.id)
def cli(obj, origin, tags, timeout, customer, delete)
Send or delete a heartbeat.
2.725463
2.411626
1.130135
client = obj['client'] if obj['output'] == 'json': r = client.http.get('/customers') click.echo(json.dumps(r['customers'], sort_keys=True, indent=4, ensure_ascii=False)) else: headers = {'id': 'ID', 'customer': 'CUSTOMER', 'match': 'GROUP'} click.echo(tabulate([c.tabular() for c in client.get_customers()], headers=headers, tablefmt=obj['output']))
def cli(obj)
List customer lookups.
3.993551
3.652021
1.093518
client = obj['client'] def send_alert(resource, event, **kwargs): try: id, alert, message = client.send_alert( resource=resource, event=event, environment=kwargs.get('environment'), severity=kwargs.get('severity'), correlate=kwargs.get('correlate', None) or list(), service=kwargs.get('service', None) or list(), group=kwargs.get('group'), value=kwargs.get('value'), text=kwargs.get('text'), tags=kwargs.get('tags', None) or list(), attributes=kwargs.get('attributes', None) or dict(), origin=kwargs.get('origin'), type=kwargs.get('type'), timeout=kwargs.get('timeout'), raw_data=kwargs.get('raw_data'), customer=kwargs.get('customer') ) except Exception as e: click.echo('ERROR: {}'.format(e)) sys.exit(1) if alert: if alert.repeat: message = '{} duplicates'.format(alert.duplicate_count) else: message = '{} -> {}'.format(alert.previous_severity, alert.severity) click.echo('{} ({})'.format(id, message)) # read entire alert object from terminal stdin if not sys.stdin.isatty() and (os.environ.get('TERM', None) or os.environ.get('PS1', None)): with click.get_text_stream('stdin') as stdin: for line in stdin.readlines(): try: payload = json.loads(line) except Exception as e: click.echo('ERROR: JSON parse failure - {}'.format(e)) sys.exit(1) send_alert(**payload) sys.exit(0) # read raw data from file or stdin if raw_data and raw_data.startswith('@') or raw_data == '-': raw_data_file = raw_data.lstrip('@') with click.open_file(raw_data_file, 'r') as f: raw_data = f.read() send_alert( resource=resource, event=event, environment=environment, severity=severity, correlate=correlate, service=service, group=group, value=value, text=text, tags=tags, attributes=dict(a.split('=', maxsplit=1) if '=' in a else (a, None) for a in attributes), origin=origin, type=type, timeout=timeout, raw_data=raw_data, customer=customer )
def cli(obj, resource, event, environment, severity, correlate, service, group, value, text, tags, attributes, origin, type, timeout, raw_data, customer)
Send an alert.
2.065721
2.054677
1.005375
client = obj['client'] if obj['output'] == 'json': r = client.http.get('/keys') click.echo(json.dumps(r['keys'], sort_keys=True, indent=4, ensure_ascii=False)) else: timezone = obj['timezone'] headers = { 'id': 'ID', 'key': 'API KEY', 'user': 'USER', 'scopes': 'SCOPES', 'text': 'TEXT', 'expireTime': 'EXPIRES', 'count': 'COUNT', 'lastUsedTime': 'LAST USED', 'customer': 'CUSTOMER' } click.echo(tabulate([k.tabular(timezone) for k in client.get_keys()], headers=headers, tablefmt=obj['output']))
def cli(obj)
List API keys.
3.996019
3.655952
1.093018
client = obj['client'] if delete: client.delete_perm(delete) else: if not role: raise click.UsageError('Missing option "--role".') if not scopes: raise click.UsageError('Missing option "--scope".') try: perm = client.create_perm(role, scopes) except Exception as e: click.echo('ERROR: {}'.format(e)) sys.exit(1) click.echo(perm.id)
def cli(obj, role, scopes, delete)
Add or delete role-to-permission lookup entry.
2.657549
2.661563
0.998492
client = obj['client'] timezone = obj['timezone'] screen = Screen(client, timezone) screen.run()
def cli(obj)
Display alerts like unix "top" command.
7.012528
6.583086
1.065234
client = obj['client'] if obj['output'] == 'json': r = client.http.get('/heartbeats') click.echo(json.dumps(r['heartbeats'], sort_keys=True, indent=4, ensure_ascii=False)) else: timezone = obj['timezone'] headers = { 'id': 'ID', 'origin': 'ORIGIN', 'customer': 'CUSTOMER', 'tags': 'TAGS', 'createTime': 'CREATED', 'receiveTime': 'RECEIVED', 'latency': 'LATENCY', 'timeout': 'TIMEOUT', 'since': 'SINCE', 'status': 'STATUS' } heartbeats = client.get_heartbeats() click.echo(tabulate([h.tabular(timezone) for h in heartbeats], headers=headers, tablefmt=obj['output'])) not_ok = [hb for hb in heartbeats if hb.status != 'ok'] if purge: with click.progressbar(not_ok, label='Purging {} heartbeats'.format(len(not_ok))) as bar: for b in bar: client.delete_heartbeat(b.id) elif alert: with click.progressbar(heartbeats, label='Alerting {} heartbeats'.format(len(heartbeats))) as bar: for b in bar: params = dict(filter(lambda a: len(a) == 2, map(lambda a: a.split(':'), b.tags))) environment = params.get('environment', 'Production') group = params.get('group', 'System') tags = list(filter(lambda a: not a.startswith('environment:') and not a.startswith('group:'), b.tags)) if b.status == 'expired': # aka. "stale" client.send_alert( resource=b.origin, event='HeartbeatFail', correlate=['HeartbeatFail', 'HeartbeatSlow', 'HeartbeatOK'], group=group, environment=environment, service=['Alerta'], severity=severity, value='{}'.format(b.since), text='Heartbeat not received in {} seconds'.format(b.timeout), tags=tags, type='heartbeatAlert', timeout=timeout, customer=b.customer ) elif b.status == 'slow': client.send_alert( resource=b.origin, event='HeartbeatSlow', correlate=['HeartbeatFail', 'HeartbeatSlow', 'HeartbeatOK'], group=group, environment=environment, service=['Alerta'], severity=severity, value='{}ms'.format(b.latency), text='Heartbeat took more than {}ms to be processed'.format(MAX_LATENCY), tags=tags, type='heartbeatAlert', timeout=timeout, customer=b.customer ) else: client.send_alert( resource=b.origin, event='HeartbeatOK', correlate=['HeartbeatFail', 'HeartbeatSlow', 'HeartbeatOK'], group=group, environment=environment, service=['Alerta'], severity='normal', value='', text='Heartbeat OK', tags=tags, type='heartbeatAlert', customer=b.customer )
def cli(obj, alert, severity, timeout, purge)
List heartbeats.
2.562597
2.513468
1.019546
client = obj['client'] client.housekeeping(expired_delete_hours=expired, info_delete_hours=info)
def cli(obj, expired=None, info=None)
Trigger the expiration and deletion of alerts.
9.312928
9.345525
0.996512
client = obj['client'] if obj['output'] == 'json': r = client.http.get('/blackouts') click.echo(json.dumps(r['blackouts'], sort_keys=True, indent=4, ensure_ascii=False)) else: timezone = obj['timezone'] headers = { 'id': 'ID', 'priority': 'P', 'environment': 'ENVIRONMENT', 'service': 'SERVICE', 'resource': 'RESOURCE', 'event': 'EVENT', 'group': 'GROUP', 'tags': 'TAGS', 'customer': 'CUSTOMER', 'startTime': 'START', 'endTime': 'END', 'duration': 'DURATION', 'user': 'USER', 'createTime': 'CREATED', 'text': 'COMMENT', 'status': 'STATUS', 'remaining': 'REMAINING' } blackouts = client.get_blackouts() click.echo(tabulate([b.tabular(timezone) for b in blackouts], headers=headers, tablefmt=obj['output'])) expired = [b for b in blackouts if b.status == 'expired'] if purge: with click.progressbar(expired, label='Purging {} blackouts'.format(len(expired))) as bar: for b in bar: client.delete_blackout(b.id)
def cli(obj, purge)
List alert suppressions.
3.061965
3.060707
1.000411
client = obj['client'] if not email: raise click.UsageError('Need "--email" to sign-up new user.') if not password: raise click.UsageError('Need "--password" to sign-up new user.') try: r = client.signup(name=name, email=email, password=password, status=status, attributes=None, text=text) except Exception as e: click.echo('ERROR: {}'.format(e)) sys.exit(1) if 'token' in r: click.echo('Signed Up.') else: raise AuthError
def cli(obj, name, email, password, status, text)
Create new Basic Auth user.
2.91491
2.853072
1.021674
config = Config(config_file) config.get_config_for_profle(profile) config.get_remote_config(endpoint_url) ctx.obj = config.options # override current options with command-line options or environment variables ctx.obj['output'] = output or config.options['output'] ctx.obj['color'] = color or os.environ.get('CLICOLOR', None) or config.options['color'] endpoint = endpoint_url or config.options['endpoint'] ctx.obj['client'] = Client( endpoint=endpoint, key=config.options['key'], token=get_token(endpoint), username=config.options.get('username', None), password=config.options.get('password', None), timeout=float(config.options['timeout']), ssl_verify=config.options['sslverify'], debug=debug or os.environ.get('DEBUG', None) or config.options['debug'] )
def cli(ctx, config_file, profile, endpoint_url, output, color, debug)
Alerta client unified command-line tool.
2.964199
2.979142
0.994984
client = obj['client'] if ids: query = [('id', x) for x in ids] elif query: query = [('q', query)] else: query = build_query(filters) alerts = client.search(query) headers = {'id': 'ID', 'rawData': 'RAW DATA'} click.echo( tabulate([{'id': a.id, 'rawData': a.raw_data} for a in alerts], headers=headers, tablefmt=obj['output']))
def cli(obj, ids, query, filters)
Show raw data for alerts.
3.697277
3.45237
1.070939
if not any([name, email, password, status, text]): click.echo('Nothing to update.') sys.exit(1) client = obj['client'] try: r = client.update_me(name=name, email=email, password=password, status=status, attributes=None, text=text) except Exception as e: click.echo('ERROR: {}'.format(e)) sys.exit(1) if r['status'] == 'ok': click.echo('Updated.') else: click.echo(r['message'])
def cli(obj, name, email, password, status, text)
Update current user details, including password reset.
2.358841
2.31314
1.019757
client = obj['client'] if obj['output'] == 'json': r = client.http.get('/alerts/history') click.echo(json.dumps(r['history'], sort_keys=True, indent=4, ensure_ascii=False)) else: timezone = obj['timezone'] if ids: query = [('id', x) for x in ids] elif query: query = [('q', query)] else: query = build_query(filters) alerts = client.get_history(query) headers = {'id': 'ID', 'updateTime': 'LAST UPDATED', 'severity': 'SEVERITY', 'status': 'STATUS', 'type': 'TYPE', 'customer': 'CUSTOMER', 'environment': 'ENVIRONMENT', 'service': 'SERVICE', 'resource': 'RESOURCE', 'group': 'GROUP', 'event': 'EVENT', 'value': 'VALUE', 'text': 'TEXT'} click.echo( tabulate([a.tabular(timezone) for a in alerts], headers=headers, tablefmt=obj['output']))
def cli(obj, ids, query, filters)
Show status and severity changes for alerts.
3.137135
3.002987
1.044672
'''Converts files to a format that pocketsphinx can deal wtih (16khz mono 16bit wav)''' converted = [] for f in files: new_name = f + '.temp.wav' print(new_name) if (os.path.exists(f + '.transcription.txt') is False) and (os.path.exists(new_name) is False): subprocess.call(['ffmpeg', '-y', '-i', f, '-acodec', 'pcm_s16le', '-ac', '1', '-ar', '16000', new_name]) converted.append(new_name) return converted
def convert_to_wav(files)
Converts files to a format that pocketsphinx can deal wtih (16khz mono 16bit wav)
2.958765
2.140177
1.382486
'''Uses pocketsphinx to transcribe audio files''' total = len(files) for i, f in enumerate(files): filename = f.replace('.temp.wav', '') + '.transcription.txt' if os.path.exists(filename) is False: print(str(i+1) + '/' + str(total) + ' Transcribing ' + f) transcript = subprocess.check_output(['pocketsphinx_continuous', '-infile', f, '-time', 'yes', '-logfn', '/dev/null', '-vad_prespeech', str(pre), '-vad_postspeech', str(post)]) with open(filename, 'w') as outfile: outfile.write(transcript.decode('utf8')) os.remove(f)
def transcribe(files=[], pre=10, post=50)
Uses pocketsphinx to transcribe audio files
3.282833
3.265672
1.005255
'''Converts pocketsphinx transcriptions to usable timestamps''' sentences = [] for f in files: if not f.endswith('.transcription.txt'): f = f + '.transcription.txt' if os.path.exists(f) is False: continue with open(f, 'r') as infile: lines = infile.readlines() lines = [re.sub(r'\(.*?\)', '', l).strip().split(' ') for l in lines] lines = [l for l in lines if len(l) == 4] seg_start = -1 seg_end = -1 for index, line in enumerate(lines): word, start, end, conf = line if word == '<s>' or word == '<sil>' or word == '</s>': if seg_start == -1: seg_start = index seg_end = -1 else: seg_end = index if seg_start > -1 and seg_end > -1: words = lines[seg_start+1:seg_end] start = float(lines[seg_start][1]) end = float(lines[seg_end][1]) if words: sentences.append({'start': start, 'end': end, 'words': words, 'file': f}) if word == '</s>': seg_start = -1 else: seg_start = seg_end seg_end = -1 return sentences
def convert_timestamps(files)
Converts pocketsphinx transcriptions to usable timestamps
2.375813
2.215681
1.072272
'''Returns the whole transcribed text''' sentences = convert_timestamps(files) out = [] for s in sentences: out.append(' '.join([w[0] for w in s['words']])) return '\n'.join(out)
def text(files)
Returns the whole transcribed text
5.174881
4.215442
1.227601
'''Searches for words or sentences containing a search phrase''' out = [] sentences = convert_timestamps(files) if mode == 'fragment': out = fragment_search(query, sentences, regex) elif mode == 'word': out = word_search(query, sentences, regex) elif mode == 'franken': out = franken_sentence(query, files) else: out = sentence_search(query, sentences, regex) return out
def search(query, files, mode='sentence', regex=False)
Searches for words or sentences containing a search phrase
4.221262
3.900259
1.082303
''' Extracts individual words form files and exports them to individual files. ''' output_directory = 'extracted_words' if not os.path.exists(output_directory): os.makedirs(output_directory) for f in files: file_format = None source_segment = None if f.lower().endswith('.mp3'): file_format = 'mp3' source_segment = AudioSegment.from_mp3(f) elif f.lower().endswith('.wav'): file_format = 'wav' source_segment = AudioSegment.from_wav(f) if not file_format or source_segment: print('Unsupported audio format for ' + f) sentences = convert_timestamps(files) for s in sentences: for word in s['words']: start = float(word[1]) * 1000 end = float(word[2]) * 1000 word = word[0] total_time = end - start audio = AudioSegment.silent(duration=total_time) audio = audio.overlay(source_segment[start:end]) number = 0 output_path = None while True: output_filename = word if number: output_filename += "_" + str(number) output_filename = output_filename + '.' + file_format output_path = os.path.join(output_directory, output_filename) if not os.path.exists(output_path): # this file doesn't exist, so we can continue break # file already exists, increment name and try again number += 1 print('Exporting to: ' + output_path) audio.export(output_path, format=file_format)
def extract_words(files)
Extracts individual words form files and exports them to individual files.
2.629078
2.495528
1.053516
'''Stiches together a new audiotrack''' files = {} working_segments = [] audio = AudioSegment.empty() if layer: total_time = max([s['end'] - s['start'] for s in segments]) * 1000 audio = AudioSegment.silent(duration=total_time) for i, s in enumerate(segments): try: start = s['start'] * 1000 end = s['end'] * 1000 f = s['file'].replace('.transcription.txt', '') if f not in files: if f.endswith('.wav'): files[f] = AudioSegment.from_wav(f) elif f.endswith('.mp3'): files[f] = AudioSegment.from_mp3(f) segment = files[f][start:end] print(start, end, f) if layer: audio = audio.overlay(segment, times=1) else: if i > 0: audio = audio.append(segment, crossfade=crossfade) else: audio = audio + segment if padding > 0: audio = audio + AudioSegment.silent(duration=padding) s['duration'] = len(segment) working_segments.append(s) except: continue audio.export(out, format=os.path.splitext(out)[1].replace('.', '')) return working_segments
def compose(segments, out='out.mp3', padding=0, crossfade=0, layer=False)
Stiches together a new audiotrack
2.658352
2.503388
1.061902
''' Encode and sign a pickle-able object. Return a (byte) string ''' msg = base64.b64encode(pickle.dumps(data, -1)) sig = base64.b64encode(hmac.new(tob(key), msg).digest()) return tob('!') + sig + tob('?') + msg
def cookie_encode(data, key)
Encode and sign a pickle-able object. Return a (byte) string
5.266165
3.675686
1.432703
''' Verify and decode an encoded string. Return an object or None.''' data = tob(data) if cookie_is_encoded(data): sig, msg = data.split(tob('?'), 1) if _lscmp(sig[1:], base64.b64encode(hmac.new(tob(key), msg).digest())): return pickle.loads(base64.b64decode(msg)) return None
def cookie_decode(data, key)
Verify and decode an encoded string. Return an object or None.
5.495506
4.22288
1.301364
module, target = target.split(":", 1) if ':' in target else (target, None) if module not in sys.modules: __import__(module) if not target: return sys.modules[module] if target.isalnum(): return getattr(sys.modules[module], target) package_name = module.split('.')[0] namespace[package_name] = sys.modules[package_name] return eval('%s.%s' % (module, target), namespace)
def load(target, **namespace)
Import a module or fetch an object from a module. * ``package.module`` returns `module` as a module object. * ``pack.mod:name`` returns the module variable `name` from `pack.mod`. * ``pack.mod:func()`` calls `pack.mod.func()` and returns the result. The last form accepts not only function calls, but any type of expression. Keyword arguments passed to this function are available as local variables. Example: ``import_string('re:compile(x)', x='[a-z]')``
2.848018
2.900986
0.981742
''' Add a new route or replace the target for an existing route. ''' if rule in self.rules: self.rules[rule][method] = target if name: self.builder[name] = self.builder[rule] return target = self.rules[rule] = {method: target} # Build pattern and other structures for dynamic routes anons = 0 # Number of anonymous wildcards pattern = '' # Regular expression pattern filters = [] # Lists of wildcard input filters builder = [] # Data structure for the URL builder is_static = True for key, mode, conf in self.parse_rule(rule): if mode: is_static = False mask, in_filter, out_filter = self.filters[mode](conf) if key: pattern += '(?P<%s>%s)' % (key, mask) else: pattern += '(?:%s)' % mask key = 'anon%d' % anons; anons += 1 if in_filter: filters.append((key, in_filter)) builder.append((key, out_filter or str)) elif key: pattern += re.escape(key) builder.append((None, key)) self.builder[rule] = builder if name: self.builder[name] = builder if is_static and not self.strict_order: self.static[self.build(rule)] = target return def fpat_sub(m): return m.group(0) if len(m.group(1)) % 2 else m.group(1) + '(?:' flat_pattern = re.sub(r'(\\*)(\(\?P<[^>]*>|\((?!\?))', fpat_sub, pattern) try: re_match = re.compile('^(%s)$' % pattern).match except re.error, e: raise RouteSyntaxError("Could not add Route: %s (%s)" % (rule, e)) def match(path): url_args = re_match(path).groupdict() for name, wildcard_filter in filters: try: url_args[name] = wildcard_filter(url_args[name]) except ValueError: raise HTTPError(400, 'Path has wrong format.') return url_args try: combined = '%s|(^%s$)' % (self.dynamic[-1][0].pattern, flat_pattern) self.dynamic[-1] = (re.compile(combined), self.dynamic[-1][1]) self.dynamic[-1][1].append((match, target)) except (AssertionError, IndexError), e: # AssertionError: Too many groups self.dynamic.append((re.compile('(^%s$)' % flat_pattern), [(match, target)])) return match
def add(self, rule, method, target, name=None)
Add a new route or replace the target for an existing route.
4.017941
3.942073
1.019246
''' Return a (target, url_agrs) tuple or raise HTTPError(400/404/405). ''' path, targets, urlargs = environ['PATH_INFO'] or '/', None, {} if path in self.static: targets = self.static[path] else: for combined, rules in self.dynamic: match = combined.match(path) if not match: continue getargs, targets = rules[match.lastindex - 1] urlargs = getargs(path) if getargs else {} break if not targets: raise HTTPError(404, "Not found: " + repr(environ['PATH_INFO'])) method = environ['REQUEST_METHOD'].upper() if method in targets: return targets[method], urlargs if method == 'HEAD' and 'GET' in targets: return targets['GET'], urlargs if 'ANY' in targets: return targets['ANY'], urlargs allowed = [verb for verb in targets if verb != 'ANY'] if 'GET' in allowed and 'HEAD' not in allowed: allowed.append('HEAD') raise HTTPError(405, "Method not allowed.", header=[('Allow',",".join(allowed))])
def match(self, environ)
Return a (target, url_agrs) tuple or raise HTTPError(400/404/405).
3.614364
2.916852
1.239132
''' Yield all Plugins affecting this route. ''' unique = set() for p in reversed(self.app.plugins + self.plugins): if True in self.skiplist: break name = getattr(p, 'name', False) if name and (name in self.skiplist or name in unique): continue if p in self.skiplist or type(p) in self.skiplist: continue if name: unique.add(name) yield p
def all_plugins(self)
Yield all Plugins affecting this route.
5.59438
4.42576
1.26405
''' Reset all routes (force plugins to be re-applied) and clear all caches. If an ID or route object is given, only that specific route is affected. ''' if route is None: routes = self.routes elif isinstance(route, Route): routes = [route] else: routes = [self.routes[route]] for route in routes: route.reset() if DEBUG: for route in routes: route.prepare() self.hooks.trigger('app_reset')
def reset(self, route=None)
Reset all routes (force plugins to be re-applied) and clear all caches. If an ID or route object is given, only that specific route is affected.
6.188556
2.931113
2.111333
if callable(path): path, callback = None, path plugins = makelist(apply) skiplist = makelist(skip) def decorator(callback): # TODO: Documentation and tests if isinstance(callback, basestring): callback = load(callback) for rule in makelist(path) or yieldroutes(callback): for verb in makelist(method): verb = verb.upper() route = Route(self, rule, verb, callback, name=name, plugins=plugins, skiplist=skiplist, **config) self.routes.append(route) self.router.add(rule, verb, route, name=name) if DEBUG: route.prepare() return callback return decorator(callback) if callback else decorator
def route(self, path=None, method='GET', callback=None, name=None, apply=None, skip=None, **config)
A decorator to bind a function to a request URL. Example:: @app.route('/hello/:name') def hello(name): return 'Hello %s' % name The ``:name`` part is a wildcard. See :class:`Router` for syntax details. :param path: Request path or a list of paths to listen to. If no path is specified, it is automatically generated from the signature of the function. :param method: HTTP method (`GET`, `POST`, `PUT`, ...) or a list of methods to listen to. (default: `GET`) :param callback: An optional shortcut to avoid the decorator syntax. ``route(..., callback=func)`` equals ``route(...)(func)`` :param name: The name for this route. (default: None) :param apply: A decorator or plugin or a list of plugins. These are applied to the route callback in addition to installed plugins. :param skip: A list of plugins, plugin classes or names. Matching plugins are not installed to this route. ``True`` skips all. Any additional keyword arguments are stored as route-specific configuration and passed to plugins (see :meth:`Plugin.apply`).
3.944206
4.134764
0.953913
# Empty output is done here if not out: response['Content-Length'] = 0 return [] # Join lists of byte or unicode strings. Mixed lists are NOT supported if isinstance(out, (tuple, list))\ and isinstance(out[0], (bytes, unicode)): out = out[0][0:0].join(out) # b'abc'[0:0] -> b'' # Encode unicode strings if isinstance(out, unicode): out = out.encode(response.charset) # Byte Strings are just returned if isinstance(out, bytes): response['Content-Length'] = len(out) return [out] # HTTPError or HTTPException (recursive, because they may wrap anything) # TODO: Handle these explicitly in handle() or make them iterable. if isinstance(out, HTTPError): out.apply(response) out = self.error_handler.get(out.status, repr)(out) if isinstance(out, HTTPResponse): depr('Error handlers must not return :exc:`HTTPResponse`.') #0.9 return self._cast(out, request, response) if isinstance(out, HTTPResponse): out.apply(response) return self._cast(out.output, request, response) # File-like objects. if hasattr(out, 'read'): if 'wsgi.file_wrapper' in request.environ: return request.environ['wsgi.file_wrapper'](out) elif hasattr(out, 'close') or not hasattr(out, '__iter__'): return WSGIFileWrapper(out) # Handle Iterables. We peek into them to detect their inner type. try: out = iter(out) first = out.next() while not first: first = out.next() except StopIteration: return self._cast('', request, response) except HTTPResponse, e: first = e except Exception, e: first = HTTPError(500, 'Unhandled exception', e, format_exc(10)) if isinstance(e, (KeyboardInterrupt, SystemExit, MemoryError))\ or not self.catchall: raise # These are the inner types allowed in iterator or generator objects. if isinstance(first, HTTPResponse): return self._cast(first, request, response) if isinstance(first, bytes): return itertools.chain([first], out) if isinstance(first, unicode): return itertools.imap(lambda x: x.encode(response.charset), itertools.chain([first], out)) return self._cast(HTTPError(500, 'Unsupported response type: %s'\ % type(first)), request, response)
def _cast(self, out, request, response, peek=None)
Try to convert the parameter into something WSGI compatible and set correct HTTP headers when possible. Support: False, str, unicode, dict, HTTPResponse, HTTPError, file-like, iterable of strings and iterable of unicodes
4.111899
3.991398
1.03019
try: environ['bottle.app'] = self request.bind(environ) response.bind() out = self._cast(self._handle(environ), request, response) # rfc2616 section 4.3 if response._status_code in (100, 101, 204, 304)\ or request.method == 'HEAD': if hasattr(out, 'close'): out.close() out = [] start_response(response._status_line, list(response.iter_headers())) return out except (KeyboardInterrupt, SystemExit, MemoryError): raise except Exception, e: if not self.catchall: raise err = '<h1>Critical error while processing request: %s</h1>' \ % html_escape(environ.get('PATH_INFO', '/')) if DEBUG: err += '<h2>Error:</h2>\n<pre>\n%s\n</pre>\n' \ '<h2>Traceback:</h2>\n<pre>\n%s\n</pre>\n' \ % (html_escape(repr(e)), html_escape(format_exc(10))) environ['wsgi.errors'].write(err) headers = [('Content-Type', 'text/html; charset=UTF-8')] start_response('500 INTERNAL SERVER ERROR', headers) return [tob(err)]
def wsgi(self, environ, start_response)
The bottle WSGI-interface.
2.988225
2.924329
1.02185
value = self.cookies.get(key) if secret and value: dec = cookie_decode(value, secret) # (key, value) tuple or None return dec[1] if dec and dec[0] == key else default return value or default
def get_cookie(self, key, default=None, secret=None)
Return the content of a cookie. To read a `Signed Cookie`, the `secret` must match the one used to create the cookie (see :meth:`BaseResponse.set_cookie`). If anything goes wrong (missing cookie or wrong signature), return a default value.
4.099922
3.948748
1.038284
forms = FormsDict() for name, item in self.POST.iterallitems(): if not hasattr(item, 'filename'): forms[name] = item return forms
def forms(self)
Form values parsed from an `url-encoded` or `multipart/form-data` encoded POST or PUT request body. The result is retuned as a :class:`FormsDict`. All keys and values are strings. File uploads are stored separately in :attr:`files`.
8.441718
5.884875
1.434477
params = FormsDict() for key, value in self.query.iterallitems(): params[key] = value for key, value in self.forms.iterallitems(): params[key] = value return params
def params(self)
A :class:`FormsDict` with the combined values of :attr:`query` and :attr:`forms`. File uploads are stored in :attr:`files`.
4.319808
2.612717
1.653378
files = FormsDict() for name, item in self.POST.iterallitems(): if hasattr(item, 'filename'): files[name] = item return files
def files(self)
File uploads parsed from an `url-encoded` or `multipart/form-data` encoded POST or PUT request body. The values are instances of :class:`cgi.FieldStorage`. The most important attributes are: filename The filename, if specified; otherwise None; this is the client side filename, *not* the file name on which it is stored (that's a temporary file you don't deal with) file The file(-like) object from which you can read the data. value The value as a *string*; for file uploads, this transparently reads the file every time you request the value. Do not do this on big files.
8.573458
8.57922
0.999328
''' If the ``Content-Type`` header is ``application/json``, this property holds the parsed content of the request body. Only requests smaller than :attr:`MEMFILE_MAX` are processed to avoid memory exhaustion. ''' if 'application/json' in self.environ.get('CONTENT_TYPE', '') \ and 0 < self.content_length < self.MEMFILE_MAX: return json_loads(self.body.read(self.MEMFILE_MAX)) return None
def json(self)
If the ``Content-Type`` header is ``application/json``, this property holds the parsed content of the request body. Only requests smaller than :attr:`MEMFILE_MAX` are processed to avoid memory exhaustion.
5.085626
2.255278
2.254988
post = FormsDict() # We default to application/x-www-form-urlencoded for everything that # is not multipart and take the fast path (also: 3.1 workaround) if not self.content_type.startswith('multipart/'): maxlen = max(0, min(self.content_length, self.MEMFILE_MAX)) pairs = _parse_qsl(tonat(self.body.read(maxlen), 'latin1')) for key, value in pairs[:self.MAX_PARAMS]: post[key] = value return post safe_env = {'QUERY_STRING':''} # Build a safe environment for cgi for key in ('REQUEST_METHOD', 'CONTENT_TYPE', 'CONTENT_LENGTH'): if key in self.environ: safe_env[key] = self.environ[key] args = dict(fp=self.body, environ=safe_env, keep_blank_values=True) if py >= (3,2,0): args['encoding'] = 'ISO-8859-1' if NCTextIOWrapper: args['fp'] = NCTextIOWrapper(args['fp'], encoding='ISO-8859-1', newline='\n') data = cgi.FieldStorage(**args) for item in (data.list or [])[:self.MAX_PARAMS]: post[item.name] = item if item.filename else item.value return post
def POST(self)
The values of :attr:`forms` and :attr:`files` combined into a single :class:`FormsDict`. Values are either strings (form values) or instances of :class:`cgi.FieldStorage` (file uploads).
4.663071
4.374031
1.066081
basic = parse_auth(self.environ.get('HTTP_AUTHORIZATION','')) if basic: return basic ruser = self.environ.get('REMOTE_USER') if ruser: return (ruser, None) return None
def auth(self)
HTTP authentication data as a (user, password) tuple. This implementation currently supports basic (not digest) authentication only. If the authentication happened at a higher level (e.g. in the front web-server or a middleware), the password field is None, but the user field is looked up from the ``REMOTE_USER`` environ variable. On any errors, None is returned.
4.052357
3.55949
1.138465
proxy = self.environ.get('HTTP_X_FORWARDED_FOR') if proxy: return [ip.strip() for ip in proxy.split(',')] remote = self.environ.get('REMOTE_ADDR') return [remote] if remote else []
def remote_route(self)
A list of all IPs that were involved in this request, starting with the client IP and followed by zero or more proxies. This does only work if all proxies support the ```X-Forwarded-For`` header. Note that this information can be forged by malicious clients.
2.971326
2.532581
1.17324
''' An instance of :class:`HeaderDict`, a case-insensitive dict-like view on the response headers. ''' self.__dict__['headers'] = hdict = HeaderDict() hdict.dict = self._headers return hdict
def headers(self)
An instance of :class:`HeaderDict`, a case-insensitive dict-like view on the response headers.
8.058892
4.161107
1.936719
''' Return the value of a previously defined header. If there is no header with that name, return a default value. ''' return self._headers.get(_hkey(name), [default])[-1]
def get_header(self, name, default=None)
Return the value of a previously defined header. If there is no header with that name, return a default value.
7.822553
4.498921
1.738762
''' Create a new response header, replacing any previously defined headers with the same name. ''' if append: self.add_header(name, value) else: self._headers[_hkey(name)] = [str(value)]
def set_header(self, name, value, append=False)
Create a new response header, replacing any previously defined headers with the same name.
5.607633
3.488029
1.607679
''' Yield (header, value) tuples, skipping headers that are not allowed with the current response status code. ''' headers = self._headers.iteritems() bad_headers = self.bad_headers.get(self.status_code) if bad_headers: headers = [h for h in headers if h[0] not in bad_headers] for name, values in headers: for value in values: yield name, value if self._cookies: for c in self._cookies.values(): yield 'Set-Cookie', c.OutputString()
def iter_headers(self)
Yield (header, value) tuples, skipping headers that are not allowed with the current response status code.
3.399741
2.364643
1.43774
depr('The COOKIES dict is deprecated. Use `set_cookie()` instead.') # 0.10 if not self._cookies: self._cookies = SimpleCookie() return self._cookies
def COOKIES(self)
A dict-like SimpleCookie instance. This should not be used directly. See :meth:`set_cookie`.
9.272137
7.111344
1.303851
''' Remove a callback from a hook. ''' was_empty = self._empty() if name in self.hooks and func in self.hooks[name]: self.hooks[name].remove(func) if self.app and not was_empty and self._empty(): self.app.reset()
def remove(self, name, func)
Remove a callback from a hook.
4.399617
4.290423
1.025451
''' Trigger a hook and return a list of results. ''' hooks = self.hooks[name] if ka.pop('reversed', False): hooks = hooks[::-1] return [hook(*a, **ka) for hook in hooks]
def trigger(self, name, *a, **ka)
Trigger a hook and return a list of results.
4.945254
4.301127
1.149758
''' Return the most recent value for a key. :param default: The default value to be returned if the key is not present or the type conversion fails. :param index: An index for the list of available values. :param type: If defined, this callable is used to cast the value into a specific type. Exception are suppressed and result in the default value to be returned. ''' try: val = self.dict[key][index] return type(val) if type else val except Exception, e: pass return default
def get(self, key, default=None, index=-1, type=None)
Return the most recent value for a key. :param default: The default value to be returned if the key is not present or the type conversion fails. :param index: An index for the list of available values. :param type: If defined, this callable is used to cast the value into a specific type. Exception are suppressed and result in the default value to be returned.
5.443611
1.773963
3.068617
if os.path.isfile(name): return name for spath in lookup: fname = os.path.join(spath, name) if os.path.isfile(fname): return fname for ext in cls.extensions: if os.path.isfile('%s.%s' % (fname, ext)): return '%s.%s' % (fname, ext)
def search(cls, name, lookup=[])
Search name in all directories specified in lookup. First without, then with common extensions. Return first hit.
2.205775
1.966026
1.121946
url = "%s?client_id=%s&response_type=code&redirect_uri=%s" % ( self.AUTHORIZE_URL, self.CLIENT_ID, quote_plus(self.REDIRECT_URI) ) if getattr(self, 'SCOPE', None) is not None: url = '%s&scope=%s' % (url, '+'.join(self.SCOPE)) return url
def authorize_url(self)
Rewrite this property method If there are more arguments need attach to the url. Like bellow: class NewSubClass(OAuth2): @property def authorize_url(self): url = super(NewSubClass, self).authorize_url url += '&blabla' return url
2.377964
2.133726
1.114466
data = { 'client_id': self.CLIENT_ID, 'client_secret': self.CLIENT_SECRET, 'redirect_uri': self.REDIRECT_URI, 'code': code, 'grant_type': 'authorization_code' } if method == 'POST': res = self.http_post(self.ACCESS_TOKEN_URL, data, parse=parse) else: res = self.http_get(self.ACCESS_TOKEN_URL, data, parse=parse) self.parse_token_response(res)
def get_access_token(self, code, method='POST', parse=True)
parse is True means that the api return a json string. So, the result will be parsed by json library. Most sites will follow this rule, return a json string. But some sites (e.g. Tencent), Will return an non json string, This sites MUST set parse=False when call this method, And handle the result by themselves. This method Maybe raise SocialAPIError. Application MUST try this Exception.
1.712998
1.799867
0.951736
opts = {'harmony': harmony, 'stripTypes': strip_types} try: result = self.context.call( '%s.transform' % self.JSX_TRANSFORMER_JS_EXPR, jsx, opts) except execjs.ProgramError as e: raise TransformError(str(e)) js = result['code'] return js
def transform_string(self, jsx, harmony=False, strip_types=False)
Transform ``jsx`` JSX string into javascript :param jsx: JSX source code :type jsx: basestring :keyword harmony: Transform ES6 code into ES3 (default: False) :type harmony: bool :keyword strip_types: Strip type declarations (default: False) :type harmony: bool :return: compiled JS code :rtype: str
4.871957
5.403703
0.901596
''' Fetch a redis conenction pool for the unique combination of host and port. Will create a new one if there isn't one already. ''' key = (host, port, db) rval = pools.get(key) if not isinstance(rval, ConnectionPool): rval = ConnectionPool(host=host, port=port, db=db, **options) pools[key] = rval return rval
def pool(self, host, port, db, pools={}, **options)
Fetch a redis conenction pool for the unique combination of host and port. Will create a new one if there isn't one already.
3.736508
2.071874
1.803443
''' Rank a member in the leaderboard. @param member [String] Member name. @param score [float] Member score. @param member_data [String] Optional member data. ''' self.rank_member_in(self.leaderboard_name, member, score, member_data)
def rank_member(self, member, score, member_data=None)
Rank a member in the leaderboard. @param member [String] Member name. @param score [float] Member score. @param member_data [String] Optional member data.
3.793568
2.322793
1.633192
''' Rank a member in the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param member [String] Member name. @param score [float] Member score. @param member_data [String] Optional member data. ''' pipeline = self.redis_connection.pipeline() if isinstance(self.redis_connection, Redis): pipeline.zadd(leaderboard_name, member, score) else: pipeline.zadd(leaderboard_name, score, member) if member_data: pipeline.hset( self._member_data_key(leaderboard_name), member, member_data) pipeline.execute()
def rank_member_in( self, leaderboard_name, member, score, member_data=None)
Rank a member in the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param member [String] Member name. @param score [float] Member score. @param member_data [String] Optional member data.
2.375035
1.865062
1.273435
''' Rank a member in the leaderboard based on execution of the +rank_conditional+. The +rank_conditional+ is passed the following parameters: member: Member name. current_score: Current score for the member in the leaderboard. score: Member score. member_data: Optional member data. leaderboard_options: Leaderboard options, e.g. 'reverse': Value of reverse option @param rank_conditional [function] Function which must return +True+ or +False+ that controls whether or not the member is ranked in the leaderboard. @param member [String] Member name. @param score [float] Member score. @param member_data [String] Optional member_data. ''' self.rank_member_if_in( self.leaderboard_name, rank_conditional, member, score, member_data)
def rank_member_if( self, rank_conditional, member, score, member_data=None)
Rank a member in the leaderboard based on execution of the +rank_conditional+. The +rank_conditional+ is passed the following parameters: member: Member name. current_score: Current score for the member in the leaderboard. score: Member score. member_data: Optional member data. leaderboard_options: Leaderboard options, e.g. 'reverse': Value of reverse option @param rank_conditional [function] Function which must return +True+ or +False+ that controls whether or not the member is ranked in the leaderboard. @param member [String] Member name. @param score [float] Member score. @param member_data [String] Optional member_data.
5.040975
1.44744
3.482682
''' Rank a member in the named leaderboard based on execution of the +rank_conditional+. The +rank_conditional+ is passed the following parameters: member: Member name. current_score: Current score for the member in the leaderboard. score: Member score. member_data: Optional member data. leaderboard_options: Leaderboard options, e.g. 'reverse': Value of reverse option @param leaderboard_name [String] Name of the leaderboard. @param rank_conditional [function] Function which must return +True+ or +False+ that controls whether or not the member is ranked in the leaderboard. @param member [String] Member name. @param score [float] Member score. @param member_data [String] Optional member_data. ''' current_score = self.redis_connection.zscore(leaderboard_name, member) if current_score is not None: current_score = float(current_score) if rank_conditional(self, member, current_score, score, member_data, {'reverse': self.order}): self.rank_member_in(leaderboard_name, member, score, member_data)
def rank_member_if_in( self, leaderboard_name, rank_conditional, member, score, member_data=None)
Rank a member in the named leaderboard based on execution of the +rank_conditional+. The +rank_conditional+ is passed the following parameters: member: Member name. current_score: Current score for the member in the leaderboard. score: Member score. member_data: Optional member data. leaderboard_options: Leaderboard options, e.g. 'reverse': Value of reverse option @param leaderboard_name [String] Name of the leaderboard. @param rank_conditional [function] Function which must return +True+ or +False+ that controls whether or not the member is ranked in the leaderboard. @param member [String] Member name. @param score [float] Member score. @param member_data [String] Optional member_data.
3.681957
1.481837
2.484724
''' Rank an array of members in the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param members_and_scores [Array] Variable list of members and scores. ''' pipeline = self.redis_connection.pipeline() for member, score in grouper(2, members_and_scores): if isinstance(self.redis_connection, Redis): pipeline.zadd(leaderboard_name, member, score) else: pipeline.zadd(leaderboard_name, score, member) pipeline.execute()
def rank_members_in(self, leaderboard_name, members_and_scores)
Rank an array of members in the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param members_and_scores [Array] Variable list of members and scores.
3.006033
2.150476
1.397846
''' Retrieve the optional member data for a given member in the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param member [String] Member name. @return String of optional member data. ''' return self.redis_connection.hget( self._member_data_key(leaderboard_name), member)
def member_data_for_in(self, leaderboard_name, member)
Retrieve the optional member data for a given member in the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param member [String] Member name. @return String of optional member data.
4.303699
2.134108
2.016627
''' Retrieve the optional member data for a given list of members in the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param members [Array] Member names. @return Array of strings of optional member data. ''' return self.redis_connection.hmget( self._member_data_key(leaderboard_name), members)
def members_data_for_in(self, leaderboard_name, members)
Retrieve the optional member data for a given list of members in the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param members [Array] Member names. @return Array of strings of optional member data.
5.059564
2.136112
2.368585
''' Update the optional member data for a given member in the leaderboard. @param member [String] Member name. @param member_data [String] Optional member data. ''' self.update_member_data_in(self.leaderboard_name, member, member_data)
def update_member_data(self, member, member_data)
Update the optional member data for a given member in the leaderboard. @param member [String] Member name. @param member_data [String] Optional member data.
5.223386
2.337421
2.234679
''' Update the optional member data for a given member in the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param member [String] Member name. @param member_data [String] Optional member data. ''' self.redis_connection.hset( self._member_data_key(leaderboard_name), member, member_data)
def update_member_data_in(self, leaderboard_name, member, member_data)
Update the optional member data for a given member in the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param member [String] Member name. @param member_data [String] Optional member data.
3.331212
2.044843
1.62908
''' Remove the optional member data for a given member in the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param member [String] Member name. ''' self.redis_connection.hdel( self._member_data_key(leaderboard_name), member)
def remove_member_data_in(self, leaderboard_name, member)
Remove the optional member data for a given member in the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param member [String] Member name.
4.283395
2.515213
1.702995
''' Remove the optional member data for a given member in the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param member [String] Member name. ''' pipeline = self.redis_connection.pipeline() pipeline.zrem(leaderboard_name, member) pipeline.hdel(self._member_data_key(leaderboard_name), member) pipeline.execute()
def remove_member_from(self, leaderboard_name, member)
Remove the optional member data for a given member in the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param member [String] Member name.
3.688658
2.173525
1.697086
''' Retrieve the total number of pages in the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param page_size [int, nil] Page size to be used when calculating the total number of pages. @return the total number of pages in the named leaderboard. ''' if page_size is None: page_size = self.page_size return int( math.ceil( self.total_members_in(leaderboard_name) / float(page_size)))
def total_pages_in(self, leaderboard_name, page_size=None)
Retrieve the total number of pages in the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param page_size [int, nil] Page size to be used when calculating the total number of pages. @return the total number of pages in the named leaderboard.
3.123046
1.767889
1.76654
''' Retrieve the total members in a given score range from the leaderboard. @param min_score [float] Minimum score. @param max_score [float] Maximum score. @return the total members in a given score range from the leaderboard. ''' return self.total_members_in_score_range_in( self.leaderboard_name, min_score, max_score)
def total_members_in_score_range(self, min_score, max_score)
Retrieve the total members in a given score range from the leaderboard. @param min_score [float] Minimum score. @param max_score [float] Maximum score. @return the total members in a given score range from the leaderboard.
3.507697
2.119101
1.655276
''' Retrieve the total members in a given score range from the named leaderboard. @param leaderboard_name Name of the leaderboard. @param min_score [float] Minimum score. @param max_score [float] Maximum score. @return the total members in a given score range from the named leaderboard. ''' return self.redis_connection.zcount( leaderboard_name, min_score, max_score)
def total_members_in_score_range_in( self, leaderboard_name, min_score, max_score)
Retrieve the total members in a given score range from the named leaderboard. @param leaderboard_name Name of the leaderboard. @param min_score [float] Minimum score. @param max_score [float] Maximum score. @return the total members in a given score range from the named leaderboard.
2.999318
1.73031
1.733399
''' Sum of scores for all members in the named leaderboard. @param leaderboard_name Name of the leaderboard. @return Sum of scores for all members in the named leaderboard. ''' return sum([leader[self.SCORE_KEY] for leader in self.all_leaders_from(self.leaderboard_name)])
def total_scores_in(self, leaderboard_name)
Sum of scores for all members in the named leaderboard. @param leaderboard_name Name of the leaderboard. @return Sum of scores for all members in the named leaderboard.
4.174989
2.845177
1.467392
''' Retrieve the rank for a member in the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param member [String] Member name. @return the rank for a member in the leaderboard. ''' if self.order == self.ASC: try: return self.redis_connection.zrank( leaderboard_name, member) + 1 except: return None else: try: return self.redis_connection.zrevrank( leaderboard_name, member) + 1 except: return None
def rank_for_in(self, leaderboard_name, member)
Retrieve the rank for a member in the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param member [String] Member name. @return the rank for a member in the leaderboard.
2.72137
1.958177
1.389746
''' Retrieve the score for a member in the named leaderboard. @param leaderboard_name Name of the leaderboard. @param member [String] Member name. @return the score for a member in the leaderboard or +None+ if the member is not in the leaderboard. ''' score = self.redis_connection.zscore(leaderboard_name, member) if score is not None: score = float(score) return score
def score_for_in(self, leaderboard_name, member)
Retrieve the score for a member in the named leaderboard. @param leaderboard_name Name of the leaderboard. @param member [String] Member name. @return the score for a member in the leaderboard or +None+ if the member is not in the leaderboard.
3.519307
1.763718
1.995391
''' Retrieve the score and rank for a member in the named leaderboard. @param leaderboard_name [String]Name of the leaderboard. @param member [String] Member name. @return the score and rank for a member in the named leaderboard as a Hash. ''' return { self.MEMBER_KEY: member, self.SCORE_KEY: self.score_for_in(leaderboard_name, member), self.RANK_KEY: self.rank_for_in(leaderboard_name, member) }
def score_and_rank_for_in(self, leaderboard_name, member)
Retrieve the score and rank for a member in the named leaderboard. @param leaderboard_name [String]Name of the leaderboard. @param member [String] Member name. @return the score and rank for a member in the named leaderboard as a Hash.
2.897755
1.657247
1.748536
''' Change the score for a member in the leaderboard by a score delta which can be positive or negative. @param member [String] Member name. @param delta [float] Score change. @param member_data [String] Optional member data. ''' self.change_score_for_member_in(self.leaderboard_name, member, delta, member_data)
def change_score_for(self, member, delta, member_data=None)
Change the score for a member in the leaderboard by a score delta which can be positive or negative. @param member [String] Member name. @param delta [float] Score change. @param member_data [String] Optional member data.
4.0857
1.955273
2.089581
''' Change the score for a member in the named leaderboard by a delta which can be positive or negative. @param leaderboard_name [String] Name of the leaderboard. @param member [String] Member name. @param delta [float] Score change. @param member_data [String] Optional member data. ''' pipeline = self.redis_connection.pipeline() pipeline.zincrby(leaderboard_name, member, delta) if member_data: pipeline.hset( self._member_data_key(leaderboard_name), member, member_data) pipeline.execute()
def change_score_for_member_in(self, leaderboard_name, member, delta, member_data=None)
Change the score for a member in the named leaderboard by a delta which can be positive or negative. @param leaderboard_name [String] Name of the leaderboard. @param member [String] Member name. @param delta [float] Score change. @param member_data [String] Optional member data.
2.713419
1.783735
1.521201
''' Remove members from the leaderboard in a given score range. @param min_score [float] Minimum score. @param max_score [float] Maximum score. ''' self.remove_members_in_score_range_in( self.leaderboard_name, min_score, max_score)
def remove_members_in_score_range(self, min_score, max_score)
Remove members from the leaderboard in a given score range. @param min_score [float] Minimum score. @param max_score [float] Maximum score.
3.65242
2.626498
1.390605
''' Remove members from the named leaderboard in a given score range. @param leaderboard_name [String] Name of the leaderboard. @param min_score [float] Minimum score. @param max_score [float] Maximum score. ''' self.redis_connection.zremrangebyscore( leaderboard_name, min_score, max_score)
def remove_members_in_score_range_in( self, leaderboard_name, min_score, max_score)
Remove members from the named leaderboard in a given score range. @param leaderboard_name [String] Name of the leaderboard. @param min_score [float] Minimum score. @param max_score [float] Maximum score.
2.864775
2.023386
1.415832
''' Remove members from the named leaderboard in a given rank range. @param leaderboard_name [String] Name of the leaderboard. @param rank [int] the rank (inclusive) which we should keep. @return the total member count which was removed. ''' if self.order == self.DESC: rank = -(rank) - 1 return self.redis_connection.zremrangebyrank( leaderboard_name, 0, rank) else: return self.redis_connection.zremrangebyrank( leaderboard_name, rank, -1)
def remove_members_outside_rank_in(self, leaderboard_name, rank)
Remove members from the named leaderboard in a given rank range. @param leaderboard_name [String] Name of the leaderboard. @param rank [int] the rank (inclusive) which we should keep. @return the total member count which was removed.
4.080443
2.145454
1.901902
''' Determine the page where a member falls in the leaderboard. @param member [String] Member name. @param page_size [int] Page size to be used in determining page location. @return the page where a member falls in the leaderboard. ''' return self.page_for_in(self.leaderboard_name, member, page_size)
def page_for(self, member, page_size=DEFAULT_PAGE_SIZE)
Determine the page where a member falls in the leaderboard. @param member [String] Member name. @param page_size [int] Page size to be used in determining page location. @return the page where a member falls in the leaderboard.
5.56514
1.985218
2.803289
''' Determine the page where a member falls in the named leaderboard. @param leaderboard [String] Name of the leaderboard. @param member [String] Member name. @param page_size [int] Page size to be used in determining page location. @return the page where a member falls in the leaderboard. ''' rank_for_member = None if self.order == self.ASC: rank_for_member = self.redis_connection.zrank( leaderboard_name, member) else: rank_for_member = self.redis_connection.zrevrank( leaderboard_name, member) if rank_for_member is None: rank_for_member = 0 else: rank_for_member += 1 return int(math.ceil(float(rank_for_member) / float(page_size)))
def page_for_in(self, leaderboard_name, member, page_size=DEFAULT_PAGE_SIZE)
Determine the page where a member falls in the named leaderboard. @param leaderboard [String] Name of the leaderboard. @param member [String] Member name. @param page_size [int] Page size to be used in determining page location. @return the page where a member falls in the leaderboard.
2.664662
1.750943
1.521844
''' Retrieve the percentile for a member in the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param member [String] Member name. @return the percentile for a member in the named leaderboard. ''' if not self.check_member_in(leaderboard_name, member): return None responses = self.redis_connection.pipeline().zcard( leaderboard_name).zrevrank(leaderboard_name, member).execute() percentile = math.ceil( (float( (responses[0] - responses[1] - 1)) / float( responses[0]) * 100)) if self.order == self.ASC: return 100 - percentile else: return percentile
def percentile_for_in(self, leaderboard_name, member)
Retrieve the percentile for a member in the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param member [String] Member name. @return the percentile for a member in the named leaderboard.
3.504802
2.760395
1.269674
''' Calculate the score for a given percentile value in the leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param percentile [float] Percentile value (0.0 to 100.0 inclusive). @return the score corresponding to the percentile argument. Return +None+ for arguments outside 0-100 inclusive and for leaderboards with no members. ''' if not 0 <= percentile <= 100: return None total_members = self.total_members_in(leaderboard_name) if total_members < 1: return None if self.order == self.ASC: percentile = 100 - percentile index = (total_members - 1) * (percentile / 100.0) scores = [ pair[1] for pair in self.redis_connection.zrange( leaderboard_name, int( math.floor(index)), int( math.ceil(index)), withscores=True)] if index == math.floor(index): return scores[0] else: interpolate_fraction = index - math.floor(index) return scores[0] + interpolate_fraction * (scores[1] - scores[0])
def score_for_percentile_in(self, leaderboard_name, percentile)
Calculate the score for a given percentile value in the leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param percentile [float] Percentile value (0.0 to 100.0 inclusive). @return the score corresponding to the percentile argument. Return +None+ for arguments outside 0-100 inclusive and for leaderboards with no members.
3.424965
2.098227
1.632314
''' Expire the given leaderboard in a set number of seconds. Do not use this with leaderboards that utilize member data as there is no facility to cascade the expiration out to the keys for the member data. @param leaderboard_name [String] Name of the leaderboard. @param seconds [int] Number of seconds after which the leaderboard will be expired. ''' pipeline = self.redis_connection.pipeline() pipeline.expire(leaderboard_name, seconds) pipeline.expire(self._member_data_key(leaderboard_name), seconds) pipeline.execute()
def expire_leaderboard_for(self, leaderboard_name, seconds)
Expire the given leaderboard in a set number of seconds. Do not use this with leaderboards that utilize member data as there is no facility to cascade the expiration out to the keys for the member data. @param leaderboard_name [String] Name of the leaderboard. @param seconds [int] Number of seconds after which the leaderboard will be expired.
4.766901
1.705524
2.794977
''' Retrieve a page of leaders from the leaderboard. @param current_page [int] Page to retrieve from the leaderboard. @param options [Hash] Options to be used when retrieving the page from the leaderboard. @return a page of leaders from the leaderboard. ''' return self.leaders_in(self.leaderboard_name, current_page, **options)
def leaders(self, current_page, **options)
Retrieve a page of leaders from the leaderboard. @param current_page [int] Page to retrieve from the leaderboard. @param options [Hash] Options to be used when retrieving the page from the leaderboard. @return a page of leaders from the leaderboard.
4.293118
1.998161
2.148535
''' Retrieve a page of leaders from the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param current_page [int] Page to retrieve from the named leaderboard. @param options [Hash] Options to be used when retrieving the page from the named leaderboard. @return a page of leaders from the named leaderboard. ''' if current_page < 1: current_page = 1 page_size = options.get('page_size', self.page_size) index_for_redis = current_page - 1 starting_offset = (index_for_redis * page_size) if starting_offset < 0: starting_offset = 0 ending_offset = (starting_offset + page_size) - 1 raw_leader_data = self._range_method( self.redis_connection, leaderboard_name, int(starting_offset), int(ending_offset), withscores=False) return self._parse_raw_members( leaderboard_name, raw_leader_data, **options)
def leaders_in(self, leaderboard_name, current_page, **options)
Retrieve a page of leaders from the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param current_page [int] Page to retrieve from the named leaderboard. @param options [Hash] Options to be used when retrieving the page from the named leaderboard. @return a page of leaders from the named leaderboard.
3.026744
2.175828
1.391077
''' Retrieves all leaders from the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param options [Hash] Options to be used when retrieving the leaders from the named leaderboard. @return the named leaderboard. ''' raw_leader_data = self._range_method( self.redis_connection, leaderboard_name, 0, -1, withscores=False) return self._parse_raw_members( leaderboard_name, raw_leader_data, **options)
def all_leaders_from(self, leaderboard_name, **options)
Retrieves all leaders from the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param options [Hash] Options to be used when retrieving the leaders from the named leaderboard. @return the named leaderboard.
4.580552
2.748787
1.66639
''' Retrieve members from the leaderboard within a given score range. @param minimum_score [float] Minimum score (inclusive). @param maximum_score [float] Maximum score (inclusive). @param options [Hash] Options to be used when retrieving the data from the leaderboard. @return members from the leaderboard that fall within the given score range. ''' return self.members_from_score_range_in( self.leaderboard_name, minimum_score, maximum_score, **options)
def members_from_score_range( self, minimum_score, maximum_score, **options)
Retrieve members from the leaderboard within a given score range. @param minimum_score [float] Minimum score (inclusive). @param maximum_score [float] Maximum score (inclusive). @param options [Hash] Options to be used when retrieving the data from the leaderboard. @return members from the leaderboard that fall within the given score range.
3.781817
1.748767
2.162562
''' Retrieve members from the named leaderboard within a given score range. @param leaderboard_name [String] Name of the leaderboard. @param minimum_score [float] Minimum score (inclusive). @param maximum_score [float] Maximum score (inclusive). @param options [Hash] Options to be used when retrieving the data from the leaderboard. @return members from the leaderboard that fall within the given score range. ''' raw_leader_data = [] if self.order == self.DESC: raw_leader_data = self.redis_connection.zrevrangebyscore( leaderboard_name, maximum_score, minimum_score) else: raw_leader_data = self.redis_connection.zrangebyscore( leaderboard_name, minimum_score, maximum_score) return self._parse_raw_members( leaderboard_name, raw_leader_data, **options)
def members_from_score_range_in( self, leaderboard_name, minimum_score, maximum_score, **options)
Retrieve members from the named leaderboard within a given score range. @param leaderboard_name [String] Name of the leaderboard. @param minimum_score [float] Minimum score (inclusive). @param maximum_score [float] Maximum score (inclusive). @param options [Hash] Options to be used when retrieving the data from the leaderboard. @return members from the leaderboard that fall within the given score range.
2.711673
1.784653
1.51944
''' Retrieve members from the leaderboard within a given rank range. @param starting_rank [int] Starting rank (inclusive). @param ending_rank [int] Ending rank (inclusive). @param options [Hash] Options to be used when retrieving the data from the leaderboard. @return members from the leaderboard that fall within the given rank range. ''' return self.members_from_rank_range_in( self.leaderboard_name, starting_rank, ending_rank, **options)
def members_from_rank_range(self, starting_rank, ending_rank, **options)
Retrieve members from the leaderboard within a given rank range. @param starting_rank [int] Starting rank (inclusive). @param ending_rank [int] Ending rank (inclusive). @param options [Hash] Options to be used when retrieving the data from the leaderboard. @return members from the leaderboard that fall within the given rank range.
3.66717
1.770412
2.071365
''' Retrieve members from the named leaderboard within a given rank range. @param leaderboard_name [String] Name of the leaderboard. @param starting_rank [int] Starting rank (inclusive). @param ending_rank [int] Ending rank (inclusive). @param options [Hash] Options to be used when retrieving the data from the leaderboard. @return members from the leaderboard that fall within the given rank range. ''' starting_rank -= 1 if starting_rank < 0: starting_rank = 0 ending_rank -= 1 if ending_rank > self.total_members_in(leaderboard_name): ending_rank = self.total_members_in(leaderboard_name) - 1 raw_leader_data = [] if self.order == self.DESC: raw_leader_data = self.redis_connection.zrevrange( leaderboard_name, starting_rank, ending_rank, withscores=False) else: raw_leader_data = self.redis_connection.zrange( leaderboard_name, starting_rank, ending_rank, withscores=False) return self._parse_raw_members( leaderboard_name, raw_leader_data, **options)
def members_from_rank_range_in( self, leaderboard_name, starting_rank, ending_rank, **options)
Retrieve members from the named leaderboard within a given rank range. @param leaderboard_name [String] Name of the leaderboard. @param starting_rank [int] Starting rank (inclusive). @param ending_rank [int] Ending rank (inclusive). @param options [Hash] Options to be used when retrieving the data from the leaderboard. @return members from the leaderboard that fall within the given rank range.
2.280044
1.717125
1.327826
''' Retrieve members from the leaderboard within a range from 1 to the number given. @param ending_rank [int] Ending rank (inclusive). @param options [Hash] Options to be used when retrieving the data from the leaderboard. @return number from the leaderboard that fall within the given rank range. ''' return self.top_in(self.leaderboard_name, number, **options)
def top(self, number, **options)
Retrieve members from the leaderboard within a range from 1 to the number given. @param ending_rank [int] Ending rank (inclusive). @param options [Hash] Options to be used when retrieving the data from the leaderboard. @return number from the leaderboard that fall within the given rank range.
10.013041
2.01033
4.980795
''' Retrieve members from the named leaderboard within a range from 1 to the number given. @param leaderboard_name [String] Name of the leaderboard. @param starting_rank [int] Starting rank (inclusive). @param ending_rank [int] Ending rank (inclusive). @param options [Hash] Options to be used when retrieving the data from the leaderboard. @return members from the leaderboard that fall within the given rank range. ''' return self.members_from_rank_range_in(leaderboard_name, 1, number, **options)
def top_in(self, leaderboard_name, number, **options)
Retrieve members from the named leaderboard within a range from 1 to the number given. @param leaderboard_name [String] Name of the leaderboard. @param starting_rank [int] Starting rank (inclusive). @param ending_rank [int] Ending rank (inclusive). @param options [Hash] Options to be used when retrieving the data from the leaderboard. @return members from the leaderboard that fall within the given rank range.
4.356181
1.610091
2.705549
''' Retrieve a member at the specified index from the leaderboard. @param position [int] Position in leaderboard. @param options [Hash] Options to be used when retrieving the member from the leaderboard. @return a member from the leaderboard. ''' return self.member_at_in(self.leaderboard_name, position, **options)
def member_at(self, position, **options)
Retrieve a member at the specified index from the leaderboard. @param position [int] Position in leaderboard. @param options [Hash] Options to be used when retrieving the member from the leaderboard. @return a member from the leaderboard.
5.210823
1.944271
2.680091
''' Retrieve a member at the specified index from the leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param position [int] Position in named leaderboard. @param options [Hash] Options to be used when retrieving the member from the named leaderboard. @return a page of leaders from the named leaderboard. ''' if position > 0 and position <= self.total_members_in(leaderboard_name): page_size = options.get('page_size', self.page_size) current_page = math.ceil(float(position) / float(page_size)) offset = (position - 1) % page_size leaders = self.leaders_in( leaderboard_name, current_page, **options) if leaders: return leaders[offset]
def member_at_in(self, leaderboard_name, position, **options)
Retrieve a member at the specified index from the leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param position [int] Position in named leaderboard. @param options [Hash] Options to be used when retrieving the member from the named leaderboard. @return a page of leaders from the named leaderboard.
3.263591
1.947167
1.676071
''' Retrieve a page of leaders from the leaderboard around a given member. @param member [String] Member name. @param options [Hash] Options to be used when retrieving the page from the leaderboard. @return a page of leaders from the leaderboard around a given member. ''' return self.around_me_in(self.leaderboard_name, member, **options)
def around_me(self, member, **options)
Retrieve a page of leaders from the leaderboard around a given member. @param member [String] Member name. @param options [Hash] Options to be used when retrieving the page from the leaderboard. @return a page of leaders from the leaderboard around a given member.
6.576842
2.246701
2.927333
''' Retrieve a page of leaders from the named leaderboard around a given member. @param leaderboard_name [String] Name of the leaderboard. @param member [String] Member name. @param options [Hash] Options to be used when retrieving the page from the named leaderboard. @return a page of leaders from the named leaderboard around a given member. Returns an empty array for a non-existent member. ''' reverse_rank_for_member = None if self.order == self.DESC: reverse_rank_for_member = self.redis_connection.zrevrank( leaderboard_name, member) else: reverse_rank_for_member = self.redis_connection.zrank( leaderboard_name, member) if reverse_rank_for_member is None: return [] page_size = options.get('page_size', self.page_size) starting_offset = reverse_rank_for_member - (page_size // 2) if starting_offset < 0: starting_offset = 0 ending_offset = (starting_offset + page_size) - 1 raw_leader_data = self._range_method( self.redis_connection, leaderboard_name, int(starting_offset), int(ending_offset), withscores=False) return self._parse_raw_members( leaderboard_name, raw_leader_data, **options)
def around_me_in(self, leaderboard_name, member, **options)
Retrieve a page of leaders from the named leaderboard around a given member. @param leaderboard_name [String] Name of the leaderboard. @param member [String] Member name. @param options [Hash] Options to be used when retrieving the page from the named leaderboard. @return a page of leaders from the named leaderboard around a given member. Returns an empty array for a non-existent member.
2.855044
1.949613
1.464415
''' Retrieve a page of leaders from the leaderboard for a given list of members. @param members [Array] Member names. @param options [Hash] Options to be used when retrieving the page from the leaderboard. @return a page of leaders from the leaderboard for a given list of members. ''' return self.ranked_in_list_in( self.leaderboard_name, members, **options)
def ranked_in_list(self, members, **options)
Retrieve a page of leaders from the leaderboard for a given list of members. @param members [Array] Member names. @param options [Hash] Options to be used when retrieving the page from the leaderboard. @return a page of leaders from the leaderboard for a given list of members.
4.843009
2.040451
2.373499
''' Retrieve a page of leaders from the named leaderboard for a given list of members. @param leaderboard_name [String] Name of the leaderboard. @param members [Array] Member names. @param options [Hash] Options to be used when retrieving the page from the named leaderboard. @return a page of leaders from the named leaderboard for a given list of members. ''' ranks_for_members = [] pipeline = self.redis_connection.pipeline() for member in members: if self.order == self.ASC: pipeline.zrank(leaderboard_name, member) else: pipeline.zrevrank(leaderboard_name, member) pipeline.zscore(leaderboard_name, member) responses = pipeline.execute() for index, member in enumerate(members): data = {} data[self.MEMBER_KEY] = member rank = responses[index * 2] if rank is not None: rank += 1 else: if not options.get('include_missing', True): continue data[self.RANK_KEY] = rank score = responses[index * 2 + 1] if score is not None: score = float(score) data[self.SCORE_KEY] = score ranks_for_members.append(data) if ('with_member_data' in options) and (True == options['with_member_data']): for index, member_data in enumerate(self.members_data_for_in(leaderboard_name, members)): try: ranks_for_members[index][self.MEMBER_DATA_KEY] = member_data except: pass if 'sort_by' in options: sort_value_if_none = float('-inf') if self.order == self.ASC else float('+inf') if self.RANK_KEY == options['sort_by']: ranks_for_members = sorted( ranks_for_members, key=lambda member: member.get(self.RANK_KEY) if member.get(self.RANK_KEY) is not None else sort_value_if_none ) elif self.SCORE_KEY == options['sort_by']: ranks_for_members = sorted( ranks_for_members, key=lambda member: member.get(self.SCORE_KEY) if member.get(self.SCORE_KEY) is not None else sort_value_if_none ) return ranks_for_members
def ranked_in_list_in(self, leaderboard_name, members, **options)
Retrieve a page of leaders from the named leaderboard for a given list of members. @param leaderboard_name [String] Name of the leaderboard. @param members [Array] Member names. @param options [Hash] Options to be used when retrieving the page from the named leaderboard. @return a page of leaders from the named leaderboard for a given list of members.
2.136844
1.804031
1.184483
''' Merge leaderboards given by keys with this leaderboard into a named destination leaderboard. @param destination [String] Destination leaderboard name. @param keys [Array] Leaderboards to be merged with the current leaderboard. @param options [Hash] Options for merging the leaderboards. ''' keys.insert(0, self.leaderboard_name) self.redis_connection.zunionstore(destination, keys, aggregate)
def merge_leaderboards(self, destination, keys, aggregate='SUM')
Merge leaderboards given by keys with this leaderboard into a named destination leaderboard. @param destination [String] Destination leaderboard name. @param keys [Array] Leaderboards to be merged with the current leaderboard. @param options [Hash] Options for merging the leaderboards.
4.810885
2.067765
2.326611
''' Intersect leaderboards given by keys with this leaderboard into a named destination leaderboard. @param destination [String] Destination leaderboard name. @param keys [Array] Leaderboards to be merged with the current leaderboard. @param options [Hash] Options for intersecting the leaderboards. ''' keys.insert(0, self.leaderboard_name) self.redis_connection.zinterstore(destination, keys, aggregate)
def intersect_leaderboards(self, destination, keys, aggregate='SUM')
Intersect leaderboards given by keys with this leaderboard into a named destination leaderboard. @param destination [String] Destination leaderboard name. @param keys [Array] Leaderboards to be merged with the current leaderboard. @param options [Hash] Options for intersecting the leaderboards.
5.016384
2.05787
2.437658
''' Key for retrieving optional member data. @param leaderboard_name [String] Name of the leaderboard. @return a key in the form of +leaderboard_name:member_data+ ''' if self.global_member_data is False: return '%s:%s' % (leaderboard_name, self.member_data_namespace) else: return self.member_data_namespace
def _member_data_key(self, leaderboard_name)
Key for retrieving optional member data. @param leaderboard_name [String] Name of the leaderboard. @return a key in the form of +leaderboard_name:member_data+
4.744268
2.39015
1.984925
''' Parse the raw leaders data as returned from a given leader board query. Do associative lookups with the member to rank, score and potentially sort the results. @param leaderboard_name [String] Name of the leaderboard. @param members [List] A list of members as returned from a sorted set range query @param members_only [bool] Set True to return the members as is, Default is False. @param options [Hash] Options to be used when retrieving the page from the named leaderboard. @return a list of members. ''' if members_only: return [{self.MEMBER_KEY: m} for m in members] if members: return self.ranked_in_list_in(leaderboard_name, members, **options) else: return []
def _parse_raw_members( self, leaderboard_name, members, members_only=False, **options)
Parse the raw leaders data as returned from a given leader board query. Do associative lookups with the member to rank, score and potentially sort the results. @param leaderboard_name [String] Name of the leaderboard. @param members [List] A list of members as returned from a sorted set range query @param members_only [bool] Set True to return the members as is, Default is False. @param options [Hash] Options to be used when retrieving the page from the named leaderboard. @return a list of members.
7.358058
1.794293
4.100812