text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def _min(self):
"""Getter for the minimum series value"""
return (
self.range[0] if (self.range and self.range[0] is not None) else
(min(self.yvals) if self.yvals else None)
) | [
"def",
"_min",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"range",
"[",
"0",
"]",
"if",
"(",
"self",
".",
"range",
"and",
"self",
".",
"range",
"[",
"0",
"]",
"is",
"not",
"None",
")",
"else",
"(",
"min",
"(",
"self",
".",
"yvals",
")... | 36.333333 | 21.5 |
def multiplot(self, f, lfilter=None, plot_xy=False, **kargs):
"""Uses a function that returns a label and a value for this label, then
plots all the values label by label.
A list of matplotlib.lines.Line2D is returned.
"""
# Python 2 backward compatibility
f = lambda_tu... | [
"def",
"multiplot",
"(",
"self",
",",
"f",
",",
"lfilter",
"=",
"None",
",",
"plot_xy",
"=",
"False",
",",
"*",
"*",
"kargs",
")",
":",
"# Python 2 backward compatibility",
"f",
"=",
"lambda_tuple_converter",
"(",
"f",
")",
"lfilter",
"=",
"lambda_tuple_conv... | 32 | 18.282051 |
def create_gtk_grid(self, row_spacing=6, col_spacing=6, row_homogenous=False, col_homogenous=True):
"""
Function creates a Gtk Grid with spacing
and homogeous tags
"""
grid_lang = Gtk.Grid()
grid_lang.set_column_spacing(row_spacing)
grid_lang.set_row_spacing(col_s... | [
"def",
"create_gtk_grid",
"(",
"self",
",",
"row_spacing",
"=",
"6",
",",
"col_spacing",
"=",
"6",
",",
"row_homogenous",
"=",
"False",
",",
"col_homogenous",
"=",
"True",
")",
":",
"grid_lang",
"=",
"Gtk",
".",
"Grid",
"(",
")",
"grid_lang",
".",
"set_c... | 40.916667 | 12.75 |
def _patch_tcpserver():
"""
Patch shutdown_request to open blocking interaction after the end of the
request
"""
shutdown_request = TCPServer.shutdown_request
def shutdown_request_patched(*args, **kwargs):
thread = current_thread()
shutdown_request(*args, **kwargs)
if th... | [
"def",
"_patch_tcpserver",
"(",
")",
":",
"shutdown_request",
"=",
"TCPServer",
".",
"shutdown_request",
"def",
"shutdown_request_patched",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"thread",
"=",
"current_thread",
"(",
")",
"shutdown_request",
"(",
... | 31.857143 | 16.714286 |
def evaluation(evaluation_id):
"""Show or delete an ACMG evaluation."""
evaluation_obj = store.get_evaluation(evaluation_id)
controllers.evaluation(store, evaluation_obj)
if request.method == 'POST':
link = url_for('.variant', institute_id=evaluation_obj['institute']['_id'],
... | [
"def",
"evaluation",
"(",
"evaluation_id",
")",
":",
"evaluation_obj",
"=",
"store",
".",
"get_evaluation",
"(",
"evaluation_id",
")",
"controllers",
".",
"evaluation",
"(",
"store",
",",
"evaluation_obj",
")",
"if",
"request",
".",
"method",
"==",
"'POST'",
"... | 54.615385 | 18.923077 |
def _check_and_update_params(self, required, params):
"""
Ensure all required parameters were passed to the API call and format
them correctly.
"""
for r in required:
if r not in params:
raise PayPalError("Missing required param: %s" % r)
# Up... | [
"def",
"_check_and_update_params",
"(",
"self",
",",
"required",
",",
"params",
")",
":",
"for",
"r",
"in",
"required",
":",
"if",
"r",
"not",
"in",
"params",
":",
"raise",
"PayPalError",
"(",
"\"Missing required param: %s\"",
"%",
"r",
")",
"# Upper case all ... | 37.636364 | 17.454545 |
def get_route(self, route_id):
"""
Gets specified route.
Will be detail-level if owned by authenticated user; otherwise summary-level.
https://strava.github.io/api/v3/routes/#retreive
:param route_id: The ID of route to fetch.
:type route_id: int
:rtype: :clas... | [
"def",
"get_route",
"(",
"self",
",",
"route_id",
")",
":",
"raw",
"=",
"self",
".",
"protocol",
".",
"get",
"(",
"'/routes/{id}'",
",",
"id",
"=",
"route_id",
")",
"return",
"model",
".",
"Route",
".",
"deserialize",
"(",
"raw",
",",
"bind_client",
"=... | 31.066667 | 20.8 |
def Drop(self: Iterable, n):
"""
[
{
'self': [1, 2, 3, 4, 5],
'n': 3,
'assert': lambda ret: list(ret) == [1, 2]
}
]
"""
con = tuple(self)
n = len(con) - n
if n <= 0:
yield from con
else:
for i, e in enumerate(con):
... | [
"def",
"Drop",
"(",
"self",
":",
"Iterable",
",",
"n",
")",
":",
"con",
"=",
"tuple",
"(",
"self",
")",
"n",
"=",
"len",
"(",
"con",
")",
"-",
"n",
"if",
"n",
"<=",
"0",
":",
"yield",
"from",
"con",
"else",
":",
"for",
"i",
",",
"e",
"in",
... | 19.052632 | 18.842105 |
def is_businessdate(in_date):
"""
checks whether the provided date is a date
:param BusinessDate, int or float in_date:
:return bool:
"""
# Note: if the data range has been created from pace_xl, then all the dates are bank dates
# and here it remains to check the ... | [
"def",
"is_businessdate",
"(",
"in_date",
")",
":",
"# Note: if the data range has been created from pace_xl, then all the dates are bank dates",
"# and here it remains to check the validity.",
"# !!! However, if the data has been read from json string via json.load() function",
"# it does not rec... | 48.65 | 20.05 |
def empty_like(self, shape):
"""
Make an empty LabelArray with the same categories as ``self``, filled
with ``self.missing_value``.
"""
return type(self).from_codes_and_metadata(
codes=np.full(
shape,
self.reverse_categories[self.missin... | [
"def",
"empty_like",
"(",
"self",
",",
"shape",
")",
":",
"return",
"type",
"(",
"self",
")",
".",
"from_codes_and_metadata",
"(",
"codes",
"=",
"np",
".",
"full",
"(",
"shape",
",",
"self",
".",
"reverse_categories",
"[",
"self",
".",
"missing_value",
"... | 37.2 | 15.2 |
def search(self, q, labels, state='open,closed', **kwargs):
"""Search for issues in Github.
:param q: query string to search
:param state: state of the issue
:returns: list of issue objects
:rtype: list
"""
search_result = self.github_request.search(q=q, state=s... | [
"def",
"search",
"(",
"self",
",",
"q",
",",
"labels",
",",
"state",
"=",
"'open,closed'",
",",
"*",
"*",
"kwargs",
")",
":",
"search_result",
"=",
"self",
".",
"github_request",
".",
"search",
"(",
"q",
"=",
"q",
",",
"state",
"=",
"state",
",",
"... | 35.6875 | 15.5625 |
def body(self):
"""Yields the encoded body."""
for chunk in self.gen_chunks(self.envelope.file_open(self.name)):
yield chunk
for chunk in self.gen_chunks(self.data):
yield chunk
for chunk in self.gen_chunks(self.envelope.file_close()):
yield chunk
... | [
"def",
"body",
"(",
"self",
")",
":",
"for",
"chunk",
"in",
"self",
".",
"gen_chunks",
"(",
"self",
".",
"envelope",
".",
"file_open",
"(",
"self",
".",
"name",
")",
")",
":",
"yield",
"chunk",
"for",
"chunk",
"in",
"self",
".",
"gen_chunks",
"(",
... | 36.5 | 16.5 |
def getusers(self, context, request):
"""/@@API/getusers: Return users belonging to specified roles
Required parameters:
- roles: The role of which users to return
{
runtime: Function running time.
error: true or string(message) if error. false if no error.... | [
"def",
"getusers",
"(",
"self",
",",
"context",
",",
"request",
")",
":",
"roles",
"=",
"request",
".",
"get",
"(",
"'roles'",
",",
"''",
")",
"if",
"len",
"(",
"roles",
")",
"==",
"0",
":",
"raise",
"BadRequest",
"(",
"\"No roles specified\"",
")",
... | 35.372549 | 20.941176 |
def join_content_version(self, to_cache):
"""
Add the version(s) to the content to cache : internal version at first
and then the template version if versioning is activated.
Each version, and the content, are separated with `VERSION_SEPARATOR`.
This method is called after the en... | [
"def",
"join_content_version",
"(",
"self",
",",
"to_cache",
")",
":",
"parts",
"=",
"[",
"self",
".",
"INTERNAL_VERSION",
"]",
"if",
"self",
".",
"options",
".",
"versioning",
":",
"parts",
".",
"append",
"(",
"force_bytes",
"(",
"self",
".",
"version",
... | 43.428571 | 14.142857 |
def _cursor(self):
"""Asserts that the connection is open and returns a cursor"""
if self._conn is None:
self._conn = sqlite3.connect(self.filename,
check_same_thread=False)
return self._conn.cursor() | [
"def",
"_cursor",
"(",
"self",
")",
":",
"if",
"self",
".",
"_conn",
"is",
"None",
":",
"self",
".",
"_conn",
"=",
"sqlite3",
".",
"connect",
"(",
"self",
".",
"filename",
",",
"check_same_thread",
"=",
"False",
")",
"return",
"self",
".",
"_conn",
"... | 45.333333 | 13 |
def extend(self, step):
"""
Adds the data from another STObject to this object.
Args:
step: another STObject being added after the current one in time.
"""
self.timesteps.extend(step.timesteps)
self.masks.extend(step.masks)
self.x.extend(step.... | [
"def",
"extend",
"(",
"self",
",",
"step",
")",
":",
"self",
".",
"timesteps",
".",
"extend",
"(",
"step",
".",
"timesteps",
")",
"self",
".",
"masks",
".",
"extend",
"(",
"step",
".",
"masks",
")",
"self",
".",
"x",
".",
"extend",
"(",
"step",
"... | 38.8 | 14.3 |
def to_irc(self):
"""
Convert to mIRC color format
:return:
"""
ignore_re = re.compile('[\x03\x02\x1D\x1F\x16\x0F]')
text = ignore_re.sub('', self.text)
if self.color and self.bg_color:
return '\x03%02d,%02d%s' % (self.color.to_8bit().to_irc(),
... | [
"def",
"to_irc",
"(",
"self",
")",
":",
"ignore_re",
"=",
"re",
".",
"compile",
"(",
"'[\\x03\\x02\\x1D\\x1F\\x16\\x0F]'",
")",
"text",
"=",
"ignore_re",
".",
"sub",
"(",
"''",
",",
"self",
".",
"text",
")",
"if",
"self",
".",
"color",
"and",
"self",
"... | 36.952381 | 14 |
def init_repo(path):
"""clone the gh-pages repo if we haven't already."""
sh("git clone %s %s"%(pages_repo, path))
here = os.getcwd()
cd(path)
sh('git checkout gh-pages')
cd(here) | [
"def",
"init_repo",
"(",
"path",
")",
":",
"sh",
"(",
"\"git clone %s %s\"",
"%",
"(",
"pages_repo",
",",
"path",
")",
")",
"here",
"=",
"os",
".",
"getcwd",
"(",
")",
"cd",
"(",
"path",
")",
"sh",
"(",
"'git checkout gh-pages'",
")",
"cd",
"(",
"her... | 28.142857 | 15.285714 |
def save_unmet(self, job):
"""Save a message for later submission when its dependencies are met."""
msg_id = job.msg_id
self.depending[msg_id] = job
# track the ids in follow or after, but not those already finished
for dep_id in job.after.union(job.follow).difference(self.all_do... | [
"def",
"save_unmet",
"(",
"self",
",",
"job",
")",
":",
"msg_id",
"=",
"job",
".",
"msg_id",
"self",
".",
"depending",
"[",
"msg_id",
"]",
"=",
"job",
"# track the ids in follow or after, but not those already finished",
"for",
"dep_id",
"in",
"job",
".",
"after... | 49.222222 | 11.666667 |
def get():
"""Returns the current version without importing pymds."""
pkgnames = find_packages()
if len(pkgnames) == 0:
raise ValueError("Can't find any packages")
pkgname = pkgnames[0]
content = open(join(pkgname, '__init__.py')).read()
c = re.compile(r"__version__ *= *('[^']+'|\"[^\... | [
"def",
"get",
"(",
")",
":",
"pkgnames",
"=",
"find_packages",
"(",
")",
"if",
"len",
"(",
"pkgnames",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"Can't find any packages\"",
")",
"pkgname",
"=",
"pkgnames",
"[",
"0",
"]",
"content",
"=",
"open",... | 27.176471 | 23.058824 |
def p_constant_declaration(p):
'constant_declaration : STRING EQUALS static_scalar'
p[0] = ast.ConstantDeclaration(p[1], p[3], lineno=p.lineno(1)) | [
"def",
"p_constant_declaration",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"ast",
".",
"ConstantDeclaration",
"(",
"p",
"[",
"1",
"]",
",",
"p",
"[",
"3",
"]",
",",
"lineno",
"=",
"p",
".",
"lineno",
"(",
"1",
")",
")"
] | 50.666667 | 17.333333 |
def transformProperMotionErrors(self, phi, theta, sigMuPhiStar, sigMuTheta, rhoMuPhiMuTheta=0):
"""
Converts the proper motion errors from one reference system to another, including the covariance
term. Equations (1.5.4) and (1.5.20) from section 1.5 in the Hipparcos Explanatory Volume 1 are use... | [
"def",
"transformProperMotionErrors",
"(",
"self",
",",
"phi",
",",
"theta",
",",
"sigMuPhiStar",
",",
"sigMuTheta",
",",
"rhoMuPhiMuTheta",
"=",
"0",
")",
":",
"return",
"self",
".",
"transformSkyCoordinateErrors",
"(",
"phi",
",",
"theta",
",",
"sigMuPhiStar",... | 48.933333 | 35.133333 |
def read_int(self, lpBaseAddress):
"""
Reads a signed integer from the memory of the process.
@see: L{peek_int}
@type lpBaseAddress: int
@param lpBaseAddress: Memory address to begin reading.
@rtype: int
@return: Integer value read from the process memory.
... | [
"def",
"read_int",
"(",
"self",
",",
"lpBaseAddress",
")",
":",
"return",
"self",
".",
"__read_c_type",
"(",
"lpBaseAddress",
",",
"compat",
".",
"b",
"(",
"'@l'",
")",
",",
"ctypes",
".",
"c_int",
")"
] | 30.466667 | 22.066667 |
def _setup_stats_total(self, redis_conn):
'''
Sets up the total stats collectors
@param redis_conn: the redis connection
'''
self.stats_dict['total'] = {}
self.stats_dict['fail'] = {}
temp_key1 = 'stats:kafka-monitor:total'
temp_key2 = 'stats:kafka-monito... | [
"def",
"_setup_stats_total",
"(",
"self",
",",
"redis_conn",
")",
":",
"self",
".",
"stats_dict",
"[",
"'total'",
"]",
"=",
"{",
"}",
"self",
".",
"stats_dict",
"[",
"'fail'",
"]",
"=",
"{",
"}",
"temp_key1",
"=",
"'stats:kafka-monitor:total'",
"temp_key2",
... | 53.682927 | 20.02439 |
def next_sibling(self):
""" Returns the next sibling of the current node.
The next sibling is searched in the parent node if we are not considering a top-level node.
Otherwise it is searched inside the list of nodes (which should be sorted by tree ID) that
is associated with the conside... | [
"def",
"next_sibling",
"(",
"self",
")",
":",
"if",
"self",
".",
"parent",
":",
"nodes",
"=",
"self",
".",
"parent",
".",
"children",
"index",
"=",
"nodes",
".",
"index",
"(",
"self",
")",
"sibling",
"=",
"nodes",
"[",
"index",
"+",
"1",
"]",
"if",... | 41.842105 | 20.789474 |
def template(page=None, layout=None, **kwargs):
"""
Decorator to change the view template and layout.
It works on both View class and view methods
on class
only $layout is applied, everything else will be passed to the kwargs
Using as first argument, it will be the layout.
:fi... | [
"def",
"template",
"(",
"page",
"=",
"None",
",",
"layout",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"pkey",
"=",
"\"_template_extends__\"",
"def",
"decorator",
"(",
"f",
")",
":",
"if",
"inspect",
".",
"isclass",
"(",
"f",
")",
":",
"layout_"... | 33.09375 | 16.09375 |
def _checkBuildDependencies():
compiler = distutils.ccompiler.new_compiler()
"""check if function without parameters from stdlib can be called
There should be better way to check, if C compiler is installed
"""
if not compiler.has_function('rand', includes=['stdlib.h']):
print("It seems like... | [
"def",
"_checkBuildDependencies",
"(",
")",
":",
"compiler",
"=",
"distutils",
".",
"ccompiler",
".",
"new_compiler",
"(",
")",
"if",
"not",
"compiler",
".",
"has_function",
"(",
"'rand'",
",",
"includes",
"=",
"[",
"'stdlib.h'",
"]",
")",
":",
"print",
"(... | 56.285714 | 28.685714 |
def create_template(self):
"""Create template (main function called by Stacker)."""
template = self.template
variables = self.get_variables()
template.add_version('2010-09-09')
template.add_description('Static Website - Bucket and Distribution')
# Conditions
temp... | [
"def",
"create_template",
"(",
"self",
")",
":",
"template",
"=",
"self",
".",
"template",
"variables",
"=",
"self",
".",
"get_variables",
"(",
")",
"template",
".",
"add_version",
"(",
"'2010-09-09'",
")",
"template",
".",
"add_description",
"(",
"'Static Web... | 41.843511 | 19.041985 |
def show(source):
"""Merely returns the metadata for the provided archive.
"""
if is_verbose():
logger.info('Retrieving Metadata for: %s', source)
processed_source = get_source(source)
metadata = _get_metadata(processed_source)
shutil.rmtree(processed_source)
return metadata | [
"def",
"show",
"(",
"source",
")",
":",
"if",
"is_verbose",
"(",
")",
":",
"logger",
".",
"info",
"(",
"'Retrieving Metadata for: %s'",
",",
"source",
")",
"processed_source",
"=",
"get_source",
"(",
"source",
")",
"metadata",
"=",
"_get_metadata",
"(",
"pro... | 33.666667 | 10.444444 |
def p_instance_bodylist(self, p):
'instance_bodylist : instance_bodylist COMMA instance_body'
p[0] = p[1] + (p[3],)
p.set_lineno(0, p.lineno(1)) | [
"def",
"p_instance_bodylist",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
"+",
"(",
"p",
"[",
"3",
"]",
",",
")",
"p",
".",
"set_lineno",
"(",
"0",
",",
"p",
".",
"lineno",
"(",
"1",
")",
")"
] | 41.25 | 12.25 |
def _process_collection(self, collection_id, label, page):
"""
This function will process the data supplied internally
about the repository from Coriell.
Triples:
Repository a ERO:collection
rdf:label Literal(label)
foaf:page Literal(page)
:p... | [
"def",
"_process_collection",
"(",
"self",
",",
"collection_id",
",",
"label",
",",
"page",
")",
":",
"# ############# BUILD THE CELL LINE REPOSITORY #############",
"for",
"graph",
"in",
"[",
"self",
".",
"graph",
",",
"self",
".",
"testgraph",
"]",
":",
"#... | 32.344828 | 16.758621 |
def _set_params_callback(self, **params):
"""Special handling for setting params on callbacks."""
# model after sklearn.utils._BaseCompostion._set_params
# 1. All steps
if 'callbacks' in params:
setattr(self, 'callbacks', params.pop('callbacks'))
# 2. Step replacemen... | [
"def",
"_set_params_callback",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"# model after sklearn.utils._BaseCompostion._set_params",
"# 1. All steps",
"if",
"'callbacks'",
"in",
"params",
":",
"setattr",
"(",
"self",
",",
"'callbacks'",
",",
"params",
".",
"pop... | 39.071429 | 15.25 |
def _convertNonNumericData(self, spatialOutput, temporalOutput, output):
"""
Converts all of the non-numeric fields from spatialOutput and temporalOutput
into their scalar equivalents and records them in the output dictionary.
:param spatialOutput: The results of topDownCompute() for the spatial input.... | [
"def",
"_convertNonNumericData",
"(",
"self",
",",
"spatialOutput",
",",
"temporalOutput",
",",
"output",
")",
":",
"encoders",
"=",
"self",
".",
"encoder",
".",
"getEncoderList",
"(",
")",
"types",
"=",
"self",
".",
"encoder",
".",
"getDecoderOutputFieldTypes",... | 47.259259 | 21.62963 |
def p_expression_eq(self, p):
'expression : expression EQ expression'
p[0] = Eq(p[1], p[3], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | [
"def",
"p_expression_eq",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"Eq",
"(",
"p",
"[",
"1",
"]",
",",
"p",
"[",
"3",
"]",
",",
"lineno",
"=",
"p",
".",
"lineno",
"(",
"1",
")",
")",
"p",
".",
"set_lineno",
"(",
"0",
",",... | 40.25 | 7.75 |
def get_float(strings: Sequence[str],
prefix: str,
ignoreleadingcolon: bool = False,
precedingline: str = "") -> Optional[float]:
"""
Fetches a float parameter via :func:`get_string`.
"""
return get_float_raw(get_string(strings, prefix,
... | [
"def",
"get_float",
"(",
"strings",
":",
"Sequence",
"[",
"str",
"]",
",",
"prefix",
":",
"str",
",",
"ignoreleadingcolon",
":",
"bool",
"=",
"False",
",",
"precedingline",
":",
"str",
"=",
"\"\"",
")",
"->",
"Optional",
"[",
"float",
"]",
":",
"return... | 42.6 | 12.6 |
def max_insertion(seqs, gene, domain):
"""
length of largest insertion
"""
seqs = [i[2] for i in list(seqs.values()) if i[2] != [] and i[0] == gene and i[1] == domain]
lengths = []
for seq in seqs:
for ins in seq:
lengths.append(int(ins[2]))
if lengths == []:
retu... | [
"def",
"max_insertion",
"(",
"seqs",
",",
"gene",
",",
"domain",
")",
":",
"seqs",
"=",
"[",
"i",
"[",
"2",
"]",
"for",
"i",
"in",
"list",
"(",
"seqs",
".",
"values",
"(",
")",
")",
"if",
"i",
"[",
"2",
"]",
"!=",
"[",
"]",
"and",
"i",
"[",... | 28.333333 | 15.5 |
def get_profile_info(self, obj):
"""Returns the info for a Profile
"""
info = self.get_base_info(obj)
info.update({})
return info | [
"def",
"get_profile_info",
"(",
"self",
",",
"obj",
")",
":",
"info",
"=",
"self",
".",
"get_base_info",
"(",
"obj",
")",
"info",
".",
"update",
"(",
"{",
"}",
")",
"return",
"info"
] | 27.333333 | 8 |
def bulleted_list(items, indent=0, bullet_type='-'):
"""Format a bulleted list of values.
Parameters
----------
items : sequence
The items to make a list.
indent : int, optional
The number of spaces to add before each bullet.
bullet_type : str, optional
The bullet type t... | [
"def",
"bulleted_list",
"(",
"items",
",",
"indent",
"=",
"0",
",",
"bullet_type",
"=",
"'-'",
")",
":",
"format_string",
"=",
"' '",
"*",
"indent",
"+",
"bullet_type",
"+",
"' {}'",
"return",
"\"\\n\"",
".",
"join",
"(",
"map",
"(",
"format_string",
"."... | 27.526316 | 17.157895 |
def SetScrollPercent(self, horizontalPercent: float, verticalPercent: float, waitTime: float = OPERATION_WAIT_TIME) -> bool:
"""
Call IUIAutomationScrollPattern::SetScrollPercent.
Set the horizontal and vertical scroll positions as a percentage of the total content area within the UI Automation ... | [
"def",
"SetScrollPercent",
"(",
"self",
",",
"horizontalPercent",
":",
"float",
",",
"verticalPercent",
":",
"float",
",",
"waitTime",
":",
"float",
"=",
"OPERATION_WAIT_TIME",
")",
"->",
"bool",
":",
"ret",
"=",
"self",
".",
"pattern",
".",
"SetScrollPercent"... | 70.307692 | 42.461538 |
def checkPrediction2(possibleOutcome, predictedOutcome):
"""
:param possibleOutcome: list of all possible outcomes
:param predictedOutcome: list of all predicted outomes
:return missN: number of misses (a possible outcome not predicted)
fpN: number of false positives (a predicted outcome is not poss... | [
"def",
"checkPrediction2",
"(",
"possibleOutcome",
",",
"predictedOutcome",
")",
":",
"missN",
"=",
"0",
"for",
"i",
"in",
"xrange",
"(",
"len",
"(",
"possibleOutcome",
")",
")",
":",
"miss",
"=",
"1",
"for",
"j",
"in",
"xrange",
"(",
"len",
"(",
"pred... | 30.25 | 19.583333 |
def timing_decorator(func):
"""Prints the time func takes to execute."""
@functools.wraps(func)
def wrapper(*args, **kwargs):
"""
Wrapper for printing execution time.
Parameters
----------
print_time: bool, optional
whether or not to print time function t... | [
"def",
"timing_decorator",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"\n Wrapper for printing execution time.\n\n Parameters\n ----------\n... | 30.869565 | 11.478261 |
def comments_between_tokens(token1, token2):
"""Find all comments between two tokens"""
if token2 is None:
buf = token1.end_mark.buffer[token1.end_mark.pointer:]
elif (token1.end_mark.line == token2.start_mark.line and
not isinstance(token1, yaml.StreamStartToken) and
not isinsta... | [
"def",
"comments_between_tokens",
"(",
"token1",
",",
"token2",
")",
":",
"if",
"token2",
"is",
"None",
":",
"buf",
"=",
"token1",
".",
"end_mark",
".",
"buffer",
"[",
"token1",
".",
"end_mark",
".",
"pointer",
":",
"]",
"elif",
"(",
"token1",
".",
"en... | 34.533333 | 18.333333 |
def simple_transaction(self, from_address, to, op_return=None, min_confirmations=6):
"""
Args:
from_address (str): bitcoin address originating the transaction
to: tuple of ``(to_address, amount)`` or list of tuples ``[(to_addr1, amount1), (to_addr2, amount2)]``. Amounts are in *s... | [
"def",
"simple_transaction",
"(",
"self",
",",
"from_address",
",",
"to",
",",
"op_return",
"=",
"None",
",",
"min_confirmations",
"=",
"6",
")",
":",
"to",
"=",
"[",
"to",
"]",
"if",
"not",
"isinstance",
"(",
"to",
",",
"list",
")",
"else",
"to",
"a... | 42.535714 | 28.75 |
def pull_byte(self, stack_pointer):
""" pulled a byte from stack """
addr = stack_pointer.value
byte = self.memory.read_byte(addr)
# log.info(
# log.error(
# "%x|\tpull $%x from %s stack at $%x\t|%s",
# self.last_op_address, byte, stack_pointer.name, addr,
# ... | [
"def",
"pull_byte",
"(",
"self",
",",
"stack_pointer",
")",
":",
"addr",
"=",
"stack_pointer",
".",
"value",
"byte",
"=",
"self",
".",
"memory",
".",
"read_byte",
"(",
"addr",
")",
"# log.info(",
"# log.error(",
"# \"%x|\\tpull $%x from %s ... | 32.333333 | 17.666667 |
def anomaly(self, test_data, per_feature=False):
"""
Obtain the reconstruction error for the input test_data.
:param H2OFrame test_data: The dataset upon which the reconstruction error is computed.
:param bool per_feature: Whether to return the square reconstruction error per feature.
... | [
"def",
"anomaly",
"(",
"self",
",",
"test_data",
",",
"per_feature",
"=",
"False",
")",
":",
"if",
"test_data",
"is",
"None",
"or",
"test_data",
".",
"nrow",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"Must specify test data\"",
")",
"j",
"=",
"h2o",
... | 57.5 | 33.071429 |
def input_validation(group_idx, a, size=None, order='C', axis=None,
ravel_group_idx=True, check_bounds=True):
""" Do some fairly extensive checking of group_idx and a, trying to
give the user as much help as possible with what is wrong. Also,
convert ndim-indexing to 1d indexing.
""... | [
"def",
"input_validation",
"(",
"group_idx",
",",
"a",
",",
"size",
"=",
"None",
",",
"order",
"=",
"'C'",
",",
"axis",
"=",
"None",
",",
"ravel_group_idx",
"=",
"True",
",",
"check_bounds",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"a",
... | 45.391304 | 19.478261 |
def checksum(thing):
"""
Get the checksum of a calculation from the calculation ID (if already
done) or from the job.ini/job.zip file (if not done yet). If `thing`
is a source model logic tree file, get the checksum of the model by
ignoring the job.ini, the gmpe logic tree file and possibly other fi... | [
"def",
"checksum",
"(",
"thing",
")",
":",
"try",
":",
"job_id",
"=",
"int",
"(",
"thing",
")",
"job_file",
"=",
"None",
"except",
"ValueError",
":",
"job_id",
"=",
"None",
"job_file",
"=",
"thing",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",... | 38.84 | 19 |
def _extract_multiple_hits(self, hits, reads_path, output_path):
'''
splits out regions of a read that hit the HMM. For example when two of
same gene are identified within the same contig, The regions mapping to
the HMM will be split out and written out to a new file as a new record.
... | [
"def",
"_extract_multiple_hits",
"(",
"self",
",",
"hits",
",",
"reads_path",
",",
"output_path",
")",
":",
"complement_information",
"=",
"{",
"}",
"try",
":",
"reads",
"=",
"SeqIO",
".",
"to_dict",
"(",
"SeqIO",
".",
"parse",
"(",
"reads_path",
",",
"\"f... | 48.561404 | 31.508772 |
def run(self, inputcode, iterations=None, run_forever=False, frame_limiter=False, verbose=False,
break_on_error=False):
'''
Executes the contents of a Nodebox/Shoebot script
in current surface's context.
:param inputcode: Path to shoebot source or string containing source
... | [
"def",
"run",
"(",
"self",
",",
"inputcode",
",",
"iterations",
"=",
"None",
",",
"run_forever",
"=",
"False",
",",
"frame_limiter",
"=",
"False",
",",
"verbose",
"=",
"False",
",",
"break_on_error",
"=",
"False",
")",
":",
"source",
"=",
"None",
"filena... | 41.230769 | 22.791209 |
def update_issue_remote_link_by_id(self, issue_key, link_id, url, title, global_id=None, relationship=None):
"""
Update existing Remote Link on Issue
:param issue_key: str
:param link_id: str
:param url: str
:param title: str
:param global_id: str, OPTIONAL:
... | [
"def",
"update_issue_remote_link_by_id",
"(",
"self",
",",
"issue_key",
",",
"link_id",
",",
"url",
",",
"title",
",",
"global_id",
"=",
"None",
",",
"relationship",
"=",
"None",
")",
":",
"data",
"=",
"{",
"'object'",
":",
"{",
"'url'",
":",
"url",
",",... | 41.333333 | 18.333333 |
def toList(self):
"""
Return a list with the DataFrame data.
"""
if self.getNumCols() > 1:
return [
tuple(self.getRowByIndex(i))
for i in range(self.getNumRows())
]
else:
return [
self.getRowByInd... | [
"def",
"toList",
"(",
"self",
")",
":",
"if",
"self",
".",
"getNumCols",
"(",
")",
">",
"1",
":",
"return",
"[",
"tuple",
"(",
"self",
".",
"getRowByIndex",
"(",
"i",
")",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"getNumRows",
"(",
")",
... | 27.071429 | 12.785714 |
def set_clock_divisor(self, clock_divisor):
"""
Sets the clock divisor value. The higher is the value, the faster is the clock in the
virtual machine. The default is 4, but it is often required to adjust it.
:param clock_divisor: clock divisor value (integer)
"""
yield ... | [
"def",
"set_clock_divisor",
"(",
"self",
",",
"clock_divisor",
")",
":",
"yield",
"from",
"self",
".",
"_hypervisor",
".",
"send",
"(",
"'vm set_clock_divisor \"{name}\" {clock}'",
".",
"format",
"(",
"name",
"=",
"self",
".",
"_name",
",",
"clock",
"=",
"cloc... | 69 | 44.571429 |
def get_extname(self):
"""
Get the name for this extension, can be an empty string
"""
name = self._info['extname']
if name.strip() == '':
name = self._info['hduname']
return name.strip() | [
"def",
"get_extname",
"(",
"self",
")",
":",
"name",
"=",
"self",
".",
"_info",
"[",
"'extname'",
"]",
"if",
"name",
".",
"strip",
"(",
")",
"==",
"''",
":",
"name",
"=",
"self",
".",
"_info",
"[",
"'hduname'",
"]",
"return",
"name",
".",
"strip",
... | 30 | 8.5 |
def _initialize(self, runtime):
"""Common initializer for OsidManager and OsidProxyManager"""
if runtime is None:
raise NullArgument()
if self._my_runtime is not None:
raise IllegalState('this manager has already been initialized.')
self._my_runtime = runtime
... | [
"def",
"_initialize",
"(",
"self",
",",
"runtime",
")",
":",
"if",
"runtime",
"is",
"None",
":",
"raise",
"NullArgument",
"(",
")",
"if",
"self",
".",
"_my_runtime",
"is",
"not",
"None",
":",
"raise",
"IllegalState",
"(",
"'this manager has already been initia... | 46.119048 | 26.047619 |
def cosi_pdf(z,k=1):
"""Equation (11) of Morton & Winn (2014)
"""
return 2*k/(np.pi*np.sinh(k)) * quad(cosi_integrand,z,1,args=(k,z))[0] | [
"def",
"cosi_pdf",
"(",
"z",
",",
"k",
"=",
"1",
")",
":",
"return",
"2",
"*",
"k",
"/",
"(",
"np",
".",
"pi",
"*",
"np",
".",
"sinh",
"(",
"k",
")",
")",
"*",
"quad",
"(",
"cosi_integrand",
",",
"z",
",",
"1",
",",
"args",
"=",
"(",
"k",... | 36.25 | 13.5 |
def load_factors():
"""Load risk factor returns.
Factors
-------
Symbol Description Source
------ ---------- ------
MKT French
... | [
"def",
"load_factors",
"(",
")",
":",
"# TODO: factors elegible for addition\r",
"# VIIX, VIIZ, XIV, ZIV, CRP (AQR)\r",
"# http://www.cboe.com/micro/buywrite/monthendpricehistory.xls ends 2016\r",
"# could use:\r",
"# http://www.cboe.com/publish/scheduledtask/mktdata/datahouse/putdailypric... | 37.684211 | 23.20614 |
def register_plugin(self, plugin):
"""Registers a plugin and commands with the dispatcher for push()"""
self.log.info("Registering plugin %s", type(plugin).__name__)
self._register_commands(plugin)
plugin.on_load() | [
"def",
"register_plugin",
"(",
"self",
",",
"plugin",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"Registering plugin %s\"",
",",
"type",
"(",
"plugin",
")",
".",
"__name__",
")",
"self",
".",
"_register_commands",
"(",
"plugin",
")",
"plugin",
".",
... | 48.4 | 10.4 |
def ldcoeffs(teff,logg=4.5,feh=0):
"""
Returns limb-darkening coefficients in Kepler band.
"""
teffs = np.atleast_1d(teff)
loggs = np.atleast_1d(logg)
Tmin,Tmax = (LDPOINTS[:,0].min(),LDPOINTS[:,0].max())
gmin,gmax = (LDPOINTS[:,1].min(),LDPOINTS[:,1].max())
teffs[(teffs < Tmin)] = Tmi... | [
"def",
"ldcoeffs",
"(",
"teff",
",",
"logg",
"=",
"4.5",
",",
"feh",
"=",
"0",
")",
":",
"teffs",
"=",
"np",
".",
"atleast_1d",
"(",
"teff",
")",
"loggs",
"=",
"np",
".",
"atleast_1d",
"(",
"logg",
")",
"Tmin",
",",
"Tmax",
"=",
"(",
"LDPOINTS",
... | 29.058824 | 13.882353 |
def model(x_train, y_train, x_test, y_test):
"""
Model providing function:
Create Keras model with double curly brackets dropped-in as needed.
Return value has to be a valid python dictionary with two customary keys:
- loss: Specify a numeric evaluation metric to be minimized
- status: ... | [
"def",
"model",
"(",
"x_train",
",",
"y_train",
",",
"x_test",
",",
"y_test",
")",
":",
"model",
"=",
"Sequential",
"(",
")",
"model",
".",
"add",
"(",
"Dense",
"(",
"512",
",",
"input_shape",
"=",
"(",
"784",
",",
")",
")",
")",
"model",
".",
"a... | 38.952381 | 19.47619 |
def _error(self, request, status, headers={}, prefix_template_path=False, **kwargs):
"""
Convenience method to render an error response. The template is inferred from the status code.
:param request: A django.http.HttpRequest instance.
:param status: An integer describing the HTTP statu... | [
"def",
"_error",
"(",
"self",
",",
"request",
",",
"status",
",",
"headers",
"=",
"{",
"}",
",",
"prefix_template_path",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_render",
"(",
"request",
"=",
"request",
",",
"template",... | 42.565217 | 27 |
def human(self):
"""Human-readable timestamp."""
# get timezone offset
delta_sec = time.timezone
m, s = divmod(delta_sec, 60)
h, m = divmod(m, 60)
# create output
format_string = "%Y-%m-%d %H:%M:%S"
out = self.datetime.strftime(format_string)
retur... | [
"def",
"human",
"(",
"self",
")",
":",
"# get timezone offset",
"delta_sec",
"=",
"time",
".",
"timezone",
"m",
",",
"s",
"=",
"divmod",
"(",
"delta_sec",
",",
"60",
")",
"h",
",",
"m",
"=",
"divmod",
"(",
"m",
",",
"60",
")",
"# create output",
"for... | 31.6 | 11.1 |
def send(self, change):
"""send the given policy change"""
self.buf.append(change)
if len(self.buf) % self.BUF_SIZE == 0:
self.flush() | [
"def",
"send",
"(",
"self",
",",
"change",
")",
":",
"self",
".",
"buf",
".",
"append",
"(",
"change",
")",
"if",
"len",
"(",
"self",
".",
"buf",
")",
"%",
"self",
".",
"BUF_SIZE",
"==",
"0",
":",
"self",
".",
"flush",
"(",
")"
] | 33.2 | 9.6 |
def node_hist_fig(
node_color_distribution,
title="Graph Node Distribution",
width=400,
height=300,
top=60,
left=25,
bottom=60,
right=25,
bgcolor="rgb(240,240,240)",
y_gridcolor="white",
):
"""Define the plotly plot representing the node histogram
Param... | [
"def",
"node_hist_fig",
"(",
"node_color_distribution",
",",
"title",
"=",
"\"Graph Node Distribution\"",
",",
"width",
"=",
"400",
",",
"height",
"=",
"300",
",",
"top",
"=",
"60",
",",
"left",
"=",
"25",
",",
"bottom",
"=",
"60",
",",
"right",
"=",
"25... | 30.358491 | 24.433962 |
def create_table(self,keyColumn=None,keyColumnType=None,title=None,verbose=None):
"""
Adds a new table to the network.
:param keyColumn (string, optional): Specifies the name of a column in the
table
:param keyColumnType (string, optional): The syntactical type of the value
... | [
"def",
"create_table",
"(",
"self",
",",
"keyColumn",
"=",
"None",
",",
"keyColumnType",
"=",
"None",
",",
"title",
"=",
"None",
",",
"verbose",
"=",
"None",
")",
":",
"PARAMS",
"=",
"set_param",
"(",
"[",
"'keyColumn'",
",",
"'keyColumnType'",
",",
"'ti... | 41.529412 | 25.764706 |
def _get_contexts_for_squash(self, batch_signature):
"""Starting with the batch referenced by batch_signature, iterate back
through the batches and for each valid batch collect the context_id.
At the end remove contexts for txns that are other txn's predecessors.
Args:
batch... | [
"def",
"_get_contexts_for_squash",
"(",
"self",
",",
"batch_signature",
")",
":",
"batch",
"=",
"self",
".",
"_batches_by_id",
"[",
"batch_signature",
"]",
".",
"batch",
"index",
"=",
"self",
".",
"_batches",
".",
"index",
"(",
"batch",
")",
"contexts",
"=",... | 40.6 | 17.885714 |
def path_and_line(req):
"""Return the path and line number of the file from which an
InstallRequirement came.
"""
path, line = (re.match(r'-r (.*) \(line (\d+)\)$',
req.comes_from).groups())
return path, int(line) | [
"def",
"path_and_line",
"(",
"req",
")",
":",
"path",
",",
"line",
"=",
"(",
"re",
".",
"match",
"(",
"r'-r (.*) \\(line (\\d+)\\)$'",
",",
"req",
".",
"comes_from",
")",
".",
"groups",
"(",
")",
")",
"return",
"path",
",",
"int",
"(",
"line",
")"
] | 31.75 | 13.625 |
def build(self, tool):
"""build the project"""
tools = self._validate_tools(tool)
if tools == -1:
return -1
result = 0
for build_tool in tools:
builder = ToolsSupported().get_tool(build_tool)
# None is an error
if builder is None... | [
"def",
"build",
"(",
"self",
",",
"tool",
")",
":",
"tools",
"=",
"self",
".",
"_validate_tools",
"(",
"tool",
")",
"if",
"tools",
"==",
"-",
"1",
":",
"return",
"-",
"1",
"result",
"=",
"0",
"for",
"build_tool",
"in",
"tools",
":",
"builder",
"=",... | 31.478261 | 20.043478 |
def from_dict(data, ctx):
"""
Instantiate a new TradeClientExtensionsModifyTransaction from a dict
(generally from loading a JSON response). The data used to instantiate
the TradeClientExtensionsModifyTransaction is a shallow copy of the
dict passed in, with any complex child typ... | [
"def",
"from_dict",
"(",
"data",
",",
"ctx",
")",
":",
"data",
"=",
"data",
".",
"copy",
"(",
")",
"if",
"data",
".",
"get",
"(",
"'tradeClientExtensionsModify'",
")",
"is",
"not",
"None",
":",
"data",
"[",
"'tradeClientExtensionsModify'",
"]",
"=",
"ctx... | 38.888889 | 23.222222 |
def audit_1_4(self):
"""1.4 Ensure access keys are rotated every 90 days or less (Scored)"""
for row in self.credential_report:
for access_key in "1", "2":
if json.loads(row["access_key_{}_active".format(access_key)]):
last_rotated = row["access_key_{}_las... | [
"def",
"audit_1_4",
"(",
"self",
")",
":",
"for",
"row",
"in",
"self",
".",
"credential_report",
":",
"for",
"access_key",
"in",
"\"1\"",
",",
"\"2\"",
":",
"if",
"json",
".",
"loads",
"(",
"row",
"[",
"\"access_key_{}_active\"",
".",
"format",
"(",
"acc... | 68.333333 | 28.666667 |
def find_modules_with_decorators(path,decorator_module,decorator_name):
'''
Finds all the modules decorated with the specified decorator in the path, file or module specified.
Args :
path : All modules in the directory and its sub-directories will be scanned.
decorato... | [
"def",
"find_modules_with_decorators",
"(",
"path",
",",
"decorator_module",
",",
"decorator_name",
")",
":",
"modules_paths",
"=",
"[",
"]",
"#If a path to a module file",
"if",
"path",
"[",
"-",
"3",
":",
"]",
"==",
"'.py'",
":",
"modules_paths",
".",
"append"... | 41.5 | 30.1 |
def format_to_http_prompt(context, excluded_options=None):
"""Format a Context object to HTTP Prompt commands."""
cmds = _extract_httpie_options(context, quote=True, join_key_value=True,
excluded_keys=excluded_options)
cmds.append('cd ' + smart_quote(context.url))
cmds... | [
"def",
"format_to_http_prompt",
"(",
"context",
",",
"excluded_options",
"=",
"None",
")",
":",
"cmds",
"=",
"_extract_httpie_options",
"(",
"context",
",",
"quote",
"=",
"True",
",",
"join_key_value",
"=",
"True",
",",
"excluded_keys",
"=",
"excluded_options",
... | 57.428571 | 16.857143 |
def env_updated(cls, app, env):
"""Abort Sphinx after initializing config and discovering all pages to build.
:param sphinx.application.Sphinx app: Sphinx application object.
:param sphinx.environment.BuildEnvironment env: Sphinx build environment.
"""
if cls.ABORT_AFTER_READ:
... | [
"def",
"env_updated",
"(",
"cls",
",",
"app",
",",
"env",
")",
":",
"if",
"cls",
".",
"ABORT_AFTER_READ",
":",
"config",
"=",
"{",
"n",
":",
"getattr",
"(",
"app",
".",
"config",
",",
"n",
")",
"for",
"n",
"in",
"(",
"a",
"for",
"a",
"in",
"dir... | 51.833333 | 22.833333 |
def send_packed_command(self, command):
"Send an already packed command to the Redis server"
if not self._sock:
self.connect()
try:
if isinstance(command, str):
command = [command]
for item in command:
self._sock.sendall(item)
... | [
"def",
"send_packed_command",
"(",
"self",
",",
"command",
")",
":",
"if",
"not",
"self",
".",
"_sock",
":",
"self",
".",
"connect",
"(",
")",
"try",
":",
"if",
"isinstance",
"(",
"command",
",",
"str",
")",
":",
"command",
"=",
"[",
"command",
"]",
... | 35.44 | 12.24 |
def pipe_urlinput(context=None, _INPUT=None, conf=None, **kwargs):
"""An input that prompts the user for a url and yields it forever.
Not loopable.
Parameters
----------
context : pipe2py.Context object
_INPUT : unused
conf : {
'name': {'value': 'parameter name'},
'prompt': ... | [
"def",
"pipe_urlinput",
"(",
"context",
"=",
"None",
",",
"_INPUT",
"=",
"None",
",",
"conf",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"value",
"=",
"utils",
".",
"get_input",
"(",
"context",
",",
"conf",
")",
"value",
"=",
"utils",
".",
"ur... | 24.208333 | 19.166667 |
def excel_to_html(path, sheetname='Sheet1', css_classes='', \
caption='', details=[], row_headers=False, merge=False):
"""
Convert an excel spreadsheet to an html table.
This function supports the conversion of merged
cells. It can be used in code or run from the
command-line. If passed the co... | [
"def",
"excel_to_html",
"(",
"path",
",",
"sheetname",
"=",
"'Sheet1'",
",",
"css_classes",
"=",
"''",
",",
"caption",
"=",
"''",
",",
"details",
"=",
"[",
"]",
",",
"row_headers",
"=",
"False",
",",
"merge",
"=",
"False",
")",
":",
"def",
"get_data_on... | 33.608142 | 17.709924 |
def get_aggregation_propensity(self, seq, outdir, cutoff_v=5, cutoff_n=5, run_amylmuts=False):
"""Run the AMYLPRED2 web server for a protein sequence and get the consensus result for aggregation propensity.
Args:
seq (str, Seq, SeqRecord): Amino acid sequence
outdir (str): Direc... | [
"def",
"get_aggregation_propensity",
"(",
"self",
",",
"seq",
",",
"outdir",
",",
"cutoff_v",
"=",
"5",
",",
"cutoff_n",
"=",
"5",
",",
"run_amylmuts",
"=",
"False",
")",
":",
"seq",
"=",
"ssbio",
".",
"protein",
".",
"sequence",
".",
"utils",
".",
"ca... | 55.304348 | 39.826087 |
def create(self, email, phone, country_code=1, send_install_link_via_sms=False):
"""
sends request to create new user.
:param string email:
:param string phone:
:param string country_code:
:param bool send_install_link_via_sms:
:return:
"""
data = ... | [
"def",
"create",
"(",
"self",
",",
"email",
",",
"phone",
",",
"country_code",
"=",
"1",
",",
"send_install_link_via_sms",
"=",
"False",
")",
":",
"data",
"=",
"{",
"\"user\"",
":",
"{",
"\"email\"",
":",
"email",
",",
"\"cellphone\"",
":",
"phone",
",",... | 28.272727 | 17.818182 |
def build_module(self, module, loglevel=logging.DEBUG):
"""Build passed-in module.
"""
shutit_global.shutit_global_object.yield_to_draw()
cfg = self.cfg
self.log('Building ShutIt module: ' + module.module_id + ' with run order: ' + str(module.run_order), level=logging.INFO)
self.build['report'] = (self.buil... | [
"def",
"build_module",
"(",
"self",
",",
"module",
",",
"loglevel",
"=",
"logging",
".",
"DEBUG",
")",
":",
"shutit_global",
".",
"shutit_global_object",
".",
"yield_to_draw",
"(",
")",
"cfg",
"=",
"self",
".",
"cfg",
"self",
".",
"log",
"(",
"'Building Sh... | 87 | 53.194444 |
def temporal_from_rdf(period_of_time):
'''Failsafe parsing of a temporal coverage'''
try:
if isinstance(period_of_time, Literal):
return temporal_from_literal(str(period_of_time))
elif isinstance(period_of_time, RdfResource):
return temporal_from_resource(period_of_time)
... | [
"def",
"temporal_from_rdf",
"(",
"period_of_time",
")",
":",
"try",
":",
"if",
"isinstance",
"(",
"period_of_time",
",",
"Literal",
")",
":",
"return",
"temporal_from_literal",
"(",
"str",
"(",
"period_of_time",
")",
")",
"elif",
"isinstance",
"(",
"period_of_ti... | 50.25 | 19.083333 |
def dragDip(self, (x0, y0), (x1, y1), duration, steps=1, orientation=-1):
"""
Sends drag event in DIP (actually it's using C{input swipe} command.
@param (x0, y0): starting point in DIP
@param (x1, y1): ending point in DIP
@param duration: duration of the event in ms
@pa... | [
"def",
"dragDip",
"(",
"self",
",",
"(",
"x0",
",",
"y0",
")",
",",
"(",
"x1",
",",
"y1",
")",
",",
"duration",
",",
"steps",
"=",
"1",
",",
"orientation",
"=",
"-",
"1",
")",
":",
"self",
".",
"__checkTransport",
"(",
")",
"if",
"orientation",
... | 39.315789 | 19.210526 |
def valid_lock(self):
"""
See if the lock exists and is left over from an old process.
"""
lock_pid = self.get_lock_pid()
# If we're unable to get lock_pid
if lock_pid is None:
return False
# this is our process
if self._pid == lock_pid:
... | [
"def",
"valid_lock",
"(",
"self",
")",
":",
"lock_pid",
"=",
"self",
".",
"get_lock_pid",
"(",
")",
"# If we're unable to get lock_pid",
"if",
"lock_pid",
"is",
"None",
":",
"return",
"False",
"# this is our process",
"if",
"self",
".",
"_pid",
"==",
"lock_pid",... | 22.04 | 17.96 |
def get_indic_syllabic_category_property(value, is_bytes=False):
"""Get `INDIC SYLLABIC CATEGORY` property."""
obj = unidata.ascii_indic_syllabic_category if is_bytes else unidata.unicode_indic_syllabic_category
if value.startswith('^'):
negated = value[1:]
value = '^' + unidata.unicode_al... | [
"def",
"get_indic_syllabic_category_property",
"(",
"value",
",",
"is_bytes",
"=",
"False",
")",
":",
"obj",
"=",
"unidata",
".",
"ascii_indic_syllabic_category",
"if",
"is_bytes",
"else",
"unidata",
".",
"unicode_indic_syllabic_category",
"if",
"value",
".",
"startsw... | 39.416667 | 31 |
def save(self, filething=None):
"""Save changes to a file.
If no filename is given, the one most recently loaded is used.
Tags are always written at the end of the file, and include
a header and a footer.
"""
fileobj = filething.fileobj
data = _APEv2Data(fileo... | [
"def",
"save",
"(",
"self",
",",
"filething",
"=",
"None",
")",
":",
"fileobj",
"=",
"filething",
".",
"fileobj",
"data",
"=",
"_APEv2Data",
"(",
"fileobj",
")",
"if",
"data",
".",
"is_at_start",
":",
"delete_bytes",
"(",
"fileobj",
",",
"data",
".",
"... | 32.830508 | 17.355932 |
def get_db_prep_save(self, value, connection=None):
"""
Returns field's value prepared for saving into a database.
"""
## convert to settings.TIME_ZONE
if value is not None:
if value.tzinfo is None:
value = default_tz.localize(value)
else:
... | [
"def",
"get_db_prep_save",
"(",
"self",
",",
"value",
",",
"connection",
"=",
"None",
")",
":",
"## convert to settings.TIME_ZONE",
"if",
"value",
"is",
"not",
"None",
":",
"if",
"value",
".",
"tzinfo",
"is",
"None",
":",
"value",
"=",
"default_tz",
".",
"... | 41.818182 | 14 |
def gen_radio_list(sig_dic):
'''
For generating List view HTML file for RADIO.
for each item.
'''
view_zuoxiang = '''<span class="iga_pd_val">'''
dic_tmp = sig_dic['dic']
for key in dic_tmp.keys():
tmp_str = '''{{% if postinfo.extinfo['{0}'][0] == "{1}" %}} {2} {{% end %}}
'... | [
"def",
"gen_radio_list",
"(",
"sig_dic",
")",
":",
"view_zuoxiang",
"=",
"'''<span class=\"iga_pd_val\">'''",
"dic_tmp",
"=",
"sig_dic",
"[",
"'dic'",
"]",
"for",
"key",
"in",
"dic_tmp",
".",
"keys",
"(",
")",
":",
"tmp_str",
"=",
"'''{{% if postinfo.extinfo['{0}'... | 29.533333 | 20.466667 |
def check_eigen_solver(eigen_solver, solver_kwds, size=None, nvec=None):
"""Check that the selected eigensolver is valid
Parameters
----------
eigen_solver : string
string value to validate
size, nvec : int (optional)
if both provided, use the specified problem size and number of ve... | [
"def",
"check_eigen_solver",
"(",
"eigen_solver",
",",
"solver_kwds",
",",
"size",
"=",
"None",
",",
"nvec",
"=",
"None",
")",
":",
"if",
"eigen_solver",
"in",
"BAD_EIGEN_SOLVERS",
":",
"raise",
"ValueError",
"(",
"BAD_EIGEN_SOLVERS",
"[",
"eigen_solver",
"]",
... | 37.422222 | 17.6 |
def _check_stringify_year_column(self, column_index):
'''
Same as _check_stringify_year_row but for columns.
'''
table_column = TableTranspose(self.table)[column_index]
# State trackers
prior_year = None
for row_index in range(self.start[0]+1, self.end[0]):
... | [
"def",
"_check_stringify_year_column",
"(",
"self",
",",
"column_index",
")",
":",
"table_column",
"=",
"TableTranspose",
"(",
"self",
".",
"table",
")",
"[",
"column_index",
"]",
"# State trackers",
"prior_year",
"=",
"None",
"for",
"row_index",
"in",
"range",
... | 39.352941 | 18.058824 |
def negotiate_forced_aspect(self, options, accepts):
"""Order specified options in function of the specified
accept priorities."""
if not options:
return None
priorities = {}
for i, o in enumerate(options):
p = accepts.get(o, None)
if p is No... | [
"def",
"negotiate_forced_aspect",
"(",
"self",
",",
"options",
",",
"accepts",
")",
":",
"if",
"not",
"options",
":",
"return",
"None",
"priorities",
"=",
"{",
"}",
"for",
"i",
",",
"o",
"in",
"enumerate",
"(",
"options",
")",
":",
"p",
"=",
"accepts",... | 31.181818 | 17.545455 |
def images(self, type):
"""
Return the list of images available for this type on controller
and on the compute node.
"""
images = []
res = yield from self.http_query("GET", "/{}/images".format(type), timeout=None)
images = res.json
try:
if ty... | [
"def",
"images",
"(",
"self",
",",
"type",
")",
":",
"images",
"=",
"[",
"]",
"res",
"=",
"yield",
"from",
"self",
".",
"http_query",
"(",
"\"GET\"",
",",
"\"/{}/images\"",
".",
"format",
"(",
"type",
")",
",",
"timeout",
"=",
"None",
")",
"images",
... | 38.047619 | 22.047619 |
def _get_stack_frame(stacklevel):
"""
utility functions to get a stackframe, skipping internal frames.
"""
stacklevel = stacklevel + 1
if stacklevel <= 1 or _is_internal_frame(sys._getframe(1)):
# If frame is too small to care or if the warning originated in
# internal code, then do ... | [
"def",
"_get_stack_frame",
"(",
"stacklevel",
")",
":",
"stacklevel",
"=",
"stacklevel",
"+",
"1",
"if",
"stacklevel",
"<=",
"1",
"or",
"_is_internal_frame",
"(",
"sys",
".",
"_getframe",
"(",
"1",
")",
")",
":",
"# If frame is too small to care or if the warning ... | 38.352941 | 14.117647 |
def ped_parser(self, family_info):
"""
Parse .ped formatted family info.
Add all family info to the parser object
Arguments:
family_info (iterator): An iterator with family info
"""
for line in family_info:
# Che... | [
"def",
"ped_parser",
"(",
"self",
",",
"family_info",
")",
":",
"for",
"line",
"in",
"family_info",
":",
"# Check if commented line or empty line:",
"if",
"not",
"line",
".",
"startswith",
"(",
"'#'",
")",
"and",
"not",
"all",
"(",
"c",
"in",
"whitespace",
"... | 41.941176 | 19.470588 |
def _get_style_of_faulting_term(self, C, rup):
"""
Get fault type dummy variables
Fault type (Strike-slip, Normal, Thrust/reverse) is
derived from rake angle.
Rakes angles within 30 of horizontal are strike-slip,
angles from 30 to 150 are reverse, and angles from
... | [
"def",
"_get_style_of_faulting_term",
"(",
"self",
",",
"C",
",",
"rup",
")",
":",
"if",
"np",
".",
"abs",
"(",
"rup",
".",
"rake",
")",
"<=",
"30.0",
"or",
"(",
"180.0",
"-",
"np",
".",
"abs",
"(",
"rup",
".",
"rake",
")",
")",
"<=",
"30.0",
"... | 36.15 | 14.35 |
def pattern_to_str(pattern):
"""Convert regex pattern to string.
If pattern is string it returns itself,
if pattern is SRE_Pattern then return pattern attribute
:param pattern: pattern object or string
:return: str: pattern sttring
"""
if isinstance(pattern, str):
return repr(patter... | [
"def",
"pattern_to_str",
"(",
"pattern",
")",
":",
"if",
"isinstance",
"(",
"pattern",
",",
"str",
")",
":",
"return",
"repr",
"(",
"pattern",
")",
"else",
":",
"return",
"repr",
"(",
"pattern",
".",
"pattern",
")",
"if",
"pattern",
"else",
"None"
] | 31.583333 | 12.75 |
def dispatch_hook(key, hooks, hook_data, **kwargs):
"""Dispatches a hook dictionary on a given piece of data."""
hooks = hooks or {}
hooks = hooks.get(key)
if hooks:
if hasattr(hooks, '__call__'):
hooks = [hooks]
for hook in hooks:
_hook_data = hook(hook_data, **k... | [
"def",
"dispatch_hook",
"(",
"key",
",",
"hooks",
",",
"hook_data",
",",
"*",
"*",
"kwargs",
")",
":",
"hooks",
"=",
"hooks",
"or",
"{",
"}",
"hooks",
"=",
"hooks",
".",
"get",
"(",
"key",
")",
"if",
"hooks",
":",
"if",
"hasattr",
"(",
"hooks",
"... | 34.5 | 11 |
async def update_queue(self):
"""
Send waiting jobs to available agents
"""
# For now, round-robin
not_found_for_agent = []
while len(self._available_agents) > 0 and len(self._waiting_jobs) > 0:
agent_addr = self._available_agents.pop(0)
# Find ... | [
"async",
"def",
"update_queue",
"(",
"self",
")",
":",
"# For now, round-robin",
"not_found_for_agent",
"=",
"[",
"]",
"while",
"len",
"(",
"self",
".",
"_available_agents",
")",
">",
"0",
"and",
"len",
"(",
"self",
".",
"_waiting_jobs",
")",
">",
"0",
":"... | 50.026316 | 31.447368 |
def sample(self, input_sample, num_samples, num_params, k_choices,
num_groups):
"""Computes the optimum k_choices of trajectories
from the input_sample.
Arguments
---------
input_sample : numpy.ndarray
num_samples : int
The number of samples to... | [
"def",
"sample",
"(",
"self",
",",
"input_sample",
",",
"num_samples",
",",
"num_params",
",",
"k_choices",
",",
"num_groups",
")",
":",
"return",
"self",
".",
"_strategy",
".",
"sample",
"(",
"input_sample",
",",
"num_samples",
",",
"num_params",
",",
"k_ch... | 31.041667 | 16.375 |
def find(cls, _id):
"""
Returns the individual instance with the given ID, if it exists. Raises
:py:class:`PanoptesAPIException` if the object with that ID is not
found.
"""
if not _id:
return None
try:
return next(cls.where(id=_id))
... | [
"def",
"find",
"(",
"cls",
",",
"_id",
")",
":",
"if",
"not",
"_id",
":",
"return",
"None",
"try",
":",
"return",
"next",
"(",
"cls",
".",
"where",
"(",
"id",
"=",
"_id",
")",
")",
"except",
"StopIteration",
":",
"raise",
"PanoptesAPIException",
"(",... | 30.6 | 20.066667 |
def getEdgeDirected(self, networkId, edgeId, verbose=None):
"""
Returns true if the edge specified by the `edgeId` and `networkId` parameters is directed.
:param networkId: SUID of the network containing the edge
:param edgeId: SUID of the edge
:param verbose: print more
... | [
"def",
"getEdgeDirected",
"(",
"self",
",",
"networkId",
",",
"edgeId",
",",
"verbose",
"=",
"None",
")",
":",
"response",
"=",
"api",
"(",
"url",
"=",
"self",
".",
"___url",
"+",
"'networks/'",
"+",
"str",
"(",
"networkId",
")",
"+",
"'/edges/'",
"+",... | 41.076923 | 27.692308 |
def get_report_data_rows(self, request, queryset):
"""
Using the builders for the queryset model, iterates over the queryset to generate a result
with headers and rows. This queryset must be the exact same received in the .process method,
which tells us that this function should be c... | [
"def",
"get_report_data_rows",
"(",
"self",
",",
"request",
",",
"queryset",
")",
":",
"model",
"=",
"queryset",
".",
"model",
"meta",
"=",
"model",
".",
"_meta",
"field_names",
"=",
"set",
"(",
"field",
".",
"name",
"for",
"field",
"in",
"meta",
".",
... | 47.909091 | 25.727273 |
def configuration_file(cfgfile):
'''Find the best match for the configuration file.
'''
if cfgfile is not None:
return cfgfile
# If no file is explicitely specified, probe for the configuration file
# location.
cfg = './etc/pyca.conf'
if not os.path.isfile(cfg):
return '/etc/... | [
"def",
"configuration_file",
"(",
"cfgfile",
")",
":",
"if",
"cfgfile",
"is",
"not",
"None",
":",
"return",
"cfgfile",
"# If no file is explicitely specified, probe for the configuration file",
"# location.",
"cfg",
"=",
"'./etc/pyca.conf'",
"if",
"not",
"os",
".",
"pat... | 30.454545 | 18.454545 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.