text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def transFringe(beta=None, rho=None):
""" Transport matrix of fringe field
:param beta: angle of rotation of pole-face in [RAD]
:param rho: bending radius in [m]
:return: 6x6 numpy array
"""
m = np.eye(6, 6, dtype=np.float64)
if None in (beta, rho):
print("warning: 'theta', 'rho' sh... | [
"def",
"transFringe",
"(",
"beta",
"=",
"None",
",",
"rho",
"=",
"None",
")",
":",
"m",
"=",
"np",
".",
"eye",
"(",
"6",
",",
"6",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
"if",
"None",
"in",
"(",
"beta",
",",
"rho",
")",
":",
"print",
... | 30.533333 | 0.002119 |
def get_tables(self, models):
'''
Extract all peewee models from the passed in module
'''
return { obj._meta.db_table : obj for obj in
models.__dict__.itervalues() if
isinstance(obj, peewee.BaseModel) and
len(obj._meta.fields) > 1
... | [
"def",
"get_tables",
"(",
"self",
",",
"models",
")",
":",
"return",
"{",
"obj",
".",
"_meta",
".",
"db_table",
":",
"obj",
"for",
"obj",
"in",
"models",
".",
"__dict__",
".",
"itervalues",
"(",
")",
"if",
"isinstance",
"(",
"obj",
",",
"peewee",
"."... | 35.111111 | 0.024691 |
def identical(self, a, b):
"""
This should return whether `a` is identical to `b`. Of course, this isn't always clear. True should mean that it
is definitely identical. False eans that, conservatively, it might not be.
:param a: an AST
:param b: another AST
"""
r... | [
"def",
"identical",
"(",
"self",
",",
"a",
",",
"b",
")",
":",
"return",
"self",
".",
"_identical",
"(",
"self",
".",
"convert",
"(",
"a",
")",
",",
"self",
".",
"convert",
"(",
"b",
")",
")"
] | 40.777778 | 0.010667 |
def load_object(self, obj=None):
"Add the object and all their childs"
# if not obj is given, do a full reload using the current root
if obj:
self.root_obj = obj
else:
obj = self.root_obj
self.tree.DeleteAllItems()
self.root = self.tree.AddRoot("ap... | [
"def",
"load_object",
"(",
"self",
",",
"obj",
"=",
"None",
")",
":",
"# if not obj is given, do a full reload using the current root",
"if",
"obj",
":",
"self",
".",
"root_obj",
"=",
"obj",
"else",
":",
"obj",
"=",
"self",
".",
"root_obj",
"self",
".",
"tree"... | 42.25 | 0.008683 |
def music_comment(id, offset=0, limit=20):
"""获取歌曲的评论列表
:param id: 歌曲 ID
:param offset: (optional) 分段起始位置,默认 0
:param limit: (optional) 数据上限多少行,默认 20
"""
if id is None:
raise ParamsError()
r = NCloudBot()
r.method = 'MUSIC_COMMENT'
r.params = {'id': id}
r.data = {'offset... | [
"def",
"music_comment",
"(",
"id",
",",
"offset",
"=",
"0",
",",
"limit",
"=",
"20",
")",
":",
"if",
"id",
"is",
"None",
":",
"raise",
"ParamsError",
"(",
")",
"r",
"=",
"NCloudBot",
"(",
")",
"r",
".",
"method",
"=",
"'MUSIC_COMMENT'",
"r",
".",
... | 24.75 | 0.002433 |
def _pot_quat(self):
"""Returns the orientation of the pot."""
return T.convert_quat(self.sim.data.body_xquat[self.cube_body_id], to="xyzw") | [
"def",
"_pot_quat",
"(",
"self",
")",
":",
"return",
"T",
".",
"convert_quat",
"(",
"self",
".",
"sim",
".",
"data",
".",
"body_xquat",
"[",
"self",
".",
"cube_body_id",
"]",
",",
"to",
"=",
"\"xyzw\"",
")"
] | 51.333333 | 0.019231 |
def on_backspace_binding_changed(self, combo):
"""Changes the value of compat_backspace in dconf
"""
val = combo.get_active_text()
self.settings.general.set_string('compat-backspace', ERASE_BINDINGS[val]) | [
"def",
"on_backspace_binding_changed",
"(",
"self",
",",
"combo",
")",
":",
"val",
"=",
"combo",
".",
"get_active_text",
"(",
")",
"self",
".",
"settings",
".",
"general",
".",
"set_string",
"(",
"'compat-backspace'",
",",
"ERASE_BINDINGS",
"[",
"val",
"]",
... | 46.4 | 0.012712 |
def first(self):
"""Return the first result. If there are no results, raises :exc:`~bloop.exceptions.ConstraintViolation`.
:return: The first result.
:raises bloop.exceptions.ConstraintViolation: No results.
"""
self.reset()
value = next(self, None)
if value is ... | [
"def",
"first",
"(",
"self",
")",
":",
"self",
".",
"reset",
"(",
")",
"value",
"=",
"next",
"(",
"self",
",",
"None",
")",
"if",
"value",
"is",
"None",
":",
"raise",
"ConstraintViolation",
"(",
"\"{} did not find any results.\"",
".",
"format",
"(",
"se... | 39.727273 | 0.008949 |
def hyphenate_word(self, word):
""" Given a word, returns a list of pieces, broken at the possible
hyphenation points.
"""
# Short words aren't hyphenated.
if len(word) <= 4:
return [word]
# If the word is an exception, get the stored points.
if wo... | [
"def",
"hyphenate_word",
"(",
"self",
",",
"word",
")",
":",
"# Short words aren't hyphenated.",
"if",
"len",
"(",
"word",
")",
"<=",
"4",
":",
"return",
"[",
"word",
"]",
"# If the word is an exception, get the stored points.",
"if",
"word",
".",
"lower",
"(",
... | 36.647059 | 0.001564 |
def wrap_ufunc_productspace(name, n_in, n_out, doc):
"""Return ufunc wrapper for `ProductSpaceUfuncs`."""
if n_in == 1:
if n_out == 1:
def wrapper(self, out=None, **kwargs):
if out is None:
result = [getattr(x.ufuncs, name)(**kwargs)
... | [
"def",
"wrap_ufunc_productspace",
"(",
"name",
",",
"n_in",
",",
"n_out",
",",
"doc",
")",
":",
"if",
"n_in",
"==",
"1",
":",
"if",
"n_out",
"==",
"1",
":",
"def",
"wrapper",
"(",
"self",
",",
"out",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":"... | 39.508772 | 0.000433 |
def check_initial_subdomain(cls, subdomain_rec):
"""
Verify that a first-ever subdomain record is well-formed.
* n must be 0
* the subdomain must not be independent of its domain
"""
if subdomain_rec.n != 0:
return False
if subdomain_rec.indepe... | [
"def",
"check_initial_subdomain",
"(",
"cls",
",",
"subdomain_rec",
")",
":",
"if",
"subdomain_rec",
".",
"n",
"!=",
"0",
":",
"return",
"False",
"if",
"subdomain_rec",
".",
"independent",
":",
"return",
"False",
"return",
"True"
] | 27.692308 | 0.008065 |
def mostDeviant(requestContext, seriesList, n):
"""
Takes one metric or a wildcard seriesList followed by an integer N.
Draws the N most deviant metrics.
To find the deviants, the standard deviation (sigma) of each series
is taken and ranked. The top N standard deviations are returned.
Example:... | [
"def",
"mostDeviant",
"(",
"requestContext",
",",
"seriesList",
",",
"n",
")",
":",
"deviants",
"=",
"[",
"]",
"for",
"series",
"in",
"seriesList",
":",
"mean",
"=",
"safeAvg",
"(",
"series",
")",
"if",
"mean",
"is",
"None",
":",
"continue",
"square_sum"... | 36.178571 | 0.000962 |
def _deserialize_primitive(data, klass):
"""Deserializes to primitive type.
:param data: data to deserialize.
:param klass: class literal.
:return: int, long, float, str, bool.
:rtype: int | long | float | str | bool
"""
try:
value = klass(data)
except UnicodeEncodeError:
... | [
"def",
"_deserialize_primitive",
"(",
"data",
",",
"klass",
")",
":",
"try",
":",
"value",
"=",
"klass",
"(",
"data",
")",
"except",
"UnicodeEncodeError",
":",
"value",
"=",
"six",
".",
"u",
"(",
"data",
")",
"except",
"TypeError",
":",
"value",
"=",
"... | 24.1875 | 0.002488 |
def set_range(self, x=None, y=None, z=None, margin=0.05):
""" Set the range of the view region for the camera
Parameters
----------
x : tuple | None
X range.
y : tuple | None
Y range.
z : tuple | None
Z range.
margin : float
... | [
"def",
"set_range",
"(",
"self",
",",
"x",
"=",
"None",
",",
"y",
"=",
"None",
",",
"z",
"=",
"None",
",",
"margin",
"=",
"0.05",
")",
":",
"# Flag to indicate that this is an initializing (not user-invoked)",
"init",
"=",
"self",
".",
"_xlim",
"is",
"None",... | 35.029851 | 0.001243 |
def from_soup(self,soup):
"""
Factory Pattern. Fetches author data from given soup and builds the object
"""
if soup is None or soup is '':
return None
else:
author_name = soup.find('em').contents[0].strip() if soup.find('em') else ''
author_image = soup.find('img').get('src') if soup.find('img') ... | [
"def",
"from_soup",
"(",
"self",
",",
"soup",
")",
":",
"if",
"soup",
"is",
"None",
"or",
"soup",
"is",
"''",
":",
"return",
"None",
"else",
":",
"author_name",
"=",
"soup",
".",
"find",
"(",
"'em'",
")",
".",
"contents",
"[",
"0",
"]",
".",
"str... | 38.545455 | 0.041475 |
def remove_annotations(self, remove_sequence):
"""
Removes several annotations from this AST.
:param remove_sequence: a sequence/set of the annotations to remove
:returns: a new AST, with the annotations removed
"""
return self._apply_to_annotations(lambda alist: tuple(o... | [
"def",
"remove_annotations",
"(",
"self",
",",
"remove_sequence",
")",
":",
"return",
"self",
".",
"_apply_to_annotations",
"(",
"lambda",
"alist",
":",
"tuple",
"(",
"oa",
"for",
"oa",
"in",
"alist",
"if",
"oa",
"not",
"in",
"remove_sequence",
")",
")"
] | 45.125 | 0.008152 |
def set_title(self, title, **kwargs):
"""Sets the title on the underlying matplotlib AxesSubplot."""
ax = self.get_axes()
ax.set_title(title, **kwargs) | [
"def",
"set_title",
"(",
"self",
",",
"title",
",",
"*",
"*",
"kwargs",
")",
":",
"ax",
"=",
"self",
".",
"get_axes",
"(",
")",
"ax",
".",
"set_title",
"(",
"title",
",",
"*",
"*",
"kwargs",
")"
] | 43 | 0.011429 |
def resolution(self, channels=None):
"""
Get the resolution of the specified channel(s).
The resolution specifies the number of different values that the
events can take. The resolution is directly obtained from the $PnR
parameter.
Parameters
----------
... | [
"def",
"resolution",
"(",
"self",
",",
"channels",
"=",
"None",
")",
":",
"# Check default",
"if",
"channels",
"is",
"None",
":",
"channels",
"=",
"self",
".",
"_channels",
"# Get numerical indices of channels",
"channels",
"=",
"self",
".",
"_name_to_index",
"(... | 32.323529 | 0.001767 |
def get_temp_filename (content):
"""Get temporary filename for content to parse."""
# store content in temporary file
fd, filename = fileutil.get_temp_file(mode='wb', suffix='.doc',
prefix='lc_')
try:
fd.write(content)
finally:
fd.close()
return filename | [
"def",
"get_temp_filename",
"(",
"content",
")",
":",
"# store content in temporary file",
"fd",
",",
"filename",
"=",
"fileutil",
".",
"get_temp_file",
"(",
"mode",
"=",
"'wb'",
",",
"suffix",
"=",
"'.doc'",
",",
"prefix",
"=",
"'lc_'",
")",
"try",
":",
"fd... | 29.3 | 0.009934 |
def registerDirectory(self,name,physicalPath,directoryType,cleanupMode,
maxFileAge,description):
"""
Registers a new server directory. While registering the server directory,
you can also specify the directory's cleanup parameters. You can also
register a direct... | [
"def",
"registerDirectory",
"(",
"self",
",",
"name",
",",
"physicalPath",
",",
"directoryType",
",",
"cleanupMode",
",",
"maxFileAge",
",",
"description",
")",
":",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/directories/register\"",
"params",
"=",
"{",
"\"f\""... | 44.314286 | 0.010095 |
def to_keep(datetimes,
years=0, months=0, weeks=0, days=0,
hours=0, minutes=0, seconds=0,
firstweekday=SATURDAY, now=None):
"""
Return a set of datetimes that should be kept, out of ``datetimes``.
Keeps up to ``years``, ``months``, ``weeks``, ``days``,
``hours``, ``m... | [
"def",
"to_keep",
"(",
"datetimes",
",",
"years",
"=",
"0",
",",
"months",
"=",
"0",
",",
"weeks",
"=",
"0",
",",
"days",
"=",
"0",
",",
"hours",
"=",
"0",
",",
"minutes",
"=",
"0",
",",
"seconds",
"=",
"0",
",",
"firstweekday",
"=",
"SATURDAY",
... | 44.576923 | 0.000845 |
def callproc(self, procname, args=()):
"""Execute stored procedure procname with args
procname -- string, name of procedure to execute on server
args -- Sequence of parameters to use with procedure
Returns the original args.
Compatibility warning: PEP-249 specifies that any m... | [
"def",
"callproc",
"(",
"self",
",",
"procname",
",",
"args",
"=",
"(",
")",
")",
":",
"conn",
"=",
"self",
".",
"_get_db",
"(",
")",
"if",
"args",
":",
"fmt",
"=",
"'@_{0}_%d=%s'",
".",
"format",
"(",
"procname",
")",
"self",
".",
"_query",
"(",
... | 45.146341 | 0.001058 |
def cartesian(arrays, out=None):
"""Generate a cartesian product of input arrays.
Parameters
----------
arrays : list of array-like
1-D arrays to form the cartesian product of.
out : ndarray
Array to place the cartesian product in.
Returns
-------
out : ndarray
... | [
"def",
"cartesian",
"(",
"arrays",
",",
"out",
"=",
"None",
")",
":",
"arrays",
"=",
"[",
"np",
".",
"asarray",
"(",
"x",
")",
"for",
"x",
"in",
"arrays",
"]",
"shape",
"=",
"(",
"len",
"(",
"x",
")",
"for",
"x",
"in",
"arrays",
")",
"dtype",
... | 22.468085 | 0.000907 |
def common_cli_output_options(f):
"""Add common CLI output options to commands."""
@click.option(
"-d",
"--debug",
default=False,
is_flag=True,
help="Produce debug output during processing.",
)
@click.option(
"-F",
"--output-format",
defau... | [
"def",
"common_cli_output_options",
"(",
"f",
")",
":",
"@",
"click",
".",
"option",
"(",
"\"-d\"",
",",
"\"--debug\"",
",",
"default",
"=",
"False",
",",
"is_flag",
"=",
"True",
",",
"help",
"=",
"\"Produce debug output during processing.\"",
",",
")",
"@",
... | 29.108108 | 0.000898 |
def run(self, start_point=None, stop_before=None, stop_after=None):
"""
Run the pipeline, optionally specifying start and/or stop points.
:param str start_point: Name of stage at which to begin execution.
:param str stop_before: Name of stage at which to cease execution;
exc... | [
"def",
"run",
"(",
"self",
",",
"start_point",
"=",
"None",
",",
"stop_before",
"=",
"None",
",",
"stop_after",
"=",
"None",
")",
":",
"# Start the run with a clean slate of Stage status/label tracking.",
"self",
".",
"_reset",
"(",
")",
"# TODO: validate starting poi... | 43.096154 | 0.000436 |
def nlms(u, d, M, step, eps=0.001, leak=0, initCoeffs=None, N=None,
returnCoeffs=False):
"""
Perform normalized least-mean-squares (NLMS) adaptive filtering on u to
minimize error given by e=d-y, where y is the output of the adaptive
filter.
Parameters
----------
u : array-like
... | [
"def",
"nlms",
"(",
"u",
",",
"d",
",",
"M",
",",
"step",
",",
"eps",
"=",
"0.001",
",",
"leak",
"=",
"0",
",",
"initCoeffs",
"=",
"None",
",",
"N",
"=",
"None",
",",
"returnCoeffs",
"=",
"False",
")",
":",
"# Check epsilon",
"_pchk",
".",
"check... | 31.5 | 0.000205 |
def crypto_secretstream_xchacha20poly1305_pull(state, c, ad=None):
"""
Read a decrypted message from the secret stream.
:param state: a secretstream state object
:type state: crypto_secretstream_xchacha20poly1305_state
:param c: the ciphertext to decrypt, the maximum length of an individual
... | [
"def",
"crypto_secretstream_xchacha20poly1305_pull",
"(",
"state",
",",
"c",
",",
"ad",
"=",
"None",
")",
":",
"ensure",
"(",
"isinstance",
"(",
"state",
",",
"crypto_secretstream_xchacha20poly1305_state",
")",
",",
"'State must be a crypto_secretstream_xchacha20poly1305_st... | 30.310811 | 0.000432 |
def save(self, filename=None, tc=None):
""" Write this workflow to DAX file
"""
if filename is None:
filename = self.filename
for sub in self.sub_workflows:
sub.save()
# FIXME this is ugly as pegasus 4.9.0 does not support the full
# transformati... | [
"def",
"save",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"tc",
"=",
"None",
")",
":",
"if",
"filename",
"is",
"None",
":",
"filename",
"=",
"self",
".",
"filename",
"for",
"sub",
"in",
"self",
".",
"sub_workflows",
":",
"sub",
".",
"save",
"(... | 33.578947 | 0.002285 |
def free(self):
"""Free the map"""
if self._ptr is None:
return
Gauged.map_free(self.ptr)
SparseMap.ALLOCATIONS -= 1
self._ptr = None | [
"def",
"free",
"(",
"self",
")",
":",
"if",
"self",
".",
"_ptr",
"is",
"None",
":",
"return",
"Gauged",
".",
"map_free",
"(",
"self",
".",
"ptr",
")",
"SparseMap",
".",
"ALLOCATIONS",
"-=",
"1",
"self",
".",
"_ptr",
"=",
"None"
] | 25.571429 | 0.010811 |
def delete(self):
""" Deletes one instance """
if self.instance is None:
raise CQLEngineException("DML Query instance attribute is None")
ds = DeleteStatement(self.column_family_name, timestamp=self._timestamp)
for name, col in self.model._primary_keys.items():
i... | [
"def",
"delete",
"(",
"self",
")",
":",
"if",
"self",
".",
"instance",
"is",
"None",
":",
"raise",
"CQLEngineException",
"(",
"\"DML Query instance attribute is None\"",
")",
"ds",
"=",
"DeleteStatement",
"(",
"self",
".",
"column_family_name",
",",
"timestamp",
... | 43 | 0.00813 |
def symmetric_sqrt(x, out=None):
"""Compute the 'symmetric' square root: sign(x) * sqrt(abs(x)).
Parameters
----------
x : array_like or number
Input array.
out : ndarray, None, or tuple of ndarray and None (optional)
A location into which the result is stored. If provided, it must
... | [
"def",
"symmetric_sqrt",
"(",
"x",
",",
"out",
"=",
"None",
")",
":",
"factor",
"=",
"np",
".",
"sign",
"(",
"x",
")",
"out",
"=",
"np",
".",
"sqrt",
"(",
"np",
".",
"abs",
"(",
"x",
")",
",",
"out",
"=",
"out",
")",
"return",
"out",
"*",
"... | 33.190476 | 0.001395 |
def make_shell_endpoint(topologyInfo, instance_id):
"""
Makes the http endpoint for the heron shell
if shell port is present, otherwise returns None.
"""
# Format: container_<id>_<instance_id>
pplan = topologyInfo["physical_plan"]
stmgrId = pplan["instances"][instance_id]["stmgrId"]
host = pplan["stmgrs... | [
"def",
"make_shell_endpoint",
"(",
"topologyInfo",
",",
"instance_id",
")",
":",
"# Format: container_<id>_<instance_id>",
"pplan",
"=",
"topologyInfo",
"[",
"\"physical_plan\"",
"]",
"stmgrId",
"=",
"pplan",
"[",
"\"instances\"",
"]",
"[",
"instance_id",
"]",
"[",
... | 38.909091 | 0.018265 |
def render(template_file, saltenv='base', sls='', context=None, tmplpath=None, **kws):
'''
Render the template_file, passing the functions and grains into the
Mako rendering system.
:rtype: string
'''
tmp_data = salt.utils.templates.MAKO(template_file, to_str=True,
salt=__sa... | [
"def",
"render",
"(",
"template_file",
",",
"saltenv",
"=",
"'base'",
",",
"sls",
"=",
"''",
",",
"context",
"=",
"None",
",",
"tmplpath",
"=",
"None",
",",
"*",
"*",
"kws",
")",
":",
"tmp_data",
"=",
"salt",
".",
"utils",
".",
"templates",
".",
"M... | 37.238095 | 0.014963 |
def first(self, cascadeFetch=False):
'''
First - Returns the oldest record (lowerst primary key) with current filters.
This makes an efficient queue, as it only fetches a single object.
@param cascadeFetch <bool> Default False, If True, all Foreign objects associated with this model
will be fetche... | [
"def",
"first",
"(",
"self",
",",
"cascadeFetch",
"=",
"False",
")",
":",
"obj",
"=",
"None",
"matchedKeys",
"=",
"self",
".",
"getPrimaryKeys",
"(",
"sortByAge",
"=",
"True",
")",
"if",
"matchedKeys",
":",
"# Loop so we don't return None when there are items, if ... | 38.45 | 0.030457 |
def load_smc_file(cls, filename):
"""Read an SMC formatted time series.
Format of the time series is provided by:
https://escweb.wr.usgs.gov/nsmp-data/smcfmt.html
Parameters
----------
filename: str
Filename to open.
"""
from .tools impo... | [
"def",
"load_smc_file",
"(",
"cls",
",",
"filename",
")",
":",
"from",
".",
"tools",
"import",
"parse_fixed_width",
"with",
"open",
"(",
"filename",
")",
"as",
"fp",
":",
"lines",
"=",
"list",
"(",
"fp",
")",
"# 11 lines of strings",
"lines_str",
"=",
"[",... | 31.555556 | 0.001366 |
def stop(self):
"""Gracefully shutdown a server that is serving forever."""
self.ready = False
if self._start_time is not None:
self._run_time += (time.time() - self._start_time)
self._start_time = None
sock = getattr(self, 'socket', None)
if sock:
... | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"ready",
"=",
"False",
"if",
"self",
".",
"_start_time",
"is",
"not",
"None",
":",
"self",
".",
"_run_time",
"+=",
"(",
"time",
".",
"time",
"(",
")",
"-",
"self",
".",
"_start_time",
")",
"self",
... | 44.826087 | 0.000949 |
def global_request(self, kind, data=None, wait=True):
"""
Make a global request to the remote host. These are normally
extensions to the SSH2 protocol.
:param str kind: name of the request.
:param tuple data:
an optional tuple containing additional data to attach to... | [
"def",
"global_request",
"(",
"self",
",",
"kind",
",",
"data",
"=",
"None",
",",
"wait",
"=",
"True",
")",
":",
"if",
"wait",
":",
"self",
".",
"completion_event",
"=",
"threading",
".",
"Event",
"(",
")",
"m",
"=",
"Message",
"(",
")",
"m",
".",
... | 36.055556 | 0.0015 |
def add_base(self):
""" add "base" control file values as a realization
"""
if "base" in self.index:
raise Exception("'base' already in index")
self.loc["base",:] = self.pst.observation_data.loc[self.columns,"obsval"] | [
"def",
"add_base",
"(",
"self",
")",
":",
"if",
"\"base\"",
"in",
"self",
".",
"index",
":",
"raise",
"Exception",
"(",
"\"'base' already in index\"",
")",
"self",
".",
"loc",
"[",
"\"base\"",
",",
":",
"]",
"=",
"self",
".",
"pst",
".",
"observation_dat... | 36.571429 | 0.019084 |
def option_descriptions(operation):
""" Extract parameter help from docstring of the command. """
lines = inspect.getdoc(operation)
if not lines:
return {}
param_breaks = ["'''", '"""', ':param', ':type', ':return', ':rtype']
option_descs = {}
lines = lines.splitlines()
index = 0
... | [
"def",
"option_descriptions",
"(",
"operation",
")",
":",
"lines",
"=",
"inspect",
".",
"getdoc",
"(",
"operation",
")",
"if",
"not",
"lines",
":",
"return",
"{",
"}",
"param_breaks",
"=",
"[",
"\"'''\"",
",",
"'\"\"\"'",
",",
"':param'",
",",
"':type'",
... | 28.756757 | 0.001818 |
def show_text(self, text):
"""A drawing operator that generates the shape from a string text,
rendered according to the current
font :meth:`face <set_font_face>`,
font :meth:`size <set_font_size>`
(font :meth:`matrix <set_font_matrix>`),
and font :meth:`options <set_font_... | [
"def",
"show_text",
"(",
"self",
",",
"text",
")",
":",
"cairo",
".",
"cairo_show_text",
"(",
"self",
".",
"_pointer",
",",
"_encode_string",
"(",
"text",
")",
")",
"self",
".",
"_check_status",
"(",
")"
] | 41.945946 | 0.001259 |
def _set_channels(self):
"""Sets the main channels for the pipeline
This method will parse de the :attr:`~Process.processes` attribute
and perform the following tasks for each process:
- Sets the input/output channels and main input forks and adds
them to the process'... | [
"def",
"_set_channels",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"\"=====================\"",
")",
"logger",
".",
"debug",
"(",
"\"Setting main channels\"",
")",
"logger",
".",
"debug",
"(",
"\"=====================\"",
")",
"for",
"i",
",",
"p",
"i... | 42.960784 | 0.001339 |
def as_steam3(self):
"""
:return: steam3 format (e.g ``[U:1:1234]``)
:rtype: :class:`str`
"""
typechar = str(ETypeChar(self.type))
instance = None
if self.type in (EType.AnonGameServer, EType.Multiseat):
instance = self.instance
elif self.type... | [
"def",
"as_steam3",
"(",
"self",
")",
":",
"typechar",
"=",
"str",
"(",
"ETypeChar",
"(",
"self",
".",
"type",
")",
")",
"instance",
"=",
"None",
"if",
"self",
".",
"type",
"in",
"(",
"EType",
".",
"AnonGameServer",
",",
"EType",
".",
"Multiseat",
")... | 30.518519 | 0.002353 |
def get_template_names(self):
"""
datagrid的默认模板
"""
names = super(CommandDatagridView, self).get_template_names()
names.append('easyui/command_datagrid.html')
return names | [
"def",
"get_template_names",
"(",
"self",
")",
":",
"names",
"=",
"super",
"(",
"CommandDatagridView",
",",
"self",
")",
".",
"get_template_names",
"(",
")",
"names",
".",
"append",
"(",
"'easyui/command_datagrid.html'",
")",
"return",
"names"
] | 30.428571 | 0.009132 |
def daemon_start(self):
"""Start daemon when gtk loaded
"""
if daemon_status() == "SUN not running":
subprocess.call("{0} &".format(self.cmd), shell=True) | [
"def",
"daemon_start",
"(",
"self",
")",
":",
"if",
"daemon_status",
"(",
")",
"==",
"\"SUN not running\"",
":",
"subprocess",
".",
"call",
"(",
"\"{0} &\"",
".",
"format",
"(",
"self",
".",
"cmd",
")",
",",
"shell",
"=",
"True",
")"
] | 37.2 | 0.010526 |
def to_html(self, wrap_slash=False):
"""Render a Text MessageElement as html.
:param wrap_slash: Whether to replace slashes with the slash plus the
html <wbr> tag which will help to e.g. wrap html in small cells if
it contains a long filename. Disabled by default as it may cause... | [
"def",
"to_html",
"(",
"self",
",",
"wrap_slash",
"=",
"False",
")",
":",
"if",
"self",
".",
"text",
"is",
"None",
":",
"return",
"else",
":",
"text",
"=",
"''",
"for",
"t",
"in",
"self",
".",
"text",
":",
"text",
"+=",
"t",
".",
"to_html",
"(",
... | 36.2 | 0.002153 |
def lookup_whois(self, hr=True, show_name=False, colorize=True, **kwargs):
"""
The function for wrapping IPWhois.lookup_whois() and generating
formatted CLI output.
Args:
hr (:obj:`bool`): Enable human readable key translations. Defaults
to True.
... | [
"def",
"lookup_whois",
"(",
"self",
",",
"hr",
"=",
"True",
",",
"show_name",
"=",
"False",
",",
"colorize",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"# Perform the RDAP lookup",
"ret",
"=",
"self",
".",
"obj",
".",
"lookup_whois",
"(",
"*",
"*"... | 33.172414 | 0.00101 |
def commands(config, names):
"""Return the list of commands to run."""
commands = {cmd: Command(**dict((minus_to_underscore(k), v)
for k, v in config.items(cmd)))
for cmd in config.sections()
if cmd != 'packages'}
try:
return tuple(... | [
"def",
"commands",
"(",
"config",
",",
"names",
")",
":",
"commands",
"=",
"{",
"cmd",
":",
"Command",
"(",
"*",
"*",
"dict",
"(",
"(",
"minus_to_underscore",
"(",
"k",
")",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"config",
".",
"items",
"(",
... | 44.333333 | 0.001842 |
def sync(self, rules: list):
"""
Synchronizes the given ruleset with the
one on the server and adds the not yet
existing rules to the server.
:type rules: collections.Iterable[Rule]
"""
self.client = self.connect()
try:
server_rules = set(self.... | [
"def",
"sync",
"(",
"self",
",",
"rules",
":",
"list",
")",
":",
"self",
".",
"client",
"=",
"self",
".",
"connect",
"(",
")",
"try",
":",
"server_rules",
"=",
"set",
"(",
"self",
".",
"server_rules",
")",
"rules",
"=",
"set",
"(",
"rules",
")",
... | 36.2 | 0.001537 |
def do_notification_update(mc, args):
'''Update notification.'''
fields = {}
fields['notification_id'] = args.id
fields['name'] = args.name
fields['type'] = args.type
fields['address'] = args.address
if not _validate_notification_period(args.period, args.type.upper()):
return
fi... | [
"def",
"do_notification_update",
"(",
"mc",
",",
"args",
")",
":",
"fields",
"=",
"{",
"}",
"fields",
"[",
"'notification_id'",
"]",
"=",
"args",
".",
"id",
"fields",
"[",
"'name'",
"]",
"=",
"args",
".",
"name",
"fields",
"[",
"'type'",
"]",
"=",
"a... | 35.058824 | 0.001634 |
def get_sub_node(dsp, path, node_attr='auto', solution=NONE, _level=0,
_dsp_name=NONE):
"""
Returns a sub node of a dispatcher.
:param dsp:
A dispatcher object or a sub dispatch function.
:type dsp: schedula.Dispatcher | SubDispatch
:param path:
A sequence of node... | [
"def",
"get_sub_node",
"(",
"dsp",
",",
"path",
",",
"node_attr",
"=",
"'auto'",
",",
"solution",
"=",
"NONE",
",",
"_level",
"=",
"0",
",",
"_dsp_name",
"=",
"NONE",
")",
":",
"path",
"=",
"list",
"(",
"path",
")",
"if",
"isinstance",
"(",
"dsp",
... | 32.7875 | 0.000185 |
def epost(database, ids: List[str], webenv=False, api_key=False, email=False, **kwargs) -> Optional[EpostResult]:
"""Post IDs using the Entrez ESearch API.
Parameters
----------
database : str
Entez database to search.
ids : list
List of IDs to submit to the server.
webenv : str... | [
"def",
"epost",
"(",
"database",
",",
"ids",
":",
"List",
"[",
"str",
"]",
",",
"webenv",
"=",
"False",
",",
"api_key",
"=",
"False",
",",
"email",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
"->",
"Optional",
"[",
"EpostResult",
"]",
":",
"url",
... | 30.533333 | 0.002116 |
def exciterInit(self, Xexc, Vexc):
""" Based on ExciterInit.m from MatDyn by Stijn Cole, developed at
Katholieke Universiteit Leuven. See U{http://www.esat.kuleuven.be/
electa/teaching/matdyn/} for more information.
@rtype: tuple
@return: Exciter initial conditions.
"""
... | [
"def",
"exciterInit",
"(",
"self",
",",
"Xexc",
",",
"Vexc",
")",
":",
"exciters",
"=",
"self",
".",
"exciters",
"Xexc0",
"=",
"zeros",
"(",
"Xexc",
".",
"shape",
")",
"Pexc0",
"=",
"zeros",
"(",
"len",
"(",
"exciters",
")",
")",
"typ1",
"=",
"[",
... | 32.02 | 0.001818 |
def _updatePolicyElements(policy_item, regkey):
'''
helper function to add the reg key to each policies element definitions if
the key attribute is not defined to make xpath searching easier for each
child in the policy <elements> item
'''
for child in policy_item.getiterator():
if 'valu... | [
"def",
"_updatePolicyElements",
"(",
"policy_item",
",",
"regkey",
")",
":",
"for",
"child",
"in",
"policy_item",
".",
"getiterator",
"(",
")",
":",
"if",
"'valueName'",
"in",
"child",
".",
"attrib",
":",
"if",
"'key'",
"not",
"in",
"child",
".",
"attrib",... | 40.272727 | 0.002208 |
def iter_subnets(self, prefixlen_diff=1, new_prefix=None):
"""The subnets which join to make the current subnet.
In the case that self contains only one IP
(self._prefixlen == 32 for IPv4 or self._prefixlen == 128
for IPv6), return a list with just ourself.
Args:
pr... | [
"def",
"iter_subnets",
"(",
"self",
",",
"prefixlen_diff",
"=",
"1",
",",
"new_prefix",
"=",
"None",
")",
":",
"if",
"self",
".",
"_prefixlen",
"==",
"self",
".",
"_max_prefixlen",
":",
"yield",
"self",
"return",
"if",
"new_prefix",
"is",
"not",
"None",
... | 38.311475 | 0.001252 |
def to_dict(self):
"""
Return dict representation of service to embed in DID document.
"""
rv = {
'id': self.id,
'type': self.type,
'priority': self.priority
}
if self.recip_keys:
rv['routingKeys'] = [canon_ref(k.did, k.id,... | [
"def",
"to_dict",
"(",
"self",
")",
":",
"rv",
"=",
"{",
"'id'",
":",
"self",
".",
"id",
",",
"'type'",
":",
"self",
".",
"type",
",",
"'priority'",
":",
"self",
".",
"priority",
"}",
"if",
"self",
".",
"recip_keys",
":",
"rv",
"[",
"'routingKeys'"... | 30.588235 | 0.009328 |
def readAlignedString(self, align = 4):
"""
Reads an ASCII string aligned to the next align-bytes boundary.
@type align: int
@param align: (Optional) The value we want the ASCII string to be aligned.
@rtype: str
@return: A 4-bytes aligned (default) ASCI... | [
"def",
"readAlignedString",
"(",
"self",
",",
"align",
"=",
"4",
")",
":",
"s",
"=",
"self",
".",
"readString",
"(",
")",
"r",
"=",
"align",
"-",
"len",
"(",
"s",
")",
"%",
"align",
"while",
"r",
":",
"s",
"+=",
"self",
".",
"data",
"[",
"self"... | 31 | 0.014733 |
def largest_connected_submatrix(C, directed=True, lcc=None):
r"""Compute the count matrix on the largest connected set.
Parameters
----------
C : scipy.sparse matrix
Count matrix specifying edge weights.
directed : bool, optional
Whether to compute connected components for a directed... | [
"def",
"largest_connected_submatrix",
"(",
"C",
",",
"directed",
"=",
"True",
",",
"lcc",
"=",
"None",
")",
":",
"if",
"isdense",
"(",
"C",
")",
":",
"return",
"sparse",
".",
"connectivity",
".",
"largest_connected_submatrix",
"(",
"csr_matrix",
"(",
"C",
... | 30.576271 | 0.001611 |
def keyPressEvent( self, event ):
"""
Overloads the keyPressEvent method to support backtab operations.
:param event | <QKeyPressEvent>
"""
if ( event.key() == Qt.Key_Backtab ):
self.unindentSelection()
else:
super(XScintilla... | [
"def",
"keyPressEvent",
"(",
"self",
",",
"event",
")",
":",
"if",
"(",
"event",
".",
"key",
"(",
")",
"==",
"Qt",
".",
"Key_Backtab",
")",
":",
"self",
".",
"unindentSelection",
"(",
")",
"else",
":",
"super",
"(",
"XScintillaEdit",
",",
"self",
")"... | 34.3 | 0.019886 |
def coriolis_parameter(latitude):
r"""Calculate the coriolis parameter at each point.
The implementation uses the formula outlined in [Hobbs1977]_ pg.370-371.
Parameters
----------
latitude : array_like
Latitude at each point
Returns
-------
`pint.Quantity`
The corresp... | [
"def",
"coriolis_parameter",
"(",
"latitude",
")",
":",
"latitude",
"=",
"_check_radians",
"(",
"latitude",
",",
"max_radians",
"=",
"np",
".",
"pi",
"/",
"2",
")",
"return",
"(",
"2.",
"*",
"mpconsts",
".",
"omega",
"*",
"np",
".",
"sin",
"(",
"latitu... | 26.222222 | 0.002045 |
def execute(self, stmt, **params):
"""Execute a SQL statement.
The statement may be a string SQL string,
an :func:`sqlalchemy.sql.expression.select` construct, or a
:func:`sqlalchemy.sql.expression.text`
construct.
"""
return self.session.execute(sql.text(stmt... | [
"def",
"execute",
"(",
"self",
",",
"stmt",
",",
"*",
"*",
"params",
")",
":",
"return",
"self",
".",
"session",
".",
"execute",
"(",
"sql",
".",
"text",
"(",
"stmt",
",",
"bind",
"=",
"self",
".",
"bind",
")",
",",
"*",
"*",
"params",
")"
] | 33.9 | 0.011494 |
def is_data_dependent(fmto, data):
"""Check whether a formatoption is data dependent
Parameters
----------
fmto: Formatoption
The :class:`Formatoption` instance to check
data: xarray.DataArray
The data array to use if the :attr:`~Formatoption.data_dependent`
attribute is a c... | [
"def",
"is_data_dependent",
"(",
"fmto",
",",
"data",
")",
":",
"if",
"callable",
"(",
"fmto",
".",
"data_dependent",
")",
":",
"return",
"fmto",
".",
"data_dependent",
"(",
"data",
")",
"return",
"fmto",
".",
"data_dependent"
] | 28.388889 | 0.001894 |
def supports_version_type(self, version_type=None):
"""Tests if the given version type is supported.
arg: version_type (osid.type.Type): a version Type
return: (boolean) - ``true`` if the type is supported, ``false``
otherwise
raise: IllegalState - syntax is not a ``... | [
"def",
"supports_version_type",
"(",
"self",
",",
"version_type",
"=",
"None",
")",
":",
"# Implemented from template for osid.Metadata.supports_coordinate_type",
"from",
".",
"osid_errors",
"import",
"IllegalState",
",",
"NullArgument",
"if",
"not",
"version_type",
":",
... | 47.555556 | 0.002291 |
def _batch_norm(self, name, x):
"""Batch normalization."""
with tf.variable_scope(name):
params_shape = [x.get_shape()[-1]]
beta = tf.get_variable(
"beta",
params_shape,
tf.float32,
initializer=tf.constant_initializ... | [
"def",
"_batch_norm",
"(",
"self",
",",
"name",
",",
"x",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
")",
":",
"params_shape",
"=",
"[",
"x",
".",
"get_shape",
"(",
")",
"[",
"-",
"1",
"]",
"]",
"beta",
"=",
"tf",
".",
"get_varia... | 40.084746 | 0.000825 |
def convert_ini(config_dict):
"""Convert _config_dict_ into a list of INI formatted strings.
Args:
config_dict (dict): Configuration dictionary to be flattened.
Returns:
(list) Lines to be written to a file in the format of KEY1_KEY2=value.
"""
config_lines = []
for env, confi... | [
"def",
"convert_ini",
"(",
"config_dict",
")",
":",
"config_lines",
"=",
"[",
"]",
"for",
"env",
",",
"configs",
"in",
"sorted",
"(",
"config_dict",
".",
"items",
"(",
")",
")",
":",
"for",
"resource",
",",
"app_properties",
"in",
"sorted",
"(",
"configs... | 39.628571 | 0.002111 |
def _get_static_predicate(pred):
"""Helper function for statically evaluating predicates in `cond`."""
if pred in {0, 1}: # Accept 1/0 as valid boolean values
pred_value = bool(pred)
elif isinstance(pred, bool):
pred_value = pred
elif isinstance(pred, tf.Tensor):
pred_value = tf.get_static_value(pr... | [
"def",
"_get_static_predicate",
"(",
"pred",
")",
":",
"if",
"pred",
"in",
"{",
"0",
",",
"1",
"}",
":",
"# Accept 1/0 as valid boolean values",
"pred_value",
"=",
"bool",
"(",
"pred",
")",
"elif",
"isinstance",
"(",
"pred",
",",
"bool",
")",
":",
"pred_va... | 39.55 | 0.009877 |
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'ali... | [
"def",
"create",
"(",
"vm_",
")",
":",
"try",
":",
"# Check for required profile parameters before sending any API calls.",
"if",
"vm_",
"[",
"'profile'",
"]",
"and",
"config",
".",
"is_profile_configured",
"(",
"__opts__",
",",
"__active_provider_name__",
"or",
"'aliyu... | 34.977099 | 0.001486 |
def view_umatrix(self, figsize=None, colormap=cm.Spectral_r,
colorbar=False, bestmatches=False, bestmatchcolors=None,
labels=None, zoom=None, filename=None):
"""Plot the U-matrix of the trained map.
:param figsize: Optional parameter to specify the size of the ... | [
"def",
"view_umatrix",
"(",
"self",
",",
"figsize",
"=",
"None",
",",
"colormap",
"=",
"cm",
".",
"Spectral_r",
",",
"colorbar",
"=",
"False",
",",
"bestmatches",
"=",
"False",
",",
"bestmatchcolors",
"=",
"None",
",",
"labels",
"=",
"None",
",",
"zoom",... | 54.060606 | 0.002203 |
def get(self, param, config, target, fallback):
"""Return the value of `param`, according to priority / expansion.
First priority - the target itself.
Second priority - the project config.
Third priority - a global default ("fallback").
In list-params, a '$*' term processed as ... | [
"def",
"get",
"(",
"self",
",",
"param",
",",
"config",
",",
"target",
",",
"fallback",
")",
":",
"target_val",
"=",
"target",
".",
"props",
".",
"get",
"(",
"param",
")",
"config_val",
"=",
"config",
".",
"get",
"(",
"param",
",",
"fallback",
")",
... | 36.173913 | 0.002342 |
def load_image(image_path, image_hdu, pixel_scale):
"""Factory for loading the image from a .fits file
Parameters
----------
image_path : str
The path to the image .fits file containing the image (e.g. '/path/to/image.fits')
image_hdu : int
The hdu the image is contained in the .fit... | [
"def",
"load_image",
"(",
"image_path",
",",
"image_hdu",
",",
"pixel_scale",
")",
":",
"return",
"ScaledSquarePixelArray",
".",
"from_fits_with_pixel_scale",
"(",
"file_path",
"=",
"image_path",
",",
"hdu",
"=",
"image_hdu",
",",
"pixel_scale",
"=",
"pixel_scale",
... | 43.142857 | 0.008104 |
def container_to_etree(obj, parent=None, to_str=None, **options):
"""
Convert a dict-like object to XML ElementTree.
:param obj: Container instance to convert to
:param parent: XML ElementTree parent node object or None
:param to_str: Callable to convert value to string or None
:param options: ... | [
"def",
"container_to_etree",
"(",
"obj",
",",
"parent",
"=",
"None",
",",
"to_str",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"if",
"to_str",
"is",
"None",
":",
"to_str",
"=",
"_to_str_fn",
"(",
"*",
"*",
"options",
")",
"if",
"not",
"anyconfi... | 38.055556 | 0.000712 |
def __set_output(self):
"""
Private method to set the file to write the cache to. Automaticaly set
once the ifo, start and end times have been set.
"""
if self.__start and self.__end and self.__observatory and self.__type:
self.__output = os.path.join(self.__job.get_cache_dir(), self.__observa... | [
"def",
"__set_output",
"(",
"self",
")",
":",
"if",
"self",
".",
"__start",
"and",
"self",
".",
"__end",
"and",
"self",
".",
"__observatory",
"and",
"self",
".",
"__type",
":",
"self",
".",
"__output",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self"... | 57.375 | 0.01073 |
def make_url_fetcher(dispatcher=None,
next_fetcher=weasyprint.default_url_fetcher):
"""Return an function suitable as a ``url_fetcher`` in WeasyPrint.
You generally don’t need to call this directly.
If ``dispatcher`` is not provided, :func:`make_flask_url_dispatcher`
is called to ... | [
"def",
"make_url_fetcher",
"(",
"dispatcher",
"=",
"None",
",",
"next_fetcher",
"=",
"weasyprint",
".",
"default_url_fetcher",
")",
":",
"if",
"dispatcher",
"is",
"None",
":",
"dispatcher",
"=",
"make_flask_url_dispatcher",
"(",
")",
"def",
"flask_url_fetcher",
"(... | 45.823529 | 0.000419 |
def use_federated_log_view(self):
"""Pass through to provider LogEntryLookupSession.use_federated_log_view"""
self._log_view = FEDERATED
# self._get_provider_session('log_entry_lookup_session') # To make sure the session is tracked
for session in self._get_provider_sessions():
... | [
"def",
"use_federated_log_view",
"(",
"self",
")",
":",
"self",
".",
"_log_view",
"=",
"FEDERATED",
"# self._get_provider_session('log_entry_lookup_session') # To make sure the session is tracked",
"for",
"session",
"in",
"self",
".",
"_get_provider_sessions",
"(",
")",
":",
... | 47 | 0.009281 |
def getImage(self):
'''
Returns last Image.
@return last JdeRobotTypes Image saved
'''
img = Image()
if self.hasproxy():
self.lock.acquire()
img = self.image
self.lock.release()
return img | [
"def",
"getImage",
"(",
"self",
")",
":",
"img",
"=",
"Image",
"(",
")",
"if",
"self",
".",
"hasproxy",
"(",
")",
":",
"self",
".",
"lock",
".",
"acquire",
"(",
")",
"img",
"=",
"self",
".",
"image",
"self",
".",
"lock",
".",
"release",
"(",
")... | 21.307692 | 0.013841 |
def match_path(rule, path):
""" Match path.
>>> match_path('/foo', '/foo')
(True, {})
>>> match_path('/foo', '/bar')
(False, {})
>>> match_path('/users/{user_id}', '/users/1')
(True, {'user_id': '1'})
>>> match_path('/users/{user_id}', '/users/not-integer')
(True, {'user_id': 'not-i... | [
"def",
"match_path",
"(",
"rule",
",",
"path",
")",
":",
"split_rule",
"=",
"split_by_slash",
"(",
"rule",
")",
"split_path",
"=",
"split_by_slash",
"(",
"path",
")",
"url_vars",
"=",
"{",
"}",
"if",
"len",
"(",
"split_rule",
")",
"!=",
"len",
"(",
"sp... | 26.923077 | 0.001379 |
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 | 0.008086 |
def dragEnterEvent( self, event ):
"""
Processes the drag drop event using the filter set by the \
setDragDropFilter
:param event | <QDragEvent>
"""
filt = self.dragDropFilter()
if not filt:
super(XTreeWidget, self).dragEnterEven... | [
"def",
"dragEnterEvent",
"(",
"self",
",",
"event",
")",
":",
"filt",
"=",
"self",
".",
"dragDropFilter",
"(",
")",
"if",
"not",
"filt",
":",
"super",
"(",
"XTreeWidget",
",",
"self",
")",
".",
"dragEnterEvent",
"(",
"event",
")",
"return",
"filt",
"("... | 29 | 0.017995 |
def _await_socket(self, timeout):
"""Blocks for the nailgun subprocess to bind and emit a listening port in the nailgun stdout."""
with safe_open(self._ng_stdout, 'r') as ng_stdout:
start_time = time.time()
accumulated_stdout = ''
while 1:
# TODO: share the decreasing timeout logic her... | [
"def",
"_await_socket",
"(",
"self",
",",
"timeout",
")",
":",
"with",
"safe_open",
"(",
"self",
".",
"_ng_stdout",
",",
"'r'",
")",
"as",
"ng_stdout",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"accumulated_stdout",
"=",
"''",
"while",
"1",
... | 42.8 | 0.012797 |
def start(st_reg_number):
"""Checks the number valiaty for the Amazonas state"""
weights = range(2, 10)
digits = st_reg_number[0:len(st_reg_number) - 1]
control_digit = 11
check_digit = st_reg_number[-1:]
if len(st_reg_number) != 9:
return False
... | [
"def",
"start",
"(",
"st_reg_number",
")",
":",
"weights",
"=",
"range",
"(",
"2",
",",
"10",
")",
"digits",
"=",
"st_reg_number",
"[",
"0",
":",
"len",
"(",
"st_reg_number",
")",
"-",
"1",
"]",
"control_digit",
"=",
"11",
"check_digit",
"=",
"st_reg_n... | 30 | 0.009044 |
def fieldname_to_dtype(fieldname):
"""Converts a column header from the MPT file into a tuple of
canonical name and appropriate numpy dtype"""
if fieldname == 'mode':
return ('mode', np.uint8)
elif fieldname in ("ox/red", "error", "control changes", "Ns changes",
"counter... | [
"def",
"fieldname_to_dtype",
"(",
"fieldname",
")",
":",
"if",
"fieldname",
"==",
"'mode'",
":",
"return",
"(",
"'mode'",
",",
"np",
".",
"uint8",
")",
"elif",
"fieldname",
"in",
"(",
"\"ox/red\"",
",",
"\"error\"",
",",
"\"control changes\"",
",",
"\"Ns cha... | 44.5 | 0.000917 |
def _generateRangeDescription(self, ranges):
"""generate description from a text description of the ranges"""
desc = ""
numRanges = len(ranges)
for i in xrange(numRanges):
if ranges[i][0] != ranges[i][1]:
desc += "%.2f-%.2f" % (ranges[i][0], ranges[i][1])
else:
desc += "%.2f"... | [
"def",
"_generateRangeDescription",
"(",
"self",
",",
"ranges",
")",
":",
"desc",
"=",
"\"\"",
"numRanges",
"=",
"len",
"(",
"ranges",
")",
"for",
"i",
"in",
"xrange",
"(",
"numRanges",
")",
":",
"if",
"ranges",
"[",
"i",
"]",
"[",
"0",
"]",
"!=",
... | 32.583333 | 0.00995 |
def top(self, number, **options):
'''
Retrieve members from the leaderboard within a range from 1 to the number given.
@param ending_rank [int] Ending rank (inclusive).
@param options [Hash] Options to be used when retrieving the data from the leaderboard.
@return number from t... | [
"def",
"top",
"(",
"self",
",",
"number",
",",
"*",
"*",
"options",
")",
":",
"return",
"self",
".",
"top_in",
"(",
"self",
".",
"leaderboard_name",
",",
"number",
",",
"*",
"*",
"options",
")"
] | 44.5 | 0.011013 |
def get_classes(cls, el):
"""Get classes."""
classes = cls.get_attribute_by_name(el, 'class', [])
if isinstance(classes, util.ustr):
classes = RE_NOT_WS.findall(classes)
return classes | [
"def",
"get_classes",
"(",
"cls",
",",
"el",
")",
":",
"classes",
"=",
"cls",
".",
"get_attribute_by_name",
"(",
"el",
",",
"'class'",
",",
"[",
"]",
")",
"if",
"isinstance",
"(",
"classes",
",",
"util",
".",
"ustr",
")",
":",
"classes",
"=",
"RE_NOT... | 31.857143 | 0.008734 |
def eqncpv(et, epoch, eqel, rapol, decpol):
"""
Compute the state (position and velocity of an object whose
trajectory is described via equinoctial elements relative to some
fixed plane (usually the equatorial plane of some planet).
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/eqncpv_c.h... | [
"def",
"eqncpv",
"(",
"et",
",",
"epoch",
",",
"eqel",
",",
"rapol",
",",
"decpol",
")",
":",
"et",
"=",
"ctypes",
".",
"c_double",
"(",
"et",
")",
"epoch",
"=",
"ctypes",
".",
"c_double",
"(",
"epoch",
")",
"eqel",
"=",
"stypes",
".",
"toDoubleVec... | 39.448276 | 0.000853 |
def value(self, extra=None):
"""The value used for processing. Can be a tuple.
with optional extra bits
"""
if isinstance(self.code, WithExtra):
if not 0<=extra<1<<self.extraBits():
raise ValueError("value: extra value doesn't fit in extraBits")
re... | [
"def",
"value",
"(",
"self",
",",
"extra",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"code",
",",
"WithExtra",
")",
":",
"if",
"not",
"0",
"<=",
"extra",
"<",
"1",
"<<",
"self",
".",
"extraBits",
"(",
")",
":",
"raise",
"ValueE... | 44.454545 | 0.01002 |
def watch_import(name, globals=None, *args, **kwargs):
"""
When a module is asked to be imported, check if we have previously imported
it. If so, check if the time stamp of it, a companion yaml file, or any
modules it imports have changed. If so, reimport the module.
:params: see __builtin__.__im... | [
"def",
"watch_import",
"(",
"name",
",",
"globals",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Don\"t monitor builtin modules. types seem special, so don\"t monitor it",
"# either.",
"monitor",
"=",
"not",
"imp",
".",
"is_builtin",
"(",
... | 39.139535 | 0.001159 |
def simultaneous_challenge(self, node_ip, node_port, proto):
"""
Used by active simultaneous nodes to attempt to initiate
a simultaneous open to a compatible node after retrieving
its details from bootstrapping. The function advertises
itself as a potential candidate to the ... | [
"def",
"simultaneous_challenge",
"(",
"self",
",",
"node_ip",
",",
"node_port",
",",
"proto",
")",
":",
"parts",
"=",
"self",
".",
"sequential_connect",
"(",
")",
"if",
"parts",
"is",
"None",
":",
"log",
".",
"debug",
"(",
"\"Sequential connect failed\"",
")... | 40.5 | 0.001722 |
def blocks(file, blocksize=None, overlap=0, frames=-1, start=0, stop=None,
dtype='float64', always_2d=False, fill_value=None, out=None,
samplerate=None, channels=None,
format=None, subtype=None, endian=None, closefd=True):
"""Return a generator for block-wise reading.
By defaul... | [
"def",
"blocks",
"(",
"file",
",",
"blocksize",
"=",
"None",
",",
"overlap",
"=",
"0",
",",
"frames",
"=",
"-",
"1",
",",
"start",
"=",
"0",
",",
"stop",
"=",
"None",
",",
"dtype",
"=",
"'float64'",
",",
"always_2d",
"=",
"False",
",",
"fill_value"... | 37.526316 | 0.000456 |
def skip(self):
'''Mark the item as processed without download.'''
_logger.debug(__(_('Skipping ‘{url}’.'), url=self.url_record.url))
self.app_session.factory['URLTable'].check_in(self.url_record.url, Status.skipped)
self._processed = True | [
"def",
"skip",
"(",
"self",
")",
":",
"_logger",
".",
"debug",
"(",
"__",
"(",
"_",
"(",
"'Skipping ‘{url}’.'), u",
"r",
"l",
"sel",
"f",
".url",
"_",
"record.url",
")",
")",
"",
"",
"self",
".",
"app_session",
".",
"factory",
"[",
"'URLTable'",
"]",... | 44.5 | 0.011029 |
def add_veto(self, reason):
"""Adds a veto on this event.
in reason of type str
Reason for veto, could be null or empty string.
"""
if not isinstance(reason, basestring):
raise TypeError("reason can only be an instance of type basestring")
self._call("ad... | [
"def",
"add_veto",
"(",
"self",
",",
"reason",
")",
":",
"if",
"not",
"isinstance",
"(",
"reason",
",",
"basestring",
")",
":",
"raise",
"TypeError",
"(",
"\"reason can only be an instance of type basestring\"",
")",
"self",
".",
"_call",
"(",
"\"addVeto\"",
","... | 32.090909 | 0.011019 |
async def setLocalDescription(self, sessionDescription):
"""
Change the local description associated with the connection.
:param: sessionDescription: An :class:`RTCSessionDescription` generated
by :meth:`createOffer` or :meth:`createAnswer()`.
"""
... | [
"async",
"def",
"setLocalDescription",
"(",
"self",
",",
"sessionDescription",
")",
":",
"# parse and validate description",
"description",
"=",
"sdp",
".",
"SessionDescription",
".",
"parse",
"(",
"sessionDescription",
".",
"sdp",
")",
"description",
".",
"type",
"... | 40.649123 | 0.002107 |
def image(self):
'''Return an image of the structure of the compound'''
r = requests.get(self.image_url, stream=True)
r.raise_for_status()
return r.raw.read() | [
"def",
"image",
"(",
"self",
")",
":",
"r",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"image_url",
",",
"stream",
"=",
"True",
")",
"r",
".",
"raise_for_status",
"(",
")",
"return",
"r",
".",
"raw",
".",
"read",
"(",
")"
] | 37.2 | 0.010526 |
def get_nx_graph(ea):
"""Convert an IDA flowchart to a NetworkX graph."""
nx_graph = networkx.DiGraph()
func = idaapi.get_func(ea)
flowchart = FlowChart(func)
for block in flowchart:
# Make sure all nodes are added (including edge-less nodes)
nx_graph.add_node(block.startEA)
... | [
"def",
"get_nx_graph",
"(",
"ea",
")",
":",
"nx_graph",
"=",
"networkx",
".",
"DiGraph",
"(",
")",
"func",
"=",
"idaapi",
".",
"get_func",
"(",
"ea",
")",
"flowchart",
"=",
"FlowChart",
"(",
"func",
")",
"for",
"block",
"in",
"flowchart",
":",
"# Make ... | 33.8 | 0.001919 |
def _setextra(self, extradata):
'''
Set the _extra field in the struct, which stands for the additional ("extra") data after the
defined fields.
'''
current = self
while hasattr(current, '_sub'):
current = current._sub
_set(current, '_extra', extradata... | [
"def",
"_setextra",
"(",
"self",
",",
"extradata",
")",
":",
"current",
"=",
"self",
"while",
"hasattr",
"(",
"current",
",",
"'_sub'",
")",
":",
"current",
"=",
"current",
".",
"_sub",
"_set",
"(",
"current",
",",
"'_extra'",
",",
"extradata",
")"
] | 34.777778 | 0.009346 |
def labels(self, pores=[], throats=[], element=None, mode='union'):
r"""
Returns a list of labels present on the object
Additionally, this function can return labels applied to a specified
set of pores or throats
Parameters
----------
element : string
... | [
"def",
"labels",
"(",
"self",
",",
"pores",
"=",
"[",
"]",
",",
"throats",
"=",
"[",
"]",
",",
"element",
"=",
"None",
",",
"mode",
"=",
"'union'",
")",
":",
"# Short-circuit query when no pores or throats are given",
"if",
"(",
"sp",
".",
"size",
"(",
"... | 37.447368 | 0.000685 |
def signed_headers(self):
"""
An ordered dictionary containing the signed header names and values.
"""
# See if the signed headers are listed in the query string
signed_headers = self.query_parameters.get(_x_amz_signedheaders)
if signed_headers is not None:
si... | [
"def",
"signed_headers",
"(",
"self",
")",
":",
"# See if the signed headers are listed in the query string",
"signed_headers",
"=",
"self",
".",
"query_parameters",
".",
"get",
"(",
"_x_amz_signedheaders",
")",
"if",
"signed_headers",
"is",
"not",
"None",
":",
"signed_... | 43.269231 | 0.001739 |
def ff(items, targets):
"""First-Fit
This is perhaps the simplest packing heuristic;
it simply packs items in the next available bin.
Complexity O(n^2)
"""
bins = [(target, []) for target in targets]
skip = []
for item in items:
for target, content in bins:
if item... | [
"def",
"ff",
"(",
"items",
",",
"targets",
")",
":",
"bins",
"=",
"[",
"(",
"target",
",",
"[",
"]",
")",
"for",
"target",
"in",
"targets",
"]",
"skip",
"=",
"[",
"]",
"for",
"item",
"in",
"items",
":",
"for",
"target",
",",
"content",
"in",
"b... | 23.947368 | 0.002114 |
def _grow_overlaps(dna, melting_temp, require_even, length_max, overlap_min,
min_exception):
'''Grows equidistant overlaps until they meet specified constraints.
:param dna: Input sequence.
:type dna: coral.DNA
:param melting_temp: Ideal Tm of the overlaps, in degrees C.
:type me... | [
"def",
"_grow_overlaps",
"(",
"dna",
",",
"melting_temp",
",",
"require_even",
",",
"length_max",
",",
"overlap_min",
",",
"min_exception",
")",
":",
"# TODO: prevent growing overlaps from bumping into each other -",
"# should halt when it happens, give warning, let user decide if ... | 43.503759 | 0.000169 |
def nl2br(self, text):
"""
Replace \'\n\' with \'<br/>\\n\'
"""
if isinstance(text, bytes):
return text.replace(b'\n', b'<br/>\n')
else:
return text.replace('\n', '<br/>\n') | [
"def",
"nl2br",
"(",
"self",
",",
"text",
")",
":",
"if",
"isinstance",
"(",
"text",
",",
"bytes",
")",
":",
"return",
"text",
".",
"replace",
"(",
"b'\\n'",
",",
"b'<br/>\\n'",
")",
"else",
":",
"return",
"text",
".",
"replace",
"(",
"'\\n'",
",",
... | 28.75 | 0.008439 |
def add_inline_interface(self, interface_id, second_interface_id,
logical_interface_ref=None, vlan_id=None, second_vlan_id=None, zone_ref=None,
second_zone_ref=None, failure_mode='normal', comment=None, **kw):
"""
Add an inline interface pair. This method is only for IPS or L2FW engine
... | [
"def",
"add_inline_interface",
"(",
"self",
",",
"interface_id",
",",
"second_interface_id",
",",
"logical_interface_ref",
"=",
"None",
",",
"vlan_id",
"=",
"None",
",",
"second_vlan_id",
"=",
"None",
",",
"zone_ref",
"=",
"None",
",",
"second_zone_ref",
"=",
"N... | 51.333333 | 0.009558 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.