code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
for e in self.xsl_elements:
e.render(e.run) | def render_xsl(self, node, context) | Render all XSL elements | 18.322651 | 12.107515 | 1.513329 |
for n in self.root.xpath('.//w:rStyle[@w:val="%s"]' % self.style, namespaces=self.namespaces):
n.getparent().remove(n) | def remove_style(self) | Remove all XSL run rStyle elements | 5.494589 | 4.084751 | 1.345147 |
if xml:
self.xml = xml
# render XSL
self.render_xsl(self.root, context)
# create root XSL sheet
xsl_ns = self.namespaces['xsl']
rootName = etree.QName(xsl_ns, 'stylesheet')
root = etree.Element(rootName, nsmap={'xsl'... | def render(self, xml, context, raise_on_errors=True) | Render xml string and apply XSLT transfomation with context | 2.965775 | 2.925778 | 1.013671 |
@wraps(function, assigned=available_attrs(function))
def _wrapped_view(request, *args, **kwargs):
if 'image' in request.META['CONTENT_TYPE']:
name = default_storage.save(os.path.join('images', 'aloha-uploads', request.META['HTTP_X_FILE_NAME']),
Co... | def handle_image_posts(function=None) | Decorator for views that handles ajax image posts in base64 encoding, saving
the image and returning the url | 2.985265 | 2.744149 | 1.087865 |
if cls.name == 'RootLogger':
for meth in ['notice', 'spam', 'success', 'verbose']:
cls.locals[meth] = [scoped_nodes.Function(meth, None)] | def verboselogs_class_transform(cls) | Make Pylint aware of our custom logger methods. | 16.275749 | 14.620224 | 1.113235 |
if mod.name == 'logging':
for const in ['NOTICE', 'SPAM', 'SUCCESS', 'VERBOSE']:
mod.locals[const] = [nodes.Const(const)] | def verboselogs_module_transform(mod) | Make Pylint aware of our custom log levels. | 8.258709 | 6.760959 | 1.221529 |
'''Produce etag value for a cached page.
Intended for usage in conditional views (@condition decorator).'''
response, site, cachekey = kwz.get('_view_data') or initview(request)
if not response: return None
return fjcache.str2md5(
'{0}--{1}--{2}'.format( site.id if site else 'x', cachekey,
response[1].strfti... | def cache_etag(request, *argz, **kwz) | Produce etag value for a cached page.
Intended for usage in conditional views (@condition decorator). | 10.499713 | 6.26298 | 1.676472 |
'''Last modification date for a cached page.
Intended for usage in conditional views (@condition decorator).'''
response, site, cachekey = kwz.get('_view_data') or initview(request)
if not response: return None
return response[1] | def cache_last_modified(request, *argz, **kwz) | Last modification date for a cached page.
Intended for usage in conditional views (@condition decorator). | 17.436367 | 7.012253 | 2.486557 |
'''Retrieves the basic data needed by all feeds (host, feeds, etc)
Returns a tuple of:
1. A valid cached response or None
2. The current site object
3. The cache key
4. The subscribers for the site (objects)
5. The feeds for the site (ids)'''
http_host, path_info = ( smart_unicode(part.strip('/')) f... | def initview(request, response_cache=True) | Retrieves the basic data needed by all feeds (host, feeds, etc)
Returns a tuple of:
1. A valid cached response or None
2. The current site object
3. The cache key
4. The subscribers for the site (objects)
5. The feeds for the site (ids) | 3.61129 | 3.028372 | 1.192486 |
'View that handles the generation of blogrolls.'
response, site, cachekey = initview(request)
if response: return response[0]
template = loader.get_template('feedjack/{0}.xml'.format(btype))
ctx = dict()
fjlib.get_extra_context(site, ctx)
ctx = Context(ctx)
response = HttpResponse(
template.render(ctx), cont... | def blogroll(request, btype) | View that handles the generation of blogrolls. | 6.515396 | 5.894059 | 1.105418 |
'View that handles the feeds.'
view_data = initview(request)
wrap = lambda func: ft.partial(func, _view_data=view_data, **criterias)
return condition(
etag_func=wrap(cache_etag),
last_modified_func=wrap(cache_last_modified) )\
(_buildfeed)(request, feedclass, view_data, **criterias) | def buildfeed(request, feedclass, **criterias) | View that handles the feeds. | 7.788021 | 6.705967 | 1.161357 |
'View that handles all page requests.'
view_data = initview(request)
wrap = lambda func: ft.partial(func, _view_data=view_data, **criterias)
return condition(
etag_func=wrap(cache_etag),
last_modified_func=wrap(cache_last_modified) )\
(_mainview)(request, view_data, **criterias) | def mainview(request, **criterias) | View that handles all page requests. | 7.453843 | 6.510664 | 1.144867 |
if request.method == 'GET':
return get(request, obj_id)
elif request.method == 'POST':
return post(request)
elif request.method == 'PUT':
getPutData(request)
return put(request, obj_id)
elif request.method == 'DELETE':
getPutData(request)
return delet... | def index(request, obj_id=None) | Handles a request based on method and calls the appropriate function | 2.138524 | 1.896118 | 1.127843 |
defaultname = 'New Gallery %i' % Gallery.objects.all().count()
data = request.POST or json.loads(request.body)['body']
title = data.get('title', defaultname)
description = data.get('description', '')
security = int(data.get('security', Gallery.PUBLIC))
g, created = Gallery.objects.get_or_c... | def post(request) | Create a Gallery | 3.623376 | 3.409682 | 1.062673 |
data = request.PUT or json.loads(request.body)['body']
guids = data.get('guids', '').split(',')
move = data.get('from')
security = request.PUT.get('security')
gallery = Gallery.objects.get(pk=obj_id)
if guids:
objects = getObjectsFromGuids(guids)
images = filter(lambda... | def put(request, obj_id=None) | Adds Image and Video objects to Gallery based on GUIDs | 3.144496 | 2.852659 | 1.102304 |
data = request.DELETE or json.loads(request.body)
guids = data.get('guids').split(',')
objects = getObjectsFromGuids(guids)
gallery = Gallery.objects.get(pk=obj_id)
LOGGER.info('{} removed {} from {}'.format(request.user.email, guids, gallery))
for o in objects:
if isinstance(o, I... | def delete(request, obj_id=None) | Removes ImageVideo objects from Gallery | 3.611032 | 3.247319 | 1.112004 |
if int(obj_id) == 0:
obj = None
else:
obj = Gallery.objects.get(pk=obj_id)
isanonymous = request.user.is_anonymous()
if isanonymous and obj is None:
LOGGER.warn('There was an anonymous access attempt from {} to {}'.format(getClientIP(request), obj))
raise Permissio... | def filterObjects(request, obj_id) | Filters Gallery for the requested ImageVideo objects. Returns a Result object with
serialized objects | 3.693668 | 3.739818 | 0.98766 |
res = Result()
models = QUERY_MODELS
idDict = {}
objDict = {}
data = {}
modelmap = {}
length = 75
# -- Get all IDs for each model
for m in models:
modelmap[m.model_class()] = m.model
if object_:
idDict[m.model] = m.model_class().objects.filter(gal... | def _filter(request, object_, tags=None, more=False, orderby='created') | Filters Piece objects from self based on filters, search, and range
:param tags: List of tag IDs to filter
:type tags: list
:param more -- bool, Returns more of the same filtered set of images based on session range
return list, Objects filtered | 3.186386 | 3.251839 | 0.979872 |
o = []
for m in kwargs.values():
for l in iter(m):
o.append(l)
o = list(set(o))
sortfunc = _sortByCreated if orderby == 'created' else _sortByModified
if six.PY2:
o.sort(sortfunc)
else:
o.sort(key=functools.cmp_to_key(sortfunc))
return o | def _sortObjects(orderby='created', **kwargs) | Sorts lists of objects and combines them into a single list | 3.384676 | 3.202703 | 1.056818 |
if a.created < b.created:
return 1
elif a.created > b.created:
return -1
else:
return 0 | def _sortByCreated(a, b) | Sort function for object by created date | 1.821533 | 1.874507 | 0.97174 |
if a.modified < b.modified:
return 1
elif a.modified > b.modified:
return -1
else:
return 0 | def _sortByModified(a, b) | Sort function for object by modified date | 1.875995 | 1.91292 | 0.980697 |
query = query.strip()
LOGGER.debug(query)
sqs = SearchQuerySet()
results = sqs.raw_search('{}*'.format(query)).models(model)
if not results:
results = sqs.raw_search('*{}'.format(query)).models(model)
if not results:
results = sqs.raw_search('*{}*'.format(query)).models(mode... | def search(query, model) | Performs a search query and returns the object ids | 2.717905 | 2.617862 | 1.038216 |
if whatever:
keys = [u'name', u'iso639_1', u'iso639_2_b', u'iso639_2_t', u'native']
val = whatever
elif language:
keys = [u'name']
val = language
elif iso639_1:
keys = [u'iso639_1']
val = iso639_1
elif iso639_2:
keys = [u'iso639_2_b', u'iso639... | def find(whatever=None, language=None, iso639_1=None,
iso639_2=None, native=None) | Find data row with the language.
:param whatever: key to search in any of the following fields
:param language: key to search in English language name
:param iso639_1: key to search in ISO 639-1 code (2 digits)
:param iso639_2: key to search in ISO 639-2 code (3 digits,
bibliograph... | 1.963236 | 1.801154 | 1.089988 |
item = find(whatever=key)
if not item:
raise NonExistentLanguageError('Language does not exist.')
return item[u'iso639_1'] | def to_iso639_1(key) | Find ISO 639-1 code for language specified by key.
>>> to_iso639_1("swe")
u'sv'
>>> to_iso639_1("English")
u'en' | 8.280685 | 9.914256 | 0.83523 |
if type not in ('B', 'T'):
raise ValueError('Type must be either "B" or "T".')
item = find(whatever=key)
if not item:
raise NonExistentLanguageError('Language does not exist.')
if type == 'T' and item[u'iso639_2_t']:
return item[u'iso639_2_t']
return item[u'iso639_2_b'] | def to_iso639_2(key, type='B') | Find ISO 639-2 code for language specified by key.
:param type: "B" - bibliographical (default), "T" - terminological
>>> to_iso639_2("German")
u'ger'
>>> to_iso639_2("German", "T")
u'deu' | 3.134917 | 3.523326 | 0.889761 |
item = find(whatever=key)
if not item:
raise NonExistentLanguageError('Language does not exist.')
return item[u'name'] | def to_name(key) | Find the English name for the language specified by key.
>>> to_name('br')
u'Breton'
>>> to_name('sw')
u'Swahili' | 12.408206 | 12.338712 | 1.005632 |
item = find(whatever=key)
if not item:
raise NonExistentLanguageError('Language does not exist.')
return item[u'native'] | def to_native(key) | Find the native name for the language specified by key.
>>> to_native('br')
u'brezhoneg'
>>> to_native('sw')
u'Kiswahili' | 13.396186 | 12.712599 | 1.053772 |
country_prefix = "country"
prefix = request.POST.get('prefix', prefix)
if prefix:
country_prefix = prefix + '-country'
country_code = request.POST.get(country_prefix, country_code)
form_class = form_factory(country_code=country_code)
if request.method == "POST":
... | def address_inline(request, prefix="", country_code=None, template_name="postal/form.html") | Displays postal address with localized fields | 2.22465 | 2.231724 | 0.99683 |
log = StringIO.StringIO()
log.write(self.setup_src)
# If the function is not bound, write the test score to the log
if not self.is_class_method:
time_avg = convert_time_units(self.time_average_seconds)
log.write("\nAverage time: {0} \n".format(time_avg))... | def write_log(self, fs=None) | Write the results of the benchmark to a log file.
:param fs: file-like object. | 5.395734 | 5.678583 | 0.95019 |
_timer = timeit.Timer(stmt=stmt, setup=setup)
trials = _timer.repeat(self.timeit_repeat, self.timeit_number)
self.time_average_seconds = sum(trials) / len(trials) / self.timeit_number
# Convert into reasonable time units
time_avg = convert_time_units(self.time_average_se... | def run_timeit(self, stmt, setup) | Create the function call statement as a string used for timeit. | 3.689784 | 3.64856 | 1.011299 |
try:
answer = resolver.query(domain, 'MX')
return [str(record.exchange).lower()[:-1] for record in answer]
except (resolver.NoAnswer, resolver.NoNameservers, resolver.NotAbsolute,
resolver.NoRootSOA, resolver.NXDOMAIN, resolver.Timeout) as error:
LOGGER.error('Error quer... | def _get_mx_exchanges(domain) | Fetch the MX records for the specified domain
:param str domain: The domain to get the MX records for
:rtype: list | 3.679326 | 3.63385 | 1.012515 |
if domain in domain_list:
return True
if resolve:
for exchange in _get_mx_exchanges(domain):
for value in domain_list:
if exchange.endswith(value):
return True
return False | def _domain_check(domain, domain_list, resolve) | Returns ``True`` if the ``domain`` is serviced by the ``domain_list``.
:param str domain: The domain to check
:param list domain_list: The domains to check for
:param bool resolve: Resolve the domain
:rtype: bool | 3.694977 | 4.213006 | 0.87704 |
address = utils.parseaddr(email_address)
local_part, domain_part = address[1].lower().split('@')
# Plus addressing is supported by Microsoft domains and FastMail
if domain_part in MICROSOFT_DOMAINS:
if '+' in local_part:
local_part = local_part.split('+')[0]
# GMail suppor... | def normalize(email_address, resolve=True) | Return the normalized email address, removing
:param str email_address: The normalized email address
:param bool resolve: Resolve the domain
:rtype: str | 3.470902 | 3.662895 | 0.947584 |
# is_css = filename.endswith(".css")
is_remote = filename.startswith("http://") or filename.startswith(
"https://")
with tempfile.TemporaryFile() if is_remote else open(
filename, "rb") as f:
if is_remote:
r = requests.get(filename, verify=False)
f.... | def validate(filename, verbose=False) | Validate file and return JSON result as dictionary.
"filename" can be a file name or an HTTP URL.
Return "" if the validator does not return valid JSON.
Raise OSError if curl command returns an error status. | 3.685752 | 3.477843 | 1.059781 |
parser = argparse.ArgumentParser(
description="[v" + __version__ + "] " + __doc__,
prog="w3c_validator",
)
parser.add_argument(
"--log",
default="INFO",
help=("log level: DEBUG, INFO or INFO "
"(default: INFO)"))
parser.add_argument(
"--... | def main() | Parser the command line and run the validator. | 2.491793 | 2.45289 | 1.01586 |
info = {}
for line in value.decode('utf-8').splitlines():
if not line or line[0] == '#':
continue
if ':' in line:
key, value = line.split(':', 1)
info[key] = parse_info_value(value)
return info | def format_info_response(value) | Format the response from redis
:param str value: The return response from redis
:rtype: dict | 2.468759 | 2.671446 | 0.924128 |
self.multicolors = self.multicolors + Counter(arg for arg in args) | def update(self, *args) | Updates information about colors and their multiplicity in respective :class:`Multicolor` instance.
By iterating over supplied arguments each of which should represent a color object, updates information about colors and their multiplicity in current :class:`Multicolor` instance.
:param args: variable... | 15.673355 | 6.456628 | 2.427483 |
if isinstance(multicolor, Multicolor):
to_delete = multicolor.multicolors
else:
to_delete = Counter(color for color in multicolor)
self.multicolors = self.multicolors - to_delete | def __delete(self, multicolor) | Reduces information :class:`Multicolor` attribute by iterating over supplied colors data.
In case supplied argument is a :class:`Multicolor` instance, multi-color specific information to de deleted is set to its :attr:`Multicolor.multicolors`.
In other cases multi-color specific information to de delet... | 3.422785 | 2.622598 | 1.305112 |
result = cls()
for multicolor in multicolors:
result.multicolors = result.multicolors + multicolor.multicolors
return result | def __merge(cls, *multicolors) | Produces a new :class:`Multicolor` object resulting from gathering information from all supplied :class:`Multicolor` instances.
New :class:`Multicolor` is created and its :attr:`Multicolor.multicolors` attribute is updated with similar attributes of supplied :class:`Multicolor` objects.
Accounts for s... | 2.703848 | 2.645169 | 1.022184 |
multicolor1.multicolors = multicolor1.multicolors + multicolor2.multicolors
return multicolor1 | def __left_merge(multicolor1, multicolor2) | Updates first supplied :class:`Multicolor` instance with information from second supplied :class:`Multicolor` instance.
First supplied instances attribute :attr:`Multicolor.multicolors` is updated with a help of ``+`` method of python Counter object.
:param multicolor1: instance to update information ... | 2.988377 | 2.861452 | 1.044357 |
result = 0
for key, value in multicolor1.multicolors.items():
if key in multicolor2.multicolors:
result += min(value, multicolor2.multicolors[key])
return result | def similarity_score(multicolor1, multicolor2) | Computes how similar two :class:`Multicolor` objects are from perspective of information, that they contain.
Two multicolors are called to be similar if they contain same colors (at least one). Multiplicity of colors is taken into account as well.
:param multicolor1: first out of two multi-colors to c... | 2.346792 | 2.442183 | 0.96094 |
if not isinstance(other, Multicolor):
raise TypeError("Multicolor can be intersected only with another Multicolor object")
intersection_colors_core = self.colors.intersection(other.colors)
colors_count = {color: min(self.multicolors[color], other.multicolors[color]) for colo... | def intersect(self, other) | Computes the multiset intersection, between the current Multicolor and the supplied Multicolor
:param other: another Multicolor object to compute a multiset intersection with
:return:
:raise TypeError: an intersection can be computed only between two Multicolor objects | 3.54915 | 3.112015 | 1.140467 |
cmd = ['text2wfreq', '-hash', hashtablesize,
'-verbosity', verbosity]
# Ensure that every parameter is of type 'str'
cmd = [str(x) for x in cmd]
with tempfile.SpooledTemporaryFile() as input_f:
input_f.write(text.encode('utf-8') if sys.version_info >= (3,) and typ... | def text2wfreq(text, output_file, hashtablesize=1000000, verbosity=2) | List of every word which occurred in the text, along with its number of occurrences.
Notes : Uses a hash-table to provide an efficient method of counting word occurrences. Output list is not sorted (due to "randomness" of the hash-table), but can be easily sorted into the user's desired order by the UNIX sort c... | 3.584284 | 3.73331 | 0.960082 |
cmd = ['wfreq2vocab', '-verbosity', verbosity,
'-records', records]
# Ensure that every parameter is of type 'str'
cmd = [str(x) for x in cmd]
if top:
cmd.extend(['-top',top])
elif gt:
cmd.extend(['-gt',gt])
with open(wfreq_file,'r') as input_f:... | def wfreq2vocab(wfreq_file, output_file, top=None, gt=None, records=1000000, verbosity=2) | Takes a a word unigram file, as produced by text2wfreq and converts it to a vocabulary file.
The top parameter allows the user to specify the size of the vocabulary; if the function is called with the parameter top=20000, then the vocabulary will consist of the most common 20,000 words.
The gt parameter... | 3.477922 | 3.427991 | 1.014566 |
cmd = ['text2wngram']
if n:
cmd.extend(['-n', n])
if chars:
cmd.extend(['-chars', chars])
if words:
cmd.extend(['-words', words])
if compress:
cmd.append('-compress')
if verbosity:
cmd.extend(['-verbosity', verbosity])
# Ensure t... | def text2wngram(text, output_file, n=3, chars=63636363, words=9090909, compress=False, verbosity=2) | List of every word n-gram which occurred in the text, along with its number of occurrences.
The maximum numbers of charactors and words that can be stored in the buffer are given by the chars and words parameters. | 2.827857 | 2.877553 | 0.98273 |
cmd = ['ngram2mgram', '-n', n,
'-m', m]
if words and ascii_idngram:
raise ConversionError("Parameters 'words' and 'ascii_idngram' cannot both be True")
if words:
cmd.append('-words')
elif ascii_idngram:
cmd.append('-ascii')
else:
cmd.a... | def ngram2mgram(input_file, output_file, n, m, words=False, ascii_idngram=False) | Takes either a word n-gram file, or an id n-gram file and outputs a file of the same type where m < n. | 2.922074 | 2.92374 | 0.99943 |
cmd = ['wngram2idngram', '-vocab', os.path.abspath(vocab_file),
'-idngram', os.path.abspath(output_file)]
if buffersize:
cmd.extend(['-buffer', buffersize])
if hashtablesize:
cmd.extend(['-hash', hashtablesize])
if files:
cmd.extend(['-files', ... | def wngram2idngram(input_file, vocab_file, output_file, buffersize=100, hashtablesize=2000000, files=20, compress=False, verbosity=2, n=3, write_ascii=False, fof_size=10) | Takes a word N-gram file and a vocabulary file and lists every id n-gram which occurred in the text, along with its number of occurrences, in either ASCII or binary format.
Note : It is important that the vocabulary file is in alphabetical order. If you are using vocabularies generated by wfreq2vocab then this... | 2.389898 | 2.415962 | 0.989212 |
cmd = ['idngram2stats']
if n:
cmd.extend(['-n', n])
if fof_size:
cmd.extend(['-fof_size'], fof_size)
if verbosity:
cmd.extend(['-verbosity'], verbosity)
if ascii_input:
cmd.append(['-ascii_input'])
# Ensure that every parameter is of type 'str'
cm... | def idngram2stats(input_file, output_file, n=3, fof_size=50, verbosity=2, ascii_input=False) | Lists the frequency-of-frequencies for each of the 2-grams, ... , n-grams, which can enable the user to choose appropriate cut-offs, and to specify appropriate memory requirements with the spec_num parameter in idngram2lm. | 3.014115 | 2.969869 | 1.014898 |
cmd = ['mergeidngram']
if n:
cmd.extend(['-n', n])
if ascii_input:
cmd.append('-ascii_input')
if ascii_output:
cmd.append('-ascii_output')
if len(input_file) > 1:
raise MergeError("mergeidngram needs at least 1 input file")
cmd.extend(input_files)... | def mergeidngram(output_file, input_files, n=3, ascii_input=False, ascii_output=False) | Takes a set of id n-gram files (in either binary (by default) or ASCII (if specified) format - note that they should all be in the same format, however) and outputs a merged id N-gram.
Notes : This function can also be used to convert id n-gram files between ascii and binary formats. | 3.319363 | 3.398345 | 0.976759 |
# TODO: Args still missing
# [ -calc_mem | -buffer 100 | -spec_num y ... z ]
# [ -two_byte_bo_weights
# [ -min_bo_weight nnnnn] [ -max_bo_weight nnnnn] [ -out_of_range_bo_weights] ]
# [ -linear | -absolute | -good_turing | -witten_bell ]
# [ -disc_ranges 1 7 7 ]
# [ -cutof... | def idngram2lm(idngram_file, vocab_file, output_file, context_file=None, vocab_type=1, oov_fraction=0.5, four_byte_counts=False, min_unicount=0, zeroton_fraction=False, n=3, verbosity=2, arpa_output=True, ascii_input=False) | Takes an idngram-file (in either binary (by default) or ASCII (if specified) format), a vocabulary file, and (optionally) a context cues file. Additional command line parameters will specify the cutoffs, the discounting strategy and parameters, etc. It outputs a language model, in either binary format (to be read by ev... | 4.120134 | 4.023704 | 1.023965 |
cmd = ['binlm2arpa', '-binary', input_file,
'-arpa'. output_file]
if verbosity:
cmd.extend(['-verbosity', verbosity])
# Ensure that every parameter is of type 'str'
cmd = [str(x) for x in cmd]
with tempfile.SpooledTemporaryFile() as output_f:
... | def binlm2arpa(input_file, output_file, verbosity=2) | Converts a binary format language model, as generated by idngram2lm, into an an ARPA format language model. | 3.915862 | 3.92584 | 0.997458 |
with tempfile.NamedTemporaryFile(suffix='.wfreq', delete=False) as f:
wfreq_file = f.name
try:
text2wfreq(text, wfreq_file, **text2wfreq_kwargs)
wfreq2vocab(wfreq_file, output_file, **wfreq2vocab_kwargs)
except ConversionError:
raise
finally:
os.remove(wfreq... | def text2vocab(text, output_file, text2wfreq_kwargs={}, wfreq2vocab_kwargs={}) | Convienience function that uses text2wfreq and wfreq2vocab to create a vocabulary file from text. | 1.99401 | 1.987189 | 1.003433 |
if vocab_file:
used_vocab_file = vocab_file
else:
# Create temporary vocab file
with tempfile.NamedTemporaryFile(suffix='.vocab', delete=False) as f:
used_vocab_file = f.name
text2vocab(text, used_vocab_file)
# Create temporary idngram file
with tempfile... | def text2lm(text, output_file, vocab_file=None, text2idngram_kwargs={}, idngram2lm_kwargs={}) | Convienience function to directly convert text (and vocabulary) into a language model. | 1.830889 | 1.822567 | 1.004566 |
return self._execute([b'PFADD', key] + list(elements), 1) | def pfadd(self, key, *elements) | Adds all the element arguments to the HyperLogLog data structure
stored at the variable name specified as first argument.
As a side effect of this command the HyperLogLog internals may be
updated to reflect a different estimation of the number of unique items
added so far (the cardinali... | 6.214989 | 7.801532 | 0.796637 |
return self._execute([b'PFMERGE', dest_key] + list(keys), b'OK') | def pfmerge(self, dest_key, *keys) | Merge multiple HyperLogLog values into an unique value that will
approximate the cardinality of the union of the observed Sets of the
source HyperLogLog structures.
The computed merged HyperLogLog is set to the destination variable,
which is created if does not exist (defaulting to an e... | 6.431937 | 6.46617 | 0.994706 |
if cls.EMITTERS.has_key(format):
return cls.EMITTERS.get(format)
raise ValueError("No emitters found for type %s" % format) | def get(cls, format) | Gets an emitter, returns the class and a content-type. | 4.171926 | 3.179355 | 1.312193 |
cls.EMITTERS[name] = (klass, content_type) | def register(cls, name, klass, content_type='text/plain') | Register an emitter.
Parameters::
- `name`: The name of the emitter ('json', 'xml', 'yaml', ...)
- `klass`: The emitter class.
- `content_type`: The content type to serve response as. | 6.026654 | 6.081314 | 0.991012 |
em = kwargs.pop('emitter_format', None)
if not em:
em = request.GET.get('format', 'json')
return em | def determine_emitter(self, request, *args, **kwargs) | Function for determening which emitter to use
for output. It lives here so you can easily subclass
`Resource` in order to change how emission is detected.
You could also check for the `Accept` HTTP header here,
since that pretty much makes sense. Refer to `Mimer` for
that as wel... | 4.928909 | 5.87516 | 0.83894 |
resp = rc.BAD_REQUEST
resp.write(' '+str(e.form.errors))
return resp | def form_validation_response(self, e) | Method to return form validation error information.
You will probably want to override this in your own
`Resource` subclass. | 20.018457 | 19.457161 | 1.028848 |
if hasattr(self.handler, 'anonymous'):
anon = self.handler.anonymous
if callable(anon):
return anon
for klass in typemapper.keys():
if anon == klass.__name__:
return klass
return None | def anonymous(self) | Gets the anonymous handler. Also tries to grab a class
if the `anonymous` value is a string, so that we can define
anonymous handlers that aren't defined yet (like, when
you're subclassing your basehandler into an anonymous one.) | 6.212519 | 4.652697 | 1.335251 |
for method_type in ('GET', 'PUT', 'POST', 'DELETE'):
block = getattr(request, method_type, { })
if True in [ k.startswith("oauth_") for k in block.keys() ]:
sanitized = block.copy()
for k in sanitized.keys():
if k.startswith(... | def cleanup_request(request) | Removes `oauth_` keys from various dicts on the
request object, and returns the sanitized version. | 3.665264 | 2.92966 | 1.251089 |
if isinstance(e, FormValidationError):
return self.form_validation_response(e)
elif isinstance(e, TypeError):
result = rc.BAD_REQUEST
hm = HandlerMethod(meth)
sig = hm.signature
msg = 'Method signature does not match.\n\n'
... | def error_handler(self, e, request, meth, em_format) | Override this method to add handling of errors customized for your
needs | 4.09821 | 4.130437 | 0.992198 |
doc = ET.parse(path).getroot()
channel = doc.find("./channel")
blog = _parse_blog(channel)
authors = _parse_authors(channel)
categories = _parse_categories(channel)
tags = _parse_tags(channel)
posts = _parse_posts(channel)
return {
"blog": blog,
"authors": author... | def parse(path) | Parses xml and returns a formatted dict.
Example:
wpparser.parse("./blog.wordpress.2014-09-26.xml")
Will return:
{
"blog": {
"tagline": "Tagline",
"site_url": "http://marteinn.se/blog",
"blog_url": "http://marteinn.se/blog",
"language":... | 2.291347 | 1.867504 | 1.226957 |
title = element.find("./title").text
tagline = element.find("./description").text
language = element.find("./language").text
site_url = element.find("./{%s}base_site_url" % WP_NAMESPACE).text
blog_url = element.find("./{%s}base_blog_url" % WP_NAMESPACE).text
return {
"title": titl... | def _parse_blog(element) | Parse and return genral blog data (title, tagline etc). | 2.370579 | 2.142027 | 1.106699 |
authors = []
items = element.findall("./{%s}author" % WP_NAMESPACE)
for item in items:
login = item.find("./{%s}author_login" % WP_NAMESPACE).text
email = item.find("./{%s}author_email" % WP_NAMESPACE).text
first_name = item.find("./{%s}author_first_name" % WP_NAMESPACE).text
... | def _parse_authors(element) | Returns a well formatted list of users that can be matched against posts. | 1.783839 | 1.665648 | 1.070958 |
reference = {}
items = element.findall("./{%s}category" % WP_NAMESPACE)
for item in items:
term_id = item.find("./{%s}term_id" % WP_NAMESPACE).text
nicename = item.find("./{%s}category_nicename" % WP_NAMESPACE).text
name = item.find("./{%s}cat_name" % WP_NAMESPACE).text
... | def _parse_categories(element) | Returns a list with categories with relations. | 2.443634 | 2.378679 | 1.027307 |
if items is None:
items = []
for key in reference:
category = reference[key]
if category["parent"] == slug:
children = _build_category_tree(category["nicename"],
reference=reference)
category["children"] = childr... | def _build_category_tree(slug, reference=None, items=None) | Builds a recursive tree with category relations as children. | 3.507716 | 3.24519 | 1.080897 |
tags = []
items = element.findall("./{%s}tag" % WP_NAMESPACE)
for item in items:
term_id = item.find("./{%s}term_id" % WP_NAMESPACE).text
slug = item.find("./{%s}tag_slug" % WP_NAMESPACE).text
name = item.find("./{%s}tag_name" % WP_NAMESPACE).text
tag = {
... | def _parse_tags(element) | Retrieves and parses tags into a array/dict.
Example:
[{"term_id": 1, "slug": "python", "name": "Python"},
{"term_id": 2, "slug": "java", "name": "Java"}] | 2.151045 | 1.849826 | 1.162836 |
posts = []
items = element.findall("item")
for item in items:
title = item.find("./title").text
link = item.find("./link").text
pub_date = item.find("./pubDate").text
creator = item.find("./{%s}creator" % DC_NAMESPACE).text
guid = item.find("./guid").text
... | def _parse_posts(element) | Returns a list with posts. | 1.520581 | 1.507412 | 1.008736 |
import phpserialize
metadata = {}
fields = element.findall("./{%s}postmeta" % WP_NAMESPACE)
for field in fields:
key = field.find("./{%s}meta_key" % WP_NAMESPACE).text
value = field.find("./{%s}meta_value" % WP_NAMESPACE).text
if key == "_wp_attachment_metadata":
... | def _parse_postmeta(element) | Retrive post metadata as a dictionary | 3.352179 | 3.221756 | 1.040482 |
comments = []
items = element.findall("./{%s}comment" % WP_NAMESPACE)
for item in items:
comment_id = item.find("./{%s}comment_id" % WP_NAMESPACE).text
author = item.find("./{%s}comment_author" % WP_NAMESPACE).text
email = item.find("./{%s}comment_author_email" % WP_NAMESPACE)... | def _parse_comments(element) | Returns a list with comments. | 1.408937 | 1.373707 | 1.025646 |
if self.umanager_opened:
return
self.ser.write(self.cmd_umanager_invocation)
# optimistic approach first: assume umanager is not invoked
if self.read_loop(lambda x: x.endswith(self.umanager_prompt),self.timeout*self.umanager_waitcoeff):
self.umanager_ope... | def open_umanager(self) | Used to open an uManager session. | 6.099466 | 5.869497 | 1.03918 |
if not (force or self.umanager_opened):
return
# make sure we've got a fresh prompt
self.ser.write(self.cr)
if self.read_loop(lambda x: x.endswith(self.umanager_prompt),self.timeout):
self.ser.write(''.join((self.cmd_umanager_termination,self.cr)))... | def close_umanager(self, force=False) | Used to close an uManager session.
:param force: try to close a session regardless of a connection object internal state | 5.907627 | 6.045592 | 0.977179 |
self.open_umanager()
self.ser.write(''.join((self.cmd_download,self.cr)))
if self.read_loop(lambda x: x.endswith(self.xmodem_crc),self.timeout):
if self.xmodem.send(StringIO.StringIO(data)):
log.info("Data sent")
else:
rai... | def download(self,data,um_update=False) | Used to download firmware or filter set.
:param data: binary string to push via serial
:param um_update: flag whether to update umanager | 4.14362 | 4.120185 | 1.005688 |
buf = []
self.open_umanager()
self.ser.write(''.join((self.cmd_current_filter_list,self.cr)))
if self.read_loop(lambda x: x.endswith(self.umanager_prompt),self.timeout,lambda x,y,z: buf.append(y.rstrip()[:-1])):
if raw:
rv = buf = buf[0]
... | def list_current_filter_set(self,raw=False) | User to list a currently selected filter set | 8.858457 | 8.644778 | 1.024718 |
return self._execute([b'LRANGE', key, start, end]) | def lrange(self, key, start, end) | Returns the specified elements of the list stored at key.
:param key: The list's key
:type key: :class:`str`, :class:`bytes`
:param int start: zero-based index to start retrieving elements from
:param int end: zero-based index at which to stop retrieving elements
:rtype: list
... | 6.31679 | 10.300171 | 0.61327 |
return self._execute([b'LTRIM', key, start, stop], b'OK') | def ltrim(self, key, start, stop) | Crop a list to the specified range.
:param key: The list's key
:type key: :class:`str`, :class:`bytes`
:param int start: zero-based index to first element to retain
:param int stop: zero-based index of the last element to retain
:returns: did the operation succeed?
:rtyp... | 7.151566 | 8.494583 | 0.841897 |
return self._execute([b'LPUSH', key] + list(values)) | def lpush(self, key, *values) | Insert all the specified values at the head of the list stored at key.
:param key: The list's key
:type key: :class:`str`, :class:`bytes`
:param values: One or more positional arguments to insert at the
beginning of the list. Each value is inserted at the beginning
of t... | 5.726582 | 10.83919 | 0.528322 |
return self._execute([b'LPUSHX', key] + list(values)) | def lpushx(self, key, *values) | Insert values at the head of an existing list.
:param key: The list's key
:type key: :class:`str`, :class:`bytes`
:param values: One or more positional arguments to insert at the
beginning of the list. Each value is inserted at the beginning
of the list individually (se... | 5.778668 | 10.910937 | 0.529622 |
return self._execute([b'RPUSH', key] + list(values)) | def rpush(self, key, *values) | Insert all the specified values at the tail of the list stored at key.
:param key: The list's key
:type key: :class:`str`, :class:`bytes`
:param values: One or more positional arguments to insert at the
tail of the list.
:returns: the length of the list after push operations... | 5.648779 | 11.014083 | 0.512869 |
return self._execute([b'RPUSHX', key] + list(values)) | def rpushx(self, key, *values) | Insert values at the tail of an existing list.
:param key: The list's key
:type key: :class:`str`, :class:`bytes`
:param values: One or more positional arguments to insert at the
tail of the list.
:returns: the length of the list after push operations or
zero if ... | 5.882358 | 11.397552 | 0.516107 |
if isinstance(obj, datetime.datetime):
return timezone("UTC").normalize(obj.astimezone(timezone("UTC"))).strftime('%Y-%m-%dT%H:%M:%SZ')
raise TypeError("{0} is not JSON serializable".format(repr(obj))) | def encode_date_optional_time(obj) | ISO encode timezone-aware datetimes | 2.734078 | 2.542301 | 1.075434 |
if self.faster:
if prefixed_path not in self.found_files:
self.found_files[prefixed_path] = (source_storage, path)
self.task_queue.put({
'handler_type': handler_type,
'path': path,
'prefixed_path': prefixed_path,
... | def file_handler(self, handler_type, path, prefixed_path, source_storage) | Create a dict with all kwargs of the `copy_file` or `link_file` method of the super class and add it to
the queue for later processing. | 2.507889 | 2.167196 | 1.157204 |
if self.faster:
return True
else:
return super(Command, self).delete_file(path, prefixed_path, source_storage) | def delete_file(self, path, prefixed_path, source_storage) | We don't need all the file_exists stuff because we have to override all files anyways. | 5.232926 | 4.16729 | 1.255715 |
collected = super(Command, self).collect()
if self.faster:
self.worker_spawn_method()
self.post_processor()
return collected | def collect(self) | Create some concurrent workers that process the tasks simultaneously. | 16.016993 | 15.530542 | 1.031322 |
monkey.patch_all(thread=False)
joinall([spawn(self.gevent_worker) for x in range(self.queue_worker_amount)]) | def gevent_spawn(self) | Spawn worker threads (using gevent) | 8.605995 | 6.763214 | 1.272471 |
while not self.task_queue.empty():
task_kwargs = self.task_queue.get()
handler_type = task_kwargs.pop('handler_type')
if handler_type == 'link':
super(Command, self).link_file(**task_kwargs)
else:
super(Command, self).copy... | def gevent_worker(self) | Process one task after another by calling the handler (`copy_file` or `copy_link`) method of the super class. | 3.560134 | 2.548042 | 1.397204 |
processes = []
for x in range(self.queue_worker_amount):
process = multiprocessing.Process(target=self.mp_worker)
process.start()
processes.append(process)
for process in processes:
process.join() | def mp_spawn(self) | Spawn worker processes (using multiprocessing) | 2.972711 | 2.734586 | 1.087079 |
while not self.task_queue.empty():
task_kwargs = self.task_queue.get()
handler_type = task_kwargs.pop('handler_type')
if handler_type == 'link':
super(Command, self).link_file(**task_kwargs)
else:
super(Command, self).copy... | def mp_worker(self) | Process one task after another by calling the handler (`copy_file` or `copy_link`) method of the super class. | 3.110374 | 2.254797 | 1.379447 |
try:
resp = requests.get(github_url + '/meta')
if resp.status_code == 200:
return resp.json()['hooks']
else:
if resp.headers.get('X-RateLimit-Remaining') == '0':
reset_ts = int(resp.headers['X-RateLimit-Reset'])
reset_string = time... | def _load_github_hooks(github_url='https://api.github.com') | Request GitHub's IP block from their API.
Return the IP network.
If we detect a rate-limit error, raise an error message stating when
the rate limit will reset.
If something else goes wrong, raise a generic 503. | 2.494486 | 2.29013 | 1.089233 |
if isinstance(ip_str, bytes):
ip_str = ip_str.decode()
ip = ipaddress.ip_address(ip_str)
if ip.version == 6 and ip.ipv4_mapped:
ip = ip.ipv4_mapped
for block in load_github_hooks():
if ip in ipaddress.ip_network(block):
return True
return False | def is_github_ip(ip_str) | Verify that an IP address is owned by GitHub. | 3.146837 | 2.883187 | 1.091444 |
if isinstance(key, type(u'')):
key = key.encode()
digest = 'sha1=' + hmac.new(key, data, hashlib.sha1).hexdigest()
# Covert everything to byte sequences
if isinstance(digest, type(u'')):
digest = digest.encode()
if isinstance(signature, type(u'')):
signature = signatur... | def check_signature(signature, key, data) | Compute the HMAC signature and test against a given hash. | 2.959302 | 2.864367 | 1.033143 |
app.config.setdefault('VALIDATE_IP', True)
app.config.setdefault('VALIDATE_SIGNATURE', True)
@app.route(url, methods=['POST'])
def hook():
if app.config['VALIDATE_IP']:
if not is_github_ip(request.remote_addr):
raise Forbidden('Re... | def init_app(self, app, url='/hooks') | Register the URL route to the application.
:param app: the optional :class:`~flask.Flask` instance to
register the extension
:param url: the url that events will be posted to | 2.283044 | 2.393131 | 0.953999 |
if hook_name not in self._hooks:
self._hooks[hook_name] = fn
else:
raise Exception('%s hook already registered' % hook_name) | def register_hook(self, hook_name, fn) | Register a function to be called on a GitHub event. | 2.298347 | 2.368427 | 0.970411 |
def wrapper(fn):
self.register_hook(hook_name, fn)
return fn
return wrapper | def hook(self, hook_name) | A decorator that's used to register a new hook handler.
:param hook_name: the event to handle | 3.287981 | 4.816722 | 0.682618 |
sock, address = self.sock.accept()
wsock = websocket(sock)
wsock.secure = self.secure
ServerHandshake(wsock).perform(self)
wsock.handshake_sent = True
return wsock, address | def accept(self) | Equivalent to socket.accept(), but transforms the socket into a
websocket instance and sends a server handshake (after receiving a
client handshake). Note that the handshake may raise a HandshakeError
exception. | 7.629209 | 4.767866 | 1.600131 |
self.sock.connect(address)
ClientHandshake(self).perform()
self.handshake_sent = True | def connect(self, address) | Equivalent to socket.connect(), but sends an client handshake request
after connecting.
`address` is a (host, port) tuple of the server to connect to. | 8.983902 | 10.424822 | 0.86178 |
for frame in args:
self.sock.sendall(self.apply_send_hooks(frame, False).pack()) | def send(self, *args) | Send a number of frames. | 12.489033 | 9.790242 | 1.275661 |
frame = self.apply_send_hooks(frame, False)
self.sendbuf += frame.pack()
self.sendbuf_frames.append([frame, len(self.sendbuf), callback])
if recv_callback:
self.recv_callback = recv_callback | def queue_send(self, frame, callback=None, recv_callback=None) | Enqueue `frame` to the send buffer so that it is send on the next
`do_async_send`. `callback` is an optional callable to call when the
frame has been fully written. `recv_callback` is an optional callable
to quickly set the `recv_callback` attribute to. | 5.011062 | 5.183794 | 0.966678 |
assert len(self.sendbuf)
nwritten = self.sock.send(self.sendbuf)
nframes = 0
for entry in self.sendbuf_frames:
frame, offset, callback = entry
if offset <= nwritten:
nframes += 1
if callback:
callbac... | def do_async_send(self) | Send any queued data. This function should only be called after a write
event on a file descriptor. | 3.723766 | 3.483817 | 1.068875 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.