text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def get_first_part_id_for_assessment(assessment_id, runtime=None, proxy=None, create=False, bank_id=None):
"""Gets the first part id, which represents the first section, of assessment"""
if create and bank_id is None:
raise NullArgument('Bank Id must be provided for create option')
try:
retu... | [
"def",
"get_first_part_id_for_assessment",
"(",
"assessment_id",
",",
"runtime",
"=",
"None",
",",
"proxy",
"=",
"None",
",",
"create",
"=",
"False",
",",
"bank_id",
"=",
"None",
")",
":",
"if",
"create",
"and",
"bank_id",
"is",
"None",
":",
"raise",
"Null... | 49.909091 | 28.909091 |
def make_logger(name, stream_type, jobs):
"""Create a logger component.
:param name: name of logger child, i.e. logger will be named
`noodles.<name>`.
:type name: str
:param stream_type: type of the stream that this logger will
be inserted into, should be |pull_map| or |push_map|.
:... | [
"def",
"make_logger",
"(",
"name",
",",
"stream_type",
",",
"jobs",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"'noodles'",
")",
".",
"getChild",
"(",
"name",
")",
"# logger.setLevel(logging.DEBUG)",
"@",
"stream_type",
"def",
"log_message",
"(... | 34.346939 | 19.489796 |
def _tile(self, n):
"""Get the update tile surrounding particle `n` """
pos = self._trans(self.pos[n])
return Tile(pos, pos).pad(self.support_pad) | [
"def",
"_tile",
"(",
"self",
",",
"n",
")",
":",
"pos",
"=",
"self",
".",
"_trans",
"(",
"self",
".",
"pos",
"[",
"n",
"]",
")",
"return",
"Tile",
"(",
"pos",
",",
"pos",
")",
".",
"pad",
"(",
"self",
".",
"support_pad",
")"
] | 41.75 | 8.5 |
def _map_purchase_request_to_func(self, purchase_request_type):
"""Provides appropriate parameters to the on_purchase functions."""
if purchase_request_type in self._intent_view_funcs:
view_func = self._intent_view_funcs[purchase_request_type]
else:
raise NotImpl... | [
"def",
"_map_purchase_request_to_func",
"(",
"self",
",",
"purchase_request_type",
")",
":",
"if",
"purchase_request_type",
"in",
"self",
".",
"_intent_view_funcs",
":",
"view_func",
"=",
"self",
".",
"_intent_view_funcs",
"[",
"purchase_request_type",
"]",
"else",
":... | 52.214286 | 30.714286 |
def start(self):
"""
Start a producer/consumer service
"""
component = Component(self.config, self.handlers)
component.run() | [
"def",
"start",
"(",
"self",
")",
":",
"component",
"=",
"Component",
"(",
"self",
".",
"config",
",",
"self",
".",
"handlers",
")",
"component",
".",
"run",
"(",
")"
] | 26.5 | 9.833333 |
def replace_header(self, _name, _value):
"""Replace a header.
Replace the first matching header found in the message, retaining
header order and case. If no matching header was found, a KeyError is
raised.
"""
_name = _name.lower()
for i, (k, v) in zip(range(len... | [
"def",
"replace_header",
"(",
"self",
",",
"_name",
",",
"_value",
")",
":",
"_name",
"=",
"_name",
".",
"lower",
"(",
")",
"for",
"i",
",",
"(",
"k",
",",
"v",
")",
"in",
"zip",
"(",
"range",
"(",
"len",
"(",
"self",
".",
"_headers",
")",
")",... | 37.285714 | 19.5 |
def zs_to_ws(zs, MWs):
r'''Converts a list of mole fractions to mass fractions. Requires molecular
weights for all species.
.. math::
w_i = \frac{z_i MW_i}{MW_{avg}}
MW_{avg} = \sum_i z_i MW_i
Parameters
----------
zs : iterable
Mole fractions [-]
MWs : iterable
... | [
"def",
"zs_to_ws",
"(",
"zs",
",",
"MWs",
")",
":",
"Mavg",
"=",
"sum",
"(",
"zi",
"*",
"MWi",
"for",
"zi",
",",
"MWi",
"in",
"zip",
"(",
"zs",
",",
"MWs",
")",
")",
"ws",
"=",
"[",
"zi",
"*",
"MWi",
"/",
"Mavg",
"for",
"zi",
",",
"MWi",
... | 21.882353 | 24.058824 |
def get_allow_repeat_items_metadata(self):
"""get the metadata for allow repeat items"""
metadata = dict(self._allow_repeat_items_metadata)
metadata.update({'existing_id_values': self.my_osid_object_form._my_map['allowRepeatItems']})
return Metadata(**metadata) | [
"def",
"get_allow_repeat_items_metadata",
"(",
"self",
")",
":",
"metadata",
"=",
"dict",
"(",
"self",
".",
"_allow_repeat_items_metadata",
")",
"metadata",
".",
"update",
"(",
"{",
"'existing_id_values'",
":",
"self",
".",
"my_osid_object_form",
".",
"_my_map",
"... | 57.8 | 17.2 |
def _processEscapeSequences(replaceText):
"""Replace symbols like \n \\, etc
"""
def _replaceFunc(escapeMatchObject):
char = escapeMatchObject.group(0)[1]
if char in _escapeSequences:
return _escapeSequences[char]
return escapeMatchObject.group(0) # no any replacements,... | [
"def",
"_processEscapeSequences",
"(",
"replaceText",
")",
":",
"def",
"_replaceFunc",
"(",
"escapeMatchObject",
")",
":",
"char",
"=",
"escapeMatchObject",
".",
"group",
"(",
"0",
")",
"[",
"1",
"]",
"if",
"char",
"in",
"_escapeSequences",
":",
"return",
"_... | 35.272727 | 13.727273 |
def _get_retention_policy_value(self):
"""
Sets the deletion policy on this resource. The default is 'Retain'.
:return: value for the DeletionPolicy attribute.
"""
if self.RetentionPolicy is None or self.RetentionPolicy.lower() == self.RETAIN.lower():
return self.RE... | [
"def",
"_get_retention_policy_value",
"(",
"self",
")",
":",
"if",
"self",
".",
"RetentionPolicy",
"is",
"None",
"or",
"self",
".",
"RetentionPolicy",
".",
"lower",
"(",
")",
"==",
"self",
".",
"RETAIN",
".",
"lower",
"(",
")",
":",
"return",
"self",
"."... | 49.2 | 26.666667 |
def render_category_averages(obj, normalize_to=100):
"""Renders all the sub-averages for each category."""
context = {'reviewed_item': obj}
ctype = ContentType.objects.get_for_model(obj)
reviews = models.Review.objects.filter(
content_type=ctype, object_id=obj.id)
category_averages = {}
... | [
"def",
"render_category_averages",
"(",
"obj",
",",
"normalize_to",
"=",
"100",
")",
":",
"context",
"=",
"{",
"'reviewed_item'",
":",
"obj",
"}",
"ctype",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"obj",
")",
"reviews",
"=",
"models",
... | 47.225806 | 15.387097 |
def run_in_order(l, show_output=True, show_err=True, ignore_err=False,
args=(), **kwargs):
'''
Processes each element of l in order:
if it is a string: execute it as a shell command
elif it is a callable, call it with *args, **kwargs
l-->list: Each elem is either a string (... | [
"def",
"run_in_order",
"(",
"l",
",",
"show_output",
"=",
"True",
",",
"show_err",
"=",
"True",
",",
"ignore_err",
"=",
"False",
",",
"args",
"=",
"(",
")",
",",
"*",
"*",
"kwargs",
")",
":",
"# Set defaults",
"if",
"show_output",
"is",
"None",
":",
... | 39.782609 | 19.086957 |
def path(self, which=None):
"""Extend ``nailgun.entity_mixins.Entity.path``.
The format of the returned path depends on the value of ``which``:
smart_class_parameters
/api/puppetclasses/:puppetclass_id/smart_class_parameters
Otherwise, call ``super``.
"""
i... | [
"def",
"path",
"(",
"self",
",",
"which",
"=",
"None",
")",
":",
"if",
"which",
"in",
"(",
"'smart_class_parameters'",
",",
"'smart_variables'",
")",
":",
"return",
"'{0}/{1}'",
".",
"format",
"(",
"super",
"(",
"PuppetClass",
",",
"self",
")",
".",
"pat... | 34.25 | 19.9375 |
def process_mavlink_packet(self, m):
'''handle an incoming mavlink packet'''
mtype = m.get_type()
# if you add processing for an mtype here, remember to add it
# to mavlink_packet, above
if mtype in ['WAYPOINT_COUNT','MISSION_COUNT']:
if (self.num_wps_expected == 0):... | [
"def",
"process_mavlink_packet",
"(",
"self",
",",
"m",
")",
":",
"mtype",
"=",
"m",
".",
"get_type",
"(",
")",
"# if you add processing for an mtype here, remember to add it",
"# to mavlink_packet, above",
"if",
"mtype",
"in",
"[",
"'WAYPOINT_COUNT'",
",",
"'MISSION_CO... | 51.15 | 21.05 |
def describe_identity_pools(IdentityPoolName, IdentityPoolId=None,
region=None, key=None, keyid=None, profile=None):
'''
Given an identity pool name, (optionally if an identity pool id is given,
the given name will be ignored)
Returns a list of matched identity pool name's pool properti... | [
"def",
"describe_identity_pools",
"(",
"IdentityPoolName",
",",
"IdentityPoolId",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
... | 34.242424 | 27.69697 |
def recursive_symlink_dirs(source_d, destination_d):
'''
Create dirs and symlink all files recursively from source_d, ignoring
errors (e.g. existing files)
'''
func = os.symlink
if os.name == 'nt':
# NOTE: need to verify that default perms only allow admins to create
# symlinks o... | [
"def",
"recursive_symlink_dirs",
"(",
"source_d",
",",
"destination_d",
")",
":",
"func",
"=",
"os",
".",
"symlink",
"if",
"os",
".",
"name",
"==",
"'nt'",
":",
"# NOTE: need to verify that default perms only allow admins to create",
"# symlinks on Windows",
"func",
"="... | 36.846154 | 19.461538 |
def intuition(args):
'''
Main simulation wrapper
Load the configuration, run the engine and return the analyze.
'''
# Use the provided context builder to fill:
# - config: General behavior
# - strategy: Modules properties
# - market: The universe we will trade on
with setup.Co... | [
"def",
"intuition",
"(",
"args",
")",
":",
"# Use the provided context builder to fill:",
"# - config: General behavior",
"# - strategy: Modules properties",
"# - market: The universe we will trade on",
"with",
"setup",
".",
"Context",
"(",
"args",
"[",
"'context'",
"]",
... | 35.977273 | 16.613636 |
def instance_norm(attrs, inputs, proto_obj):
"""Instance Normalization."""
new_attrs = translation_utils._fix_attribute_names(attrs, {'epsilon' : 'eps'})
new_attrs['eps'] = attrs.get('epsilon', 1e-5)
return 'InstanceNorm', new_attrs, inputs | [
"def",
"instance_norm",
"(",
"attrs",
",",
"inputs",
",",
"proto_obj",
")",
":",
"new_attrs",
"=",
"translation_utils",
".",
"_fix_attribute_names",
"(",
"attrs",
",",
"{",
"'epsilon'",
":",
"'eps'",
"}",
")",
"new_attrs",
"[",
"'eps'",
"]",
"=",
"attrs",
... | 50.4 | 11.8 |
def callAfter(func, *args, **kwargs):
"""call a function on the main thread (async)"""
pool = NSAutoreleasePool.alloc().init()
obj = PyObjCAppHelperCaller_wrap.alloc().initWithArgs_((func, args, kwargs))
obj.callAfter_(None)
del obj
del pool | [
"def",
"callAfter",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"pool",
"=",
"NSAutoreleasePool",
".",
"alloc",
"(",
")",
".",
"init",
"(",
")",
"obj",
"=",
"PyObjCAppHelperCaller_wrap",
".",
"alloc",
"(",
")",
".",
"initWithArgs_... | 37 | 17 |
def touch_log(log, cwd='.'):
"""
Touches the log file. Creates if not exists OR updates the modification date if exists.
:param log:
:return: nothing
"""
logfile = '%s/%s' % (cwd, log)
with open(logfile, 'a'):
os.utime(logfile, None) | [
"def",
"touch_log",
"(",
"log",
",",
"cwd",
"=",
"'.'",
")",
":",
"logfile",
"=",
"'%s/%s'",
"%",
"(",
"cwd",
",",
"log",
")",
"with",
"open",
"(",
"logfile",
",",
"'a'",
")",
":",
"os",
".",
"utime",
"(",
"logfile",
",",
"None",
")"
] | 27 | 16.111111 |
def _cache_metrics_metadata(self, instance):
"""
Get all the performance counters metadata meaning name/group/description...
from the server instance, attached with the corresponding ID
"""
# ## <TEST-INSTRUMENTATION>
t = Timer()
# ## </TEST-INSTRUMENTATION>
... | [
"def",
"_cache_metrics_metadata",
"(",
"self",
",",
"instance",
")",
":",
"# ## <TEST-INSTRUMENTATION>",
"t",
"=",
"Timer",
"(",
")",
"# ## </TEST-INSTRUMENTATION>",
"i_key",
"=",
"self",
".",
"_instance_key",
"(",
"instance",
")",
"self",
".",
"metadata_cache",
"... | 52.690476 | 28.833333 |
def mutual_info_score(self, reference_clusters):
"""
Calculates the MI (mutual information) w.r.t. the reference clusters (explicit evaluation)
:param reference_clusters: Clusters that are to be used as reference
:return: The resulting MI score.
"""
return mutual_info_sc... | [
"def",
"mutual_info_score",
"(",
"self",
",",
"reference_clusters",
")",
":",
"return",
"mutual_info_score",
"(",
"self",
".",
"get_labels",
"(",
"self",
")",
",",
"self",
".",
"get_labels",
"(",
"reference_clusters",
")",
")"
] | 47 | 24.25 |
def get_doc(self, objtxt):
"""Get object documentation dictionary"""
obj, valid = self._eval(objtxt)
if valid:
return getdoc(obj) | [
"def",
"get_doc",
"(",
"self",
",",
"objtxt",
")",
":",
"obj",
",",
"valid",
"=",
"self",
".",
"_eval",
"(",
"objtxt",
")",
"if",
"valid",
":",
"return",
"getdoc",
"(",
"obj",
")"
] | 33 | 9 |
def idxmax(self,skipna=True, axis=0):
"""
Get the index of the max value in a column or row
:param bool skipna: If True (default), then NAs are ignored during the search. Otherwise presence
of NAs renders the entire result NA.
:param int axis: Direction of finding the max in... | [
"def",
"idxmax",
"(",
"self",
",",
"skipna",
"=",
"True",
",",
"axis",
"=",
"0",
")",
":",
"return",
"H2OFrame",
".",
"_expr",
"(",
"expr",
"=",
"ExprNode",
"(",
"\"which.max\"",
",",
"self",
",",
"skipna",
",",
"axis",
")",
")"
] | 67.923077 | 39 |
def bind_top_down(lower, upper, __fval=None, **fval):
"""Bind 2 layers for building.
When the upper layer is added as a payload of the lower layer, all the arguments # noqa: E501
will be applied to them.
ex:
>>> bind_top_down(Ether, SNAP, type=0x1234)
>>> Ether()/SNAP()
<Ether ... | [
"def",
"bind_top_down",
"(",
"lower",
",",
"upper",
",",
"__fval",
"=",
"None",
",",
"*",
"*",
"fval",
")",
":",
"if",
"__fval",
"is",
"not",
"None",
":",
"fval",
".",
"update",
"(",
"__fval",
")",
"upper",
".",
"_overload_fields",
"=",
"upper",
".",... | 35.285714 | 16.214286 |
def build_filter(self, filter):
"""
Tries to build a :class:`filter.Filter` instance from the given filter.
Raises ValueError if the :class:`filter.Filter` object can't be build
from the given filter.
"""
try:
self.filter = Filter.from_string(filter, self.lim... | [
"def",
"build_filter",
"(",
"self",
",",
"filter",
")",
":",
"try",
":",
"self",
".",
"filter",
"=",
"Filter",
".",
"from_string",
"(",
"filter",
",",
"self",
".",
"limit",
")",
"except",
"ValueError",
":",
"raise",
"return",
"self"
] | 29 | 21.923077 |
def notification_message(self, title, content, icon=""):
"""This function sends "javascript" message to the client, that executes its content.
In this particular code, a notification message is shown
"""
code = """
var options = {
body: "%(content)s",
... | [
"def",
"notification_message",
"(",
"self",
",",
"title",
",",
"content",
",",
"icon",
"=",
"\"\"",
")",
":",
"code",
"=",
"\"\"\"\n var options = {\n body: \"%(content)s\",\n icon: \"%(icon)s\"\n }\n if (!(\"Notification... | 45 | 15.181818 |
def files(self):
"""Return list of files in root directory"""
self._printer('\tFiles Walk')
for directory in self.directory:
for path in os.listdir(directory):
full_path = os.path.join(directory, path)
if os.path.isfile(full_path):
... | [
"def",
"files",
"(",
"self",
")",
":",
"self",
".",
"_printer",
"(",
"'\\tFiles Walk'",
")",
"for",
"directory",
"in",
"self",
".",
"directory",
":",
"for",
"path",
"in",
"os",
".",
"listdir",
"(",
"directory",
")",
":",
"full_path",
"=",
"os",
".",
... | 43.3 | 8.3 |
def go_to_line(self):
"""
Moves current **Script_Editor_tabWidget** Widget tab Model editor cursor to user defined line.
:return: Method success.
:rtype: bool
:note: May require user interaction.
"""
editor = self.get_current_editor()
if not editor:
... | [
"def",
"go_to_line",
"(",
"self",
")",
":",
"editor",
"=",
"self",
".",
"get_current_editor",
"(",
")",
"if",
"not",
"editor",
":",
"return",
"False",
"line",
",",
"state",
"=",
"QInputDialog",
".",
"getInt",
"(",
"self",
",",
"\"Goto Line Number\"",
",",
... | 28.35 | 23.05 |
def _begin_write(session: UpdateSession,
loop: asyncio.AbstractEventLoop,
rootfs_file_path: str):
""" Start the write process. """
session.set_progress(0)
session.set_stage(Stages.WRITING)
write_future = asyncio.ensure_future(loop.run_in_executor(
None, file_act... | [
"def",
"_begin_write",
"(",
"session",
":",
"UpdateSession",
",",
"loop",
":",
"asyncio",
".",
"AbstractEventLoop",
",",
"rootfs_file_path",
":",
"str",
")",
":",
"session",
".",
"set_progress",
"(",
"0",
")",
"session",
".",
"set_stage",
"(",
"Stages",
".",... | 34.473684 | 14.263158 |
def pictures(self):
"""list[Picture]: List of embedded pictures"""
return [b for b in self.metadata_blocks if b.code == Picture.code] | [
"def",
"pictures",
"(",
"self",
")",
":",
"return",
"[",
"b",
"for",
"b",
"in",
"self",
".",
"metadata_blocks",
"if",
"b",
".",
"code",
"==",
"Picture",
".",
"code",
"]"
] | 36.75 | 23.75 |
def snooze(self, requester, duration):
"""Snooze incident.
:param requester: The email address of the individual requesting snooze.
"""
path = '{0}/{1}/{2}'.format(self.collection.name, self.id, 'snooze')
data = {"duration": duration}
extra_headers = {"From": requester}
... | [
"def",
"snooze",
"(",
"self",
",",
"requester",
",",
"duration",
")",
":",
"path",
"=",
"'{0}/{1}/{2}'",
".",
"format",
"(",
"self",
".",
"collection",
".",
"name",
",",
"self",
".",
"id",
",",
"'snooze'",
")",
"data",
"=",
"{",
"\"duration\"",
":",
... | 52.125 | 18.625 |
def lines_from_file(path, as_interned=False, encoding=None):
"""
Create a list of file lines from a given filepath.
Args:
path (str): File path
as_interned (bool): List of "interned" strings (default False)
Returns:
strings (list): File line list
"""
lines = None
wi... | [
"def",
"lines_from_file",
"(",
"path",
",",
"as_interned",
"=",
"False",
",",
"encoding",
"=",
"None",
")",
":",
"lines",
"=",
"None",
"with",
"io",
".",
"open",
"(",
"path",
",",
"encoding",
"=",
"encoding",
")",
"as",
"f",
":",
"if",
"as_interned",
... | 28.555556 | 19.333333 |
def normalized_mutation_entropy(counts, total_cts=None):
"""Calculate the normalized mutation entropy based on a list/array
of mutation counts.
Note: Any grouping of mutation counts together should be done before hand
Parameters
----------
counts : np.array_like
array/list of mutation ... | [
"def",
"normalized_mutation_entropy",
"(",
"counts",
",",
"total_cts",
"=",
"None",
")",
":",
"cts",
"=",
"np",
".",
"asarray",
"(",
"counts",
",",
"dtype",
"=",
"float",
")",
"if",
"total_cts",
"is",
"None",
":",
"total_cts",
"=",
"np",
".",
"sum",
"(... | 27.074074 | 18.740741 |
def getName(self):
r"""
Returns the results name for this token expression. Useful when several
different expressions might match at a particular location.
Example::
integer = Word(nums)
ssn_expr = Regex(r"\d\d\d-\d\d-\d\d\d\d")
house_number_expr = S... | [
"def",
"getName",
"(",
"self",
")",
":",
"if",
"self",
".",
"__name",
":",
"return",
"self",
".",
"__name",
"elif",
"self",
".",
"__parent",
":",
"par",
"=",
"self",
".",
"__parent",
"(",
")",
"if",
"par",
":",
"return",
"par",
".",
"__lookup",
"("... | 32.179487 | 18.358974 |
def getWifiInfo(self, wifiInterfaceId=1, timeout=1):
"""Execute GetInfo action to get Wifi basic information's.
:param int wifiInterfaceId: the id of the Wifi interface
:param float timeout: the timeout to wait for the action to be executed
:return: the basic informations
:rtype... | [
"def",
"getWifiInfo",
"(",
"self",
",",
"wifiInterfaceId",
"=",
"1",
",",
"timeout",
"=",
"1",
")",
":",
"namespace",
"=",
"Wifi",
".",
"getServiceType",
"(",
"\"getWifiInfo\"",
")",
"+",
"str",
"(",
"wifiInterfaceId",
")",
"uri",
"=",
"self",
".",
"getC... | 40.785714 | 20.285714 |
def _compute_log_acceptance_correction(current_state_parts,
proposed_state_parts,
current_volatility_parts,
proposed_volatility_parts,
current_drift_parts,
... | [
"def",
"_compute_log_acceptance_correction",
"(",
"current_state_parts",
",",
"proposed_state_parts",
",",
"current_volatility_parts",
",",
"proposed_volatility_parts",
",",
"current_drift_parts",
",",
"proposed_drift_parts",
",",
"step_size_parts",
",",
"independent_chain_ndims",
... | 40.860656 | 23.081967 |
def namedb_get_names_owned_by_address( cur, address, current_block ):
"""
Get the list of non-expired, non-revoked names owned by an address.
Only works if there is a *singular* address for the name.
"""
unexpired_fragment, unexpired_args = namedb_select_where_unexpired_names( current_block )
... | [
"def",
"namedb_get_names_owned_by_address",
"(",
"cur",
",",
"address",
",",
"current_block",
")",
":",
"unexpired_fragment",
",",
"unexpired_args",
"=",
"namedb_select_where_unexpired_names",
"(",
"current_block",
")",
"select_query",
"=",
"\"SELECT name FROM name_records JO... | 36.5 | 29.136364 |
def get_by_code(self, code):
"""
Retrieve a language by a code.
:param code: iso code (any of the three) or its culture code
:return: a Language object
"""
if any(x in code for x in ('_', '-')):
cc = CultureCode.objects.get(code=code.replace('_', '-'))
... | [
"def",
"get_by_code",
"(",
"self",
",",
"code",
")",
":",
"if",
"any",
"(",
"x",
"in",
"code",
"for",
"x",
"in",
"(",
"'_'",
",",
"'-'",
")",
")",
":",
"cc",
"=",
"CultureCode",
".",
"objects",
".",
"get",
"(",
"code",
"=",
"code",
".",
"replac... | 32.666667 | 17.238095 |
def build(self, text):
"""
:param text: Content of the paragraph
"""
super(Paragraph, self).build()
self.content = text | [
"def",
"build",
"(",
"self",
",",
"text",
")",
":",
"super",
"(",
"Paragraph",
",",
"self",
")",
".",
"build",
"(",
")",
"self",
".",
"content",
"=",
"text"
] | 25.666667 | 6.333333 |
def loop_check(self):
"""Check if we have a loop in the graph
:return: Nodes in loop
:rtype: list
"""
in_loop = []
# Add the tag for dfs check
for node in list(self.nodes.values()):
node['dfs_loop_status'] = 'DFS_UNCHECKED'
# Now do the job
... | [
"def",
"loop_check",
"(",
"self",
")",
":",
"in_loop",
"=",
"[",
"]",
"# Add the tag for dfs check",
"for",
"node",
"in",
"list",
"(",
"self",
".",
"nodes",
".",
"values",
"(",
")",
")",
":",
"node",
"[",
"'dfs_loop_status'",
"]",
"=",
"'DFS_UNCHECKED'",
... | 32.2 | 15.96 |
def get_all_memberships(
self, limit_to=100, max_calls=None, parameters=None,
since_when=None, start_record=0, verbose=False):
"""
Retrieve all memberships updated since "since_when"
Loop over queries of size limit_to until either a non-full queryset
is returned,... | [
"def",
"get_all_memberships",
"(",
"self",
",",
"limit_to",
"=",
"100",
",",
"max_calls",
"=",
"None",
",",
"parameters",
"=",
"None",
",",
"since_when",
"=",
"None",
",",
"start_record",
"=",
"0",
",",
"verbose",
"=",
"False",
")",
":",
"if",
"not",
"... | 36.511628 | 20.093023 |
def accel_toggle_transparency(self, *args):
"""Callback to toggle transparency.
"""
self.transparency_toggled = not self.transparency_toggled
self.settings.styleBackground.triggerOnChangedValue(
self.settings.styleBackground, 'transparency'
)
return True | [
"def",
"accel_toggle_transparency",
"(",
"self",
",",
"*",
"args",
")",
":",
"self",
".",
"transparency_toggled",
"=",
"not",
"self",
".",
"transparency_toggled",
"self",
".",
"settings",
".",
"styleBackground",
".",
"triggerOnChangedValue",
"(",
"self",
".",
"s... | 38.375 | 14.625 |
def explore_server(server_url, username, password):
""" Demo of exploring a cim server for characteristics defined by
the server class
"""
print("WBEM server URL:\n %s" % server_url)
conn = WBEMConnection(server_url, (username, password),
no_verification=True)
se... | [
"def",
"explore_server",
"(",
"server_url",
",",
"username",
",",
"password",
")",
":",
"print",
"(",
"\"WBEM server URL:\\n %s\"",
"%",
"server_url",
")",
"conn",
"=",
"WBEMConnection",
"(",
"server_url",
",",
"(",
"username",
",",
"password",
")",
",",
"no_... | 34.449275 | 16.623188 |
def replace_bytes(self, m):
"""Replace escapes."""
esc = m.group(0)
value = esc
if m.group('special'):
value = BACK_SLASH_TRANSLATION[esc]
elif m.group('char'):
try:
value = chr(int(esc[2:], 16))
except Exception:
... | [
"def",
"replace_bytes",
"(",
"self",
",",
"m",
")",
":",
"esc",
"=",
"m",
".",
"group",
"(",
"0",
")",
"value",
"=",
"esc",
"if",
"m",
".",
"group",
"(",
"'special'",
")",
":",
"value",
"=",
"BACK_SLASH_TRANSLATION",
"[",
"esc",
"]",
"elif",
"m",
... | 28.5 | 12.5 |
def get_sshconfig():
r'''
Read user's SSH configuration file
'''
with open(os.path.expanduser('~/.ssh/config')) as f:
cfg = paramiko.SSHConfig()
cfg.parse(f)
ret_dict = {}
for d in cfg._config:
_copy = dict(d)
# Avoid buggy behavior with strange h... | [
"def",
"get_sshconfig",
"(",
")",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~/.ssh/config'",
")",
")",
"as",
"f",
":",
"cfg",
"=",
"paramiko",
".",
"SSHConfig",
"(",
")",
"cfg",
".",
"parse",
"(",
"f",
")",
"ret_dict",
... | 27.944444 | 18.388889 |
def circuit_to_pdf_using_qcircuit_via_tex(circuit: circuits.Circuit,
filepath: str,
pdf_kwargs=None,
qcircuit_kwargs=None,
clean_ext=('dvi', 'ps'),
... | [
"def",
"circuit_to_pdf_using_qcircuit_via_tex",
"(",
"circuit",
":",
"circuits",
".",
"Circuit",
",",
"filepath",
":",
"str",
",",
"pdf_kwargs",
"=",
"None",
",",
"qcircuit_kwargs",
"=",
"None",
",",
"clean_ext",
"=",
"(",
"'dvi'",
",",
"'ps'",
")",
",",
"do... | 48.205882 | 16.882353 |
def read_contents(self, name, conn):
'''Read schema tables'''
sql = '''select c.relname,
d.description,
case c.relkind
when 'r' then 'table'
when 'v' then 'view'
when 'm' then 'm... | [
"def",
"read_contents",
"(",
"self",
",",
"name",
",",
"conn",
")",
":",
"sql",
"=",
"'''select c.relname,\n d.description,\n case c.relkind\n when 'r' then 'table'\n when 'v' then 'view'\n ... | 45.413793 | 12.655172 |
def is_API_online(self):
"""
Returns True if the OWM Weather API is currently online. A short timeout
is used to determine API service availability.
:returns: bool
"""
params = {'q': 'London,GB'}
uri = http_client.HttpClient.to_url(OBSERVATION_URL,
... | [
"def",
"is_API_online",
"(",
"self",
")",
":",
"params",
"=",
"{",
"'q'",
":",
"'London,GB'",
"}",
"uri",
"=",
"http_client",
".",
"HttpClient",
".",
"to_url",
"(",
"OBSERVATION_URL",
",",
"self",
".",
"_API_key",
",",
"self",
".",
"_subscription_type",
")... | 35.411765 | 20 |
def shutdown(self):
"""
Signals worker to shutdown (via sentinel) then cleanly joins the thread
"""
self.shutdownLocal()
newJobsQueue = self.newJobsQueue
self.newJobsQueue = None
newJobsQueue.put(None)
self.worker.join() | [
"def",
"shutdown",
"(",
"self",
")",
":",
"self",
".",
"shutdownLocal",
"(",
")",
"newJobsQueue",
"=",
"self",
".",
"newJobsQueue",
"self",
".",
"newJobsQueue",
"=",
"None",
"newJobsQueue",
".",
"put",
"(",
"None",
")",
"self",
".",
"worker",
".",
"join"... | 27.6 | 14.4 |
def artifact_cache_dir(self):
"""Note that this is unrelated to the general pants artifact cache."""
return (self.get_options().artifact_cache_dir or
os.path.join(self.scratch_dir, 'artifacts')) | [
"def",
"artifact_cache_dir",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"get_options",
"(",
")",
".",
"artifact_cache_dir",
"or",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"scratch_dir",
",",
"'artifacts'",
")",
")"
] | 52.75 | 9.75 |
def long_click(self):
'''
Perform a long click action on the object.
Usage:
d(text="Image").long_click() # long click on the center of the ui object
d(text="Image").long_click.topleft() # long click on the topleft of the ui object
d(text="Image").long_click.bottomright(... | [
"def",
"long_click",
"(",
"self",
")",
":",
"@",
"param_to_property",
"(",
"corner",
"=",
"[",
"\"tl\"",
",",
"\"topleft\"",
",",
"\"br\"",
",",
"\"bottomright\"",
"]",
")",
"def",
"_long_click",
"(",
"corner",
"=",
"None",
")",
":",
"info",
"=",
"self",... | 48.448276 | 22.931034 |
def submit_file_content(self, method, url, data, headers, params, halt_on_error=True):
"""Submit File Content for Documents and Reports to ThreatConnect API.
Args:
method (str): The HTTP method for the request (POST, PUT).
url (str): The URL for the request.
data (st... | [
"def",
"submit_file_content",
"(",
"self",
",",
"method",
",",
"url",
",",
"data",
",",
"headers",
",",
"params",
",",
"halt_on_error",
"=",
"True",
")",
":",
"r",
"=",
"None",
"try",
":",
"r",
"=",
"self",
".",
"tcex",
".",
"session",
".",
"request"... | 45.15 | 26.4 |
def item(self):
""" ToDo
>>> from hydpy.core.examples import prepare_full_example_1
>>> prepare_full_example_1()
>>> from hydpy import HydPy, TestIO, XMLInterface, pub
>>> hp = HydPy('LahnH')
>>> pub.timegrids = '1996-01-01', '1996-01-06', '1d'
>>> with TestIO()... | [
"def",
"item",
"(",
"self",
")",
":",
"target",
"=",
"f'{self.master.name}.{self.name}'",
"if",
"self",
".",
"master",
".",
"name",
"==",
"'nodes'",
":",
"master",
"=",
"self",
".",
"master",
".",
"name",
"itemgroup",
"=",
"self",
".",
"master",
".",
"ma... | 42.735537 | 20.826446 |
def can_add_lv_load_area(self, node):
# TODO: check docstring
"""Sums up peak load of LV stations
That is, total peak load for satellite string
Args
----
node: GridDing0
Descr
Returns
-------
bool
... | [
"def",
"can_add_lv_load_area",
"(",
"self",
",",
"node",
")",
":",
"# TODO: check docstring",
"# get power factor for loads",
"cos_phi_load",
"=",
"cfg_ding0",
".",
"get",
"(",
"'assumptions'",
",",
"'cos_phi_load'",
")",
"lv_load_area",
"=",
"node",
".",
"lv_load_are... | 33.178571 | 24.214286 |
def _dump_query_timestamps(self, current_time: float):
"""Output the number of GraphQL queries grouped by their query_hash within the last time."""
windows = [10, 11, 15, 20, 30, 60]
print("GraphQL requests:", file=sys.stderr)
for query_hash, times in self._graphql_query_timestamps.items... | [
"def",
"_dump_query_timestamps",
"(",
"self",
",",
"current_time",
":",
"float",
")",
":",
"windows",
"=",
"[",
"10",
",",
"11",
",",
"15",
",",
"20",
",",
"30",
",",
"60",
"]",
"print",
"(",
"\"GraphQL requests:\"",
",",
"file",
"=",
"sys",
".",
"st... | 68.666667 | 23.333333 |
def get_scores(self, *args):
'''
In this case, parameters a and b aren't used, since this information is taken
directly from the corpus categories.
Returns
-------
'''
def jelinek_mercer_smoothing(cat):
p_hat_w = self.tdf_[cat] * 1. / self.tdf_[cat].sum()
c_hat_w = (self.smoothing_lambda_) * self... | [
"def",
"get_scores",
"(",
"self",
",",
"*",
"args",
")",
":",
"def",
"jelinek_mercer_smoothing",
"(",
"cat",
")",
":",
"p_hat_w",
"=",
"self",
".",
"tdf_",
"[",
"cat",
"]",
"*",
"1.",
"/",
"self",
".",
"tdf_",
"[",
"cat",
"]",
".",
"sum",
"(",
")... | 28.347826 | 26.086957 |
def set_secondary_vehicle_position(self, m):
'''store second vehicle position for filtering purposes'''
if m.get_type() != 'GLOBAL_POSITION_INT':
return
(lat, lon, heading) = (m.lat*1.0e-7, m.lon*1.0e-7, m.hdg*0.01)
if abs(lat) < 1.0e-3 and abs(lon) < 1.0e-3:
retu... | [
"def",
"set_secondary_vehicle_position",
"(",
"self",
",",
"m",
")",
":",
"if",
"m",
".",
"get_type",
"(",
")",
"!=",
"'GLOBAL_POSITION_INT'",
":",
"return",
"(",
"lat",
",",
"lon",
",",
"heading",
")",
"=",
"(",
"m",
".",
"lat",
"*",
"1.0e-7",
",",
... | 44.625 | 15.625 |
def get_ips(self, instance_id):
"""Retrieves all IP addresses associated to a given instance.
:return: tuple (IPs)
"""
self._init_os_api()
instance = self._load_instance(instance_id)
try:
ip_addrs = set([self.floating_ip])
except AttributeError:
... | [
"def",
"get_ips",
"(",
"self",
",",
"instance_id",
")",
":",
"self",
".",
"_init_os_api",
"(",
")",
"instance",
"=",
"self",
".",
"_load_instance",
"(",
"instance_id",
")",
"try",
":",
"ip_addrs",
"=",
"set",
"(",
"[",
"self",
".",
"floating_ip",
"]",
... | 35.133333 | 13.8 |
def get_chebi_name_from_id(chebi_id, offline=False):
"""Return a ChEBI name corresponding to the given ChEBI ID.
Parameters
----------
chebi_id : str
The ChEBI ID whose name is to be returned.
offline : Optional[bool]
Choose whether to allow an online lookup if the local lookup fail... | [
"def",
"get_chebi_name_from_id",
"(",
"chebi_id",
",",
"offline",
"=",
"False",
")",
":",
"chebi_name",
"=",
"chebi_id_to_name",
".",
"get",
"(",
"chebi_id",
")",
"if",
"chebi_name",
"is",
"None",
"and",
"not",
"offline",
":",
"chebi_name",
"=",
"get_chebi_nam... | 33.190476 | 19.47619 |
def _convert(x, factor1, factor2):
"""
Converts mixing ratio x in comp1 - comp2 tie line to that in
c1 - c2 tie line.
Args:
x (float): Mixing ratio x in comp1 - comp2 tie line, a float
between 0 and 1.
factor1 (float): Compositional ratio between ... | [
"def",
"_convert",
"(",
"x",
",",
"factor1",
",",
"factor2",
")",
":",
"return",
"x",
"*",
"factor2",
"/",
"(",
"(",
"1",
"-",
"x",
")",
"*",
"factor1",
"+",
"x",
"*",
"factor2",
")"
] | 40.611111 | 21.611111 |
def sigmasq(htilde, psd = None, low_frequency_cutoff=None,
high_frequency_cutoff=None):
"""Return the loudness of the waveform. This is defined (see Duncan
Brown's thesis) as the unnormalized matched-filter of the input waveform,
htilde, with itself. This quantity is usually referred to as (sigm... | [
"def",
"sigmasq",
"(",
"htilde",
",",
"psd",
"=",
"None",
",",
"low_frequency_cutoff",
"=",
"None",
",",
"high_frequency_cutoff",
"=",
"None",
")",
":",
"htilde",
"=",
"make_frequency_series",
"(",
"htilde",
")",
"N",
"=",
"(",
"len",
"(",
"htilde",
")",
... | 34.853659 | 20.853659 |
def get_tx_out(self, tx_hash, vout_id, id=None, endpoint=None):
"""
Gets a transaction output by specified transaction hash and output index
Args:
tx_hash: (str) hash in the form '58c634f81fbd4ae2733d7e3930a9849021840fc19dc6af064d6f2812a333f91d'
vout_id: (int) index of th... | [
"def",
"get_tx_out",
"(",
"self",
",",
"tx_hash",
",",
"vout_id",
",",
"id",
"=",
"None",
",",
"endpoint",
"=",
"None",
")",
":",
"return",
"self",
".",
"_call_endpoint",
"(",
"GET_TX_OUT",
",",
"params",
"=",
"[",
"tx_hash",
",",
"vout_id",
"]",
",",
... | 57.75 | 31.083333 |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'name') and self.name is not None:
_dict['name'] = self.name
if hasattr(self, 'description') and self.description is not None:
_dict['description'] = self.descr... | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'name'",
")",
"and",
"self",
".",
"name",
"is",
"not",
"None",
":",
"_dict",
"[",
"'name'",
"]",
"=",
"self",
".",
"name",
"if",
"hasattr",
"(",... | 54.405405 | 21.405405 |
def _normalize_options(self, options):
"""
Generator of 2-tuples (option-key, option-value).
When options spec is a list, generate a 2-tuples per list item.
:param options: dict {option: value}
returns:
iterator (option-key, option-value)
- option names lowe... | [
"def",
"_normalize_options",
"(",
"self",
",",
"options",
")",
":",
"for",
"key",
",",
"value",
"in",
"list",
"(",
"options",
".",
"items",
"(",
")",
")",
":",
"if",
"'--'",
"in",
"key",
":",
"normalized_key",
"=",
"self",
".",
"_normalize_arg",
"(",
... | 36.652174 | 17.26087 |
def prepare_to_generate(self, data_dir, tmp_dir):
"""Make sure that the data is prepared and the vocab is generated."""
self.get_or_create_vocab(data_dir, tmp_dir)
self.train_text_filepaths(tmp_dir)
self.dev_text_filepaths(tmp_dir) | [
"def",
"prepare_to_generate",
"(",
"self",
",",
"data_dir",
",",
"tmp_dir",
")",
":",
"self",
".",
"get_or_create_vocab",
"(",
"data_dir",
",",
"tmp_dir",
")",
"self",
".",
"train_text_filepaths",
"(",
"tmp_dir",
")",
"self",
".",
"dev_text_filepaths",
"(",
"t... | 48.6 | 4.4 |
def smart_search(cls, query_string, search_options=None, extra_query = None):
""" Perform a smart VRF search.
Maps to the function
:py:func:`nipap.backend.Nipap.smart_search_vrf` in the backend.
Please see the documentation for the backend function for
informatio... | [
"def",
"smart_search",
"(",
"cls",
",",
"query_string",
",",
"search_options",
"=",
"None",
",",
"extra_query",
"=",
"None",
")",
":",
"if",
"search_options",
"is",
"None",
":",
"search_options",
"=",
"{",
"}",
"xmlrpc",
"=",
"XMLRPCConnection",
"(",
")",
... | 39.029412 | 17.794118 |
def downside_risk(returns, required_return=0, period=DAILY):
"""
Determines the downside deviation below a threshold
Parameters
----------
returns : pd.Series or pd.DataFrame
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~pyfolio.timeseries.cum_retur... | [
"def",
"downside_risk",
"(",
"returns",
",",
"required_return",
"=",
"0",
",",
"period",
"=",
"DAILY",
")",
":",
"return",
"ep",
".",
"downside_risk",
"(",
"returns",
",",
"required_return",
"=",
"required_return",
",",
"period",
"=",
"period",
")"
] | 30.142857 | 18.428571 |
def parse(self, url):
"""
Return a configuration dict from a URL
"""
parsed_url = urlparse.urlparse(url)
try:
default_config = self.CONFIG[parsed_url.scheme]
except KeyError:
raise ValueError(
'unrecognised URL scheme for {}: {}'.fo... | [
"def",
"parse",
"(",
"self",
",",
"url",
")",
":",
"parsed_url",
"=",
"urlparse",
".",
"urlparse",
"(",
"url",
")",
"try",
":",
"default_config",
"=",
"self",
".",
"CONFIG",
"[",
"parsed_url",
".",
"scheme",
"]",
"except",
"KeyError",
":",
"raise",
"Va... | 37 | 11.714286 |
def get_opcodes_from_bp_table(bp):
"""Given a 2d list structure, collect the opcodes from the best path."""
x = len(bp) - 1
y = len(bp[0]) - 1
opcodes = []
while x != 0 or y != 0:
this_bp = bp[x][y]
opcodes.append(this_bp)
if this_bp[0] == EQUAL or this_bp[0] == REPLACE:
... | [
"def",
"get_opcodes_from_bp_table",
"(",
"bp",
")",
":",
"x",
"=",
"len",
"(",
"bp",
")",
"-",
"1",
"y",
"=",
"len",
"(",
"bp",
"[",
"0",
"]",
")",
"-",
"1",
"opcodes",
"=",
"[",
"]",
"while",
"x",
"!=",
"0",
"or",
"y",
"!=",
"0",
":",
"thi... | 29.294118 | 14.705882 |
def is_allowed(self, request: AxesHttpRequest, credentials: dict = None) -> bool:
"""
Checks if the user is allowed to access or use given functionality such as a login view or authentication.
This method is abstract and other backends can specialize it as needed, but the default implementation... | [
"def",
"is_allowed",
"(",
"self",
",",
"request",
":",
"AxesHttpRequest",
",",
"credentials",
":",
"dict",
"=",
"None",
")",
"->",
"bool",
":",
"if",
"self",
".",
"is_blacklisted",
"(",
"request",
",",
"credentials",
")",
":",
"return",
"False",
"if",
"s... | 46.56 | 36.88 |
def a_list(label=None, kwargs=None, attributes=None):
"""Return assembled DOT a_list string.
>>> a_list('spam', {'spam': None, 'ham': 'ham ham', 'eggs': ''})
'label=spam eggs="" ham="ham ham"'
"""
result = ['label=%s' % quote(label)] if label is not None else []
if kwargs:
items = ['%s=... | [
"def",
"a_list",
"(",
"label",
"=",
"None",
",",
"kwargs",
"=",
"None",
",",
"attributes",
"=",
"None",
")",
":",
"result",
"=",
"[",
"'label=%s'",
"%",
"quote",
"(",
"label",
")",
"]",
"if",
"label",
"is",
"not",
"None",
"else",
"[",
"]",
"if",
... | 39.055556 | 14.888889 |
def save(nifti_filename, numpy_data):
"""
Export a numpy array to a nifti file. TODO: currently using dummy
headers and identity matrix affine transform. This can be expanded.
Arguments:
nifti_filename (str): A filename to which to save the nifti data
numpy_data (numpy.ndarray): The nu... | [
"def",
"save",
"(",
"nifti_filename",
",",
"numpy_data",
")",
":",
"# Expand filename to be absolute",
"nifti_filename",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"nifti_filename",
")",
"try",
":",
"nifti_img",
"=",
"nib",
".",
"Nifti1Image",
"(",
"numpy_d... | 34.272727 | 22.909091 |
def count(keys, axis=semantics.axis_default):
"""count the number of times each key occurs in the input set
Arguments
---------
keys : indexable object
Returns
-------
unique : ndarray, [groups, ...]
unique keys
count : ndarray, [groups], int
the number of times each ke... | [
"def",
"count",
"(",
"keys",
",",
"axis",
"=",
"semantics",
".",
"axis_default",
")",
":",
"index",
"=",
"as_index",
"(",
"keys",
",",
"axis",
",",
"base",
"=",
"True",
")",
"return",
"index",
".",
"unique",
",",
"index",
".",
"count"
] | 26.142857 | 19.190476 |
def write_touchstone(fname, options, data, noise=None, frac_length=10, exp_length=2):
r"""
Write a `Touchstone`_ file.
Parameter data is first resized to an :code:`points` x :code:`nports` x
:code:`nports` where :code:`points` represents the number of frequency
points and :code:`nports` represents ... | [
"def",
"write_touchstone",
"(",
"fname",
",",
"options",
",",
"data",
",",
"noise",
"=",
"None",
",",
"frac_length",
"=",
"10",
",",
"exp_length",
"=",
"2",
")",
":",
"# pylint: disable=R0913",
"# Exceptions definitions",
"exnports",
"=",
"pexdoc",
".",
"exh",... | 36.261682 | 20.233645 |
def get_interpolation_function(self, times, series):
""" Initializes interpolation model
:param times: Array of reference times in second relative to the first timestamp
:type times: numpy.array
:param series: One dimensional array of time series
:type series: numpy.array
... | [
"def",
"get_interpolation_function",
"(",
"self",
",",
"times",
",",
"series",
")",
":",
"return",
"self",
".",
"interpolation_object",
"(",
"times",
",",
"series",
",",
"*",
"*",
"self",
".",
"interpolation_parameters",
")"
] | 46 | 19.6 |
def update(self, options=None, attribute_options=None):
"""
Updates this mapping with the given option and attribute option maps.
:param dict options: Maps representer options to their values.
:param dict attribute_options: Maps attribute names to dictionaries
mapping attribut... | [
"def",
"update",
"(",
"self",
",",
"options",
"=",
"None",
",",
"attribute_options",
"=",
"None",
")",
":",
"attr_map",
"=",
"self",
".",
"__get_attribute_map",
"(",
"self",
".",
"__mapped_cls",
",",
"None",
",",
"0",
")",
"for",
"attributes",
"in",
"att... | 50.888889 | 18.777778 |
def update_configuration(app):
"""Update parameters which are dependent on information from the
project-specific conf.py (including its location on the filesystem)"""
config = app.config
project = config.project
config_dir = app.env.srcdir
sys.path.insert(0, os.path.join(config_dir, '..'))
... | [
"def",
"update_configuration",
"(",
"app",
")",
":",
"config",
"=",
"app",
".",
"config",
"project",
"=",
"config",
".",
"project",
"config_dir",
"=",
"app",
".",
"env",
".",
"srcdir",
"sys",
".",
"path",
".",
"insert",
"(",
"0",
",",
"os",
".",
"pat... | 39.622642 | 19.433962 |
def morelikethis(self, index, doc_type, id, fields, **query_params):
"""
Execute a "more like this" search query against one or more fields and get back search hits.
"""
path = make_path(index, doc_type, id, '_mlt')
query_params['mlt_fields'] = ','.join(fields)
body = que... | [
"def",
"morelikethis",
"(",
"self",
",",
"index",
",",
"doc_type",
",",
"id",
",",
"fields",
",",
"*",
"*",
"query_params",
")",
":",
"path",
"=",
"make_path",
"(",
"index",
",",
"doc_type",
",",
"id",
",",
"'_mlt'",
")",
"query_params",
"[",
"'mlt_fie... | 55.625 | 22.875 |
def __checkSPKTimestamp(self):
"""
Check whether the SPK is too old and generate a new one in that case.
"""
if time.time() - self.__spk["timestamp"] > self.__spk_timeout:
self.__generateSPK() | [
"def",
"__checkSPKTimestamp",
"(",
"self",
")",
":",
"if",
"time",
".",
"time",
"(",
")",
"-",
"self",
".",
"__spk",
"[",
"\"timestamp\"",
"]",
">",
"self",
".",
"__spk_timeout",
":",
"self",
".",
"__generateSPK",
"(",
")"
] | 33 | 17.857143 |
def process(self):
"""
Loops over the underlying queue of events and processes them in order.
"""
assert self.queue is not None
while True:
event = self.queue.get()
if self.pre_process_event(event):
self.invoke_handlers(event)
s... | [
"def",
"process",
"(",
"self",
")",
":",
"assert",
"self",
".",
"queue",
"is",
"not",
"None",
"while",
"True",
":",
"event",
"=",
"self",
".",
"queue",
".",
"get",
"(",
")",
"if",
"self",
".",
"pre_process_event",
"(",
"event",
")",
":",
"self",
".... | 33.2 | 10.2 |
def purge_dict(idict):
"""Remove null items from a dictionary """
odict = {}
for key, val in idict.items():
if is_null(val):
continue
odict[key] = val
return odict | [
"def",
"purge_dict",
"(",
"idict",
")",
":",
"odict",
"=",
"{",
"}",
"for",
"key",
",",
"val",
"in",
"idict",
".",
"items",
"(",
")",
":",
"if",
"is_null",
"(",
"val",
")",
":",
"continue",
"odict",
"[",
"key",
"]",
"=",
"val",
"return",
"odict"
... | 25 | 15.75 |
def _generate_download_google_link(link):
"""
-----
Brief
-----
Function that returns a direct download link of a file stored inside a Google Drive
Repository.
-----------
Description
-----------
Generally a link from a Google Drive file is only for viewing purposes.
If the... | [
"def",
"_generate_download_google_link",
"(",
"link",
")",
":",
"# Get file id.",
"if",
"\"id=\"",
"not",
"in",
"link",
":",
"# Split link into segments (split character --> /)",
"split_link",
"=",
"link",
".",
"split",
"(",
"\"/\"",
")",
"file_id",
"=",
"split_link",... | 26.568182 | 27.295455 |
def _open_fits_files(filenames):
"""
Given a {correlation: filename} mapping for filenames
returns a {correlation: file handle} mapping
"""
kw = { 'mode' : 'update', 'memmap' : False }
def _fh(fn):
""" Returns a filehandle or None if file does not exist """
return fits.open(fn, ... | [
"def",
"_open_fits_files",
"(",
"filenames",
")",
":",
"kw",
"=",
"{",
"'mode'",
":",
"'update'",
",",
"'memmap'",
":",
"False",
"}",
"def",
"_fh",
"(",
"fn",
")",
":",
"\"\"\" Returns a filehandle or None if file does not exist \"\"\"",
"return",
"fits",
".",
"... | 34.5 | 14 |
def class_declaration(self, type_):
"""
Returns reference to the class declaration.
"""
utils.loggers.queries_engine.debug(
"Container traits: searching class declaration for %s", type_)
cls_declaration = self.get_container_or_none(type_)
if not cls_declara... | [
"def",
"class_declaration",
"(",
"self",
",",
"type_",
")",
":",
"utils",
".",
"loggers",
".",
"queries_engine",
".",
"debug",
"(",
"\"Container traits: searching class declaration for %s\"",
",",
"type_",
")",
"cls_declaration",
"=",
"self",
".",
"get_container_or_no... | 32.2 | 16.866667 |
def filter_objects(self, objects, perm=None):
""" Return only objects with specified permission in objects list. If perm not specified, 'view' perm will be used. """
if perm is None:
perm = build_permission_name(self.model_class, 'view')
return filter(lambda o: self.user.has_perm(per... | [
"def",
"filter_objects",
"(",
"self",
",",
"objects",
",",
"perm",
"=",
"None",
")",
":",
"if",
"perm",
"is",
"None",
":",
"perm",
"=",
"build_permission_name",
"(",
"self",
".",
"model_class",
",",
"'view'",
")",
"return",
"filter",
"(",
"lambda",
"o",
... | 67 | 16 |
def report(self):
"""Return a report about the pool state and configuration.
:rtype: dict
"""
return {
'connections': {
'busy': len(self.busy_connections),
'closed': len(self.closed_connections),
'executing': len(self.executin... | [
"def",
"report",
"(",
"self",
")",
":",
"return",
"{",
"'connections'",
":",
"{",
"'busy'",
":",
"len",
"(",
"self",
".",
"busy_connections",
")",
",",
"'closed'",
":",
"len",
"(",
"self",
".",
"closed_connections",
")",
",",
"'executing'",
":",
"len",
... | 34.44 | 16.56 |
def to_python(self, data):
"""
Convert a data to python format.
"""
if data is None:
return ''
if isinstance(data, unicode):
data = data.encode(DEFAULT_ENCODING)
else:
data = str(data)
return data | [
"def",
"to_python",
"(",
"self",
",",
"data",
")",
":",
"if",
"data",
"is",
"None",
":",
"return",
"''",
"if",
"isinstance",
"(",
"data",
",",
"unicode",
")",
":",
"data",
"=",
"data",
".",
"encode",
"(",
"DEFAULT_ENCODING",
")",
"else",
":",
"data",... | 25.272727 | 10.909091 |
def open_data(self, text, colsep=u"\t", rowsep=u"\n",
transpose=False, skiprows=0, comments='#'):
"""Open clipboard text as table"""
if pd:
self.pd_text = text
self.pd_info = dict(sep=colsep, lineterminator=rowsep,
skiprows=skiprows, commen... | [
"def",
"open_data",
"(",
"self",
",",
"text",
",",
"colsep",
"=",
"u\"\\t\"",
",",
"rowsep",
"=",
"u\"\\n\"",
",",
"transpose",
"=",
"False",
",",
"skiprows",
"=",
"0",
",",
"comments",
"=",
"'#'",
")",
":",
"if",
"pd",
":",
"self",
".",
"pd_text",
... | 52 | 18.75 |
def get_neighbor_sentence_ngrams(
mention, d=1, attrib="words", n_min=1, n_max=1, lower=True
):
"""Get the ngrams that are in the neighoring Sentences of the given Mention.
Note that if a candidate is passed in, all of its Mentions will be searched.
:param mention: The Mention whose neighbor Sentences... | [
"def",
"get_neighbor_sentence_ngrams",
"(",
"mention",
",",
"d",
"=",
"1",
",",
"attrib",
"=",
"\"words\"",
",",
"n_min",
"=",
"1",
",",
"n_max",
"=",
"1",
",",
"lower",
"=",
"True",
")",
":",
"spans",
"=",
"_to_spans",
"(",
"mention",
")",
"for",
"s... | 41.37037 | 22.518519 |
def extend(*args):
"""shallow dictionary merge
Args:
a: dict to extend
b: dict to apply to a
Returns:
new instance of the same type as _a_, with _a_ and _b_ merged.
"""
if not args:
return {}
first = args[0]
rest = args[1:]
out = type(first)(first)
... | [
"def",
"extend",
"(",
"*",
"args",
")",
":",
"if",
"not",
"args",
":",
"return",
"{",
"}",
"first",
"=",
"args",
"[",
"0",
"]",
"rest",
"=",
"args",
"[",
"1",
":",
"]",
"out",
"=",
"type",
"(",
"first",
")",
"(",
"first",
")",
"for",
"each",
... | 18.894737 | 22.052632 |
def _get_access_token(self):
"""Get access token using app_id, login and password OR service token
(service token docs: https://vk.com/dev/service_token
"""
if self._service_token:
logger.info('Use service token: %s',
5 * '*' + self._service_token[50:]... | [
"def",
"_get_access_token",
"(",
"self",
")",
":",
"if",
"self",
".",
"_service_token",
":",
"logger",
".",
"info",
"(",
"'Use service token: %s'",
",",
"5",
"*",
"'*'",
"+",
"self",
".",
"_service_token",
"[",
"50",
":",
"]",
")",
"return",
"self",
".",... | 45 | 18.933333 |
def addTransitions(self, state, transitions):
"""
Create a new L{TransitionTable} with all the same transitions as this
L{TransitionTable} plus a number of new transitions.
@param state: The state for which the new transitions are defined.
@param transitions: A L{dict} mapping i... | [
"def",
"addTransitions",
"(",
"self",
",",
"state",
",",
"transitions",
")",
":",
"table",
"=",
"self",
".",
"_copy",
"(",
")",
"state",
"=",
"table",
".",
"table",
".",
"setdefault",
"(",
"state",
",",
"{",
"}",
")",
"for",
"(",
"input",
",",
"(",... | 42.470588 | 21.294118 |
def _process(self, plugin, instance=None):
"""Produce `result` from `plugin` and `instance`
:func:`process` shares state with :func:`_iterator` such that
an instance/plugin pair can be fetched and processed in isolation.
Arguments:
plugin (pyblish.api.Plugin): Produce resul... | [
"def",
"_process",
"(",
"self",
",",
"plugin",
",",
"instance",
"=",
"None",
")",
":",
"self",
".",
"processing",
"[",
"\"nextOrder\"",
"]",
"=",
"plugin",
".",
"order",
"try",
":",
"result",
"=",
"pyblish",
".",
"plugin",
".",
"process",
"(",
"plugin"... | 33.517241 | 24.37931 |
def save(self, filename=None, v2_version=4, v23_sep='/'):
"""Save ID3v2 data to the AIFF file"""
framedata = self._prepare_framedata(v2_version, v23_sep)
framesize = len(framedata)
if filename is None:
filename = self.filename
# Unlike the parent ID3.save method, w... | [
"def",
"save",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"v2_version",
"=",
"4",
",",
"v23_sep",
"=",
"'/'",
")",
":",
"framedata",
"=",
"self",
".",
"_prepare_framedata",
"(",
"v2_version",
",",
"v23_sep",
")",
"framesize",
"=",
"len",
"(",
"fra... | 34.097561 | 19.804878 |
def update_os_type(self):
"""Update os_type attribute."""
self.chain.connection.log("Detecting os type")
os_type = self.driver.get_os_type(self.version_text)
if os_type:
self.chain.connection.log("SW Type: {}".format(os_type))
self.os_type = os_type | [
"def",
"update_os_type",
"(",
"self",
")",
":",
"self",
".",
"chain",
".",
"connection",
".",
"log",
"(",
"\"Detecting os type\"",
")",
"os_type",
"=",
"self",
".",
"driver",
".",
"get_os_type",
"(",
"self",
".",
"version_text",
")",
"if",
"os_type",
":",
... | 42.714286 | 14.857143 |
def _set_translated_fields(self, language_code=None, **fields):
"""
Assign fields to the translated models.
"""
objects = [] # no generator, make sure objects are all filled first
for parler_meta, model_fields in self._parler_meta._split_fields(**fields):
translation... | [
"def",
"_set_translated_fields",
"(",
"self",
",",
"language_code",
"=",
"None",
",",
"*",
"*",
"fields",
")",
":",
"objects",
"=",
"[",
"]",
"# no generator, make sure objects are all filled first",
"for",
"parler_meta",
",",
"model_fields",
"in",
"self",
".",
"_... | 48.25 | 22.916667 |
def write_alignment(self, filename, file_format, interleaved=None):
"""
Write the alignment to file using Bio.AlignIO
"""
if file_format == 'phylip':
file_format = 'phylip-relaxed'
AlignIO.write(self._msa, filename, file_format) | [
"def",
"write_alignment",
"(",
"self",
",",
"filename",
",",
"file_format",
",",
"interleaved",
"=",
"None",
")",
":",
"if",
"file_format",
"==",
"'phylip'",
":",
"file_format",
"=",
"'phylip-relaxed'",
"AlignIO",
".",
"write",
"(",
"self",
".",
"_msa",
",",... | 39.142857 | 8.857143 |
def delete_processing_block(processing_block_id):
"""Delete Processing Block with the specified ID"""
scheduling_block_id = processing_block_id.split(':')[0]
config = get_scheduling_block(scheduling_block_id)
processing_blocks = config.get('processing_blocks')
processing_block = list(filter(
... | [
"def",
"delete_processing_block",
"(",
"processing_block_id",
")",
":",
"scheduling_block_id",
"=",
"processing_block_id",
".",
"split",
"(",
"':'",
")",
"[",
"0",
"]",
"config",
"=",
"get_scheduling_block",
"(",
"scheduling_block_id",
")",
"processing_blocks",
"=",
... | 52.714286 | 18.214286 |
def _negotiateHandler(self, request):
"""
Negotiate a handler based on the content types acceptable to the
client.
:rtype: 2-`tuple` of `twisted.web.iweb.IResource` and `bytes`
:return: Pair of a resource and the content type.
"""
accept = _parseAccept(request.re... | [
"def",
"_negotiateHandler",
"(",
"self",
",",
"request",
")",
":",
"accept",
"=",
"_parseAccept",
"(",
"request",
".",
"requestHeaders",
".",
"getRawHeaders",
"(",
"'Accept'",
")",
")",
"for",
"contentType",
"in",
"accept",
".",
"keys",
"(",
")",
":",
"han... | 38.388889 | 16.277778 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.