text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def skip_cycles(self) -> int:
"""The number of cycles dedicated to skips."""
return sum((int(re.sub(r'\D', '', op)) for op in self.skip_tokens)) | [
"def",
"skip_cycles",
"(",
"self",
")",
"->",
"int",
":",
"return",
"sum",
"(",
"(",
"int",
"(",
"re",
".",
"sub",
"(",
"r'\\D'",
",",
"''",
",",
"op",
")",
")",
"for",
"op",
"in",
"self",
".",
"skip_tokens",
")",
")"
] | 52.666667 | 0.0125 |
def block17(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None):
"""Builds the 17x17 resnet block."""
with tf.variable_scope(scope, 'Block17', [net], reuse=reuse):
with tf.variable_scope('Branch_0'):
tower_conv = slim.conv2d(net, 192, 1, scope='Conv2d_1x1')
with tf.variable_scope('Branch... | [
"def",
"block17",
"(",
"net",
",",
"scale",
"=",
"1.0",
",",
"activation_fn",
"=",
"tf",
".",
"nn",
".",
"relu",
",",
"scope",
"=",
"None",
",",
"reuse",
"=",
"None",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"scope",
",",
"'Block17'",
",... | 50.111111 | 0.009793 |
def lognormcdf(x, mu, tau):
"""Log-normal cumulative density function"""
x = np.atleast_1d(x)
return np.array(
[0.5 * (1 - flib.derf(-(np.sqrt(tau / 2)) * (np.log(y) - mu))) for y in x]) | [
"def",
"lognormcdf",
"(",
"x",
",",
"mu",
",",
"tau",
")",
":",
"x",
"=",
"np",
".",
"atleast_1d",
"(",
"x",
")",
"return",
"np",
".",
"array",
"(",
"[",
"0.5",
"*",
"(",
"1",
"-",
"flib",
".",
"derf",
"(",
"-",
"(",
"np",
".",
"sqrt",
"(",... | 40.4 | 0.009709 |
def magfit(logfile):
'''find best magnetometer offset fit to a log file'''
print("Processing log %s" % filename)
mlog = mavutil.mavlink_connection(filename, notimestamps=args.notimestamps)
flying = False
gps_heading = 0.0
data = []
# get the current mag offsets
m = mlog.recv_match(typ... | [
"def",
"magfit",
"(",
"logfile",
")",
":",
"print",
"(",
"\"Processing log %s\"",
"%",
"filename",
")",
"mlog",
"=",
"mavutil",
".",
"mavlink_connection",
"(",
"filename",
",",
"notimestamps",
"=",
"args",
".",
"notimestamps",
")",
"flying",
"=",
"False",
"g... | 37.375 | 0.002173 |
def get_metric(self, timestamp):
"""Get a metric including all current time series.
Get a :class:`opencensus.metrics.export.metric.Metric` with one
:class:`opencensus.metrics.export.time_series.TimeSeries` for each
set of label values with a recorded measurement. Each `TimeSeries`
... | [
"def",
"get_metric",
"(",
"self",
",",
"timestamp",
")",
":",
"if",
"not",
"self",
".",
"points",
":",
"return",
"None",
"with",
"self",
".",
"_points_lock",
":",
"ts_list",
"=",
"get_timeseries_list",
"(",
"self",
".",
"points",
",",
"timestamp",
")",
"... | 42.6 | 0.002296 |
def list_job(jid, ext_source=None, display_progress=False):
'''
List a specific job given by its jid
ext_source
If provided, specifies which external job cache to use.
display_progress : False
If ``True``, fire progress events.
.. versionadded:: 2015.8.8
CLI Example:
... | [
"def",
"list_job",
"(",
"jid",
",",
"ext_source",
"=",
"None",
",",
"display_progress",
"=",
"False",
")",
":",
"ret",
"=",
"{",
"'jid'",
":",
"jid",
"}",
"mminion",
"=",
"salt",
".",
"minion",
".",
"MasterMinion",
"(",
"__opts__",
")",
"returner",
"="... | 28.5 | 0.000771 |
def unravel(txt, binding, msgtype="response"):
"""
Will unpack the received text. Depending on the context the original
response may have been transformed before transmission.
:param txt:
:param binding:
:param msgtype:
:return:
"""
# logger.debug... | [
"def",
"unravel",
"(",
"txt",
",",
"binding",
",",
"msgtype",
"=",
"\"response\"",
")",
":",
"# logger.debug(\"unravel '%s'\", txt)",
"if",
"binding",
"not",
"in",
"[",
"BINDING_HTTP_REDIRECT",
",",
"BINDING_HTTP_POST",
",",
"BINDING_SOAP",
",",
"BINDING_URI",
",",
... | 40.90625 | 0.001493 |
def get_upper_triangle(correlation_matrix):
''' Extract upper triangle from a square matrix. Negative values are
set to 0.
Args:
correlation_matrix (pandas df): Correlations between all replicates
Returns:
upper_tri_df (pandas df): Upper triangle extracted from
correlation_matrix; rid ... | [
"def",
"get_upper_triangle",
"(",
"correlation_matrix",
")",
":",
"upper_triangle",
"=",
"correlation_matrix",
".",
"where",
"(",
"np",
".",
"triu",
"(",
"np",
".",
"ones",
"(",
"correlation_matrix",
".",
"shape",
")",
",",
"k",
"=",
"1",
")",
".",
"astype... | 36.72 | 0.002123 |
def popen_uci(cls, command: Union[str, List[str]], *, timeout: Optional[float] = 10.0, debug: bool = False, setpgrp: bool = False, **popen_args: Any) -> "SimpleEngine":
"""
Spawns and initializes an UCI engine.
Returns a :class:`~chess.engine.SimpleEngine` instance.
"""
return cl... | [
"def",
"popen_uci",
"(",
"cls",
",",
"command",
":",
"Union",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
",",
"*",
",",
"timeout",
":",
"Optional",
"[",
"float",
"]",
"=",
"10.0",
",",
"debug",
":",
"bool",
"=",
"False",
",",
"setpgrp",
":",
... | 67.5 | 0.009756 |
def get_ip_address_info(ip_address, cache=None, nameservers=None,
timeout=2.0, parallel=False):
"""
Returns reverse DNS and country information for the given IP address
Args:
ip_address (str): The IP address to check
cache (ExpiringDict): Cache storage
namese... | [
"def",
"get_ip_address_info",
"(",
"ip_address",
",",
"cache",
"=",
"None",
",",
"nameservers",
"=",
"None",
",",
"timeout",
"=",
"2.0",
",",
"parallel",
"=",
"False",
")",
":",
"ip_address",
"=",
"ip_address",
".",
"lower",
"(",
")",
"if",
"cache",
":",... | 34.222222 | 0.000789 |
def zoomTo(self, bbox):
'set visible area to bbox, maintaining aspectRatio if applicable'
self.fixPoint(self.plotviewBox.xymin, bbox.xymin)
self.zoomlevel=max(bbox.w/self.canvasBox.w, bbox.h/self.canvasBox.h) | [
"def",
"zoomTo",
"(",
"self",
",",
"bbox",
")",
":",
"self",
".",
"fixPoint",
"(",
"self",
".",
"plotviewBox",
".",
"xymin",
",",
"bbox",
".",
"xymin",
")",
"self",
".",
"zoomlevel",
"=",
"max",
"(",
"bbox",
".",
"w",
"/",
"self",
".",
"canvasBox",... | 57.25 | 0.012931 |
def transcribe(records, transcribe):
"""
Perform transcription or back-transcription.
transcribe must be one of the following:
dna2rna
rna2dna
"""
logging.info('Applying _transcribe generator: '
'operation to perform is ' + transcribe + '.')
for record in records... | [
"def",
"transcribe",
"(",
"records",
",",
"transcribe",
")",
":",
"logging",
".",
"info",
"(",
"'Applying _transcribe generator: '",
"'operation to perform is '",
"+",
"transcribe",
"+",
"'.'",
")",
"for",
"record",
"in",
"records",
":",
"sequence",
"=",
"str",
... | 37.666667 | 0.001233 |
def deleteSNPs(setName) :
"""deletes a set of polymorphisms"""
con = conf.db
try :
SMaster = SNPMaster(setName = setName)
con.beginTransaction()
SNPType = SMaster.SNPType
con.delete(SNPType, 'setName = ?', (setName,))
SMaster.delete()
con.endTransaction()
except KeyError :
raise KeyError("Can't delete... | [
"def",
"deleteSNPs",
"(",
"setName",
")",
":",
"con",
"=",
"conf",
".",
"db",
"try",
":",
"SMaster",
"=",
"SNPMaster",
"(",
"setName",
"=",
"setName",
")",
"con",
".",
"beginTransaction",
"(",
")",
"SNPType",
"=",
"SMaster",
".",
"SNPType",
"con",
".",... | 37.266667 | 0.04014 |
def parse_slab_stats(slab_stats):
"""Convert output from memcached's `stats slabs` into a Python dict.
Newlines are returned by memcached along with carriage returns
(i.e. '\r\n').
>>> parse_slab_stats(
"STAT 1:chunk_size 96\r\nSTAT 1:chunks_per_page 10922\r\nSTAT "
"active_sla... | [
"def",
"parse_slab_stats",
"(",
"slab_stats",
")",
":",
"stats_dict",
"=",
"{",
"'slabs'",
":",
"defaultdict",
"(",
"lambda",
":",
"{",
"}",
")",
"}",
"for",
"line",
"in",
"slab_stats",
".",
"splitlines",
"(",
")",
":",
"if",
"line",
"==",
"'END'",
":"... | 28.657895 | 0.000888 |
def items(self):
"Returns a list of (key, value) pairs as 2-tuples."
return (list(self._pb.IntMap.items()) + list(self._pb.StringMap.items()) +
list(self._pb.FloatMap.items()) + list(self._pb.BoolMap.items())) | [
"def",
"items",
"(",
"self",
")",
":",
"return",
"(",
"list",
"(",
"self",
".",
"_pb",
".",
"IntMap",
".",
"items",
"(",
")",
")",
"+",
"list",
"(",
"self",
".",
"_pb",
".",
"StringMap",
".",
"items",
"(",
")",
")",
"+",
"list",
"(",
"self",
... | 59.5 | 0.016598 |
def array_to_schema(arr, **options):
"""
Generate a JSON schema object with type annotation added for given object.
:param arr: Array of mapping objects like dicts
:param options: Other keyword options such as:
- ac_schema_strict: True if more strict (precise) schema is needed
- ac_sch... | [
"def",
"array_to_schema",
"(",
"arr",
",",
"*",
"*",
"options",
")",
":",
"(",
"typemap",
",",
"strict",
")",
"=",
"_process_options",
"(",
"*",
"*",
"options",
")",
"arr",
"=",
"list",
"(",
"arr",
")",
"scm",
"=",
"dict",
"(",
"type",
"=",
"typema... | 32.304348 | 0.001307 |
def _spin(coordinates, theta, around):
"""Rotate a set of coordinates in place around an arbitrary vector.
Parameters
----------
coordinates : np.ndarray, shape=(n,3), dtype=float
The coordinates being spun.
theta : float
The angle by which to spin the coordinates, in radians.
a... | [
"def",
"_spin",
"(",
"coordinates",
",",
"theta",
",",
"around",
")",
":",
"around",
"=",
"np",
".",
"asarray",
"(",
"around",
")",
".",
"reshape",
"(",
"3",
")",
"if",
"np",
".",
"array_equal",
"(",
"around",
",",
"np",
".",
"zeros",
"(",
"3",
"... | 35.095238 | 0.001321 |
def write_data(self, data, dstart=None, swap_axes=True):
"""Write ``data`` to `file`.
Parameters
----------
data : `array-like`
Data that should be written to `file`.
dstart : non-negative int, optional
Offset in bytes of the start position of the written... | [
"def",
"write_data",
"(",
"self",
",",
"data",
",",
"dstart",
"=",
"None",
",",
"swap_axes",
"=",
"True",
")",
":",
"if",
"dstart",
"is",
"None",
":",
"shape",
"=",
"self",
".",
"data_shape",
"dstart",
"=",
"int",
"(",
"self",
".",
"header_size",
")"... | 40.613636 | 0.001093 |
def num_available_breakpoints(self, arm=False, thumb=False, ram=False, flash=False, hw=False):
"""Returns the number of available breakpoints of the specified type.
If ``arm`` is set, gets the number of available ARM breakpoint units.
If ``thumb`` is set, gets the number of available THUMB brea... | [
"def",
"num_available_breakpoints",
"(",
"self",
",",
"arm",
"=",
"False",
",",
"thumb",
"=",
"False",
",",
"ram",
"=",
"False",
",",
"flash",
"=",
"False",
",",
"hw",
"=",
"False",
")",
":",
"flags",
"=",
"[",
"enums",
".",
"JLinkBreakpoint",
".",
"... | 40.979592 | 0.001459 |
def convert(in_file, out_file, in_fmt="", out_fmt=""):
"""
Converts in_file to out_file, guessing datatype in the absence of
in_fmt and out_fmt.
Arguments:
in_file: The name of the (existing) datafile to read
out_file: The name of the file to create with converted data
in_f... | [
"def",
"convert",
"(",
"in_file",
",",
"out_file",
",",
"in_fmt",
"=",
"\"\"",
",",
"out_fmt",
"=",
"\"\"",
")",
":",
"# First verify that in_file exists and out_file doesn't.",
"in_file",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"in_file",
")",
"out_file... | 33.272727 | 0.000442 |
def is_first(self, value):
"""The is_first property.
Args:
value (string). the property value.
"""
if value == self._defaults['ai.session.isFirst'] and 'ai.session.isFirst' in self._values:
del self._values['ai.session.isFirst']
else:
... | [
"def",
"is_first",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"==",
"self",
".",
"_defaults",
"[",
"'ai.session.isFirst'",
"]",
"and",
"'ai.session.isFirst'",
"in",
"self",
".",
"_values",
":",
"del",
"self",
".",
"_values",
"[",
"'ai.session.isFirs... | 35.3 | 0.01105 |
def value_nth_person(self, n, array, default = 0):
"""
Get the value of array for the person whose position in the entity is n.
Note that this position is arbitrary, and that members are not sorted.
If the nth person does not exist, return ``default`` instead.
... | [
"def",
"value_nth_person",
"(",
"self",
",",
"n",
",",
"array",
",",
"default",
"=",
"0",
")",
":",
"self",
".",
"members",
".",
"check_array_compatible_with_entity",
"(",
"array",
")",
"positions",
"=",
"self",
".",
"members_position",
"nb_persons_per_entity",
... | 52.75 | 0.010242 |
def login_required(function=None, message=None, login_url=None):
"""
Decorator for views that checks that the user is logged in, redirecting
to the log-in page if necessary.
"""
actual_decorator = user_passes_test(
lambda u: u.is_authenticated(),
message=message,
login_url=lo... | [
"def",
"login_required",
"(",
"function",
"=",
"None",
",",
"message",
"=",
"None",
",",
"login_url",
"=",
"None",
")",
":",
"actual_decorator",
"=",
"user_passes_test",
"(",
"lambda",
"u",
":",
"u",
".",
"is_authenticated",
"(",
")",
",",
"message",
"=",
... | 29.142857 | 0.002375 |
def path_regex(self):
"""Return the regex for the path to the build folder."""
if self.locale_build:
return self.build_list_regex
return '%s/' % urljoin(self.build_list_regex, self.builds[self.build_index]) | [
"def",
"path_regex",
"(",
"self",
")",
":",
"if",
"self",
".",
"locale_build",
":",
"return",
"self",
".",
"build_list_regex",
"return",
"'%s/'",
"%",
"urljoin",
"(",
"self",
".",
"build_list_regex",
",",
"self",
".",
"builds",
"[",
"self",
".",
"build_ind... | 39.666667 | 0.012346 |
def dropzoneAt(self, point):
"""
Returns the dropzone at the inputed point.
:param point | <QPoint>
"""
for dropzone in self._dropzones:
rect = dropzone.rect()
if ( rect.contains(point) ):
return dropzone
return None | [
"def",
"dropzoneAt",
"(",
"self",
",",
"point",
")",
":",
"for",
"dropzone",
"in",
"self",
".",
"_dropzones",
":",
"rect",
"=",
"dropzone",
".",
"rect",
"(",
")",
"if",
"(",
"rect",
".",
"contains",
"(",
"point",
")",
")",
":",
"return",
"dropzone",
... | 28 | 0.015723 |
def on_click(self, button, **kwargs):
"""
Maps a click event with its associated callback.
Currently implemented events are:
============ ================ =========
Event Callback setting Button ID
============ ================ =========
Left click ... | [
"def",
"on_click",
"(",
"self",
",",
"button",
",",
"*",
"*",
"kwargs",
")",
":",
"actions",
"=",
"[",
"'leftclick'",
",",
"'middleclick'",
",",
"'rightclick'",
",",
"'upscroll'",
",",
"'downscroll'",
"]",
"try",
":",
"action",
"=",
"actions",
"[",
"butt... | 37.076923 | 0.000808 |
def variations(word):
"""Create variations of the word based on letter combinations like oo,
sh, etc."""
if len(word) == 1:
return [[word[0]]]
elif word == 'aa':
return [['A']]
elif word == 'ee':
return [['i']]
elif word == 'ei':
return [['ei']]
elif word in ['oo... | [
"def",
"variations",
"(",
"word",
")",
":",
"if",
"len",
"(",
"word",
")",
"==",
"1",
":",
"return",
"[",
"[",
"word",
"[",
"0",
"]",
"]",
"]",
"elif",
"word",
"==",
"'aa'",
":",
"return",
"[",
"[",
"'A'",
"]",
"]",
"elif",
"word",
"==",
"'ee... | 37.571429 | 0.000463 |
def tokenizer(text):
"""A lexical analyzer for the `mwtab` formatted files.
:param str text: `mwtab` formatted text.
:return: Tuples of data.
:rtype: py:class:`~collections.namedtuple`
"""
stream = deque(text.split("\n"))
while len(stream) > 0:
line = stream.popleft()
if ... | [
"def",
"tokenizer",
"(",
"text",
")",
":",
"stream",
"=",
"deque",
"(",
"text",
".",
"split",
"(",
"\"\\n\"",
")",
")",
"while",
"len",
"(",
"stream",
")",
">",
"0",
":",
"line",
"=",
"stream",
".",
"popleft",
"(",
")",
"if",
"line",
".",
"starts... | 39.466667 | 0.001978 |
def getAttributeName(self, name):
'''represents the aname
'''
if self.func_aname is None:
return name
assert callable(self.func_aname), \
'expecting callable method for attribute func_aname, not %s' %type(self.func_aname)
f = self.func_aname
return... | [
"def",
"getAttributeName",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"func_aname",
"is",
"None",
":",
"return",
"name",
"assert",
"callable",
"(",
"self",
".",
"func_aname",
")",
",",
"'expecting callable method for attribute func_aname, not %s'",
"%"... | 35.555556 | 0.012195 |
def create_shell(console, manage_dict=None, extra_vars=None, exit_hooks=None):
"""Creates the shell"""
manage_dict = manage_dict or MANAGE_DICT
_vars = globals()
_vars.update(locals())
auto_imported = import_objects(manage_dict)
if extra_vars:
auto_imported.update(extra_vars)
_vars.u... | [
"def",
"create_shell",
"(",
"console",
",",
"manage_dict",
"=",
"None",
",",
"extra_vars",
"=",
"None",
",",
"exit_hooks",
"=",
"None",
")",
":",
"manage_dict",
"=",
"manage_dict",
"or",
"MANAGE_DICT",
"_vars",
"=",
"globals",
"(",
")",
"_vars",
".",
"upda... | 35.679487 | 0.00035 |
def pt2leaf(self, x):
"""
Get the leaf which domain contains x.
"""
if self.leafnode:
return self
else:
if x[self.split_dim] < self.split_value:
return self.lower.pt2leaf(x)
else:
return self.greater.pt2... | [
"def",
"pt2leaf",
"(",
"self",
",",
"x",
")",
":",
"if",
"self",
".",
"leafnode",
":",
"return",
"self",
"else",
":",
"if",
"x",
"[",
"self",
".",
"split_dim",
"]",
"<",
"self",
".",
"split_value",
":",
"return",
"self",
".",
"lower",
".",
"pt2leaf... | 26.333333 | 0.009174 |
def cmd_init_pull_from_cloud(args):
"""Initiate the local catalog by downloading the cloud catalog"""
(lcat, ccat) = (args.local_catalog, args.cloud_catalog)
logging.info("[init-pull-from-cloud]: %s => %s"%(ccat, lcat))
if isfile(lcat):
args.error("[init-pull-from-cloud] The local catalog alre... | [
"def",
"cmd_init_pull_from_cloud",
"(",
"args",
")",
":",
"(",
"lcat",
",",
"ccat",
")",
"=",
"(",
"args",
".",
"local_catalog",
",",
"args",
".",
"cloud_catalog",
")",
"logging",
".",
"info",
"(",
"\"[init-pull-from-cloud]: %s => %s\"",
"%",
"(",
"ccat",
",... | 39.22 | 0.010945 |
def avail_locations(call=None):
'''
List all available locations
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
ret = {}
conn = get_conn(ser... | [
"def",
"avail_locations",
"(",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The avail_locations function must be called with '",
"'-f or --function, or with the --list-locations option'",
")",
"ret",
"=",
"{",
... | 27.928571 | 0.001236 |
def _CamelCaseToSnakeCase(path_name):
"""Converts a field name from camelCase to snake_case."""
result = []
for c in path_name:
if c == '_':
raise ParseError('Fail to parse FieldMask: Path name '
'{0} must not contain "_"s.'.format(path_name))
if c.isupper():
result += '... | [
"def",
"_CamelCaseToSnakeCase",
"(",
"path_name",
")",
":",
"result",
"=",
"[",
"]",
"for",
"c",
"in",
"path_name",
":",
"if",
"c",
"==",
"'_'",
":",
"raise",
"ParseError",
"(",
"'Fail to parse FieldMask: Path name '",
"'{0} must not contain \"_\"s.'",
".",
"forma... | 29.923077 | 0.022444 |
def _is_valid_url(url):
""" Helper function to validate that URLs are well formed, i.e that it contains a valid
protocol and a valid domain. It does not actually check if the URL exists
"""
try:
parsed = urlparse(url)
mandatory_parts = [parsed.scheme, parsed.n... | [
"def",
"_is_valid_url",
"(",
"url",
")",
":",
"try",
":",
"parsed",
"=",
"urlparse",
"(",
"url",
")",
"mandatory_parts",
"=",
"[",
"parsed",
".",
"scheme",
",",
"parsed",
".",
"netloc",
"]",
"return",
"all",
"(",
"mandatory_parts",
")",
"except",
":",
... | 39.8 | 0.012285 |
async def fetch(self, method, url, params=None, headers=None, data=None):
"""Make an HTTP request.
Automatically uses configured HTTP proxy, and adds Google authorization
header and cookies.
Failures will be retried MAX_RETRIES times before raising NetworkError.
Args:
... | [
"async",
"def",
"fetch",
"(",
"self",
",",
"method",
",",
"url",
",",
"params",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"data",
"=",
"None",
")",
":",
"logger",
".",
"debug",
"(",
"'Sending request %s %s:\\n%r'",
",",
"method",
",",
"url",
",",
... | 41.288462 | 0.00091 |
def _get_config(**kwargs):
'''
Return configuration
'''
config = {
'filter_id_regex': ['.*!doc_skip'],
'filter_function_regex': [],
'replace_text_regex': {},
'proccesser': 'highstate_doc.proccesser_markdown',
'max_render_file_size': 10000,
'note': None
... | [
"def",
"_get_config",
"(",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"{",
"'filter_id_regex'",
":",
"[",
"'.*!doc_skip'",
"]",
",",
"'filter_function_regex'",
":",
"[",
"]",
",",
"'replace_text_regex'",
":",
"{",
"}",
",",
"'proccesser'",
":",
"'highstate... | 30.842105 | 0.001656 |
def load_json(json_file, **kwargs):
"""
Open and load data from a JSON file
.. code:: python
reusables.load_json("example.json")
# {u'key_1': u'val_1', u'key_for_dict': {u'sub_dict_key': 8}}
:param json_file: Path to JSON file as string
:param kwargs: Additional arguments for the ... | [
"def",
"load_json",
"(",
"json_file",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"open",
"(",
"json_file",
")",
"as",
"f",
":",
"return",
"json",
".",
"load",
"(",
"f",
",",
"*",
"*",
"kwargs",
")"
] | 28.266667 | 0.002283 |
def generate_words(files):
"""
Transform list of files to list of words,
removing new line character
and replace name entity '<NE>...</NE>' and abbreviation '<AB>...</AB>' symbol
"""
repls = {'<NE>' : '','</NE>' : '','<AB>': '','</AB>': ''}
words_all = []
for i, file in enumerate(files... | [
"def",
"generate_words",
"(",
"files",
")",
":",
"repls",
"=",
"{",
"'<NE>'",
":",
"''",
",",
"'</NE>'",
":",
"''",
",",
"'<AB>'",
":",
"''",
",",
"'</AB>'",
":",
"''",
"}",
"words_all",
"=",
"[",
"]",
"for",
"i",
",",
"file",
"in",
"enumerate",
... | 33.764706 | 0.011864 |
def message(self, message=None):
""" Set response message """
if message is not None:
self.response_model.message = message
return self.response_model.message | [
"def",
"message",
"(",
"self",
",",
"message",
"=",
"None",
")",
":",
"if",
"message",
"is",
"not",
"None",
":",
"self",
".",
"response_model",
".",
"message",
"=",
"message",
"return",
"self",
".",
"response_model",
".",
"message"
] | 38.8 | 0.010101 |
def getArguments(parser):
"Provides additional validation of the arguments collected by argparse."
args = parser.parse_args()
if not '{}' in args.output:
raise argparse.ArgumentError(args.output, 'The output argument string must contain the sequence "{}".')
return args | [
"def",
"getArguments",
"(",
"parser",
")",
":",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"if",
"not",
"'{}'",
"in",
"args",
".",
"output",
":",
"raise",
"argparse",
".",
"ArgumentError",
"(",
"args",
".",
"output",
",",
"'The output argument str... | 48 | 0.010239 |
def srfrec(body, longitude, latitude):
"""
Convert planetocentric latitude and longitude of a surface
point on a specified body to rectangular coordinates.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/srfrec_c.html
:param body: NAIF integer code of an extended body.
:type body: int
... | [
"def",
"srfrec",
"(",
"body",
",",
"longitude",
",",
"latitude",
")",
":",
"body",
"=",
"ctypes",
".",
"c_int",
"(",
"body",
")",
"longitude",
"=",
"ctypes",
".",
"c_double",
"(",
"longitude",
")",
"latitude",
"=",
"ctypes",
".",
"c_double",
"(",
"lati... | 36.636364 | 0.001209 |
def connected_components(G):
"""
Check if G is connected and return list of sets. Every
set contains all vertices in one connected component.
"""
result = []
vertices = set(G.vertices)
while vertices:
n = vertices.pop()
group = {n}
queue = Queue()
q... | [
"def",
"connected_components",
"(",
"G",
")",
":",
"result",
"=",
"[",
"]",
"vertices",
"=",
"set",
"(",
"G",
".",
"vertices",
")",
"while",
"vertices",
":",
"n",
"=",
"vertices",
".",
"pop",
"(",
")",
"group",
"=",
"{",
"n",
"}",
"queue",
"=",
"... | 30.772727 | 0.001433 |
def fuse_list( mafs ):
"""
Try to fuse a list of blocks by progressively fusing each adjacent pair.
"""
last = None
for m in mafs:
if last is None:
last = m
else:
fused = fuse( last, m )
if fused:
last = fused
else:
... | [
"def",
"fuse_list",
"(",
"mafs",
")",
":",
"last",
"=",
"None",
"for",
"m",
"in",
"mafs",
":",
"if",
"last",
"is",
"None",
":",
"last",
"=",
"m",
"else",
":",
"fused",
"=",
"fuse",
"(",
"last",
",",
"m",
")",
"if",
"fused",
":",
"last",
"=",
... | 22.529412 | 0.012531 |
def replace(input, **params):
"""
Replaces field value
:param input:
:param params:
:return:
"""
PARAM_REPLACE_LIST = 'replace'
REPLACE_FIELD = 'field'
REPLACE_FIND_VALUE = 'value.to_find'
REPLACE_WITH_VALUE = 'value.replace_with'
replace_list = params.get(PARAM_REPLACE_LIST... | [
"def",
"replace",
"(",
"input",
",",
"*",
"*",
"params",
")",
":",
"PARAM_REPLACE_LIST",
"=",
"'replace'",
"REPLACE_FIELD",
"=",
"'field'",
"REPLACE_FIND_VALUE",
"=",
"'value.to_find'",
"REPLACE_WITH_VALUE",
"=",
"'value.replace_with'",
"replace_list",
"=",
"params",
... | 29.388889 | 0.001832 |
def print_map(self):
"""Open impact report dialog used to tune report when printing."""
# Check if selected layer is valid
impact_layer = self.iface.activeLayer()
if impact_layer is None:
# noinspection PyCallByClass,PyTypeChecker
QMessageBox.warning(
... | [
"def",
"print_map",
"(",
"self",
")",
":",
"# Check if selected layer is valid",
"impact_layer",
"=",
"self",
".",
"iface",
".",
"activeLayer",
"(",
")",
"if",
"impact_layer",
"is",
"None",
":",
"# noinspection PyCallByClass,PyTypeChecker",
"QMessageBox",
".",
"warnin... | 37.239669 | 0.000432 |
def deploy(
config,
name,
bucket,
timeout,
memory,
description,
subnet_ids,
security_group_ids
):
""" Deploy/Update a function from a project directory """
# options should override config if it is there
myname = name or config.name
mybucket = bucket or config.bucket
... | [
"def",
"deploy",
"(",
"config",
",",
"name",
",",
"bucket",
",",
"timeout",
",",
"memory",
",",
"description",
",",
"subnet_ids",
",",
"security_group_ids",
")",
":",
"# options should override config if it is there",
"myname",
"=",
"name",
"or",
"config",
".",
... | 26.833333 | 0.000999 |
def cleanup_dataset(dataset, data_home=None, ext=".zip"):
"""
Removes the dataset directory and archive file from the data home directory.
Parameters
----------
dataset : str
The name of the dataset; should either be a folder in data home or
specified in the yellowbrick.datasets.DAT... | [
"def",
"cleanup_dataset",
"(",
"dataset",
",",
"data_home",
"=",
"None",
",",
"ext",
"=",
"\".zip\"",
")",
":",
"removed",
"=",
"0",
"data_home",
"=",
"get_data_home",
"(",
"data_home",
")",
"# Paths to remove",
"datadir",
"=",
"os",
".",
"path",
".",
"joi... | 27.35 | 0.001765 |
def submit(self, subreddit, title, text=None, url=None, captcha=None,
save=None, send_replies=None, resubmit=None, **kwargs):
"""Submit a new link to the given subreddit.
Accepts either a Subreddit object or a str containing the subreddit's
display name.
:param resubmit:... | [
"def",
"submit",
"(",
"self",
",",
"subreddit",
",",
"title",
",",
"text",
"=",
"None",
",",
"url",
"=",
"None",
",",
"captcha",
"=",
"None",
",",
"save",
"=",
"None",
",",
"send_replies",
"=",
"None",
",",
"resubmit",
"=",
"None",
",",
"*",
"*",
... | 43.277778 | 0.001255 |
def start(self):
"""
Find the first data entry and prepare to parse.
"""
while not self.is_start(self.current_tag):
self.next()
self.new_entry() | [
"def",
"start",
"(",
"self",
")",
":",
"while",
"not",
"self",
".",
"is_start",
"(",
"self",
".",
"current_tag",
")",
":",
"self",
".",
"next",
"(",
")",
"self",
".",
"new_entry",
"(",
")"
] | 23.75 | 0.010152 |
def all_options(self):
"""Returns the set of all options used in all export entries"""
items = chain.from_iterable(hosts.values() for hosts in self.data.values())
return set(chain.from_iterable(items)) | [
"def",
"all_options",
"(",
"self",
")",
":",
"items",
"=",
"chain",
".",
"from_iterable",
"(",
"hosts",
".",
"values",
"(",
")",
"for",
"hosts",
"in",
"self",
".",
"data",
".",
"values",
"(",
")",
")",
"return",
"set",
"(",
"chain",
".",
"from_iterab... | 55.5 | 0.013333 |
def find_visible_elements(driver, selector, by=By.CSS_SELECTOR):
"""
Finds all WebElements that match a selector and are visible.
Similar to webdriver.find_elements.
@Params
driver - the webdriver object (required)
selector - the locator that is used to search the DOM (required)
by - the met... | [
"def",
"find_visible_elements",
"(",
"driver",
",",
"selector",
",",
"by",
"=",
"By",
".",
"CSS_SELECTOR",
")",
":",
"elements",
"=",
"driver",
".",
"find_elements",
"(",
"by",
"=",
"by",
",",
"value",
"=",
"selector",
")",
"return",
"[",
"element",
"for... | 45.818182 | 0.001946 |
def global_items(self):
"""Iterate over (key, value) pairs in the ``globals`` table."""
for (k, v) in self.sql('global_dump'):
yield (self.unpack(k), self.unpack(v)) | [
"def",
"global_items",
"(",
"self",
")",
":",
"for",
"(",
"k",
",",
"v",
")",
"in",
"self",
".",
"sql",
"(",
"'global_dump'",
")",
":",
"yield",
"(",
"self",
".",
"unpack",
"(",
"k",
")",
",",
"self",
".",
"unpack",
"(",
"v",
")",
")"
] | 47.5 | 0.010363 |
def parse_java_version(cls, version):
"""Parses the java version (given a string or Revision object).
Handles java version-isms, converting things like '7' -> '1.7' appropriately.
Truncates input versions down to just the major and minor numbers (eg, 1.6), ignoring extra
versioning information after t... | [
"def",
"parse_java_version",
"(",
"cls",
",",
"version",
")",
":",
"conversion",
"=",
"{",
"str",
"(",
"i",
")",
":",
"'1.{}'",
".",
"format",
"(",
"i",
")",
"for",
"i",
"in",
"cls",
".",
"SUPPORTED_CONVERSION_VERSIONS",
"}",
"if",
"str",
"(",
"version... | 42.142857 | 0.00884 |
def drop_table(self, table):
"""
Drop a table from the MyDB context.
## Arguments
* `table` (str): The name of the table to drop.
"""
job_id = self.submit("DROP TABLE %s"%table, context="MYDB")
status = self.monitor(job_id)
if status[0] != 5:
... | [
"def",
"drop_table",
"(",
"self",
",",
"table",
")",
":",
"job_id",
"=",
"self",
".",
"submit",
"(",
"\"DROP TABLE %s\"",
"%",
"table",
",",
"context",
"=",
"\"MYDB\"",
")",
"status",
"=",
"self",
".",
"monitor",
"(",
"job_id",
")",
"if",
"status",
"["... | 27.461538 | 0.01084 |
def plfit_lsq(x,y):
"""
Returns A and B in y=Ax^B
http://mathworld.wolfram.com/LeastSquaresFittingPowerLaw.html
"""
n = len(x)
btop = n * (log(x)*log(y)).sum() - (log(x)).sum()*(log(y)).sum()
bbottom = n*(log(x)**2).sum() - (log(x).sum())**2
b = btop / bbottom
a = ( log(y).sum() - b ... | [
"def",
"plfit_lsq",
"(",
"x",
",",
"y",
")",
":",
"n",
"=",
"len",
"(",
"x",
")",
"btop",
"=",
"n",
"*",
"(",
"log",
"(",
"x",
")",
"*",
"log",
"(",
"y",
")",
")",
".",
"sum",
"(",
")",
"-",
"(",
"log",
"(",
"x",
")",
")",
".",
"sum",... | 27.615385 | 0.013477 |
async def validate(state, holdout_glob):
"""Validate the trained model against holdout games.
Args:
state: the RL loop State instance.
holdout_glob: a glob that matches holdout games.
"""
if not glob.glob(holdout_glob):
print('Glob "{}" didn\'t match any files, skipping validation'.format(
... | [
"async",
"def",
"validate",
"(",
"state",
",",
"holdout_glob",
")",
":",
"if",
"not",
"glob",
".",
"glob",
"(",
"holdout_glob",
")",
":",
"print",
"(",
"'Glob \"{}\" didn\\'t match any files, skipping validation'",
".",
"format",
"(",
"holdout_glob",
")",
")",
"... | 32.875 | 0.009242 |
def create_pywbem_ssl_context():
""" Create an SSL context based on what is commonly accepted as the
required limitations. This code attempts to create the same context for
Python 2 and Python 3 except for the ciphers
This list is based on what is currently defined in the Python SSL
... | [
"def",
"create_pywbem_ssl_context",
"(",
")",
":",
"if",
"six",
".",
"PY2",
":",
"context",
"=",
"SSL",
".",
"Context",
"(",
"'sslv23'",
")",
"# Many of the flags are not in the M2Crypto source so they were taken",
"# from OpenSSL SSL.h module as flags.",
"SSL",
".",
"con... | 48.113636 | 0.000463 |
def indexer_receiver(sender, json=None, record=None, index=None,
**dummy_kwargs):
"""Connect to before_record_index signal to transform record for ES."""
if index and index.startswith('grants-'):
# Generate suggest field
suggestions = [
json.get('code'),
... | [
"def",
"indexer_receiver",
"(",
"sender",
",",
"json",
"=",
"None",
",",
"record",
"=",
"None",
",",
"index",
"=",
"None",
",",
"*",
"*",
"dummy_kwargs",
")",
":",
"if",
"index",
"and",
"index",
".",
"startswith",
"(",
"'grants-'",
")",
":",
"# Generat... | 36.25 | 0.000746 |
def guess_filename(filename):
"""Guess filename"""
if osp.isfile(filename):
return filename
if not filename.endswith('.py'):
filename += '.py'
for path in [getcwd_or_home()] + sys.path:
fname = osp.join(path, filename)
if osp.isfile(fname):
return fna... | [
"def",
"guess_filename",
"(",
"filename",
")",
":",
"if",
"osp",
".",
"isfile",
"(",
"filename",
")",
":",
"return",
"filename",
"if",
"not",
"filename",
".",
"endswith",
"(",
"'.py'",
")",
":",
"filename",
"+=",
"'.py'",
"for",
"path",
"in",
"[",
"get... | 31.533333 | 0.002053 |
def segmenttable_get_by_name(xmldoc, name):
"""
Retrieve the segmentlists whose name equals name. The result is a
segmentlistdict indexed by instrument.
The output of this function is not coalesced, each segmentlist
contains the segments as found in the segment table.
NOTE: this is a light-weight version of t... | [
"def",
"segmenttable_get_by_name",
"(",
"xmldoc",
",",
"name",
")",
":",
"#",
"# find required tables",
"#",
"def_table",
"=",
"lsctables",
".",
"SegmentDefTable",
".",
"get_table",
"(",
"xmldoc",
")",
"seg_table",
"=",
"lsctables",
".",
"SegmentTable",
".",
"ge... | 31.145833 | 0.026589 |
def get_aggregate_by_id(self, account_id: str) -> AccountAggregate:
""" Returns the aggregate for the given id """
account = self.get_by_id(account_id)
return self.get_account_aggregate(account) | [
"def",
"get_aggregate_by_id",
"(",
"self",
",",
"account_id",
":",
"str",
")",
"->",
"AccountAggregate",
":",
"account",
"=",
"self",
".",
"get_by_id",
"(",
"account_id",
")",
"return",
"self",
".",
"get_account_aggregate",
"(",
"account",
")"
] | 53.75 | 0.009174 |
def get_genetic_profiles(study_id, profile_filter=None):
"""Return all the genetic profiles (data sets) for a given study.
Genetic profiles are different types of data for a given study. For
instance the study 'cellline_ccle_broad' has profiles such as
'cellline_ccle_broad_mutations' for mutations, 'ce... | [
"def",
"get_genetic_profiles",
"(",
"study_id",
",",
"profile_filter",
"=",
"None",
")",
":",
"data",
"=",
"{",
"'cmd'",
":",
"'getGeneticProfiles'",
",",
"'cancer_study_id'",
":",
"study_id",
"}",
"df",
"=",
"send_request",
"(",
"*",
"*",
"data",
")",
"res"... | 35.083333 | 0.00077 |
def retry_request(method, url, headers=None, payload=None, auth=None,
tries=10, initial_interval=5, callback=None):
"""Retry an HTTP request with linear backoff. Returns the response if
the status code is < 400 or waits (try * initial_interval) seconds and
retries (up to tries times) if i... | [
"def",
"retry_request",
"(",
"method",
",",
"url",
",",
"headers",
"=",
"None",
",",
"payload",
"=",
"None",
",",
"auth",
"=",
"None",
",",
"tries",
"=",
"10",
",",
"initial_interval",
"=",
"5",
",",
"callback",
"=",
"None",
")",
":",
"method",
"=",
... | 37.267606 | 0.000368 |
def find_offsets(data, ofs):
'''find mag offsets by applying Bills "offsets revisited" algorithm
on the data
This is an implementation of the algorithm from:
http://gentlenav.googlecode.com/files/MagnetometerOffsetNullingRevisited.pdf
'''
# a limit on the maximum change in each ... | [
"def",
"find_offsets",
"(",
"data",
",",
"ofs",
")",
":",
"# a limit on the maximum change in each step",
"max_change",
"=",
"args",
".",
"max_change",
"# the gain factor for the algorithm",
"gain",
"=",
"args",
".",
"gain",
"data2",
"=",
"[",
"]",
"for",
"d",
"in... | 29.280702 | 0.00058 |
def _ReraiseTypeErrorWithFieldName(message_name, field_name):
"""Re-raise the currently-handled TypeError with the field name added."""
exc = sys.exc_info()[1]
if len(exc.args) == 1 and type(exc) is TypeError:
# simple TypeError; add field name to exception message
exc = TypeError('%s for field %s.%s' % (... | [
"def",
"_ReraiseTypeErrorWithFieldName",
"(",
"message_name",
",",
"field_name",
")",
":",
"exc",
"=",
"sys",
".",
"exc_info",
"(",
")",
"[",
"1",
"]",
"if",
"len",
"(",
"exc",
".",
"args",
")",
"==",
"1",
"and",
"type",
"(",
"exc",
")",
"is",
"TypeE... | 51.444444 | 0.014862 |
def ensure_running(self):
'''Make sure that semaphore tracker process is running.
This can be run from any process. Usually a child process will use
the semaphore created by its parent.'''
with self._lock:
if self._fd is not None:
# semaphore tracker was lau... | [
"def",
"ensure_running",
"(",
"self",
")",
":",
"with",
"self",
".",
"_lock",
":",
"if",
"self",
".",
"_fd",
"is",
"not",
"None",
":",
"# semaphore tracker was launched before, is it still running?",
"if",
"self",
".",
"_check_alive",
"(",
")",
":",
"# => still ... | 43.902778 | 0.000928 |
def client_detect(self, client, starttime, endtime, threshold,
threshold_type, trig_int, plotvar, min_gap=None,
daylong=False, parallel_process=True, xcorr_func=None,
concurrency=None, cores=None, ignore_length=False,
group_size=Non... | [
"def",
"client_detect",
"(",
"self",
",",
"client",
",",
"starttime",
",",
"endtime",
",",
"threshold",
",",
"threshold_type",
",",
"trig_int",
",",
"plotvar",
",",
"min_gap",
"=",
"None",
",",
"daylong",
"=",
"False",
",",
"parallel_process",
"=",
"True",
... | 44.161049 | 0.000912 |
def has_split(self, split_name):
""" Checks whether or not the split with the given name exists.
Parameters
----------
split_name : str
name of the split
"""
if os.path.exists(os.path.join(self.split_dir, split_name)):
return True
... | [
"def",
"has_split",
"(",
"self",
",",
"split_name",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"split_dir",
",",
"split_name",
")",
")",
":",
"return",
"True",
"return",
"False"
] | 29.272727 | 0.009036 |
def register_view(self, view):
"""Creates treeview columns, and connect missing signals"""
# if stand-alone, connects the window delete event to
# kill the loop
if self.view.is_stand_alone():
import gtk
self.view.get_top_widget().connect('delete-event',
... | [
"def",
"register_view",
"(",
"self",
",",
"view",
")",
":",
"# if stand-alone, connects the window delete event to",
"# kill the loop",
"if",
"self",
".",
"view",
".",
"is_stand_alone",
"(",
")",
":",
"import",
"gtk",
"self",
".",
"view",
".",
"get_top_widget",
"(... | 32.166667 | 0.012594 |
def setCentralWidget(self, widget):
"""
Sets the central widget for this button.
:param widget | <QWidget>
"""
self.setEnabled(widget is not None)
self._popupWidget.setCentralWidget(widget) | [
"def",
"setCentralWidget",
"(",
"self",
",",
"widget",
")",
":",
"self",
".",
"setEnabled",
"(",
"widget",
"is",
"not",
"None",
")",
"self",
".",
"_popupWidget",
".",
"setCentralWidget",
"(",
"widget",
")"
] | 31.375 | 0.011628 |
def generator(self) -> Iterator[str]:
"""
Create a generate that iterates the whole content of the file or string.
:return: An iterator iterating the lines of the text stream, separated by ``'\\n'`` or ``'\\r'``.
"""
stream = self.stream # In case that ``self.stream`` is change... | [
"def",
"generator",
"(",
"self",
")",
"->",
"Iterator",
"[",
"str",
"]",
":",
"stream",
"=",
"self",
".",
"stream",
"# In case that ``self.stream`` is changed.",
"stream",
".",
"seek",
"(",
"0",
")",
"for",
"line",
"in",
"stream",
":",
"yield",
"line"
] | 38.7 | 0.010101 |
def _make_section_node(self, template, tag_type, tag_key, parsed_section,
section_start_index, section_end_index):
"""
Create and return a section node for the parse tree.
"""
if tag_type == '#':
return _SectionNode(tag_key, parsed_section, self._d... | [
"def",
"_make_section_node",
"(",
"self",
",",
"template",
",",
"tag_type",
",",
"tag_key",
",",
"parsed_section",
",",
"section_start_index",
",",
"section_end_index",
")",
":",
"if",
"tag_type",
"==",
"'#'",
":",
"return",
"_SectionNode",
"(",
"tag_key",
",",
... | 40.357143 | 0.008651 |
def configs_for_writer(writer=None, ppp_config_dir=None):
"""Generator of writer configuration files for one or more writers
Args:
writer (Optional[str]): Yield configs only for this writer
ppp_config_dir (Optional[str]): Additional configuration directory
to search for writer confi... | [
"def",
"configs_for_writer",
"(",
"writer",
"=",
"None",
",",
"ppp_config_dir",
"=",
"None",
")",
":",
"search_paths",
"=",
"(",
"ppp_config_dir",
",",
")",
"if",
"ppp_config_dir",
"else",
"tuple",
"(",
")",
"if",
"writer",
"is",
"not",
"None",
":",
"if",
... | 37.90625 | 0.001608 |
def default_links_factory_with_additional(additional_links):
"""Generate a links generation factory with the specified additional links.
:param additional_links: A dict of link names to links to be added to the
returned object.
:returns: A link generation factory.
"""
def factory(pid, **... | [
"def",
"default_links_factory_with_additional",
"(",
"additional_links",
")",
":",
"def",
"factory",
"(",
"pid",
",",
"*",
"*",
"kwargs",
")",
":",
"links",
"=",
"default_links_factory",
"(",
"pid",
")",
"for",
"link",
"in",
"additional_links",
":",
"links",
"... | 40.875 | 0.001495 |
def col (loc,strg):
"""Returns current column within a string, counting newlines as line separators.
The first column is number 1.
Note: the default parsing behavior is to expand tabs in the input string
before starting the parsing process. See L{I{ParserElement.parseString}<ParserElement.parseString>} f... | [
"def",
"col",
"(",
"loc",
",",
"strg",
")",
":",
"s",
"=",
"strg",
"return",
"1",
"if",
"loc",
"<",
"len",
"(",
"s",
")",
"and",
"s",
"[",
"loc",
"]",
"==",
"'\\n'",
"else",
"loc",
"-",
"s",
".",
"rfind",
"(",
"\"\\n\"",
",",
"0",
",",
"loc... | 52.25 | 0.010972 |
def find_all(soup, name=None, attrs=None, recursive=True, text=None,
limit=None, **kwargs):
"""The `find` and `find_all` methods of `BeautifulSoup` don't handle the
`text` parameter combined with other parameters. This is necessary for
e.g. finding links containing a string or pattern. This me... | [
"def",
"find_all",
"(",
"soup",
",",
"name",
"=",
"None",
",",
"attrs",
"=",
"None",
",",
"recursive",
"=",
"True",
",",
"text",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"text",
"is",
"None",
":",
"return",... | 36.041667 | 0.002252 |
def move_selection(reverse=False):
"""
Goes through the list of gunicorns, setting the selected as the one after
the currently selected.
"""
global selected_pid
if selected_pid not in gunicorns:
selected_pid = None
found = False
pids = sorted(gunicorns.keys(), reverse=reverse)
... | [
"def",
"move_selection",
"(",
"reverse",
"=",
"False",
")",
":",
"global",
"selected_pid",
"if",
"selected_pid",
"not",
"in",
"gunicorns",
":",
"selected_pid",
"=",
"None",
"found",
"=",
"False",
"pids",
"=",
"sorted",
"(",
"gunicorns",
".",
"keys",
"(",
"... | 31.5 | 0.001927 |
def _sign(private_key, data, hash_algorithm, rsa_pss_padding=False):
"""
Generates an RSA, DSA or ECDSA signature
:param private_key:
The PrivateKey to generate the signature with
:param data:
A byte string of the data the signature is for
:param hash_algorithm:
A unicode ... | [
"def",
"_sign",
"(",
"private_key",
",",
"data",
",",
"hash_algorithm",
",",
"rsa_pss_padding",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"private_key",
",",
"PrivateKey",
")",
":",
"raise",
"TypeError",
"(",
"pretty_message",
"(",
"'''\n ... | 33.698795 | 0.001389 |
def unregister(self, measurement_class, callback):
"""Stop notifying ``callback`` of new values of ``measurement_class``.
If the callback wasn't previously registered, this method will have no
effect.
"""
self.callbacks[Measurement.name_from_class(measurement_class)
... | [
"def",
"unregister",
"(",
"self",
",",
"measurement_class",
",",
"callback",
")",
":",
"self",
".",
"callbacks",
"[",
"Measurement",
".",
"name_from_class",
"(",
"measurement_class",
")",
"]",
".",
"remove",
"(",
"callback",
")"
] | 41.875 | 0.008772 |
def owned_ecs(self):
'''A list of the execution contexts owned by this component.'''
with self._mutex:
if not self._owned_ecs:
self._owned_ecs = [ExecutionContext(ec,
self._obj.get_context_handle(ec)) \
for ec in self._obj.get_owned_con... | [
"def",
"owned_ecs",
"(",
"self",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"if",
"not",
"self",
".",
"_owned_ecs",
":",
"self",
".",
"_owned_ecs",
"=",
"[",
"ExecutionContext",
"(",
"ec",
",",
"self",
".",
"_obj",
".",
"get_context_handle",
"(",
"e... | 44 | 0.011142 |
def listDatasets(self, dataset="", parent_dataset="", is_dataset_valid=1,
release_version="", pset_hash="", app_name="", output_module_label="", global_tag="",
processing_version=0, acquisition_era_name="", run_num=-1,
physics_group_name="", logical_file_name="", primary_ds_name="", primary_ds_t... | [
"def",
"listDatasets",
"(",
"self",
",",
"dataset",
"=",
"\"\"",
",",
"parent_dataset",
"=",
"\"\"",
",",
"is_dataset_valid",
"=",
"1",
",",
"release_version",
"=",
"\"\"",
",",
"pset_hash",
"=",
"\"\"",
",",
"app_name",
"=",
"\"\"",
",",
"output_module_labe... | 55.219512 | 0.009979 |
def hist_calls_with_dims(**dims):
"""Decorator to check the distribution of return values of a
function with dimensions.
"""
def hist_wrapper(fn):
@functools.wraps(fn)
def fn_wrapper(*args, **kwargs):
_histogram = histogram(
"%s_calls" % pyformance.registry.ge... | [
"def",
"hist_calls_with_dims",
"(",
"*",
"*",
"dims",
")",
":",
"def",
"hist_wrapper",
"(",
"fn",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"fn",
")",
"def",
"fn_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_histogram",
"=",
... | 34.533333 | 0.00188 |
def get_referer(req, replace_ampersands=False):
""" Return the referring page of a request.
Referer (wikipedia): Referer is a common misspelling of the word
"referrer"; so common, in fact, that it made it into the official
specification of HTTP. When visiting a webpage, the referer or
referring page... | [
"def",
"get_referer",
"(",
"req",
",",
"replace_ampersands",
"=",
"False",
")",
":",
"try",
":",
"referer",
"=",
"req",
".",
"headers_in",
"[",
"'Referer'",
"]",
"if",
"replace_ampersands",
"==",
"1",
":",
"return",
"referer",
".",
"replace",
"(",
"'&'",
... | 41.611111 | 0.001305 |
def extractall(filename, directory, backend='auto', auto_create_dir=False):
'''
:param backend: auto, patool or zipfile
:param filename: path to archive file
:param directory: directory to extract to
:param auto_create_dir: auto create directory
'''
Archive(filename, backend).extractall(dire... | [
"def",
"extractall",
"(",
"filename",
",",
"directory",
",",
"backend",
"=",
"'auto'",
",",
"auto_create_dir",
"=",
"False",
")",
":",
"Archive",
"(",
"filename",
",",
"backend",
")",
".",
"extractall",
"(",
"directory",
",",
"auto_create_dir",
"=",
"auto_cr... | 43.666667 | 0.002494 |
def dispatch(self, *args, **kwargs):
"""This decorator sets this view to have restricted permissions."""
return super(AnimalYearArchive, self).dispatch(*args, **kwargs) | [
"def",
"dispatch",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"AnimalYearArchive",
",",
"self",
")",
".",
"dispatch",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 60.666667 | 0.01087 |
def setChatPhoto(self, chat_id, photo):
""" See: https://core.telegram.org/bots/api#setchatphoto """
p = _strip(locals(), more=['photo'])
return self._api_request_with_file('setChatPhoto', _rectify(p), 'photo', photo) | [
"def",
"setChatPhoto",
"(",
"self",
",",
"chat_id",
",",
"photo",
")",
":",
"p",
"=",
"_strip",
"(",
"locals",
"(",
")",
",",
"more",
"=",
"[",
"'photo'",
"]",
")",
"return",
"self",
".",
"_api_request_with_file",
"(",
"'setChatPhoto'",
",",
"_rectify",
... | 59.5 | 0.012448 |
def before_add_field(self, field):
"""
If extract_fields is set to True, then '*' fields will be removed and each
individual field will read from the model meta data and added.
"""
if self.extract_fields and field.name == '*':
field.ignore = True
fields = ... | [
"def",
"before_add_field",
"(",
"self",
",",
"field",
")",
":",
"if",
"self",
".",
"extract_fields",
"and",
"field",
".",
"name",
"==",
"'*'",
":",
"field",
".",
"ignore",
"=",
"True",
"fields",
"=",
"[",
"model_field",
".",
"column",
"for",
"model_field... | 45.666667 | 0.009547 |
def decode(self, litmap):
"""Convert the DNF to an expression."""
return Or(*[And(*[litmap[idx] for idx in clause])
for clause in self.clauses]) | [
"def",
"decode",
"(",
"self",
",",
"litmap",
")",
":",
"return",
"Or",
"(",
"*",
"[",
"And",
"(",
"*",
"[",
"litmap",
"[",
"idx",
"]",
"for",
"idx",
"in",
"clause",
"]",
")",
"for",
"clause",
"in",
"self",
".",
"clauses",
"]",
")"
] | 44.25 | 0.011111 |
def date_to_long_form_string(dt, locale_ = 'en_US.utf8'):
'''dt should be a datetime.date object.'''
if locale_:
old_locale = locale.getlocale()
locale.setlocale(locale.LC_ALL, locale_)
v = dt.strftime("%A %B %d %Y")
if locale_:
locale.setlocale(locale.LC_ALL, old_locale)
ret... | [
"def",
"date_to_long_form_string",
"(",
"dt",
",",
"locale_",
"=",
"'en_US.utf8'",
")",
":",
"if",
"locale_",
":",
"old_locale",
"=",
"locale",
".",
"getlocale",
"(",
")",
"locale",
".",
"setlocale",
"(",
"locale",
".",
"LC_ALL",
",",
"locale_",
")",
"v",
... | 35.222222 | 0.009231 |
def first_up(ofile, Rec, file_type):
"""
writes the header for a MagIC template file
"""
keylist = []
pmag_out = open(ofile, 'a')
outstring = "tab \t" + file_type + "\n"
pmag_out.write(outstring)
keystring = ""
for key in list(Rec.keys()):
keystring = keystring + '\t' + key
... | [
"def",
"first_up",
"(",
"ofile",
",",
"Rec",
",",
"file_type",
")",
":",
"keylist",
"=",
"[",
"]",
"pmag_out",
"=",
"open",
"(",
"ofile",
",",
"'a'",
")",
"outstring",
"=",
"\"tab \\t\"",
"+",
"file_type",
"+",
"\"\\n\"",
"pmag_out",
".",
"write",
"(",... | 27.375 | 0.002208 |
def color(requestContext, seriesList, theColor):
"""
Assigns the given color to the seriesList
Example::
&target=color(collectd.hostname.cpu.0.user, 'green')
&target=color(collectd.hostname.cpu.0.system, 'ff0000')
&target=color(collectd.hostname.cpu.0.idle, 'gray')
&target=... | [
"def",
"color",
"(",
"requestContext",
",",
"seriesList",
",",
"theColor",
")",
":",
"for",
"series",
"in",
"seriesList",
":",
"series",
".",
"color",
"=",
"theColor",
"return",
"seriesList"
] | 29.733333 | 0.002174 |
def dumps(o, preserve=False):
"""Stringifies input dict as toml
Args:
o: Object to dump into toml
preserve: Boolean parameter. If true, preserve inline tables.
Returns:
String containing the toml corresponding to dict
"""
retval = ""
addtoretval, sections = _dump_sect... | [
"def",
"dumps",
"(",
"o",
",",
"preserve",
"=",
"False",
")",
":",
"retval",
"=",
"\"\"",
"addtoretval",
",",
"sections",
"=",
"_dump_sections",
"(",
"o",
",",
"\"\"",
")",
"retval",
"+=",
"addtoretval",
"while",
"sections",
"!=",
"{",
"}",
":",
"newse... | 33.133333 | 0.000978 |
def abs_energy(self, x):
"""
As in tsfresh `abs_energy <https://github.com/blue-yonder/tsfresh/blob/master/tsfresh/feature_extraction/\
feature_calculators.py#L390>`_ \
Returns the absolute energy of the time series which is the sum over the squared values\
.. math::
... | [
"def",
"abs_energy",
"(",
"self",
",",
"x",
")",
":",
"_energy",
"=",
"feature_calculators",
".",
"abs_energy",
"(",
"x",
")",
"logging",
".",
"debug",
"(",
"\"abs energy by tsfresh calculated\"",
")",
"return",
"_energy"
] | 33.5 | 0.014514 |
def create_token_generator(input_list):
"""SQL Generator to select from list of values in Oracle"""
###Generator trick from http://betteratoracle.com/posts/20-how-do-i-bind-a-variable-in-list
###The maximum length of the comma separated list is 4000 characters, therefore we need to split the list
###ORA... | [
"def",
"create_token_generator",
"(",
"input_list",
")",
":",
"###Generator trick from http://betteratoracle.com/posts/20-how-do-i-bind-a-variable-in-list",
"###The maximum length of the comma separated list is 4000 characters, therefore we need to split the list",
"###ORA-01460: unimplemented or un... | 33.87234 | 0.015263 |
def init_file(self, filename, lines, expected, line_offset):
"""Prepare storage for errors."""
super(_PycodestyleReport, self).init_file(
filename, lines, expected, line_offset)
self.errors = [] | [
"def",
"init_file",
"(",
"self",
",",
"filename",
",",
"lines",
",",
"expected",
",",
"line_offset",
")",
":",
"super",
"(",
"_PycodestyleReport",
",",
"self",
")",
".",
"init_file",
"(",
"filename",
",",
"lines",
",",
"expected",
",",
"line_offset",
")",
... | 45.2 | 0.008696 |
def detectSonyMylo(self):
"""Return detection of a Sony Mylo device
Detects if the current browser is a Sony Mylo device.
"""
return UAgentInfo.manuSony in self.__userAgent \
and (UAgentInfo.qtembedded in self.__userAgent
or UAgentInfo.mylocom2 in self.__user... | [
"def",
"detectSonyMylo",
"(",
"self",
")",
":",
"return",
"UAgentInfo",
".",
"manuSony",
"in",
"self",
".",
"__userAgent",
"and",
"(",
"UAgentInfo",
".",
"qtembedded",
"in",
"self",
".",
"__userAgent",
"or",
"UAgentInfo",
".",
"mylocom2",
"in",
"self",
".",
... | 39.875 | 0.009202 |
def close(self):
'''Clean up.'''
for path in self._temp_filenames:
if os.path.exists(path):
os.remove(path) | [
"def",
"close",
"(",
"self",
")",
":",
"for",
"path",
"in",
"self",
".",
"_temp_filenames",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"os",
".",
"remove",
"(",
"path",
")"
] | 29.4 | 0.013245 |
def index_queryset(self, using=None):
"""Used when the entire index for model is updated."""
return self.get_model().objects.filter(
modified__lte=datetime.datetime.now(),
status=STATUS.published
) | [
"def",
"index_queryset",
"(",
"self",
",",
"using",
"=",
"None",
")",
":",
"return",
"self",
".",
"get_model",
"(",
")",
".",
"objects",
".",
"filter",
"(",
"modified__lte",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
",",
"status",
"=",
... | 40 | 0.008163 |
def decode_timeseries(self, resp_ttb, tsobj,
convert_timestamp=False):
"""
Fills an TsObject with the appropriate data and
metadata from a TTB-encoded TsGetResp / TsQueryResp.
:param resp_ttb: the decoded TTB data
:type resp_ttb: TTB-encoded tsqueryrsp ... | [
"def",
"decode_timeseries",
"(",
"self",
",",
"resp_ttb",
",",
"tsobj",
",",
"convert_timestamp",
"=",
"False",
")",
":",
"if",
"resp_ttb",
"is",
"None",
":",
"return",
"tsobj",
"self",
".",
"maybe_err_ttb",
"(",
"resp_ttb",
")",
"# NB: some queries return a BAR... | 37.93617 | 0.00164 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.