text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def _configure_buffer_sizes():
"""Set up module globals controlling buffer sizes"""
global PIPE_BUF_BYTES
global OS_PIPE_SZ
PIPE_BUF_BYTES = 65536
OS_PIPE_SZ = None
# Teach the 'fcntl' module about 'F_SETPIPE_SZ', which is a Linux-ism,
# but a good one that can drastically reduce the numbe... | [
"def",
"_configure_buffer_sizes",
"(",
")",
":",
"global",
"PIPE_BUF_BYTES",
"global",
"OS_PIPE_SZ",
"PIPE_BUF_BYTES",
"=",
"65536",
"OS_PIPE_SZ",
"=",
"None",
"# Teach the 'fcntl' module about 'F_SETPIPE_SZ', which is a Linux-ism,",
"# but a good one that can drastically reduce the ... | 36.296296 | 20.592593 |
def _compute_projection_pick(artist, path, xy):
"""
Project *xy* on *path* to obtain a `Selection` for *artist*.
*path* is first transformed to screen coordinates using the artist
transform, and the target of the returned `Selection` is transformed
back to data coordinates using the artist *axes* i... | [
"def",
"_compute_projection_pick",
"(",
"artist",
",",
"path",
",",
"xy",
")",
":",
"transform",
"=",
"artist",
".",
"get_transform",
"(",
")",
".",
"frozen",
"(",
")",
"tpath",
"=",
"(",
"path",
".",
"cleaned",
"(",
"transform",
")",
"if",
"transform",
... | 44.865385 | 20.288462 |
def tx_xml(self):
"""
Return the ``<c:tx>`` (tx is short for 'text') element for this
series as unicode text. This element contains the series name.
"""
return self._tx_tmpl.format(**{
'wksht_ref': self._series.name_ref,
'series_name': self.name,
... | [
"def",
"tx_xml",
"(",
"self",
")",
":",
"return",
"self",
".",
"_tx_tmpl",
".",
"format",
"(",
"*",
"*",
"{",
"'wksht_ref'",
":",
"self",
".",
"_series",
".",
"name_ref",
",",
"'series_name'",
":",
"self",
".",
"name",
",",
"'nsdecls'",
":",
"''",
",... | 34.5 | 13.7 |
def close(self):
"""
Mark the scope as closed, i.e. all symbols have been declared,
and no further declarations should be done.
"""
if self._closed:
raise ValueError('scope is already marked as closed')
# By letting parent know which symbols this scope has l... | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_closed",
":",
"raise",
"ValueError",
"(",
"'scope is already marked as closed'",
")",
"# By letting parent know which symbols this scope has leaked, it",
"# will let them reserve all lowest identifiers first.",
"if",
"... | 34.1875 | 21.5625 |
def path_to_ls(fn):
""" Converts an absolute path to an entry resembling the output of
the ls command on most UNIX systems."""
st = os.stat(fn)
full_mode = 'rwxrwxrwx'
mode = ''
file_time = ''
d = ''
for i in range(9):
# Incrementally builds up the 9 character string, using c... | [
"def",
"path_to_ls",
"(",
"fn",
")",
":",
"st",
"=",
"os",
".",
"stat",
"(",
"fn",
")",
"full_mode",
"=",
"'rwxrwxrwx'",
"mode",
"=",
"''",
"file_time",
"=",
"''",
"d",
"=",
"''",
"for",
"i",
"in",
"range",
"(",
"9",
")",
":",
"# Incrementally buil... | 45.8125 | 24.625 |
def estimate_cpd(self, node):
"""
Method to estimate the CPD for a given variable.
Parameters
----------
node: int, string (any hashable python object)
The name of the variable for which the CPD is to be estimated.
Returns
-------
CPD: Tabula... | [
"def",
"estimate_cpd",
"(",
"self",
",",
"node",
")",
":",
"state_counts",
"=",
"self",
".",
"state_counts",
"(",
"node",
")",
"# if a column contains only `0`s (no states observed for some configuration",
"# of parents' states) fill that column uniformly instead",
"state_counts"... | 37.410714 | 19.696429 |
async def commit_prepared(self, xid, *, is_prepared=True):
"""Commit prepared twophase transaction."""
if not is_prepared:
await self.execute("XA END '%s'" % xid)
await self.execute("XA COMMIT '%s'" % xid) | [
"async",
"def",
"commit_prepared",
"(",
"self",
",",
"xid",
",",
"*",
",",
"is_prepared",
"=",
"True",
")",
":",
"if",
"not",
"is_prepared",
":",
"await",
"self",
".",
"execute",
"(",
"\"XA END '%s'\"",
"%",
"xid",
")",
"await",
"self",
".",
"execute",
... | 47.4 | 10.4 |
def _to_uniform_pwm(self, values):
"""
Convert raw pwm values to uniform values.
:param values: The raw pwm values.
:return: Converted, uniform pwm values (0.0-1.0).
"""
return [self._to_single_uniform_pwm(values[i])
for i in range(len(self._pins))] | [
"def",
"_to_uniform_pwm",
"(",
"self",
",",
"values",
")",
":",
"return",
"[",
"self",
".",
"_to_single_uniform_pwm",
"(",
"values",
"[",
"i",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"_pins",
")",
")",
"]"
] | 34 | 10.666667 |
def get_int_from_user(self, title="Enter integer value",
cond_func=lambda i: i is not None):
"""Opens an integer entry dialog and returns integer
Parameters
----------
title: String
\tDialog title
cond_func: Function
\tIf cond_func of in... | [
"def",
"get_int_from_user",
"(",
"self",
",",
"title",
"=",
"\"Enter integer value\"",
",",
"cond_func",
"=",
"lambda",
"i",
":",
"i",
"is",
"not",
"None",
")",
":",
"is_integer",
"=",
"False",
"while",
"not",
"is_integer",
":",
"dlg",
"=",
"wx",
".",
"T... | 24.138889 | 20.555556 |
def do_ls(self, subcmd, opts, folder=""):
"""${cmd_name}: list messages in the specified folder
${cmd_usage}
${cmd_option_list}
SINCE can be used with epoch times, for example:
md ls -s $(date '+%s')
"""
client = MdClient(self.maildir, filesystem=self.filesys... | [
"def",
"do_ls",
"(",
"self",
",",
"subcmd",
",",
"opts",
",",
"folder",
"=",
"\"\"",
")",
":",
"client",
"=",
"MdClient",
"(",
"self",
".",
"maildir",
",",
"filesystem",
"=",
"self",
".",
"filesystem",
")",
"client",
".",
"ls",
"(",
"foldername",
"="... | 34.222222 | 15.111111 |
def consult_hook(self, item_session: ItemSession, verdict: bool,
reason: str, test_info: dict):
'''Consult the scripting hook.
Returns:
tuple: (bool, str)
'''
try:
reasons = {
'filters': test_info['map'],
'reas... | [
"def",
"consult_hook",
"(",
"self",
",",
"item_session",
":",
"ItemSession",
",",
"verdict",
":",
"bool",
",",
"reason",
":",
"str",
",",
"test_info",
":",
"dict",
")",
":",
"try",
":",
"reasons",
"=",
"{",
"'filters'",
":",
"test_info",
"[",
"'map'",
... | 27.857143 | 19.952381 |
def parse_location(loc, default_port):
'''
loc can be of the format http://<ip/domain>[:<port>]
eg:
http://localhost:8888
http://localhost/
return ip (str), port (int)
>>> parse_location('http://localhost/', 6379)
('localhost', 6379)
>>> parse_location('http://localhost:8888'... | [
"def",
"parse_location",
"(",
"loc",
",",
"default_port",
")",
":",
"parsed",
"=",
"urlparse",
"(",
"loc",
")",
"if",
"':'",
"in",
"parsed",
".",
"netloc",
":",
"ip",
",",
"port",
"=",
"parsed",
".",
"netloc",
".",
"split",
"(",
"':'",
")",
"port",
... | 24.681818 | 19.590909 |
def write_bed_with_trackline(bed, out, trackline, add_chr=False):
"""
Read a bed file and write a copy with a trackline. Here's a simple trackline
example: 'track type=bed name="cool" description="A cool track."'
Parameters
----------
bed : str
Input bed file name.
out : str
... | [
"def",
"write_bed_with_trackline",
"(",
"bed",
",",
"out",
",",
"trackline",
",",
"add_chr",
"=",
"False",
")",
":",
"df",
"=",
"pd",
".",
"read_table",
"(",
"bed",
",",
"index_col",
"=",
"None",
",",
"header",
"=",
"None",
")",
"bt",
"=",
"pbt",
"."... | 33.36 | 19.84 |
def unread(thread, user):
"""
Check whether there are any unread messages for a particular thread for a user.
"""
return bool(thread.userthread_set.filter(user=user, unread=True)) | [
"def",
"unread",
"(",
"thread",
",",
"user",
")",
":",
"return",
"bool",
"(",
"thread",
".",
"userthread_set",
".",
"filter",
"(",
"user",
"=",
"user",
",",
"unread",
"=",
"True",
")",
")"
] | 38.2 | 17.4 |
def get_message_definitions(self, msgid_or_symbol: str) -> list:
"""Returns the Message object for this message.
:param str msgid_or_symbol: msgid_or_symbol may be either a numeric or symbolic id.
:raises UnknownMessageError: if the message id is not defined.
:rtype: List of MessageDefi... | [
"def",
"get_message_definitions",
"(",
"self",
",",
"msgid_or_symbol",
":",
"str",
")",
"->",
"list",
":",
"if",
"msgid_or_symbol",
"[",
"1",
":",
"]",
".",
"isdigit",
"(",
")",
":",
"msgid_or_symbol",
"=",
"msgid_or_symbol",
".",
"upper",
"(",
")",
"for",... | 45.210526 | 19.315789 |
def get_or_none(cls, **filter_kwargs):
"""
Returns a video or None.
"""
try:
video = cls.objects.get(**filter_kwargs)
except cls.DoesNotExist:
video = None
return video | [
"def",
"get_or_none",
"(",
"cls",
",",
"*",
"*",
"filter_kwargs",
")",
":",
"try",
":",
"video",
"=",
"cls",
".",
"objects",
".",
"get",
"(",
"*",
"*",
"filter_kwargs",
")",
"except",
"cls",
".",
"DoesNotExist",
":",
"video",
"=",
"None",
"return",
"... | 23.2 | 13.4 |
def init_original_response(self):
"""Get the original response for comparing, confirm is_cookie_necessary"""
no_cookie_resp = None
self.is_cookie_necessary = True
if 'json' in self.request:
self.request['data'] = json.dumps(self.request.pop('json')).encode(
se... | [
"def",
"init_original_response",
"(",
"self",
")",
":",
"no_cookie_resp",
"=",
"None",
"self",
".",
"is_cookie_necessary",
"=",
"True",
"if",
"'json'",
"in",
"self",
".",
"request",
":",
"self",
".",
"request",
"[",
"'data'",
"]",
"=",
"json",
".",
"dumps"... | 47.259259 | 13.259259 |
def cli(ctx, feature_id, organism="", sequence=""):
"""Delete a feature
Output:
A standard apollo feature dictionary ({"features": [{...}]})
"""
return ctx.gi.annotations.delete_feature(feature_id, organism=organism, sequence=sequence) | [
"def",
"cli",
"(",
"ctx",
",",
"feature_id",
",",
"organism",
"=",
"\"\"",
",",
"sequence",
"=",
"\"\"",
")",
":",
"return",
"ctx",
".",
"gi",
".",
"annotations",
".",
"delete_feature",
"(",
"feature_id",
",",
"organism",
"=",
"organism",
",",
"sequence"... | 30.75 | 25.25 |
def sample(self, nsims=1000):
""" Samples from the posterior predictive distribution
Parameters
----------
nsims : int (default : 1000)
How many draws from the posterior predictive distribution
Returns
----------
- np.ndarray of draws from the data
... | [
"def",
"sample",
"(",
"self",
",",
"nsims",
"=",
"1000",
")",
":",
"if",
"self",
".",
"latent_variables",
".",
"estimation_method",
"not",
"in",
"[",
"'BBVI'",
",",
"'M-H'",
"]",
":",
"raise",
"Exception",
"(",
"\"No latent variables estimated!\"",
")",
"els... | 43.894737 | 27.578947 |
def teetext(table, source=None, encoding=None, errors='strict', template=None,
prologue=None, epilogue=None):
"""
Return a table that writes rows to a text file as they are iterated over.
"""
assert template is not None, 'template is required'
return TeeTextView(table, source=source, e... | [
"def",
"teetext",
"(",
"table",
",",
"source",
"=",
"None",
",",
"encoding",
"=",
"None",
",",
"errors",
"=",
"'strict'",
",",
"template",
"=",
"None",
",",
"prologue",
"=",
"None",
",",
"epilogue",
"=",
"None",
")",
":",
"assert",
"template",
"is",
... | 42.3 | 24.9 |
def get_request(self, request):
"""Get a list of DownloadRequests for all data that are under the given field in the table of a Geopedia layer.
:return: list of items which have to be downloaded
:rtype: list(DownloadRequest)
"""
request.layer = self._parse_layer(request.layer, r... | [
"def",
"get_request",
"(",
"self",
",",
"request",
")",
":",
"request",
".",
"layer",
"=",
"self",
".",
"_parse_layer",
"(",
"request",
".",
"layer",
",",
"return_wms_name",
"=",
"True",
")",
"return",
"super",
"(",
")",
".",
"get_request",
"(",
"request... | 41.888889 | 16.777778 |
def match_lang(self, el, langs):
"""Match languages."""
match = False
has_ns = self.supports_namespaces()
root = self.root
has_html_namespace = self.has_html_namespace
# Walk parents looking for `lang` (HTML) or `xml:lang` XML property.
parent = el
found... | [
"def",
"match_lang",
"(",
"self",
",",
"el",
",",
"langs",
")",
":",
"match",
"=",
"False",
"has_ns",
"=",
"self",
".",
"supports_namespaces",
"(",
")",
"root",
"=",
"self",
".",
"root",
"has_html_namespace",
"=",
"self",
".",
"has_html_namespace",
"# Walk... | 39.694118 | 19.388235 |
def output_vm(gandi, vm, datacenters, output_keys, justify=10):
""" Helper to output a vm information."""
output_generic(gandi, vm, output_keys, justify)
if 'datacenter' in output_keys:
for dc in datacenters:
if dc['id'] == vm['datacenter_id']:
dc_name = dc.get('dc_code'... | [
"def",
"output_vm",
"(",
"gandi",
",",
"vm",
",",
"datacenters",
",",
"output_keys",
",",
"justify",
"=",
"10",
")",
":",
"output_generic",
"(",
"gandi",
",",
"vm",
",",
"output_keys",
",",
"justify",
")",
"if",
"'datacenter'",
"in",
"output_keys",
":",
... | 34.47619 | 19.952381 |
def delete_item_list(self, item_list_url):
""" Delete an Item List on the server
:type item_list_url: String or ItemList
:param item_list_url: the URL of the list to which to add the items,
or an ItemList object
:rtype: Boolean
:returns: True if the item list was de... | [
"def",
"delete_item_list",
"(",
"self",
",",
"item_list_url",
")",
":",
"try",
":",
"resp",
"=",
"self",
".",
"api_request",
"(",
"str",
"(",
"item_list_url",
")",
",",
"method",
"=",
"\"DELETE\"",
")",
"# all good if it says success",
"if",
"'success'",
"in",... | 31.153846 | 19.692308 |
def visit_NameConstant(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s name as string."""
return str(node.value) | [
"def",
"visit_NameConstant",
"(",
"self",
",",
"node",
":",
"AST",
",",
"dfltChaining",
":",
"bool",
"=",
"True",
")",
"->",
"str",
":",
"return",
"str",
"(",
"node",
".",
"value",
")"
] | 49.333333 | 14.666667 |
def replace_seqres(self, pdb, update_atoms = True):
"""Replace SEQRES lines with a new sequence, optionally removing
mutated sidechains"""
newpdb = PDB()
inserted_seqres = False
entries_before_seqres = set(["HEADER", "OBSLTE", "TITLE", "CAVEAT", "COMPND", "SOURCE",
... | [
"def",
"replace_seqres",
"(",
"self",
",",
"pdb",
",",
"update_atoms",
"=",
"True",
")",
":",
"newpdb",
"=",
"PDB",
"(",
")",
"inserted_seqres",
"=",
"False",
"entries_before_seqres",
"=",
"set",
"(",
"[",
"\"HEADER\"",
",",
"\"OBSLTE\"",
",",
"\"TITLE\"",
... | 33.391304 | 19.478261 |
def delete(self, template_name):
"""Delete a template"""
template = db.Template.find_one(template_name=template_name)
if not template:
return self.make_response('No such template found', HTTP.NOT_FOUND)
db.session.delete(template)
db.session.commit()
auditlog... | [
"def",
"delete",
"(",
"self",
",",
"template_name",
")",
":",
"template",
"=",
"db",
".",
"Template",
".",
"find_one",
"(",
"template_name",
"=",
"template_name",
")",
"if",
"not",
"template",
":",
"return",
"self",
".",
"make_response",
"(",
"'No such templ... | 38.928571 | 22 |
def send_invoice(self):
"""
Pay and send the customer's latest invoice.
:returns: True if an invoice was able to be created and paid, False otherwise
(typically if there was nothing to invoice).
"""
from .billing import Invoice
try:
invoice = Invoice._api_create(customer=self.id)
invoice.pay()
... | [
"def",
"send_invoice",
"(",
"self",
")",
":",
"from",
".",
"billing",
"import",
"Invoice",
"try",
":",
"invoice",
"=",
"Invoice",
".",
"_api_create",
"(",
"customer",
"=",
"self",
".",
"id",
")",
"invoice",
".",
"pay",
"(",
")",
"return",
"True",
"exce... | 27.933333 | 21.4 |
def htmlListToTR(l,trClass=None,tdClass=None,td1Class=None):
"""
turns a list into a <tr><td>something</td></tr>
call this when generating HTML tables dynamically.
"""
html="<tr>"
for item in l:
if 'array' in str(type(item)):
item=item[0] #TODO: why is this needed
htm... | [
"def",
"htmlListToTR",
"(",
"l",
",",
"trClass",
"=",
"None",
",",
"tdClass",
"=",
"None",
",",
"td1Class",
"=",
"None",
")",
":",
"html",
"=",
"\"<tr>\"",
"for",
"item",
"in",
"l",
":",
"if",
"'array'",
"in",
"str",
"(",
"type",
"(",
"item",
")",
... | 29.5 | 18.7 |
def parse_attr_signature(sig):
""" Parse an attribute signature """
match = ATTR_SIG_RE.match(sig.strip())
if not match:
raise RuntimeError('Attribute signature invalid, got ' + sig)
name, _, params = match.groups()
if params is not None and params.strip() != '':
params = split_sig(p... | [
"def",
"parse_attr_signature",
"(",
"sig",
")",
":",
"match",
"=",
"ATTR_SIG_RE",
".",
"match",
"(",
"sig",
".",
"strip",
"(",
")",
")",
"if",
"not",
"match",
":",
"raise",
"RuntimeError",
"(",
"'Attribute signature invalid, got '",
"+",
"sig",
")",
"name",
... | 35.916667 | 14.25 |
def get_current_thread_id(thread):
'''
Note: the difference from get_current_thread_id to get_thread_id is that
for the current thread we can get the thread id while the thread.ident
is still not set in the Thread instance.
'''
try:
# Fast path without getting lock.
tid = thread.... | [
"def",
"get_current_thread_id",
"(",
"thread",
")",
":",
"try",
":",
"# Fast path without getting lock.",
"tid",
"=",
"thread",
".",
"__pydevd_id__",
"if",
"tid",
"is",
"None",
":",
"# Fix for https://www.brainwy.com/tracker/PyDev/645",
"# if __pydevd_id__ is None, recalculat... | 41.277778 | 24.944444 |
def _execute_handler(self, p_command, p_todo_id=None, p_output=None):
"""
Executes a command, given as a string.
"""
p_output = p_output or self._output
self._console_visible = False
self._last_cmd = (p_command, p_output == self._output)
try:
p_comma... | [
"def",
"_execute_handler",
"(",
"self",
",",
"p_command",
",",
"p_todo_id",
"=",
"None",
",",
"p_output",
"=",
"None",
")",
":",
"p_output",
"=",
"p_output",
"or",
"self",
".",
"_output",
"self",
".",
"_console_visible",
"=",
"False",
"self",
".",
"_last_c... | 30.946429 | 19.303571 |
def mesh_to_BVH(mesh):
"""
Create a BVHModel object from a Trimesh object
Parameters
-----------
mesh : Trimesh
Input geometry
Returns
------------
bvh : fcl.BVHModel
BVH of input geometry
"""
bvh = fcl.BVHModel()
bvh.beginModel(num_tris_=len(mesh.faces),
... | [
"def",
"mesh_to_BVH",
"(",
"mesh",
")",
":",
"bvh",
"=",
"fcl",
".",
"BVHModel",
"(",
")",
"bvh",
".",
"beginModel",
"(",
"num_tris_",
"=",
"len",
"(",
"mesh",
".",
"faces",
")",
",",
"num_vertices_",
"=",
"len",
"(",
"mesh",
".",
"vertices",
")",
... | 22.047619 | 17.47619 |
def forward_filter(self, x, mask=None):
"""Run a Kalman filter over a provided sequence of outputs.
Note that the returned values `filtered_means`, `predicted_means`, and
`observation_means` depend on the observed time series `x`, while the
corresponding covariances are independent of the observed seri... | [
"def",
"forward_filter",
"(",
"self",
",",
"x",
",",
"mask",
"=",
"None",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"\"forward_filter\"",
")",
":",
"x",
"=",
"tf",
".",
"convert_to_tensor",
"(",
"value",
"=",
"x",
",",
"name",
"=",
"\"x\"",
")"... | 50.009217 | 20.562212 |
def should_stale_item_be_fetched_synchronously(self, delta, *args, **kwargs):
"""
Return whether to refresh an item synchronously when it is found in the
cache but stale
"""
if self.fetch_on_stale_threshold is None:
return False
return delta > (self.fetch_on_s... | [
"def",
"should_stale_item_be_fetched_synchronously",
"(",
"self",
",",
"delta",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"fetch_on_stale_threshold",
"is",
"None",
":",
"return",
"False",
"return",
"delta",
">",
"(",
"self",
"."... | 43 | 18.5 |
def flags(self, value):
"""
Setter for **self.__flags** attribute.
:param value: Attribute value.
:type value: int
"""
if value is not None:
assert type(value) is int, "'{0}' attribute: '{1}' type is not 'int'!".format("flags", value)
self.__flags = ... | [
"def",
"flags",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"assert",
"type",
"(",
"value",
")",
"is",
"int",
",",
"\"'{0}' attribute: '{1}' type is not 'int'!\"",
".",
"format",
"(",
"\"flags\"",
",",
"value",
")",
"self"... | 28.636364 | 19 |
def to_reminders(self, ical, label=None, priority=None, tags=None,
tail=None, sep=" ", postdate=None, posttime=None):
"""Return Remind commands for all events of a iCalendar"""
if not hasattr(ical, 'vevent_list'):
return ''
reminders = [self.to_remind(vevent, la... | [
"def",
"to_reminders",
"(",
"self",
",",
"ical",
",",
"label",
"=",
"None",
",",
"priority",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"tail",
"=",
"None",
",",
"sep",
"=",
"\" \"",
",",
"postdate",
"=",
"None",
",",
"posttime",
"=",
"None",
")",... | 48.5 | 19.1 |
def beep(self):
"""Make dimmer beep. Not all devices support this"""
self.logger.info("Dimmer %s beep", self.device_id)
self.hub.direct_command(self.device_id, '30', '00')
success = self.hub.check_success(self.device_id, '30', '00')
return success | [
"def",
"beep",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"\"Dimmer %s beep\"",
",",
"self",
".",
"device_id",
")",
"self",
".",
"hub",
".",
"direct_command",
"(",
"self",
".",
"device_id",
",",
"'30'",
",",
"'00'",
")",
"success",... | 31.333333 | 25.333333 |
def wrap_object(obj, decorator):
"""
Decorates the given object with the decorator function.
If obj is a method, the method is decorated with the decorator function
and returned. If obj is a class (i.e., a class based view), the methods
in the class corresponding to HTTP methods will be decorated a... | [
"def",
"wrap_object",
"(",
"obj",
",",
"decorator",
")",
":",
"actual_decorator",
"=",
"method_decorator",
"(",
"decorator",
")",
"if",
"inspect",
".",
"isfunction",
"(",
"obj",
")",
":",
"wrapped_obj",
"=",
"actual_decorator",
"(",
"obj",
")",
"update_wrapper... | 42.538462 | 21.307692 |
def fixpoint_runner(self):
"""Work list algorithm that runs the fixpoint algorithm."""
q = self.cfg.nodes
while q != []:
x_i = constraint_table[q[0]] # x_i = q[0].old_constraint
self.analysis.fixpointmethod(q[0]) # y = F_i(x_1, ..., x_n);
y = constraint_tab... | [
"def",
"fixpoint_runner",
"(",
"self",
")",
":",
"q",
"=",
"self",
".",
"cfg",
".",
"nodes",
"while",
"q",
"!=",
"[",
"]",
":",
"x_i",
"=",
"constraint_table",
"[",
"q",
"[",
"0",
"]",
"]",
"# x_i = q[0].old_constraint",
"self",
".",
"analysis",
".",
... | 43.928571 | 25 |
def add_tag(self, key, value=''):
"""
Add a tag to this object. Tag's are stored by AWS and can be used
to organize and filter resources. Adding a tag involves a round-trip
to the EC2 service.
:type key: str
:param key: The key or name of the tag being stored.
... | [
"def",
"add_tag",
"(",
"self",
",",
"key",
",",
"value",
"=",
"''",
")",
":",
"status",
"=",
"self",
".",
"connection",
".",
"create_tags",
"(",
"[",
"self",
".",
"id",
"]",
",",
"{",
"key",
":",
"value",
"}",
")",
"if",
"self",
".",
"tags",
"i... | 38.666667 | 20 |
def search_gallery(self, q):
"""Search the gallery with the given query string."""
url = self._base_url + "/3/gallery/search?q={0}".format(q)
resp = self._send_request(url)
return [_get_album_or_image(thing, self) for thing in resp] | [
"def",
"search_gallery",
"(",
"self",
",",
"q",
")",
":",
"url",
"=",
"self",
".",
"_base_url",
"+",
"\"/3/gallery/search?q={0}\"",
".",
"format",
"(",
"q",
")",
"resp",
"=",
"self",
".",
"_send_request",
"(",
"url",
")",
"return",
"[",
"_get_album_or_imag... | 52 | 13.4 |
def _set_tasks_state(self, value):
"""
Purpose: Set state of all tasks of the current stage.
:arguments: String
"""
if value not in states.state_numbers.keys():
raise ValueError(obj=self._uid,
attribute='set_tasks_state',
... | [
"def",
"_set_tasks_state",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"not",
"in",
"states",
".",
"state_numbers",
".",
"keys",
"(",
")",
":",
"raise",
"ValueError",
"(",
"obj",
"=",
"self",
".",
"_uid",
",",
"attribute",
"=",
"'set_tasks_state'... | 34.071429 | 15.071429 |
def _merge_relative_path(dst_path, rel_path):
"""Merge a relative tar file to a destination (which can be "gs://...")."""
# Convert rel_path to be relative and normalize it to remove ".", "..", "//",
# which are valid directories in fileystems like "gs://".
norm_rel_path = os.path.normpath(rel_path.lstrip("/"))... | [
"def",
"_merge_relative_path",
"(",
"dst_path",
",",
"rel_path",
")",
":",
"# Convert rel_path to be relative and normalize it to remove \".\", \"..\", \"//\",",
"# which are valid directories in fileystems like \"gs://\".",
"norm_rel_path",
"=",
"os",
".",
"path",
".",
"normpath",
... | 40.05 | 22.1 |
def length_from_nodelist(self, nodelist):
"""Returns the route length (cost) from the first to the last node in nodelist"""
cost = 0
for n1, n2 in zip(nodelist[0:len(nodelist) - 1], nodelist[1:len(nodelist)]):
cost += self._problem.distance(n1, n2)
return cost | [
"def",
"length_from_nodelist",
"(",
"self",
",",
"nodelist",
")",
":",
"cost",
"=",
"0",
"for",
"n1",
",",
"n2",
"in",
"zip",
"(",
"nodelist",
"[",
"0",
":",
"len",
"(",
"nodelist",
")",
"-",
"1",
"]",
",",
"nodelist",
"[",
"1",
":",
"len",
"(",
... | 37.375 | 22.5 |
def create(self, request, project):
"""
POST method implementation
"""
JobNote.objects.create(
job=Job.objects.get(repository__name=project,
id=int(request.data['job_id'])),
failure_classification_id=int(request.data['failure_classi... | [
"def",
"create",
"(",
"self",
",",
"request",
",",
"project",
")",
":",
"JobNote",
".",
"objects",
".",
"create",
"(",
"job",
"=",
"Job",
".",
"objects",
".",
"get",
"(",
"repository__name",
"=",
"project",
",",
"id",
"=",
"int",
"(",
"request",
".",... | 34.125 | 15.875 |
def instruction_ROL_memory(self, opcode, ea, m):
""" Rotate memory left """
r = self.ROL(m)
# log.debug("$%x ROL memory value $%x << 1 | Carry = $%x and write it to $%x \t| %s" % (
# self.program_counter,
# m, r, ea,
# self.cfg.mem_info.get_shortest(ea)
# )... | [
"def",
"instruction_ROL_memory",
"(",
"self",
",",
"opcode",
",",
"ea",
",",
"m",
")",
":",
"r",
"=",
"self",
".",
"ROL",
"(",
"m",
")",
"# log.debug(\"$%x ROL memory value $%x << 1 | Carry = $%x and write it to $%x \\t| %s\" % (",
"# self.program_counter,... | 37.888889 | 17 |
def get_protein_data(peptide, pdata, headerfields, accfield):
"""These fields are currently not pool dependent so headerfields
is ignored"""
report = get_proteins(peptide, pdata, headerfields)
return get_cov_descriptions(peptide, pdata, report) | [
"def",
"get_protein_data",
"(",
"peptide",
",",
"pdata",
",",
"headerfields",
",",
"accfield",
")",
":",
"report",
"=",
"get_proteins",
"(",
"peptide",
",",
"pdata",
",",
"headerfields",
")",
"return",
"get_cov_descriptions",
"(",
"peptide",
",",
"pdata",
",",... | 51.2 | 10.2 |
def comment_count(object):
"""
Usage:
{% comment_count obj %}
or
{% comment_count obj as var %}
"""
return Comment.objects.filter(
object_id=object.pk,
content_type=ContentType.objects.get_for_model(object)
).count() | [
"def",
"comment_count",
"(",
"object",
")",
":",
"return",
"Comment",
".",
"objects",
".",
"filter",
"(",
"object_id",
"=",
"object",
".",
"pk",
",",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"object",
")",
")",
".",
... | 23.818182 | 14.181818 |
def tagrefs(self):
"""Get the tags and reference numbers of all the vgroup
members.
Args::
no argument
Returns::
list of (tag,ref) tuples, one for each vgroup member
C library equivalent : Vgettagrefs
... | [
"def",
"tagrefs",
"(",
"self",
")",
":",
"n",
"=",
"self",
".",
"_nmembers",
"ret",
"=",
"[",
"]",
"if",
"n",
":",
"tags",
"=",
"_C",
".",
"array_int32",
"(",
"n",
")",
"refs",
"=",
"_C",
".",
"array_int32",
"(",
"n",
")",
"k",
"=",
"_C",
"."... | 26.12 | 21.16 |
def use_plenary_gradebook_view(self):
"""Pass through to provider GradeSystemGradebookSession.use_plenary_gradebook_view"""
self._gradebook_view = PLENARY
# self._get_provider_session('grade_system_gradebook_session') # To make sure the session is tracked
for session in self._get_provide... | [
"def",
"use_plenary_gradebook_view",
"(",
"self",
")",
":",
"self",
".",
"_gradebook_view",
"=",
"PLENARY",
"# self._get_provider_session('grade_system_gradebook_session') # To make sure the session is tracked",
"for",
"session",
"in",
"self",
".",
"_get_provider_sessions",
"(",
... | 50.111111 | 16.444444 |
def get_resource(self, device_id, resource_path):
"""Get a resource.
:param str device_id: ID of the device (Required)
:param str path: Path of the resource to get (Required)
:returns: Device resource
:rtype Resource
"""
resources = self.list_resources(device_id... | [
"def",
"get_resource",
"(",
"self",
",",
"device_id",
",",
"resource_path",
")",
":",
"resources",
"=",
"self",
".",
"list_resources",
"(",
"device_id",
")",
"for",
"r",
"in",
"resources",
":",
"if",
"r",
".",
"path",
"==",
"resource_path",
":",
"return",
... | 32.5 | 14.714286 |
def buckingham_potential(self, structure, val_dict=None):
"""
Generate species, buckingham, and spring options for an oxide structure
using the parameters in default libraries.
Ref:
1. G.V. Lewis and C.R.A. Catlow, J. Phys. C: Solid State Phys.,
18, 1149-1161 ... | [
"def",
"buckingham_potential",
"(",
"self",
",",
"structure",
",",
"val_dict",
"=",
"None",
")",
":",
"if",
"not",
"val_dict",
":",
"try",
":",
"#If structure is oxidation state decorated, use that first.",
"el",
"=",
"[",
"site",
".",
"specie",
".",
"symbol",
"... | 39.471429 | 14.442857 |
def process_superclass(self, entity: List[dict]) -> List[dict]:
""" Replaces ILX ID with superclass ID """
superclass = entity.pop('superclass')
label = entity['label']
if not superclass.get('ilx_id'):
raise self.SuperClassDoesNotExistError(
f'Superclass not g... | [
"def",
"process_superclass",
"(",
"self",
",",
"entity",
":",
"List",
"[",
"dict",
"]",
")",
"->",
"List",
"[",
"dict",
"]",
":",
"superclass",
"=",
"entity",
".",
"pop",
"(",
"'superclass'",
")",
"label",
"=",
"entity",
"[",
"'label'",
"]",
"if",
"n... | 52.714286 | 16.428571 |
def setRandomParams(self):
"""
set random hyperparameters
"""
params = sp.randn(self.getNumberParams())
self.setParams(params) | [
"def",
"setRandomParams",
"(",
"self",
")",
":",
"params",
"=",
"sp",
".",
"randn",
"(",
"self",
".",
"getNumberParams",
"(",
")",
")",
"self",
".",
"setParams",
"(",
"params",
")"
] | 26.833333 | 6.5 |
def list_from_metadata(cls, url, metadata):
'''return a list of DatalakeRecords for the url and metadata'''
key = cls._get_key(url)
metadata = Metadata(**metadata)
ct = cls._get_create_time(key)
time_buckets = cls.get_time_buckets_from_metadata(metadata)
return [cls(url, ... | [
"def",
"list_from_metadata",
"(",
"cls",
",",
"url",
",",
"metadata",
")",
":",
"key",
"=",
"cls",
".",
"_get_key",
"(",
"url",
")",
"metadata",
"=",
"Metadata",
"(",
"*",
"*",
"metadata",
")",
"ct",
"=",
"cls",
".",
"_get_create_time",
"(",
"key",
"... | 51.857143 | 15.285714 |
def _get_enum(self, source, bitarray):
''' Get enum value, based on the data in XML '''
raw_value = self._get_raw(source, bitarray)
# Find value description.
value_desc = source.find('item', {'value': str(raw_value)}) or self._get_rangeitem(source, raw_value)
return {
... | [
"def",
"_get_enum",
"(",
"self",
",",
"source",
",",
"bitarray",
")",
":",
"raw_value",
"=",
"self",
".",
"_get_raw",
"(",
"source",
",",
"bitarray",
")",
"# Find value description.",
"value_desc",
"=",
"source",
".",
"find",
"(",
"'item'",
",",
"{",
"'val... | 38.4 | 22.266667 |
def get_object(self, queryset=None):
"""
Implement cache on ``get_object`` method to
avoid repetitive calls, in POST.
"""
if self._cached_object is None:
self._cached_object = super(EntryCacheMixin, self).get_object(
queryset)
return self._cach... | [
"def",
"get_object",
"(",
"self",
",",
"queryset",
"=",
"None",
")",
":",
"if",
"self",
".",
"_cached_object",
"is",
"None",
":",
"self",
".",
"_cached_object",
"=",
"super",
"(",
"EntryCacheMixin",
",",
"self",
")",
".",
"get_object",
"(",
"queryset",
"... | 35.666667 | 7.888889 |
def proxy_schema(self):
"""
Get the Proxy-Schema option of a request.
:return: the Proxy-Schema values or None if not specified by the request
:rtype : String
"""
for option in self.options:
if option.number == defines.OptionRegistry.PROXY_SCHEME.number:
... | [
"def",
"proxy_schema",
"(",
"self",
")",
":",
"for",
"option",
"in",
"self",
".",
"options",
":",
"if",
"option",
".",
"number",
"==",
"defines",
".",
"OptionRegistry",
".",
"PROXY_SCHEME",
".",
"number",
":",
"return",
"option",
".",
"value",
"return",
... | 32.818182 | 17.181818 |
def is_string(val):
"""Determines whether the passed value is a string, safe for 2/3."""
try:
basestring
except NameError:
return isinstance(val, str)
return isinstance(val, basestring) | [
"def",
"is_string",
"(",
"val",
")",
":",
"try",
":",
"basestring",
"except",
"NameError",
":",
"return",
"isinstance",
"(",
"val",
",",
"str",
")",
"return",
"isinstance",
"(",
"val",
",",
"basestring",
")"
] | 30.142857 | 14.428571 |
def build_signature(self, user_api_key, user_secret, request):
"""Return the signature for the request."""
path = request.get_full_path()
sent_signature = request.META.get(
self.header_canonical('Authorization'))
signature_headers = self.get_headers_from_signature(sent_signat... | [
"def",
"build_signature",
"(",
"self",
",",
"user_api_key",
",",
"user_secret",
",",
"request",
")",
":",
"path",
"=",
"request",
".",
"get_full_path",
"(",
")",
"sent_signature",
"=",
"request",
".",
"META",
".",
"get",
"(",
"self",
".",
"header_canonical",... | 48.5 | 16.285714 |
def lookup_key(self):
"""Build a key from the "important" parts of a selector: elements,
classes, ids.
"""
parts = set()
for node in self.simple_selectors:
for token in node.tokens:
if token[0] not in ':[':
parts.add(token)
... | [
"def",
"lookup_key",
"(",
"self",
")",
":",
"parts",
"=",
"set",
"(",
")",
"for",
"node",
"in",
"self",
".",
"simple_selectors",
":",
"for",
"token",
"in",
"node",
".",
"tokens",
":",
"if",
"token",
"[",
"0",
"]",
"not",
"in",
"':['",
":",
"parts",... | 34.647059 | 16.117647 |
def head_account(self, headers=None, query=None, cdn=False):
"""
HEADs the account and returns the results. Useful headers
returned are:
=========================== =================================
x-account-bytes-used Object storage used for the
... | [
"def",
"head_account",
"(",
"self",
",",
"headers",
"=",
"None",
",",
"query",
"=",
"None",
",",
"cdn",
"=",
"False",
")",
":",
"return",
"self",
".",
"request",
"(",
"'HEAD'",
",",
"''",
",",
"''",
",",
"headers",
",",
"query",
"=",
"query",
",",
... | 43.657143 | 22.228571 |
def multiloss(losses, logging_namespace="multiloss", exclude_from_weighting=[]):
"""
Create a loss from multiple losses my mixing them.
This multi-loss implementation is inspired by the Paper "Multi-Task Learning Using Uncertainty to Weight Losses
for Scene Geometry and Semantics" by Kendall, Gal and Ci... | [
"def",
"multiloss",
"(",
"losses",
",",
"logging_namespace",
"=",
"\"multiloss\"",
",",
"exclude_from_weighting",
"=",
"[",
"]",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"logging_namespace",
")",
":",
"sum_loss",
"=",
"0",
"for",
"loss_name",
",",
... | 50.842105 | 22.842105 |
def list_users(self, instance, limit=None, marker=None):
"""Returns all users for the specified instance."""
return instance.list_users(limit=limit, marker=marker) | [
"def",
"list_users",
"(",
"self",
",",
"instance",
",",
"limit",
"=",
"None",
",",
"marker",
"=",
"None",
")",
":",
"return",
"instance",
".",
"list_users",
"(",
"limit",
"=",
"limit",
",",
"marker",
"=",
"marker",
")"
] | 59 | 12.666667 |
def infix(*kinds):
"""Decorate a method as handling infix tokens of the given kinds"""
def wrap(fn):
try:
fn.infix_kinds.extend(kinds)
except AttributeError:
fn.infix_kinds = list(kinds)
return fn
return wrap | [
"def",
"infix",
"(",
"*",
"kinds",
")",
":",
"def",
"wrap",
"(",
"fn",
")",
":",
"try",
":",
"fn",
".",
"infix_kinds",
".",
"extend",
"(",
"kinds",
")",
"except",
"AttributeError",
":",
"fn",
".",
"infix_kinds",
"=",
"list",
"(",
"kinds",
")",
"ret... | 28.888889 | 14.555556 |
def wif(self, is_compressed=None):
"""
Return the WIF representation of this key, if available.
"""
secret_exponent = self.secret_exponent()
if secret_exponent is None:
return None
if is_compressed is None:
is_compressed = self.is_compressed()
... | [
"def",
"wif",
"(",
"self",
",",
"is_compressed",
"=",
"None",
")",
":",
"secret_exponent",
"=",
"self",
".",
"secret_exponent",
"(",
")",
"if",
"secret_exponent",
"is",
"None",
":",
"return",
"None",
"if",
"is_compressed",
"is",
"None",
":",
"is_compressed",... | 34.461538 | 8.769231 |
def stop(self, timeout = 10.0):
"""
Send all pending messages, close connection.
Returns True if no message left to sent. False if dirty.
- timeout: seconds to wait for sending remaining messages. disconnect
immedately if None.
"""
if (self._send_greenlet is not None) and \
(self._send_queue.qsiz... | [
"def",
"stop",
"(",
"self",
",",
"timeout",
"=",
"10.0",
")",
":",
"if",
"(",
"self",
".",
"_send_greenlet",
"is",
"not",
"None",
")",
"and",
"(",
"self",
".",
"_send_queue",
".",
"qsize",
"(",
")",
">",
"0",
")",
":",
"self",
".",
"wait_send",
"... | 30.913043 | 11.26087 |
def get_data_view_service_status(self, data_view_id):
"""
Retrieves the status for all of the services associated with a data view:
- predict
- experimental_design
- data_reports
- model_reports
:param data_view_id: The ID number of the data view ... | [
"def",
"get_data_view_service_status",
"(",
"self",
",",
"data_view_id",
")",
":",
"url",
"=",
"\"data_views/{}/status\"",
".",
"format",
"(",
"data_view_id",
")",
"response",
"=",
"self",
".",
"_get",
"(",
"url",
")",
".",
"json",
"(",
")",
"result",
"=",
... | 37.923077 | 21.461538 |
def matrix_directed_unweighted(user):
"""
Returns a directed, unweighted matrix where an edge exists if there is at
least one call or text.
"""
matrix = _interaction_matrix(user, interaction=None)
for a in range(len(matrix)):
for b in range(len(matrix)):
if matrix[a][b] is no... | [
"def",
"matrix_directed_unweighted",
"(",
"user",
")",
":",
"matrix",
"=",
"_interaction_matrix",
"(",
"user",
",",
"interaction",
"=",
"None",
")",
"for",
"a",
"in",
"range",
"(",
"len",
"(",
"matrix",
")",
")",
":",
"for",
"b",
"in",
"range",
"(",
"l... | 32.416667 | 14.416667 |
def check_if_branch_exist(db, root_hash, key_prefix):
"""
Given a key prefix, return whether this prefix is
the prefix of an existing key in the trie.
"""
validate_is_bytes(key_prefix)
return _check_if_branch_exist(db, root_hash, encode_to_bin(key_prefix)) | [
"def",
"check_if_branch_exist",
"(",
"db",
",",
"root_hash",
",",
"key_prefix",
")",
":",
"validate_is_bytes",
"(",
"key_prefix",
")",
"return",
"_check_if_branch_exist",
"(",
"db",
",",
"root_hash",
",",
"encode_to_bin",
"(",
"key_prefix",
")",
")"
] | 34.25 | 14.25 |
def _on_changed(self):
"""
Update the tree items
"""
self._updating = True
to_collapse = []
self.clear()
if self._editor and self._outline_mode and self._folding_panel:
items, to_collapse = self.to_tree_widget_items(
self._outline_mode.... | [
"def",
"_on_changed",
"(",
"self",
")",
":",
"self",
".",
"_updating",
"=",
"True",
"to_collapse",
"=",
"[",
"]",
"self",
".",
"clear",
"(",
")",
"if",
"self",
".",
"_editor",
"and",
"self",
".",
"_outline_mode",
"and",
"self",
".",
"_folding_panel",
"... | 33.962963 | 13.592593 |
async def request(self, method, url, query_params=None, headers=None,
body=None, post_params=None, _preload_content=True,
_request_timeout=None):
"""Execute request
:param method: http request method
:param url: http request url
:param query_p... | [
"async",
"def",
"request",
"(",
"self",
",",
"method",
",",
"url",
",",
"query_params",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"body",
"=",
"None",
",",
"post_params",
"=",
"None",
",",
"_preload_content",
"=",
"True",
",",
"_request_timeout",
"=... | 41.520408 | 18.591837 |
def to_text(self, tree, force_root=False):
"""
Extract text from tags.
Skip any selectors specified and include attributes if specified.
Ignored tags will not have their attributes scanned either.
"""
self.extract_tag_metadata(tree)
text = []
attributes... | [
"def",
"to_text",
"(",
"self",
",",
"tree",
",",
"force_root",
"=",
"False",
")",
":",
"self",
".",
"extract_tag_metadata",
"(",
"tree",
")",
"text",
"=",
"[",
"]",
"attributes",
"=",
"[",
"]",
"comments",
"=",
"[",
"]",
"blocks",
"=",
"[",
"]",
"i... | 40.666667 | 17.933333 |
def is_installable_file(path):
# type: (PipfileType) -> bool
"""Determine if a path can potentially be installed"""
from packaging import specifiers
if isinstance(path, Mapping):
path = convert_entry_to_path(path)
# If the string starts with a valid specifier operator, test if it is a vali... | [
"def",
"is_installable_file",
"(",
"path",
")",
":",
"# type: (PipfileType) -> bool",
"from",
"packaging",
"import",
"specifiers",
"if",
"isinstance",
"(",
"path",
",",
"Mapping",
")",
":",
"path",
"=",
"convert_entry_to_path",
"(",
"path",
")",
"# If the string sta... | 33.880952 | 21.738095 |
def simple_write(self, s, frame, node=None):
"""Simple shortcut for start_write + write + end_write."""
self.start_write(frame, node)
self.write(s)
self.end_write(frame) | [
"def",
"simple_write",
"(",
"self",
",",
"s",
",",
"frame",
",",
"node",
"=",
"None",
")",
":",
"self",
".",
"start_write",
"(",
"frame",
",",
"node",
")",
"self",
".",
"write",
"(",
"s",
")",
"self",
".",
"end_write",
"(",
"frame",
")"
] | 39.4 | 7.4 |
def get_resource(self):
"""Return the associated resource."""
references = {"resource_id": None, "parent_id": None,
"grandparent_id": None}
for model_cls, regexp in self._regexp.iteritems():
match = regexp.search(self.resource_ref)
if match is not No... | [
"def",
"get_resource",
"(",
"self",
")",
":",
"references",
"=",
"{",
"\"resource_id\"",
":",
"None",
",",
"\"parent_id\"",
":",
"None",
",",
"\"grandparent_id\"",
":",
"None",
"}",
"for",
"model_cls",
",",
"regexp",
"in",
"self",
".",
"_regexp",
".",
"ite... | 46.5 | 16.75 |
def _fix_channels(self, op, attrs, inputs):
"""A workaround for getting 'channels' or 'units' since onnx don't provide
these attributes. We check the shape of weights provided to get the number.
"""
if op not in [mx.sym.Convolution, mx.sym.Deconvolution, mx.sym.FullyConnected]:
... | [
"def",
"_fix_channels",
"(",
"self",
",",
"op",
",",
"attrs",
",",
"inputs",
")",
":",
"if",
"op",
"not",
"in",
"[",
"mx",
".",
"sym",
".",
"Convolution",
",",
"mx",
".",
"sym",
".",
"Deconvolution",
",",
"mx",
".",
"sym",
".",
"FullyConnected",
"]... | 51.16 | 20.72 |
def __validation_property_range(self, p):
"""
if p.sub_property_of(q) then
for every y in included_ranges(p) we have y is subclass of some r in
included_ranges(q) -- for object properties
"""
for y in p.included_ranges():
superclasses = y.super_classes_closure... | [
"def",
"__validation_property_range",
"(",
"self",
",",
"p",
")",
":",
"for",
"y",
"in",
"p",
".",
"included_ranges",
"(",
")",
":",
"superclasses",
"=",
"y",
".",
"super_classes_closure",
"(",
")",
"for",
"q",
"in",
"p",
".",
"super_properties",
"(",
")... | 56.857143 | 22 |
def save(self, **kwargs):
"""Overrides models.Model.save.
- Generates slug.
- Saves image file.
"""
if not self.width or not self.height:
self.width, self.height = self.image.width, self.image.height
# prefill the slug with the ID, it requires double save
... | [
"def",
"save",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"width",
"or",
"not",
"self",
".",
"height",
":",
"self",
".",
"width",
",",
"self",
".",
"height",
"=",
"self",
".",
"image",
".",
"width",
",",
"self",
"... | 36.418605 | 18.27907 |
def _link_to_img(self):
"""
Generates a link to the user's Gravatar.
>>> Gravatar('gridaphobe@gmail.com')._link_to_img()
'http://www.gravatar.com/avatar/16b87da510d278999c892cdbdd55c1b6?s=80&r=g'
"""
# make sure options are valid
if self.rating.lower() no... | [
"def",
"_link_to_img",
"(",
"self",
")",
":",
"# make sure options are valid",
"if",
"self",
".",
"rating",
".",
"lower",
"(",
")",
"not",
"in",
"RATINGS",
":",
"raise",
"InvalidRatingError",
"(",
"self",
".",
"rating",
")",
"if",
"not",
"(",
"MIN_SIZE",
"... | 32.791667 | 15.208333 |
def to_json(self):
''' Returns the JSON representation of this graph. '''
roots = []
for r in self.roots:
roots.append(r.to_json())
return {'roots': roots} | [
"def",
"to_json",
"(",
"self",
")",
":",
"roots",
"=",
"[",
"]",
"for",
"r",
"in",
"self",
".",
"roots",
":",
"roots",
".",
"append",
"(",
"r",
".",
"to_json",
"(",
")",
")",
"return",
"{",
"'roots'",
":",
"roots",
"}"
] | 32.333333 | 15 |
def block_resource_fitnesses(self, block: block.Block):
"""Returns a map of nodename to average fitness value for this block.
Assumes that required resources have been checked on all nodes."""
# Short-circuit! My algorithm is terrible, so it doesn't work well for the edge case where
# t... | [
"def",
"block_resource_fitnesses",
"(",
"self",
",",
"block",
":",
"block",
".",
"Block",
")",
":",
"# Short-circuit! My algorithm is terrible, so it doesn't work well for the edge case where",
"# the block has no requirements",
"if",
"not",
"block",
".",
"resources",
":",
"r... | 35.555556 | 21.240741 |
def get_groupnames(self, sgs):
"""Get servicegroups list
:return: comma separated list of servicegroups
:rtype: str
"""
return ','.join([sgs[sg].get_name() for sg in self.servicegroups]) | [
"def",
"get_groupnames",
"(",
"self",
",",
"sgs",
")",
":",
"return",
"','",
".",
"join",
"(",
"[",
"sgs",
"[",
"sg",
"]",
".",
"get_name",
"(",
")",
"for",
"sg",
"in",
"self",
".",
"servicegroups",
"]",
")"
] | 31.571429 | 17 |
def _check_and_change_state_before_execution(
self,
verbose=True,
ignore_all_deps=False,
ignore_depends_on_past=False,
ignore_task_deps=False,
ignore_ti_state=False,
mark_success=False,
test_mode=False,
job_id=No... | [
"def",
"_check_and_change_state_before_execution",
"(",
"self",
",",
"verbose",
"=",
"True",
",",
"ignore_all_deps",
"=",
"False",
",",
"ignore_depends_on_past",
"=",
"False",
",",
"ignore_task_deps",
"=",
"False",
",",
"ignore_ti_state",
"=",
"False",
",",
"mark_su... | 39.954887 | 18.195489 |
def dumpu(self, data, url, **kwargs):
"""
opens url and passes to load()
kwargs are passed to both open and dump
"""
return self.dump(data, self.open(url, 'w', **kwargs), **kwargs) | [
"def",
"dumpu",
"(",
"self",
",",
"data",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"dump",
"(",
"data",
",",
"self",
".",
"open",
"(",
"url",
",",
"'w'",
",",
"*",
"*",
"kwargs",
")",
",",
"*",
"*",
"kwargs",
")"
... | 35.833333 | 7.166667 |
def child_done(self, task, result, count):
"""Acquire the condition variable for the compound task object.
Decrement the thread count. If we are the last thread to
finish, release compound task thread, which is blocked in execute().
"""
with self.regcond:
self.logger... | [
"def",
"child_done",
"(",
"self",
",",
"task",
",",
"result",
",",
"count",
")",
":",
"with",
"self",
".",
"regcond",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'Concurrent task %d/%d has completed'",
"%",
"(",
"self",
".",
"count",
",",
"self",
"."... | 45.785714 | 11.214286 |
def fit_results_to_dict(fit_results, min_bound=None, max_bound=None):
'''Create a JSON-comparable dict from a FitResults object
Parameters:
fit_results (FitResults): object containing fit parameters,\
errors and type
min_bound: optional min value to add to dictionary if min isn't\
... | [
"def",
"fit_results_to_dict",
"(",
"fit_results",
",",
"min_bound",
"=",
"None",
",",
"max_bound",
"=",
"None",
")",
":",
"type_map",
"=",
"{",
"'norm'",
":",
"'normal'",
",",
"'expon'",
":",
"'exponential'",
",",
"'uniform'",
":",
"'uniform'",
"}",
"param_m... | 35.59375 | 25.96875 |
def _itraj(self, value):
"""
Reader-internal property that tracks the upcoming trajectory index. Should not be used within iterator loop.
Parameters
----------
value : int
The upcoming trajectory index.
"""
if value != self._selected_itraj:
... | [
"def",
"_itraj",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"!=",
"self",
".",
"_selected_itraj",
":",
"self",
".",
"state",
".",
"itraj",
"=",
"value",
"# TODO: this side effect is unexpected.",
"self",
".",
"state",
".",
"t",
"=",
"0"
] | 34.583333 | 15.583333 |
def add_to_group(self, group, user):
"""
Add a user to a group
:type user: str
:param user: User's email
:type group: str
:param group: Group name
:rtype: dict
:return: an empty dictionary
"""
data = {'group': group, 'user': user}
... | [
"def",
"add_to_group",
"(",
"self",
",",
"group",
",",
"user",
")",
":",
"data",
"=",
"{",
"'group'",
":",
"group",
",",
"'user'",
":",
"user",
"}",
"return",
"self",
".",
"post",
"(",
"'addUserToGroup'",
",",
"data",
")"
] | 23.2 | 14.666667 |
def pickle_matpower_cases(case_paths, case_format=2):
""" Parses the MATPOWER case files at the given paths and pickles the
resulting Case objects to the same directory.
"""
import pylon.io
if isinstance(case_paths, basestring):
case_paths = [case_paths]
for case_path in case_paths... | [
"def",
"pickle_matpower_cases",
"(",
"case_paths",
",",
"case_format",
"=",
"2",
")",
":",
"import",
"pylon",
".",
"io",
"if",
"isinstance",
"(",
"case_paths",
",",
"basestring",
")",
":",
"case_paths",
"=",
"[",
"case_paths",
"]",
"for",
"case_path",
"in",
... | 38.571429 | 17.428571 |
def delete_item(self, item):
"""Delete an object in DynamoDB.
:param item: Unpacked into kwargs for :func:`boto3.DynamoDB.Client.delete_item`.
:raises bloop.exceptions.ConstraintViolation: if the condition (or atomic) is not met.
"""
try:
self.dynamodb_client.delete_... | [
"def",
"delete_item",
"(",
"self",
",",
"item",
")",
":",
"try",
":",
"self",
".",
"dynamodb_client",
".",
"delete_item",
"(",
"*",
"*",
"item",
")",
"except",
"botocore",
".",
"exceptions",
".",
"ClientError",
"as",
"error",
":",
"handle_constraint_violatio... | 42.7 | 21.6 |
def aggregation_result_extractor(impact_report, component_metadata):
"""Extracting aggregation result of breakdown from the impact layer.
:param impact_report: the impact report that acts as a proxy to fetch
all the data that extractor needed
:type impact_report: safe.report.impact_report.ImpactRep... | [
"def",
"aggregation_result_extractor",
"(",
"impact_report",
",",
"component_metadata",
")",
":",
"context",
"=",
"{",
"}",
"\"\"\"Initializations.\"\"\"",
"extra_args",
"=",
"component_metadata",
".",
"extra_args",
"# Find out aggregation report type",
"analysis_layer",
"=",... | 36.586777 | 17.520661 |
def residue_network():
"""The network for the residue example.
Current and previous state are all nodes OFF.
Diagram::
+~~~~~~~+ +~~~~~~~+
| A | | B |
+~~>| (AND) | | (AND) |<~~+
| +~~~~~~~+ +~~~~~~~+ |
... | [
"def",
"residue_network",
"(",
")",
":",
"tpm",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"int",
"(",
"s",
")",
"for",
"s",
"in",
"bin",
"(",
"x",
")",
"[",
"2",
":",
"]",
".",
"zfill",
"(",
"5",
")",
"[",
":",
":",
"-",
"1",
"]",
"]",
"f... | 31.469388 | 16.489796 |
def grab_idx(x,i,batch_first:bool=True):
"Grab the `i`-th batch in `x`, `batch_first` stating the batch dimension."
if batch_first: return ([o[i].cpu() for o in x] if is_listy(x) else x[i].cpu())
else: return ([o[:,i].cpu() for o in x] if is_listy(x) else x[:,i].cpu()) | [
"def",
"grab_idx",
"(",
"x",
",",
"i",
",",
"batch_first",
":",
"bool",
"=",
"True",
")",
":",
"if",
"batch_first",
":",
"return",
"(",
"[",
"o",
"[",
"i",
"]",
".",
"cpu",
"(",
")",
"for",
"o",
"in",
"x",
"]",
"if",
"is_listy",
"(",
"x",
")"... | 72.5 | 32.5 |
def getConParams(virtualhost):
"""
Connection object builder.
Args:
virtualhost (str): selected virtualhost in rabbitmq
Returns:
pika.ConnectionParameters: object filled by `constants` from
:class:`edeposit.amqp.settings`.
"""
return pika.ConnectionParameters(
h... | [
"def",
"getConParams",
"(",
"virtualhost",
")",
":",
"return",
"pika",
".",
"ConnectionParameters",
"(",
"host",
"=",
"settings",
".",
"RABBITMQ_HOST",
",",
"port",
"=",
"int",
"(",
"settings",
".",
"RABBITMQ_PORT",
")",
",",
"virtual_host",
"=",
"virtualhost"... | 27.4 | 14.6 |
def initialize_library(self, library, lib_type=VERSION_STORE, **kwargs):
"""
Create an Arctic Library or a particular type.
Parameters
----------
library : `str`
The name of the library. e.g. 'library' or 'user.library'
lib_type : `str`
The type ... | [
"def",
"initialize_library",
"(",
"self",
",",
"library",
",",
"lib_type",
"=",
"VERSION_STORE",
",",
"*",
"*",
"kwargs",
")",
":",
"lib",
"=",
"ArcticLibraryBinding",
"(",
"self",
",",
"library",
")",
"# check that we don't create too many namespaces",
"# can be di... | 45.580645 | 25 |
def execute(self, command, *args, **kw):
"""Executes redis command in a free connection and returns
future waiting for result.
Picks connection from free pool and send command through
that connection.
If no connection is found, returns coroutine waiting for
free connecti... | [
"def",
"execute",
"(",
"self",
",",
"command",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"conn",
",",
"address",
"=",
"self",
".",
"get_connection",
"(",
"command",
",",
"args",
")",
"if",
"conn",
"is",
"not",
"None",
":",
"fut",
"=",
"con... | 42.8125 | 15.625 |
def unregisterMachine(self, machineName):
"""
This operation unregisters a portal machine from a portal site. The
operation can only performed when there are two machines
participating in a portal site.
"""
url = self._url + "/machines/unregister"
params = {
... | [
"def",
"unregisterMachine",
"(",
"self",
",",
"machineName",
")",
":",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/machines/unregister\"",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
",",
"\"machineName\"",
":",
"machineName",
"}",
"return",
"self",
".",
"_p... | 37.6 | 11.6 |
def create(cls, collection):
"""
Creates document object without really creating it in the collection.
:param collection Collection instance
:returns Document
"""
api = Client.instance().api
doc = Document(
id='',
key='',
... | [
"def",
"create",
"(",
"cls",
",",
"collection",
")",
":",
"api",
"=",
"Client",
".",
"instance",
"(",
")",
".",
"api",
"doc",
"=",
"Document",
"(",
"id",
"=",
"''",
",",
"key",
"=",
"''",
",",
"collection",
"=",
"collection",
".",
"name",
",",
"a... | 20.526316 | 21.684211 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.