code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
style_attrib = {"style:name": self.name, "style:family": self.FAMILY}
if additional_style_attrib:
style_attrib.update(additional_style_attrib)
if self.PARENT_STYLE_DICT:
style_attrib.update(self.PARENT_STYLE_DICT)
node = el("style:style", attrib=style_at... | def style_node(self, additional_style_attrib=None) | generate a style node (for automatic-styles)
could specify additional attributes such as
'style:parent-style-name' or 'style:list-style-name' | 3.774904 | 3.684264 | 1.024602 |
proc_id = table.get_table(outdoc, lsctables.ProcessTable.tableName)[0].process_id
# load up the files into individual documents
xmldocs = [ligolw_add.ligolw_add(ligolw.Document(), [fname]) for fname in filenames]
# Get the list of dinstinct segment_definers across all docs
segment_definers ... | def run_file_operation(outdoc, filenames, use_segment_table, operation, preserve = True) | Performs an operation (intersect or union) across a set of files.
That is, given a set of files each with segment definers DMT-FLAG1,
DMT-FLAG2 etc the result is a file where
DMT-FLAG1 = (file 1's DMT-FLAG1 operation file 2's DMT-FLAG1 operation ...)
DMT-FLAG2 = (file 1's DMT-FLAG2 operation file 2's ... | 4.153965 | 4.04723 | 1.026372 |
proc_id = table.get_table(outdoc, lsctables.ProcessTable.tableName)[0].process_id
if preserve:
indoc = ligolw_add.ligolw_add(outdoc, filenames)
else:
indoc = ligolw_add.ligolw_add(ligolw.Document(), filenames)
# Start with a segment covering all of time, then
# intersect with... | def run_segment_operation(outdoc, filenames, segments, use_segment_table, operation, result_name = 'RESULT', preserve = True) | Performs an operation (intersect or union) across a set of segments.
That is, given a set of files each with segment definers DMT-FLAG1,
DMT-FLAG2 etc and a list of segments DMT-FLAG1,DMT-FLAG1 this returns
RESULT = (table 1's DMT-FLAG1 union table 2's DMT-FLAG1 union ...)
operation
... | 3.797377 | 3.788641 | 1.002306 |
errors = []
if not value is str and not value.split():
errors.append('wildcardSymbol_ERROR : Symbol : must be char or string!')
else:
self.__wildcardSymbol = value
if errors:
view.Tli.showErrors('SymbolError', errors) | def __setWildcardSymbol(self, value) | self.__wildcardSymbol variable setter | 15.281797 | 13.533097 | 1.129217 |
errors = []
if not value is str and not value.split():
errors.append('parentSymbol_ERROR : Symbol : must be char or string!')
else:
self.__parentSymbol = value
if errors:
view.Tli.showErrors('SymbolError', errors) | def __setParentSymbol(self, value) | self.__parentSymbol variable setter | 15.020109 | 13.336303 | 1.126257 |
error = []
header = []
decisions = []
if tableString.split() == []:
error.append('Table variable is empty!')
else:
tableString = tableString.split('\n')
newData = []
for element in tableString:
if element.strip():
newData.append(element)
for element in newData[0].split():
if ... | def __tableStringParser(self, tableString) | Will parse and check tableString parameter for any invalid strings.
Args:
tableString (str): Standard table string with header and decisions.
Raises:
ValueError: tableString is empty.
ValueError: One of the header element is not unique.
ValueError: Missing data value.
ValueError: Missing parent dat... | 3.511806 | 3.224384 | 1.08914 |
error = []
for row, line in enumerate(decisions):
if '.' in line:
for i, element in enumerate(line):
if row == 0:
error.append(
"Row: {}colume: {}==> don't have parent value".format(str(row).ljust(4), str(i).ljust(4)))
if element == self.__parentSymbol:
if decisions[row - 1][i... | def __replaceSpecialValues(self, decisions) | Will replace special values in decisions array.
Args:
decisions (array of array of str): Standard decision array format.
Raises:
ValueError: Row element don't have parent value.
Returns:
New decision array with updated values. | 4.031203 | 3.826829 | 1.053406 |
for key in values:
if not values[key] is str:
values[key] = str(values[key])
return values | def __toString(self, values) | Will replace dict values with string values
Args:
values (dict): Dictionary of values
Returns:
Updated values dict | 2.957212 | 3.319767 | 0.890789 |
machingIndexes = {}
for index, name in enumerate(self.header):
if name in values:
machingIndexes[index] = values[name]
return machingIndexes | def __valueKeyWithHeaderIndex(self, values) | This is hellper function, so that we can mach decision values with row index
as represented in header index.
Args:
values (dict): Normaly this will have dict of header values and values from decision
Return:
>>> return()
{
values[headerName] : int(headerName index in header array),
...
} | 3.987211 | 3.909518 | 1.019873 |
error = []
if not result:
error.append('Function parameter (result array) should contain one or more header string!')
if not values:
error.append('Function parameter (values variables) should contain one or more variable')
for header in result:
if not header in self.header:
error.append('Stri... | def __checkDecisionParameters(self, result, **values) | Checker of decision parameters, it will raise ValueError if finds something wrong.
Args:
result (array of str): See public decision methods
**values (array of str): See public decision methods
Raise:
ValueError: Result array none.
ValueError: Values dict none.
ValueError: Not find result key in hea... | 3.470109 | 3.305257 | 1.049876 |
values = self.__toString(values)
__valueKeyWithHeaderIndex = self.__valueKeyWithHeaderIndex(values)
errors = self.__checkDecisionParameters(result, **values)
if errors:
view.Tli.showErrors('ParametersError', errors)
machingData = {}
for line in self.decisions:
match = True
for index in __va... | def __getDecision(self, result, multiple=False, **values) | The main method for decision picking.
Args:
result (array of str): What values you want to get in return array.
multiple (bolean, optional): Do you want multiple result if it finds many maching decisions.
**values (dict): What should finder look for, (headerString : value).
Returns: Maped result values w... | 4.190694 | 3.880743 | 1.079869 |
callback(**self.__getDecision(result, **values)) | def decisionCall(self, callback, result, **values) | The decision method with callback option. This method will find matching row, construct
a dictionary and call callback with dictionary.
Args:
callback (function): Callback function will be called when decision will be finded.
result (array of str): Array of header string
**values (dict): What should finder... | 14.513577 | 42.815556 | 0.338979 |
data = self.__getDecision(result, **values)
data = [data[value] for value in result]
if len(data) == 1:
return data[0]
else:
return data | def decision(self, result, **values) | The decision method with callback option. This method will find matching row, construct
a dictionary and call callback with dictionary.
Args:
callback (function): Callback function will be called when decision will be finded.
result (array of str): Array of header string
**values (dict): What should finde... | 3.301797 | 3.977481 | 0.830123 |
data = self.__getDecision(result, multiple=True, **values)
data = [data[value] for value in result]
if len(data) == 1:
return data[0]
else:
return data | def allDecisions(self, result, **values) | Joust like self.decision but for multiple finded values.
Returns:
Arrays of arrays of finded elements or if finds only one mach, array of strings. | 3.449095 | 3.62215 | 0.952223 |
if mode:
region = '%s:%s' % (region, mode)
opener = urllib.request.build_opener()
opener.addheaders = default_headers
data = '%s\n%s' % (region, handshake_version)
return opener.open('http://m.agar.io/', data=data.encode()) \
.read().decode().split('\n')[0:2] | def find_server(region='EU-London', mode=None) | Returns `(address, token)`, both strings.
`mode` is the game mode of the requested server. It can be
`'party'`, `'teams'`, `'experimental'`, or `None` for "Free for all".
The returned `address` is in `'IP:port'` format.
Makes a request to http://m.agar.io to get address and token. | 4.662118 | 4.397084 | 1.060275 |
opener = urllib.request.build_opener()
opener.addheaders = default_headers
try:
data = party_token.encode()
return opener.open('http://m.agar.io/getToken', data=data) \
.read().decode().split('\n')[0]
except urllib.error.HTTPError:
raise ValueError('Invalid token... | def get_party_address(party_token) | Returns the address (`'IP:port'` string) of the party server.
To generate a `party_token`:
```
from agarnet.utils import find_server
_, token = find_server(mode='party')
```
Makes a request to http://m.agar.io/getToken to get the address. | 5.210727 | 4.223959 | 1.233612 |
'''绘制干扰线'''
line_num = randint(n_line[0], n_line[1]) # 干扰线条数
for i in range(line_num):
# 起始点
begin = (randint(0, width), randint(0, height))
# 结束点
end = (randint(0, width), randint(0, height))
draw.line([begin, end], fill=(0, 0, 0)) | def create_lines(self, draw, n_line, width, height) | 绘制干扰线 | 2.14123 | 1.99312 | 1.07431 |
'''绘制干扰点'''
chance = min(100, max(0, int(point_chance))) # 大小限制在[0, 100]
for w in range(width):
for h in range(height):
tmp = randint(0, 100)
if tmp > 100 - chance:
draw.point((w, h), fill=(0, 0, 0)) | def create_points(self, draw, point_chance, width, height) | 绘制干扰点 | 3.065989 | 2.841747 | 1.07891 |
# start external command process
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# get outputs
out, _ = p.communicate()
return p.returncode, out.strip() | def call_out(command) | Run the given command (with shell=False) and return a tuple of
(int returncode, str output). Strip the output of enclosing whitespace. | 4.210736 | 4.48154 | 0.939573 |
# start external command process
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# get outputs
out, _ = p.communicate()
# throw exception if process failed
if p.returncode != 0:
raise GitInvocationError, 'failed to run "%s"' % " ".join(command)
return out.strip() | def check_call_out(command) | Run the given command (with shell=False) and return the output as a
string. Strip the output of enclosing whitespace.
If the return code is non-zero, throw GitInvocationError. | 4.119892 | 3.422238 | 1.203859 |
return dict(map(
lambda (k, v): (k, str(v).lower() if isinstance(v, bool) else str(v)),
d.iteritems()
)) | def _dict_to_map_str_str(self, d) | Thrift requires the params and headers dict values to only contain str values. | 3.47474 | 2.85054 | 1.218976 |
save_stdout = sys.stdout
sys.stdout = DevNull()
yield
sys.stdout = save_stdout | def suppress_stdout() | Context manager that suppresses stdout.
Examples:
>>> with suppress_stdout():
... print('Test print')
>>> print('test')
test | 2.785006 | 6.412879 | 0.434283 |
if not validate_url(url):
raise WrongUrlError(f'Couldn\'t match domain name of this url: {url}')
ext = tldextract.extract(url)
return f'{ext.domain}.{ext.suffix}' | def get_domain_name(url) | Extract a domain name from the url (without subdomain).
Args:
url (str): Url.
Returns:
str: Domain name.
Raises:
DomainNotMatchedError: If url is wrong.
Examples:
>>> get_domain_name('https://vod.tvp.pl/video/')
'tvp.pl'
>>> get_domain_name('https://v... | 4.603203 | 3.622791 | 1.270623 |
data = _data.copy()
# TODO: fix this ugliness
title = data.get('title')
if title:
data['title'] = clean_title(title)
return data | def clean_video_data(_data) | Clean video data:
-> cleans title
-> ...
Args:
_data (dict): Information about the video.
Returns:
dict: Refined video data. | 4.838526 | 4.7286 | 1.023247 |
date_pattern = re.compile(r'\W*'
r'\d{1,2}'
r'[/\-.]'
r'\d{1,2}'
r'[/\-.]'
r'(?=\d*)(?:.{4}|.{2})'
r'\W*')
title = date_pattern... | def clean_title(title) | Clean title -> remove dates, remove duplicated spaces and strip title.
Args:
title (str): Title.
Returns:
str: Clean title without dates, duplicated, trailing and leading spaces. | 3.209277 | 3.21701 | 0.997596 |
parsed = urllib.parse.urlparse(url)
root, ext = os.path.splitext(parsed.path)
return ext.lstrip('.') | def get_ext(url) | Extract an extension from the url.
Args:
url (str): String representation of a url.
Returns:
str: Filename extension from a url (without a dot), '' if extension is not present. | 3.634914 | 3.589843 | 1.012555 |
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))] | def delete_duplicates(seq) | Remove duplicates from an iterable, preserving the order.
Args:
seq: Iterable of various type.
Returns:
list: List of unique objects. | 1.570437 | 2.452615 | 0.640311 |
return self._joinOnAsPriv(model, onIndex, model.__name__) | def joinOn(self, model, onIndex) | Performs an eqJoin on with the given model. The resulting join will be
accessible through the models name. | 19.090502 | 16.506502 | 1.156544 |
return self._joinOnAsPriv(model, onIndex, whatAs) | def joinOnAs(self, model, onIndex, whatAs) | Like `joinOn` but allows setting the joined results name to access it
from.
Performs an eqJoin on with the given model. The resulting join will be
accessible through the given name. | 6.706891 | 10.277899 | 0.652555 |
if self._join:
raise Exception("Already joined with a table!")
self._join = model
self._joinedField = whatAs
table = model.table
self._query = self._query.eq_join(onIndex, r.table(table))
return self | def _joinOnAsPriv(self, model, onIndex, whatAs) | Private method for handling joins. | 7.373332 | 7.189559 | 1.025561 |
if direct == "desc":
self._query = self._query.order_by(r.desc(field))
else:
self._query = self._query.order_by(r.asc(field))
return self | def orderBy(self, field, direct="desc") | Allows for the results to be ordered by a specific field. If given,
direction can be set with passing an additional argument in the form
of "asc" or "desc" | 2.297015 | 2.53007 | 0.907886 |
self._query = self._query.skip(value)
return self | def offset(self, value) | Allows for skipping a specified number of results in query. Useful
for pagination. | 14.59125 | 7.320684 | 1.993154 |
self._query = self._query.limit(value)
return self | def limit(self, value) | Allows for limiting number of results returned for query. Useful
for pagination. | 7.798014 | 5.73329 | 1.360129 |
returnResults = []
results = self._query.run()
for result in results:
if self._join:
# Because we can tell the models to ignore certian fields,
# through the protectedItems blacklist, we can nest models by
# name and have each... | def fetch(self) | Fetches the query and then tries to wrap the data in the model, joining
as needed, if applicable. | 10.775271 | 9.814294 | 1.097916 |
if request.method == "PUT":
# Bug fix: if _load_post_and_files has already been called, for
# example by middleware accessing request.POST, the below code to
# pretend the request is a POST instead of a PUT will be too late
# to make a difference. Also calling _load_post_and_fil... | def coerce_put_post(request) | Django doesn't particularly understand REST.
In case we send data over PUT, Django won't
actually look at the data and load it. We need
to twist its arm here.
The try/except abominiation here is due to a bug
in mod_python. This should fix it. | 5.063812 | 4.825661 | 1.049351 |
for loadee, mimes in Mimer.TYPES.iteritems():
for mime in mimes:
if ctype.startswith(mime):
return loadee | def loader_for_type(self, ctype) | Gets a function ref to deserialize content
for a certain mimetype. | 6.335751 | 6.570006 | 0.964345 |
type_formencoded = "application/x-www-form-urlencoded"
ctype = self.request.META.get('CONTENT_TYPE', type_formencoded)
if type_formencoded in ctype:
return None
return ctype | def content_type(self) | Returns the content type of the request in all cases where it is
different than a submitted form - application/x-www-form-urlencoded | 4.661408 | 3.595459 | 1.296471 |
ctype = self.content_type()
self.request.content_type = ctype
if not self.is_multipart() and ctype:
loadee = self.loader_for_type(ctype)
if loadee:
try:
self.request.data = loadee(self.request.raw_post_data)
... | def translate(self) | Will look at the `Content-type` sent by the client, and maybe
deserialize the contents into the format they sent. This will
work for JSON, YAML, XML and Pickle. Since the data is not just
key-value (and maybe just a list), the data will be placed on
`request.data` instead, and the handle... | 6.723961 | 6.048518 | 1.111671 |
ntw = levels
if ntw < 2:
ntw = 2
steps = [(stp, 1 + (stp * int(math.ceil(tagmax * 1.0 / ntw - 1))))
for stp in range(ntw)]
# just to be sure~
steps[-1] = (steps[-1][0], tagmax+1)
return steps | def getsteps(levels, tagmax) | Returns a list with the max number of posts per "tagcloud level" | 4.830963 | 4.540166 | 1.06405 |
tagdata.sort()
# we get the most popular tag to calculate the tags' weigth
tagmax = 0
for tagname, tagcount in tagdata:
if tagcount > tagmax:
tagmax = tagcount
steps = getsteps(site.tagcloud_levels, tagmax)
tags = []
for tagname, tagcount in tagdata:
weight = [twt[0] \
for twt in steps if twt[1] >... | def build(site, tagdata) | Returns the tag cloud for a list of tags. | 4.286682 | 3.944786 | 1.08667 |
'Performs a query and get the results.'
try:
conn = connection.cursor()
conn.execute(query)
data = conn.fetchall()
conn.close()
except: data = list()
return data | def getquery(query) | Performs a query and get the results. | 4.261744 | 3.30969 | 1.287657 |
# XXX: this looks like it can be done via ORM
tagdata = getquery( % site.id)
tagdict = {}
globaldict = {}
cloudict = {}
for feed_id, tagname, tagcount in tagdata:
if feed_id not in tagdict:
tagdict[feed_id] = []
tagdict[feed_id].append((tagname, tagcount))
try:
globaldict[tagname] += tagcount
exc... | def cloudata(site) | Returns a dictionary with all the tag clouds related to a site. | 3.750104 | 3.72484 | 1.006783 |
cloudict = fjcache.cache_get(site.id, 'tagclouds')
if not cloudict:
cloudict = cloudata(site)
fjcache.cache_set(site, 'tagclouds', cloudict)
# A subscriber's tag cloud has been requested.
if feed_id:
feed_id = int(feed_id)
if feed_id in cloudict:
return cloudict[feed_id]
return []
# The site tagcl... | def getcloud(site, feed_id=None) | Returns the tag cloud for a site or a site's subscriber. | 4.502551 | 3.961826 | 1.136484 |
'''Extract bus stations from routine page.
:param page: crawled page.
'''
stations = [_(station.value) for station in page('.stateName')]
return {
'terminal': {
stations[0]: list(reversed(stations)),
stations[-1]: stations
},
'stations': stations
... | def extract_stations(page) | Extract bus stations from routine page.
:param page: crawled page. | 11.286915 | 7.917526 | 1.425561 |
'''Extract current routine information from page.
:param page: crawled page.
:param stations: bus stations list. See `~extract_stations`.
'''
current_routines = CURRENT_ROUTINE_PATTERN.findall(page.text())
if not current_routines:
return
terminal_station = stations['stations'][-1]
... | def extract_current_routine(page, stations) | Extract current routine information from page.
:param page: crawled page.
:param stations: bus stations list. See `~extract_stations`. | 5.235988 | 4.19402 | 1.248441 |
'''Extract bus routine information from page.
:param page: crawled page.
'''
if not isinstance(page, pq):
page = pq(page)
stations = extract_stations(page)
return {
# Routine name.
'name': extract_routine_name(page),
# Bus stations.
'stations': stations... | def extract_bus_routine(page) | Extract bus routine information from page.
:param page: crawled page. | 4.013021 | 3.784511 | 1.06038 |
validation_code = self.setup_src + '\nvalidation_result = ' + self.stmt
validation_scope = {}
exec(validation_code, validation_scope)
# Store the result in the first function in the group.
if len(self.groups[self.group]) == 1:
self.result = validation_scope['... | def validate(self) | Execute the code once to get it's results (to be used in function validation). Compare the result to the
first function in the group. | 4.059846 | 3.630646 | 1.118216 |
_line_break = '{0:-<120}\n'.format('')
tests = sorted(ComparisonBenchmark.groups[group], key=lambda t: getattr(t, 'time_average_seconds'))
log = StringIO.StringIO()
log.write('Call statement:\n\n')
log.write('\t' + tests[0].stmt)
log.write('\n\n\n')
fmt =... | def summarize(group, fs=None, include_source=True) | Tabulate and write the results of ComparisonBenchmarks to a file or standard out.
:param str group: name of the comparison group.
:param fs: file-like object (Optional) | 2.855804 | 2.75601 | 1.03621 |
rawCursor = r.table(self.table).get(key).run(self._conn)
if rawCursor:
self._data = rawCursor
self._new = False
return True
else:
return False | def _grabData(self, key) | Tries to find the existing document in the database, if it is found,
then the objects _data is set to that document, and this returns
`True`, otherwise this will return `False`
:param key: The primary key of the object we're looking for
:type key: Str
:return: True if a documen... | 4.875487 | 4.070401 | 1.19779 |
if item not in object.__getattribute__(self, "_protectedItems") \
and item[0] != "_":
data = object.__getattribute__(self, "_data")
if item in data:
return data[item]
return object.__getattribute__(self, item) | def _get(self, item) | Helper function to keep the __getattr__ and __getitem__ calls
KISSish | 3.378897 | 3.490759 | 0.967955 |
if item not in object.__getattribute__(self, "_protectedItems") \
and item[0] != "_":
keys = object.__getattribute__(self, "_data")
if not hasattr(value, '__call__'):
keys[item] = value
return value
if hasattr(value, '_... | def _set(self, item, value) | Helper function to keep the __setattr__ and __setitem__ calls
KISSish
Will only set the objects _data if the given items name is not prefixed
with _ or if the item exists in the protected items List. | 4.12438 | 3.868341 | 1.066188 |
id = kwargs["id"]
kwargs.pop("id")
what = cls(**kwargs)
what._new = False
what.id = id
return what | def fromRawEntry(cls, **kwargs) | Helper function to allow wrapping existing data/entries, such as
those returned by collections. | 6.978236 | 8.167676 | 0.854372 |
what = cls(**kwargs)
if id:
setattr(what, cls.primaryKey, id)
what.save()
return what | def create(cls, id=None, **kwargs) | Similar to new() however this calls save() on the object before
returning it. | 5.857475 | 5.353784 | 1.094081 |
if not self._new:
data = self._data.copy()
ID = data.pop(self.primaryKey)
reply = r.table(self.table).get(ID) \
.update(data,
durability=self.durability,
non_atomic=self.non_atomic) \
.ru... | def save(self) | If an id exists in the database, we assume we'll update it, and if not
then we'll insert it. This could be a problem with creating your own
id's on new objects, however luckily, we keep track of if this is a new
object through a private _new variable, and use that to determine if we
inse... | 2.86483 | 2.569611 | 1.114889 |
if self._new:
raise Exception("This is a new object, %s not in data, \
indicating this entry isn't stored." % self.primaryKey)
r.table(self.table).get(self._data[self.primaryKey]) \
.delete(durability=self.durability).run(self._conn)
return True | def delete(self) | Deletes the current instance. This assumes that we know what we're
doing, and have a primary key in our data already. If this is a new
instance, then we'll let the user know with an Exception | 9.204013 | 7.183928 | 1.281195 |
if not self.__has_node(name=node1_name):
raise ValueError("Can not add an edge to a non-existing node {name}".format(name=node1_name))
if self.__has_node(name=node2_name):
raise ValueError("Can not add an edge to already existing node {name}".format(name=node2_name))
... | def add_edge(self, node1_name, node2_name, edge_length=DEFAULT_EDGE_LENGTH) | Adds a new edge to the current tree with specified characteristics
Forbids addition of an edge, if a parent node is not present
Forbids addition of an edge, if a child node already exists
:param node1_name: name of the parent node, to which an edge shall be added
:param node2_name: nam... | 2.923229 | 2.817363 | 1.037576 |
try:
for entry in filter(lambda x: x.name == name, self.nodes()):
return entry
except StopIteration:
raise ValueError("Attempted to retrieve a non-existing tree node with name: {name}"
"".format(name=name)) | def __get_node_by_name(self, name) | Returns a first TreeNode object, which name matches the specified argument
:raises: ValueError (if no node with specified name is present in the tree) | 5.531405 | 4.989874 | 1.108526 |
try:
p1 = self.__get_node_by_name(name=node1_name)
wdir = node2_name in (node.name for node in p1.children)
if account_for_direction:
return wdir
else:
p2 = self.__get_node_by_name(name=node2_name)
return wd... | def __has_edge(self, node1_name, node2_name, account_for_direction=True) | Returns a boolean flag, telling if a tree has an edge with two nodes, specified by their names as arguments
If a account_for_direction is specified as True, the order of specified node names has to relate to parent - child relation,
otherwise both possibilities are checked | 2.710493 | 2.63375 | 1.029138 |
return self.__has_edge(node1_name=node1_name, node2_name=node2_name, account_for_direction=account_for_direction) | def has_edge(self, node1_name, node2_name, account_for_direction=True) | Proxies a call to the __has_edge method | 2.061655 | 1.65076 | 1.248913 |
return self.__root.get_distance(target=node1_name, target2=node2_name) | def get_distance(self, node1_name, node2_name) | Returns a length of an edge / path, if exists, from the current tree
:param node1_name: a first node name in current tree
:param node2_name: a second node name in current tree
:return: a length of specified by a pair of vertices edge / path
:rtype: `Number`
:raises: ValueError, ... | 6.121928 | 8.738794 | 0.700546 |
result = []
nodes = deque([self.__root])
while len(nodes) > 0:
current_node = nodes.popleft()
children = current_node.children
nodes.extend(children)
if not current_node.is_leaf():
leaves = filter(lambda node: node.is_leaf(... | def __get_v_tree_consistent_leaf_based_hashable_multicolors(self) | Internally used method, that recalculates VTree-consistent sets of leaves in the current tree | 2.896528 | 2.817269 | 1.028133 |
v_t_consistent_multicolors = self.__get_v_tree_consistent_leaf_based_hashable_multicolors()
hashed_vtree_consistent_leaves_multicolors = {mc.hashable_representation for mc in v_t_consistent_multicolors}
self.vtree_consistent_multicolors_set = hashed_vtree_consistent_leaves_multicolors
... | def __update_consistent_multicolors(self) | Internally used method, that recalculates T-consistent / VT-consistent multicolors for current tree topology | 2.879312 | 2.548149 | 1.129962 |
self.multicolors_are_up_to_date = False
tree_to_append = tree.__root if not copy else deepcopy(tree.__root)
self.__get_node_by_name(node_name).add_child(tree_to_append) | def append(self, node_name, tree, copy=False) | Append a specified tree (represented by a root TreeNode element) to the node, specified by its name
:param copy: a flag denoting if the appended tree has to be added as is, or is the deepcopy of it has to be used
:type copy: Boolean
:raises: ValueError (if no node with a specified name, to whic... | 5.817758 | 5.834469 | 0.997136 |
hashVal = hashVal or self.hash
hashPath = hashPath or self.parent / hashVal + self.ext
source = hashPath.replace('\\', '/').replace(ROOT, '')
galleries = galleries or []
tags = tags or []
imagefile = ROOT / source
if imagefile.ext == '.psd':
... | def export(self, hashVal=None, hashPath=None, tags=None, galleries=None) | The export function needs to:
- Move source image to asset folder
- Rename to guid.ext
- Save thumbnail, small, and image versions | 3.632201 | 3.595795 | 1.010125 |
image = pilImage.open(ROOT / self.source.name)
box, width, height = cropBox(self.width, self.height)
# Resize
image.thumbnail((width, height), pilImage.ANTIALIAS)
# Crop from center
box = cropBox(*image.size)[0]
image = image.crop(box)
# save
... | def generateThumbnail(self) | Generates a square thumbnail | 4.81471 | 4.739382 | 1.015894 |
self.source = hashPath.replace('\\', '/').replace(ROOT, '')
galleries = galleries or []
tags = tags or []
# -- Get info
videodata = self.info()
self.width = videodata['width']
self.height = videodata['height']
self.framerate = videodata['framera... | def export(self, hashVal, hashPath, tags=None, galleries=None) | The export function needs to:
- Move source image to asset folder
- Rename to guid.ext
- Save thumbnail, video_thumbnail, and MP4 versions. If the source is already h264, then only transcode the thumbnails | 3.624567 | 3.58628 | 1.010676 |
source = ROOT / self.source.name
thumbnail = source.parent / '_{}.jpg'.format(source.namebase)
# -- Save thumbnail and put into queue
poster = source.parent / '__{}.jpg'.format(source.namebase)
cmd = [FROG_FFMPEG, '-i', str(source), '-ss', '1', '-vframes', '1', str(thum... | def generateThumbnail(self) | Generates a square thumbnail | 4.147316 | 4.125463 | 1.005297 |
path = "."
sig = signal.SIGTERM
delay = 0.25
ignorefile = ".reloadignore"
ignore_patterns = ignore_patterns or load_ignore_patterns(ignorefile)
event_handler = ReloadEventHandler(ignore_patterns)
reloader = Reloader(command, signal)
observer = Observer()
observer.schedule(eve... | def reload(*command, ignore_patterns=[]) | Reload given command | 2.96928 | 2.930875 | 1.013103 |
command = [sys.executable, sys.argv[0]]
command.extend(args)
reload(*command, ignore_patterns=ignore_patterns) | def reload_me(*args, ignore_patterns=[]) | Reload currently running command with given args | 5.376863 | 4.233076 | 1.270203 |
data_string = data_string.strip()
linear_terminator_index = data_string.index("$") if "$" in data_string else -1
circular_terminator_index = data_string.index("@") if "@" in data_string else -1
if linear_terminator_index < 0 and circular_terminator_index < 0:
raise V... | def parse_data_string(data_string) | Parses a string assumed to contain gene order data, retrieving information about fragment type, gene order, blocks names and their orientation
First checks if gene order termination signs are present.
Selects the earliest one.
Checks that information preceding is not empty and contains gene ord... | 3.958507 | 3.608005 | 1.097146 |
sign, name = block
data = name.split(BlockVertex.NAME_SEPARATOR)
root_name, data = data[0], data[1:]
tags = [entry.split(TaggedVertex.TAG_SEPARATOR) for entry in data]
for tag_entry in tags:
if len(tag_entry) == 1:
tag_entry.append(None)
... | def __assign_vertex_pair(block) | Assigns usual BreakpointGraph type vertices to supplied block.
Vertices are labeled as "block_name" + "h" and "block_name" + "t" according to blocks orientation.
:param block: information about a genomic block to create a pair of vertices for in a format of ( ``+`` | ``-``, block_name)
:type b... | 3.096346 | 2.868189 | 1.079547 |
chr_type, blocks = parsed_data
vertices = []
for block in blocks:
###############################################################################################
#
# each block is represented as a pair of vertices (that correspond to block extremities... | def get_edges_from_parsed_data(parsed_data) | Taking into account fragment type (circular|linear) and retrieved gene order information translates adjacencies between blocks into edges for addition to the :class:`bg.breakpoint_graph.BreakpointGraph`
In case supplied fragment is linear (``$``) special artificial vertices (with ``__infinity`` suffix) are int... | 3.639804 | 3.237506 | 1.124262 |
result = BreakpointGraph()
current_genome = None
fragment_data = {}
for line in stream:
line = line.strip()
if len(line) == 0:
###############################################################################################
... | def get_breakpoint_graph(stream, merge_edges=True) | Taking a file-like object transforms supplied gene order data into the language of
:param merge_edges: a flag that indicates if parallel edges in produced breakpoint graph shall be merged or not
:type merge_edges: ``bool``
:param stream: any iterable object where each iteration produces a ``str... | 3.944381 | 3.583544 | 1.100693 |
result = []
genomes = bg.get_overall_set_of_colors()
for genome in genomes:
genome_graph = bg.get_genome_graph(color=genome)
genome_blocks_orders = genome_graph.get_blocks_order()
blocks_orders = genome_blocks_orders[genome]
if len(blocks_... | def get_blocks_in_grimm_from_breakpoint_graph(bg) | :param bg: a breakpoint graph, that contians all the information
:type bg: ``bg.breakpoint_graph.BreakpointGraph``
:return: list of strings, which represent genomes present in breakpoint graph as orders of blocks and is compatible with GRIMM format | 4.042875 | 3.655565 | 1.105951 |
schema = cls.json_schema if json_schema_class is None else json_schema_class()
return schema.load(data) | def from_json(cls, data, json_schema_class=None) | JSON deserialization method that retrieves a genome instance from its json representation
If specific json schema is provided, it is utilized, and if not, a class specific is used | 3.102428 | 3.142509 | 0.987246 |
wrapper = FixedFileWrapper(file(filename, 'rb'))
response = HttpResponse(wrapper, content_type=content_type)
response['Content-Length'] = os.path.getsize(filename)
return response | def send_file(request, filename, content_type='image/jpeg') | Send a file through Django without loading the whole file into
memory at once. The FileWrapper will turn the file object into an
iterator for chunks of 8KB. | 2.541614 | 2.273462 | 1.117949 |
temp = tempfile.TemporaryFile()
archive = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED)
for artist,files in fileList.iteritems():
for f in files:
archive.write(f[0], '%s/%s' % (artist, f[1]))
archive.close()
wrapper = FixedFileWrapper(temp)
response = HttpResponse(wra... | def send_zipfile(request, fileList) | Create a ZIP file on disk and transmit it in chunks of 8KB,
without loading the whole file into memory. A similar approach can
be used for large dynamic PDF files. | 2.584653 | 2.634112 | 0.981224 |
Benchmark.enable = True
ComparisonBenchmark.enable = True
BenchmarkedFunction.enable = True
BenchmarkedClass.enable = True | def enable() | Enable all benchmarking. | 9.661866 | 7.52868 | 1.283341 |
Benchmark.enable = False
ComparisonBenchmark.enable = False
BenchmarkedFunction.enable = False
BenchmarkedClass.enable = False | def disable() | Disable all benchmarking. | 9.65258 | 7.763431 | 1.243339 |
json_schema = cls.json_schema if json_schema_class is None else json_schema_class()
return super(BlockVertex, cls).from_json(data=data, json_schema_class=json_schema.__class__) | def from_json(cls, data, json_schema_class=None) | This class overwrites the from_json method thus, making sure, that if `from_json` is called from this class instance, it will provide its JSON schema as a default one | 3.576921 | 3.019134 | 1.184751 |
return self.NAME_SEPARATOR.join([super(InfinityVertex, self).name, self.NAME_SUFFIX]) | def name(self) | access to classic name attribute is hidden by this property | 17.900835 | 16.147169 | 1.108605 |
schema = cls.json_schema if json_schema_class is None else json_schema_class()
return super(InfinityVertex, cls).from_json(data=data, json_schema_class=schema.__class__) | def from_json(cls, data, json_schema_class=None) | This class overwrites the from_json method, thus making sure that if `from_json` is called from this class instance, it will provide its JSON schema as a default one | 4.19259 | 3.759598 | 1.11517 |
return self.NAME_SEPARATOR.join([super(TaggedVertex, self).name] + self.get_tags_as_list_of_strings()) | def name(self) | access to classic name attribute is hidden by this property | 11.753924 | 10.566806 | 1.112344 |
index = bisect_left(self.tags, (tag, value))
contains = False
if index < len(self.tags):
contains = self.tags[index] == (tag, value)
if not contains:
self.tags.insert(index, (tag, value)) | def add_tag(self, tag, value) | as tags are kept in a sorted order, a bisection is a fastest way to identify a correct position
of or a new tag to be added. An additional check is required to make sure w don't add duplicates | 2.338693 | 2.030381 | 1.15185 |
try:
self.tags.remove((tag, value))
except ValueError as err:
if not silent_fail:
raise err | def remove_tag(self, tag, value, silent_fail=False) | we try to remove supplied pair tag -- value, and if does not exist outcome depends on the silent_fail flag | 3.031519 | 2.557988 | 1.185119 |
if edge1.vertex1 != edge2.vertex1 and edge1.vertex1 != edge2.vertex2:
raise ValueError("Edges to be merged do not connect same vertices")
forward = edge1.vertex1 == edge2.vertex1
if forward and edge1.vertex2 != edge2.vertex2:
raise ValueError("Edges to be merged ... | def merge(cls, edge1, edge2) | Merges multi-color information from two supplied :class:`BGEdge` instances into a new :class:`BGEdge`
Since :class:`BGEdge` represents an undirected edge, created edge's vertices are assign according to the order in first supplied edge.
Accounts for subclassing.
:param edge1: first out of two... | 2.036081 | 1.998681 | 1.018713 |
return [color.json_id if hasattr(color, "json_id") else hash(color) for color in self.multicolor.multicolors.elements()] | def colors_json_ids(self) | A proxy property based access to vertices in current edge
When edge is serialized to JSON object, no explicit object for its multicolor is created, but rather all colors,
taking into account their multiplicity, are referenced by their json_ids. | 8.015596 | 4.938392 | 1.623119 |
url = self._decode_url(url, "")
if url.scheme == 'http' or url.scheme == 'https':
return HttpConnection(url.geturl(), timeout=timeout, **kwargs)
else:
if sys.version_info[0] > 2:
raise ValueError("Thrift transport is not available "
... | def _get_connection_from_url(self, url, timeout, **kwargs) | Returns a connection object given a string url | 3.464968 | 3.506832 | 0.988062 |
@CustomLogLevel(level, name, logger_name)
def _default_template(logger, msg, *args, **kwargs):
return msg, args, kwargs | def new_log_level(level, name, logger_name=None) | Quick way to create a custom log level that behaves like the default levels in the logging module.
:param level: level number
:param name: level name
:param logger_name: optional logger name | 8.408146 | 8.631581 | 0.974114 |
obj = {
'id': user.id,
'username': user.username,
'name': user.get_full_name(),
'email': user.email,
}
return obj | def userToJson(user) | Returns a serializable User dict
:param user: User to get info for
:type user: User
:returns: dict | 2.256385 | 3.062522 | 0.736773 |
obj = {
'id': comment.id,
'comment': comment.comment,
'user': userToJson(comment.user),
'date': comment.submit_date.isoformat(),
}
return obj | def commentToJson(comment) | Returns a serializable Comment dict
:param comment: Comment to get info for
:type comment: Comment
:returns: dict | 2.894379 | 3.941036 | 0.734421 |
dataDict = {}
data = request.body
for n in urlparse.parse_qsl(data):
dataDict[n[0]] = n[1]
setattr(request, 'PUT', dataDict)
setattr(request, 'DELETE', dataDict) | def getPutData(request) | Adds raw post to the PUT and DELETE querydicts on the request so they behave like post
:param request: Request object to add PUT/DELETE to
:type request: Request | 3.900429 | 3.668617 | 1.063188 |
hashVal = hashlib.sha1()
while True:
r = f.read(1024)
if not r:
break
hashVal.update(r)
f.seek(0)
return hashVal.hexdigest() | def getHashForFile(f) | Returns a hash value for a file
:param f: File to hash
:type f: str
:returns: str | 2.218075 | 2.788523 | 0.79543 |
return ''.join(random.choice(chars) for x in xrange(size)) | def uniqueID(size=6, chars=string.ascii_uppercase + string.digits) | A quick and dirty way to get a unique string | 3.130698 | 2.546276 | 1.22952 |
guids = guids[:]
img = list(Image.objects.filter(guid__in=guids))
vid = list(Video.objects.filter(guid__in=guids))
objects = img + vid
sortedobjects = []
if objects:
while guids:
for obj in iter(objects):
if obj.guid == guids[0]:
sort... | def getObjectsFromGuids(guids) | Gets the model objects based on a guid list
:param guids: Guids to get objects for
:type guids: list
:returns: list | 3.194042 | 3.640906 | 0.877266 |
forwardedfor = request.META.get('HTTP_X_FORWARDED_FOR')
if forwardedfor:
ip = forwardedfor.split(',')[0]
else:
ip = request.META.get('REMOTE_ADDR')
return ip | def getClientIP(request) | Returns the best IP address found from the request | 1.795799 | 2.045769 | 0.877811 |
for app in settings.INSTALLED_APPS:
if not app.startswith('django'):
module = __import__(app)
moduledir = path.Path(module.__file__).parent
plugin = moduledir / 'frog_plugin.py'
if plugin.exists():
file_, fpath, desc = imp.find_module('fro... | def __discoverPlugins() | Discover the plugin classes contained in Python files, given a
list of directory names to scan. Return a list of plugin classes. | 3.857992 | 4.033675 | 0.956446 |
self.values.append(val)
self.value = self.values[0] | def append(self, val) | Appends the object to the end of the values list. Will also set the value to the first
item in the values list
:param val: Object to append
:type val: primitive | 4.91327 | 3.326518 | 1.477001 |
return {
'isError': self.isError,
'message': self.message,
'values': self.values,
'value': self.value,
} | def asDict(self) | Returns a serializable object | 3.787305 | 3.623041 | 1.045339 |
future = concurrent.TracebackFuture()
def on_response(response):
exc = response.exception()
if exc:
if exc.args[0] == b'invalid password':
future.set_exception(exceptions.AuthError(exc))
else:
... | def auth(self, password) | Request for authentication in a password-protected Redis server.
Redis can be instructed to require a password before allowing clients
to execute commands. This is done using the ``requirepass`` directive
in the configuration file.
If the password does not match, an
:exc:`~tredi... | 3.895565 | 3.918275 | 0.994204 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.