text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def miscellaneous_menu(self, value):
"""
Setter for **self.__miscellaneous_menu** attribute.
:param value: Attribute value.
:type value: QMenu
"""
if value is not None:
assert type(value) is QMenu, "'{0}' attribute: '{1}' type is not 'QMenu'!".format(
... | [
"def",
"miscellaneous_menu",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"assert",
"type",
"(",
"value",
")",
"is",
"QMenu",
",",
"\"'{0}' attribute: '{1}' type is not 'QMenu'!\"",
".",
"format",
"(",
"\"miscellaneous_menu\"",
"... | 32.416667 | 15.75 |
def project(self, point_cloud, round_px=True):
"""Projects a point cloud onto the camera image plane.
Parameters
----------
point_cloud : :obj:`autolab_core.PointCloud` or :obj:`autolab_core.Point`
A PointCloud or Point to project onto the camera image plane.
round_... | [
"def",
"project",
"(",
"self",
",",
"point_cloud",
",",
"round_px",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"point_cloud",
",",
"PointCloud",
")",
"and",
"not",
"(",
"isinstance",
"(",
"point_cloud",
",",
"Point",
")",
"and",
"point_cloud",
... | 44.575 | 27.45 |
def editMeta(self, title=None, description=None):
"""Set metadata for photo. (flickr.photos.setMeta)"""
method = 'flickr.photosets.editMeta'
if title is None:
title = self.title
if description is None:
description = self.description
_dopost(m... | [
"def",
"editMeta",
"(",
"self",
",",
"title",
"=",
"None",
",",
"description",
"=",
"None",
")",
":",
"method",
"=",
"'flickr.photosets.editMeta'",
"if",
"title",
"is",
"None",
":",
"title",
"=",
"self",
".",
"title",
"if",
"description",
"is",
"None",
"... | 33.2 | 14.066667 |
def csp_header(csp={}):
""" Decorator to include csp header on app.route wrapper """
_csp = csp_default().read()
_csp.update(csp)
_header = ''
if 'report-only' in _csp and _csp['report-only'] is True:
_header = 'Content-Security-Policy-Report-Only'
else:
_header = 'Content-Securit... | [
"def",
"csp_header",
"(",
"csp",
"=",
"{",
"}",
")",
":",
"_csp",
"=",
"csp_default",
"(",
")",
".",
"read",
"(",
")",
"_csp",
".",
"update",
"(",
"csp",
")",
"_header",
"=",
"''",
"if",
"'report-only'",
"in",
"_csp",
"and",
"_csp",
"[",
"'report-o... | 31.458333 | 15.541667 |
def _compute_value(power, wg):
"""Return the weight corresponding to single power."""
if power not in wg:
p1, p2 = power
# y power
if p1 == 0:
yy = wg[(0, -1)]
wg[power] = numpy.power(yy, p2 / 2).sum() / len(yy)
# x power
else:
xx = wg[... | [
"def",
"_compute_value",
"(",
"power",
",",
"wg",
")",
":",
"if",
"power",
"not",
"in",
"wg",
":",
"p1",
",",
"p2",
"=",
"power",
"# y power",
"if",
"p1",
"==",
"0",
":",
"yy",
"=",
"wg",
"[",
"(",
"0",
",",
"-",
"1",
")",
"]",
"wg",
"[",
"... | 30.846154 | 17.615385 |
def send(self, data):
"""
Send encoded instructions to Guacamole guacd server.
"""
self.logger.debug('Sending data: %s' % data)
self.client.sendall(data.encode()) | [
"def",
"send",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'Sending data: %s'",
"%",
"data",
")",
"self",
".",
"client",
".",
"sendall",
"(",
"data",
".",
"encode",
"(",
")",
")"
] | 32.833333 | 8.833333 |
def _dist_kw_arg(self, k):
"""
Returns a dictionary of keyword arguments
for the k'th distribution.
:param int k: Index of the distribution in question.
:rtype: ``dict``
"""
if self._dist_kw_args is not None:
return {
key:self._dist_kw... | [
"def",
"_dist_kw_arg",
"(",
"self",
",",
"k",
")",
":",
"if",
"self",
".",
"_dist_kw_args",
"is",
"not",
"None",
":",
"return",
"{",
"key",
":",
"self",
".",
"_dist_kw_args",
"[",
"key",
"]",
"[",
"k",
",",
":",
"]",
"for",
"key",
"in",
"self",
"... | 28.266667 | 14.666667 |
def upgradeUserInfo1to2(oldUserInfo):
"""
Concatenate the I{firstName} and I{lastName} attributes from the old user
info item and set the result as the I{realName} attribute of the upgraded
item.
"""
newUserInfo = oldUserInfo.upgradeVersion(
UserInfo.typeName, 1, 2,
realName=oldU... | [
"def",
"upgradeUserInfo1to2",
"(",
"oldUserInfo",
")",
":",
"newUserInfo",
"=",
"oldUserInfo",
".",
"upgradeVersion",
"(",
"UserInfo",
".",
"typeName",
",",
"1",
",",
"2",
",",
"realName",
"=",
"oldUserInfo",
".",
"firstName",
"+",
"u\" \"",
"+",
"oldUserInfo"... | 38.2 | 16.8 |
def epoch_rates_to_pmf(problems, epoch_rates=None):
"""Create a probability-mass-function based on relative epoch rates.
if epoch_rates=None, then we use uniform epoch rates [1.0] * len(problems)
i.e. it takes each problem the same time to go through one epoch.
If epoch_rates is given, then these are the rela... | [
"def",
"epoch_rates_to_pmf",
"(",
"problems",
",",
"epoch_rates",
"=",
"None",
")",
":",
"if",
"epoch_rates",
"is",
"None",
":",
"epoch_rates",
"=",
"[",
"1.0",
"]",
"*",
"len",
"(",
"problems",
")",
"example_rates",
"=",
"[",
"epoch_rate",
"*",
"p",
"."... | 35.869565 | 20.695652 |
def render_heading(self, token):
"""
Overrides super().render_heading; stores rendered heading first,
then returns it.
"""
rendered = super().render_heading(token)
content = self.parse_rendered_heading(rendered)
if not (self.omit_title and token.level == 1
... | [
"def",
"render_heading",
"(",
"self",
",",
"token",
")",
":",
"rendered",
"=",
"super",
"(",
")",
".",
"render_heading",
"(",
"token",
")",
"content",
"=",
"self",
".",
"parse_rendered_heading",
"(",
"rendered",
")",
"if",
"not",
"(",
"self",
".",
"omit_... | 41.416667 | 13.083333 |
def _validate_cmds(self):
"""
确保 cmd 没有重复
:return:
"""
cmd_list = list(self.rule_map.keys())
for bp in self.blueprints:
cmd_list.extend(bp.rule_map.keys())
duplicate_cmds = (Counter(cmd_list) - Counter(set(cmd_list))).keys()
assert not dupl... | [
"def",
"_validate_cmds",
"(",
"self",
")",
":",
"cmd_list",
"=",
"list",
"(",
"self",
".",
"rule_map",
".",
"keys",
"(",
")",
")",
"for",
"bp",
"in",
"self",
".",
"blueprints",
":",
"cmd_list",
".",
"extend",
"(",
"bp",
".",
"rule_map",
".",
"keys",
... | 25.428571 | 21.857143 |
def setup(self):
"""
NSCF calculations should use the same FFT mesh as the one employed in the GS task
(in principle, it's possible to interpolate inside Abinit but tests revealed some numerical noise
Here we change the input file of the NSCF task to have the same FFT mesh.
"""
... | [
"def",
"setup",
"(",
"self",
")",
":",
"for",
"dep",
"in",
"self",
".",
"deps",
":",
"if",
"\"DEN\"",
"in",
"dep",
".",
"exts",
":",
"parent_task",
"=",
"dep",
".",
"node",
"break",
"else",
":",
"raise",
"RuntimeError",
"(",
"\"Cannot find parent node pr... | 41.916667 | 23.583333 |
def stop(self):
"""
Stop the config change monitoring thread.
"""
self.observer_thread.stop()
self.observer_thread.join()
logging.info("Configfile watcher plugin: Stopped") | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"observer_thread",
".",
"stop",
"(",
")",
"self",
".",
"observer_thread",
".",
"join",
"(",
")",
"logging",
".",
"info",
"(",
"\"Configfile watcher plugin: Stopped\"",
")"
] | 26.75 | 12.75 |
def rotation_matrix(axis, theta):
"""The Euler–Rodrigues formula.
Return the rotation matrix associated with counterclockwise rotation about
the given axis by theta radians.
Parameters
----------
axis: vector to rotate around
theta: rotation angle, in rad
"""
axis = np.asarray(axis... | [
"def",
"rotation_matrix",
"(",
"axis",
",",
"theta",
")",
":",
"axis",
"=",
"np",
".",
"asarray",
"(",
"axis",
")",
"axis",
"=",
"axis",
"/",
"np",
".",
"linalg",
".",
"norm",
"(",
"axis",
")",
"a",
"=",
"np",
".",
"cos",
"(",
"theta",
"/",
"2"... | 33.136364 | 16.772727 |
def flatten(d, key_as_tuple=True, sep='.', list_of_dicts=None, all_iters=None):
""" get nested dict as flat {key:val,...},
where key is tuple/string of all nested keys
Parameters
----------
d : object
key_as_tuple : bool
whether keys are list of nested keys or delimited string of nested... | [
"def",
"flatten",
"(",
"d",
",",
"key_as_tuple",
"=",
"True",
",",
"sep",
"=",
"'.'",
",",
"list_of_dicts",
"=",
"None",
",",
"all_iters",
"=",
"None",
")",
":",
"def",
"expand",
"(",
"key",
",",
"value",
")",
":",
"if",
"is_dict_like",
"(",
"value",... | 36.906977 | 20.290698 |
def doMove(self, from_path, to_path, overwrite = False, bShareFireCopy = 'false', dummy = 56147):
"""Move a file.
>>> nd.doMove('/Picture/flower.png', '/flower.png')
:param from_path: The path to the file or folder to be moved.
:param to_path: The destination path of the file or fo... | [
"def",
"doMove",
"(",
"self",
",",
"from_path",
",",
"to_path",
",",
"overwrite",
"=",
"False",
",",
"bShareFireCopy",
"=",
"'false'",
",",
"dummy",
"=",
"56147",
")",
":",
"if",
"overwrite",
":",
"overwrite",
"=",
"'F'",
"else",
":",
"overwrite",
"=",
... | 35.965517 | 23.551724 |
def stream_reader_statements(stream_arn):
"""Returns statements to allow Lambda to read from a stream.
Handles both DynamoDB & Kinesis streams. Automatically figures out the
type of stream, and provides the correct actions from the supplied Arn.
Arg:
stream_arn (str): A kinesis or dynamodb str... | [
"def",
"stream_reader_statements",
"(",
"stream_arn",
")",
":",
"action_type",
"=",
"get_stream_action_type",
"(",
"stream_arn",
")",
"arn_parts",
"=",
"stream_arn",
".",
"split",
"(",
"\"/\"",
")",
"# Cut off the last bit and replace it with a wildcard",
"wildcard_arn_part... | 29.971429 | 18.228571 |
def word_tokenize(sentence):
"""
A generator which yields tokens based on the given sentence without deleting anything.
>>> context = "I love you. Please don't leave."
>>> list(word_tokenize(context))
['I', ' ', 'love', ' ', 'you', '.', ' ', 'Please', ' ', 'don', "'", 't', ' ', 'leave', '.']
"... | [
"def",
"word_tokenize",
"(",
"sentence",
")",
":",
"date_pattern",
"=",
"r'\\d\\d(\\d\\d)?[\\\\-]\\d\\d[\\\\-]\\d\\d(\\d\\d)?'",
"number_pattern",
"=",
"r'[\\+-]?(\\d+\\.\\d+|\\d{1,3},(\\d{3},)*\\d{3}|\\d+)'",
"arr_pattern",
"=",
"r'(?: \\w\\.){2,3}|(?:\\A|\\s)(?:\\w\\.){2,3}|[A-Z]\\. [a... | 47.8 | 26 |
def auto_build(self):
"""Auto built tool
"""
options = [
"-a",
"--autobuild"
]
if len(self.args) >= 3 and self.args[0] in options:
AutoBuild(self.args[1], self.args[2:], self.meta.path).run()
else:
usage("") | [
"def",
"auto_build",
"(",
"self",
")",
":",
"options",
"=",
"[",
"\"-a\"",
",",
"\"--autobuild\"",
"]",
"if",
"len",
"(",
"self",
".",
"args",
")",
">=",
"3",
"and",
"self",
".",
"args",
"[",
"0",
"]",
"in",
"options",
":",
"AutoBuild",
"(",
"self"... | 26.636364 | 18.727273 |
def snapshot(name, suffix=None, connection=None, username=None, password=None):
'''
Takes a snapshot of a particular VM or by a UNIX-style wildcard.
.. versionadded:: 2016.3.0
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: userna... | [
"def",
"snapshot",
"(",
"name",
",",
"suffix",
"=",
"None",
",",
"connection",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"return",
"_virt_call",
"(",
"name",
",",
"'snapshot'",
",",
"'saved'",
",",
"'Snapshot has ... | 28.655172 | 27.689655 |
def make_d2p_id(self):
"""
Make an association id for phenotypic associations with disease
that is defined by:
source of association + disease + relationship + phenotype
+ onset + frequency
:return:
"""
attributes = [self.onset, self.frequency]
... | [
"def",
"make_d2p_id",
"(",
"self",
")",
":",
"attributes",
"=",
"[",
"self",
".",
"onset",
",",
"self",
".",
"frequency",
"]",
"assoc_id",
"=",
"self",
".",
"make_association_id",
"(",
"self",
".",
"definedby",
",",
"self",
".",
"disease_id",
",",
"self"... | 28.25 | 22.5 |
def enter_maintenance_mode(self):
"""
Put the service in maintenance mode.
@return: Reference to the completed command.
@since: API v2
"""
cmd = self._cmd('enterMaintenanceMode')
if cmd.success:
self._update(_get_service(self._get_resource_root(), self._path()))
return cmd | [
"def",
"enter_maintenance_mode",
"(",
"self",
")",
":",
"cmd",
"=",
"self",
".",
"_cmd",
"(",
"'enterMaintenanceMode'",
")",
"if",
"cmd",
".",
"success",
":",
"self",
".",
"_update",
"(",
"_get_service",
"(",
"self",
".",
"_get_resource_root",
"(",
")",
",... | 27.454545 | 14.545455 |
def oridam_generate_patterns(word_in,cm,ed=1,level=0,pos=0,candidates=None):
""" ed = 1 by default, pos - internal variable for algorithm """
alternates = cm.get(word_in[pos],[])
if not candidates:
candidates = []
assert ed <= len(word_in), 'edit distance has to be comparable to word size [ins/d... | [
"def",
"oridam_generate_patterns",
"(",
"word_in",
",",
"cm",
",",
"ed",
"=",
"1",
",",
"level",
"=",
"0",
",",
"pos",
"=",
"0",
",",
"candidates",
"=",
"None",
")",
":",
"alternates",
"=",
"cm",
".",
"get",
"(",
"word_in",
"[",
"pos",
"]",
",",
... | 40.758621 | 15.586207 |
def watch(directory=None, auto_clear=False, extensions=[]):
"""Starts a server to render the specified file or directory containing a README."""
if directory and not os.path.isdir(directory):
raise ValueError('Directory not found: ' + directory)
directory = os.path.abspath(directory)
# Initial ... | [
"def",
"watch",
"(",
"directory",
"=",
"None",
",",
"auto_clear",
"=",
"False",
",",
"extensions",
"=",
"[",
"]",
")",
":",
"if",
"directory",
"and",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"directory",
")",
":",
"raise",
"ValueError",
"(",
"'Di... | 32.5 | 20.5 |
def get(self, request):
"""
Called after the user is redirected back to our application.
Tries to:
- Complete the OAuth / OAuth2 flow
- Redirect the user to another view that deals with login, connecting
or user creation.
"""
try:
client ... | [
"def",
"get",
"(",
"self",
",",
"request",
")",
":",
"try",
":",
"client",
"=",
"request",
".",
"session",
"[",
"self",
".",
"get_client",
"(",
")",
".",
"get_session_key",
"(",
")",
"]",
"logger",
".",
"debug",
"(",
"\"API returned: %s\"",
",",
"reque... | 42.521739 | 21.913043 |
def _connected(self, transport, conn):
"""Login and sync the ElkM1 panel to memory."""
LOG.info("Connected to ElkM1")
self._conn = conn
self._transport = transport
self._connection_retry_timer = 1
if url_scheme_is_secure(self._config['url']):
self._conn.write_... | [
"def",
"_connected",
"(",
"self",
",",
"transport",
",",
"conn",
")",
":",
"LOG",
".",
"info",
"(",
"\"Connected to ElkM1\"",
")",
"self",
".",
"_conn",
"=",
"conn",
"self",
".",
"_transport",
"=",
"transport",
"self",
".",
"_connection_retry_timer",
"=",
... | 49.25 | 13.166667 |
def parse(self, data):
"""
Converts a OpenVPN JSON to a NetworkX Graph object
which is then returned.
"""
# initialize graph and list of aggregated nodes
graph = self._init_graph()
server = self._server_common_name
# add server (central node) to graph
... | [
"def",
"parse",
"(",
"self",
",",
"data",
")",
":",
"# initialize graph and list of aggregated nodes",
"graph",
"=",
"self",
".",
"_init_graph",
"(",
")",
"server",
"=",
"self",
".",
"_server_common_name",
"# add server (central node) to graph",
"graph",
".",
"add_nod... | 39.511628 | 14.302326 |
def run(addr, *commands, **kwargs):
"""
Non-threaded batch command runner returning output results
"""
results = []
handler = VarnishHandler(addr, **kwargs)
for cmd in commands:
if isinstance(cmd, tuple) and len(cmd)>1:
results.extend([getattr(handler, c[0].replace('.','_'))(... | [
"def",
"run",
"(",
"addr",
",",
"*",
"commands",
",",
"*",
"*",
"kwargs",
")",
":",
"results",
"=",
"[",
"]",
"handler",
"=",
"VarnishHandler",
"(",
"addr",
",",
"*",
"*",
"kwargs",
")",
"for",
"cmd",
"in",
"commands",
":",
"if",
"isinstance",
"(",... | 34.428571 | 18.857143 |
def times(self, multiplier):
'''
Given an FSM and a multiplier, return the multiplied FSM.
'''
if multiplier < 0:
raise Exception("Can't multiply an FSM by " + repr(multiplier))
alphabet = self.alphabet
# metastate is a set of iterations+states
initial = {(self.initial, 0)}
def final(state):
'... | [
"def",
"times",
"(",
"self",
",",
"multiplier",
")",
":",
"if",
"multiplier",
"<",
"0",
":",
"raise",
"Exception",
"(",
"\"Can't multiply an FSM by \"",
"+",
"repr",
"(",
"multiplier",
")",
")",
"alphabet",
"=",
"self",
".",
"alphabet",
"# metastate is a set o... | 30.371429 | 19.8 |
def handle_vcf_calls(vcf_file, data, orig_items):
"""Prioritize VCF calls based on external annotations supplied through GEMINI.
"""
if not _do_prioritize(orig_items):
return vcf_file
else:
ann_vcf = population.run_vcfanno(vcf_file, data)
if ann_vcf:
priority_file = _... | [
"def",
"handle_vcf_calls",
"(",
"vcf_file",
",",
"data",
",",
"orig_items",
")",
":",
"if",
"not",
"_do_prioritize",
"(",
"orig_items",
")",
":",
"return",
"vcf_file",
"else",
":",
"ann_vcf",
"=",
"population",
".",
"run_vcfanno",
"(",
"vcf_file",
",",
"data... | 40.692308 | 17.076923 |
def assign_enterprise_learner_role(sender, instance, **kwargs): # pylint: disable=unused-argument
"""
Assign an enterprise learner role to EnterpriseCustomerUser whenever a new record is created.
"""
if kwargs['created'] and instance.user:
enterprise_learner_role, __ = SystemWideEnterpriseRo... | [
"def",
"assign_enterprise_learner_role",
"(",
"sender",
",",
"instance",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=unused-argument",
"if",
"kwargs",
"[",
"'created'",
"]",
"and",
"instance",
".",
"user",
":",
"enterprise_learner_role",
",",
"__",
"=",
... | 51.8 | 26.4 |
def to_json(self, destination):
"""
Save a dictionnary into a JSON file.
:param destination:
A path to a file where we're going to
write the converted dict into a JSON format.
:type destination: str
"""
try:
with open(destination, "w"... | [
"def",
"to_json",
"(",
"self",
",",
"destination",
")",
":",
"try",
":",
"with",
"open",
"(",
"destination",
",",
"\"w\"",
")",
"as",
"file",
":",
"# We open the file we are going to write.",
"# Note: We always overwrite the destination.",
"# We save the current dictionna... | 34.083333 | 16.138889 |
def TNE_metric(bpmn_graph):
"""
Returns the value of the TNE metric (Total Number of Events of the Model)
for the BPMNDiagramGraph instance.
:param bpmn_graph: an instance of BpmnDiagramGraph representing BPMN model.
"""
events_counts = get_events_counts(bpmn_graph)
return sum(
[c... | [
"def",
"TNE_metric",
"(",
"bpmn_graph",
")",
":",
"events_counts",
"=",
"get_events_counts",
"(",
"bpmn_graph",
")",
"return",
"sum",
"(",
"[",
"count",
"for",
"_",
",",
"count",
"in",
"events_counts",
".",
"items",
"(",
")",
"]",
")"
] | 27.461538 | 22.538462 |
def state_cpfs(self) -> List[CPF]:
'''Returns list of state-fluent CPFs.'''
_, cpfs = self.cpfs
state_cpfs = []
for cpf in cpfs:
name = utils.rename_next_state_fluent(cpf.name)
if name in self.state_fluents:
state_cpfs.append(cpf)
state_cpf... | [
"def",
"state_cpfs",
"(",
"self",
")",
"->",
"List",
"[",
"CPF",
"]",
":",
"_",
",",
"cpfs",
"=",
"self",
".",
"cpfs",
"state_cpfs",
"=",
"[",
"]",
"for",
"cpf",
"in",
"cpfs",
":",
"name",
"=",
"utils",
".",
"rename_next_state_fluent",
"(",
"cpf",
... | 38.5 | 12.3 |
def has_permission(self, perm):
"""
Checks if current user (or role) has the given permission.
Args:
perm: Permmission code or object.
Depends on the :attr:`~zengine.auth.auth_backend.AuthBackend` implementation.
Returns:
Boolean.
"""
... | [
"def",
"has_permission",
"(",
"self",
",",
"perm",
")",
":",
"return",
"self",
".",
"user",
".",
"superuser",
"or",
"self",
".",
"auth",
".",
"has_permission",
"(",
"perm",
")"
] | 30.916667 | 22.416667 |
def population_fraction(self):
"""The filtered/unfiltered ratio for cube response.
This value is required for properly calculating population on a cube
where a filter has been applied. Returns 1.0 for an unfiltered cube.
Returns `np.nan` if the unfiltered count is zero, which would
... | [
"def",
"population_fraction",
"(",
"self",
")",
":",
"numerator",
"=",
"self",
".",
"_cube_dict",
"[",
"\"result\"",
"]",
".",
"get",
"(",
"\"filtered\"",
",",
"{",
"}",
")",
".",
"get",
"(",
"\"weighted_n\"",
")",
"denominator",
"=",
"self",
".",
"_cube... | 43.8125 | 21.0625 |
def parse_sidebar(self, user_page):
"""Parses the DOM and returns user attributes in the sidebar.
:type user_page: :class:`bs4.BeautifulSoup`
:param user_page: MAL user page's DOM
:rtype: dict
:return: User attributes
:raises: :class:`.InvalidUserError`, :class:`.MalformedUserPageError`
"... | [
"def",
"parse_sidebar",
"(",
"self",
",",
"user_page",
")",
":",
"user_info",
"=",
"{",
"}",
"# if MAL says the series doesn't exist, raise an InvalidUserError.",
"error_tag",
"=",
"user_page",
".",
"find",
"(",
"u'div'",
",",
"{",
"u'class'",
":",
"u'badresult'",
"... | 43.991379 | 25.37069 |
def lookup_linke_turbidity(time, latitude, longitude, filepath=None,
interp_turbidity=True):
"""
Look up the Linke Turibidity from the ``LinkeTurbidities.h5``
data file supplied with pvlib.
Parameters
----------
time : pandas.DatetimeIndex
latitude : float
l... | [
"def",
"lookup_linke_turbidity",
"(",
"time",
",",
"latitude",
",",
"longitude",
",",
"filepath",
"=",
"None",
",",
"interp_turbidity",
"=",
"True",
")",
":",
"# The .h5 file 'LinkeTurbidities.h5' contains a single 2160 x 4320 x 12",
"# matrix of type uint8 called 'LinkeTurbidi... | 35.8125 | 24.9375 |
def start(self, pin, dutycycle, frequency_hz=2000):
"""Enable PWM output on specified pin. Set to intiial percent duty cycle
value (0.0 to 100.0) and frequency (in Hz).
"""
if dutycycle < 0.0 or dutycycle > 100.0:
raise ValueError('Invalid duty cycle value, must be between 0... | [
"def",
"start",
"(",
"self",
",",
"pin",
",",
"dutycycle",
",",
"frequency_hz",
"=",
"2000",
")",
":",
"if",
"dutycycle",
"<",
"0.0",
"or",
"dutycycle",
">",
"100.0",
":",
"raise",
"ValueError",
"(",
"'Invalid duty cycle value, must be between 0.0 to 100.0 (inclus... | 53.25 | 14.416667 |
def request_instance(vm_=None, call=None):
'''
Put together all of the information necessary to request an instance on EC2,
and then fire off the request the instance.
Returns data about the instance
'''
if call == 'function':
# Technically this function may be called other ways too, bu... | [
"def",
"request_instance",
"(",
"vm_",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'function'",
":",
"# Technically this function may be called other ways too, but it",
"# definitely cannot be called with --function.",
"raise",
"SaltCloudSystemExit",... | 37.384615 | 20.787879 |
def setup_actions(self):
""" Connects slots to signals """
self.actionOpen.triggered.connect(self.on_open)
self.actionNew.triggered.connect(self.on_new)
self.actionSave.triggered.connect(self.on_save)
self.actionSave_as.triggered.connect(self.on_save_as)
self.actionQuit.t... | [
"def",
"setup_actions",
"(",
"self",
")",
":",
"self",
".",
"actionOpen",
".",
"triggered",
".",
"connect",
"(",
"self",
".",
"on_open",
")",
"self",
".",
"actionNew",
".",
"triggered",
".",
"connect",
"(",
"self",
".",
"on_new",
")",
"self",
".",
"act... | 53.666667 | 16.133333 |
def declare(self, exchange='', exchange_type='direct', virtual_host='/',
passive=False, durable=False, auto_delete=False,
internal=False, arguments=None):
"""Declare an Exchange.
:param str exchange: Exchange name
:param str exchange_type: Exchange type
:... | [
"def",
"declare",
"(",
"self",
",",
"exchange",
"=",
"''",
",",
"exchange_type",
"=",
"'direct'",
",",
"virtual_host",
"=",
"'/'",
",",
"passive",
"=",
"False",
",",
"durable",
"=",
"False",
",",
"auto_delete",
"=",
"False",
",",
"internal",
"=",
"False"... | 41.054054 | 16.459459 |
def from_rel_ref(baseURI, relative_ref):
"""
Return a |PackURI| instance containing the absolute pack URI formed by
translating *relative_ref* onto *baseURI*.
"""
joined_uri = posixpath.join(baseURI, relative_ref)
abs_uri = posixpath.abspath(joined_uri)
return Pac... | [
"def",
"from_rel_ref",
"(",
"baseURI",
",",
"relative_ref",
")",
":",
"joined_uri",
"=",
"posixpath",
".",
"join",
"(",
"baseURI",
",",
"relative_ref",
")",
"abs_uri",
"=",
"posixpath",
".",
"abspath",
"(",
"joined_uri",
")",
"return",
"PackURI",
"(",
"abs_u... | 40.75 | 10.25 |
def extract_features(self, text):
"""Extracts features from a body of text.
:rtype: dictionary of features
"""
# Feature extractor may take one or two arguments
try:
return self.feature_extractor(text, self.train_set)
except (TypeError, AttributeError):
... | [
"def",
"extract_features",
"(",
"self",
",",
"text",
")",
":",
"# Feature extractor may take one or two arguments",
"try",
":",
"return",
"self",
".",
"feature_extractor",
"(",
"text",
",",
"self",
".",
"train_set",
")",
"except",
"(",
"TypeError",
",",
"Attribute... | 32.090909 | 15.181818 |
def vor_to_am(vor):
r"""
Given a Voronoi tessellation object from Scipy's ``spatial`` module,
converts to a sparse adjacency matrix network representation in COO format.
Parameters
----------
vor : Voronoi Tessellation object
This object is produced by ``scipy.spatial.Voronoi``
Ret... | [
"def",
"vor_to_am",
"(",
"vor",
")",
":",
"# Create adjacency matrix in lil format for quick matrix construction",
"N",
"=",
"vor",
".",
"vertices",
".",
"shape",
"[",
"0",
"]",
"rc",
"=",
"[",
"[",
"]",
",",
"[",
"]",
"]",
"for",
"ij",
"in",
"vor",
".",
... | 33.285714 | 17.785714 |
def get_environ_vars(self):
"""Returns a generator with all environmental vars with prefix PIP_"""
for key, val in os.environ.items():
if _environ_prefix_re.search(key):
yield (_environ_prefix_re.sub("", key).lower(), val) | [
"def",
"get_environ_vars",
"(",
"self",
")",
":",
"for",
"key",
",",
"val",
"in",
"os",
".",
"environ",
".",
"items",
"(",
")",
":",
"if",
"_environ_prefix_re",
".",
"search",
"(",
"key",
")",
":",
"yield",
"(",
"_environ_prefix_re",
".",
"sub",
"(",
... | 52.4 | 10 |
def run_calibration(self, interval, applycal):
"""Runs the calibration operation with the current settings
:param interval: The repetition interval between stimuli presentations (seconds)
:type interval: float
:param applycal: Whether to apply a previous saved calibration to thi... | [
"def",
"run_calibration",
"(",
"self",
",",
"interval",
",",
"applycal",
")",
":",
"if",
"self",
".",
"selected_calibration_index",
"==",
"2",
":",
"self",
".",
"tone_calibrator",
".",
"apply_calibration",
"(",
"applycal",
")",
"self",
".",
"tone_calibrator",
... | 48.5 | 17.722222 |
def get_db(cls):
"""Return the database for the collection"""
if cls._db:
return getattr(cls._client, cls._db)
return cls._client.get_default_database() | [
"def",
"get_db",
"(",
"cls",
")",
":",
"if",
"cls",
".",
"_db",
":",
"return",
"getattr",
"(",
"cls",
".",
"_client",
",",
"cls",
".",
"_db",
")",
"return",
"cls",
".",
"_client",
".",
"get_default_database",
"(",
")"
] | 36.8 | 12.4 |
def _parseSimpleSelector(self, src):
"""simple_selector
: [ namespace_selector ]? element_name? [ HASH | class | attrib | pseudo ]* S*
;
"""
ctxsrc = src.lstrip()
nsPrefix, src = self._getMatchResult(self.re_namespace_selector, src)
name, src = self._getMatchResul... | [
"def",
"_parseSimpleSelector",
"(",
"self",
",",
"src",
")",
":",
"ctxsrc",
"=",
"src",
".",
"lstrip",
"(",
")",
"nsPrefix",
",",
"src",
"=",
"self",
".",
"_getMatchResult",
"(",
"self",
".",
"re_namespace_selector",
",",
"src",
")",
"name",
",",
"src",
... | 38.083333 | 20 |
def manage(settingspath, root_dir, argv):
"""
Manage all processes
"""
# add settings.json to environment variables
os.environ[ENV_VAR_SETTINGS] = settingspath
# add root_dir
os.environ[ENV_VAR_ROOT_DIR] = root_dir
# get datasets list
with open(settingspath) as settings_file:
... | [
"def",
"manage",
"(",
"settingspath",
",",
"root_dir",
",",
"argv",
")",
":",
"# add settings.json to environment variables",
"os",
".",
"environ",
"[",
"ENV_VAR_SETTINGS",
"]",
"=",
"settingspath",
"# add root_dir",
"os",
".",
"environ",
"[",
"ENV_VAR_ROOT_DIR",
"]... | 32.285714 | 9.333333 |
def cluster_application_state(self, application_id):
"""
With the application state API, you can obtain the current
state of an application.
:param str application_id: The application id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base... | [
"def",
"cluster_application_state",
"(",
"self",
",",
"application_id",
")",
":",
"path",
"=",
"'/ws/v1/cluster/apps/{appid}/state'",
".",
"format",
"(",
"appid",
"=",
"application_id",
")",
"return",
"self",
".",
"request",
"(",
"path",
")"
] | 35.230769 | 15.384615 |
def masked_middle_mfcc(self):
"""
Return the MFCC speech frames
in the MIDDLE portion of the wave.
:rtype: :class:`numpy.ndarray` (2D)
"""
begin, end = self._masked_middle_begin_end()
return (self.masked_mfcc)[:, begin:end] | [
"def",
"masked_middle_mfcc",
"(",
"self",
")",
":",
"begin",
",",
"end",
"=",
"self",
".",
"_masked_middle_begin_end",
"(",
")",
"return",
"(",
"self",
".",
"masked_mfcc",
")",
"[",
":",
",",
"begin",
":",
"end",
"]"
] | 30.222222 | 8.666667 |
def get_transactions_xml(self, account: SEPAAccount, start_date: datetime.date = None,
end_date: datetime.date = None) -> list:
"""
Fetches the list of transactions of a bank account in a certain timeframe as camt.052.001.02 XML files.
:param account: SEPA
:... | [
"def",
"get_transactions_xml",
"(",
"self",
",",
"account",
":",
"SEPAAccount",
",",
"start_date",
":",
"datetime",
".",
"date",
"=",
"None",
",",
"end_date",
":",
"datetime",
".",
"date",
"=",
"None",
")",
"->",
"list",
":",
"with",
"self",
".",
"_get_d... | 41.30303 | 21.181818 |
def lookup_path(bin_name):
"""Calls to external binaries can't depend on $PATH
"""
paths = ('/usr/local/sbin/', '/usr/local/bin/', '/usr/sbin/', '/usr/bin/')
for p in paths:
fq_path = p + bin_name
found = os.path.isfile(fq_path) and os.access(fq_path, os.X_OK)
if found:
... | [
"def",
"lookup_path",
"(",
"bin_name",
")",
":",
"paths",
"=",
"(",
"'/usr/local/sbin/'",
",",
"'/usr/local/bin/'",
",",
"'/usr/sbin/'",
",",
"'/usr/bin/'",
")",
"for",
"p",
"in",
"paths",
":",
"fq_path",
"=",
"p",
"+",
"bin_name",
"found",
"=",
"os",
".",... | 34.5 | 17.5 |
def nonblocking_input(self):
'''Context manager to set the :class:`Terminal`'s input file to read in
a non-blocking way.
Normally, reading from :attr:`sys.stdin` blocks, which is bad if we
want an interactive application that can also update information on the
screen without any... | [
"def",
"nonblocking_input",
"(",
"self",
")",
":",
"# FIXME: do we handle restoring this during SIGTSTP?",
"if",
"hasattr",
"(",
"self",
".",
"infile",
",",
"'fileno'",
")",
":",
"# Use fcntl to set stdin to non-blocking. WARNING - this is not",
"# particularly portable!",
"fla... | 44 | 24.08 |
def is_me(self): # pragma: no cover, seems not to be used anywhere
"""Check if parameter name if same than name of this object
TODO: is it useful?
:return: true if parameter name if same than this name
:rtype: bool
"""
logger.info("And arbiter is launched with the host... | [
"def",
"is_me",
"(",
"self",
")",
":",
"# pragma: no cover, seems not to be used anywhere",
"logger",
".",
"info",
"(",
"\"And arbiter is launched with the hostname:%s \"",
"\"from an arbiter point of view of addr:%s\"",
",",
"self",
".",
"host_name",
",",
"socket",
".",
"get... | 46.272727 | 27 |
def get_field_schema(name, field):
"""Returns a JSON Schema representation of a form field."""
field_schema = {
'type': 'string',
}
if field.label:
field_schema['title'] = str(field.label) # force translation
if field.help_text:
field_schema['description'] = str(field.help... | [
"def",
"get_field_schema",
"(",
"name",
",",
"field",
")",
":",
"field_schema",
"=",
"{",
"'type'",
":",
"'string'",
",",
"}",
"if",
"field",
".",
"label",
":",
"field_schema",
"[",
"'title'",
"]",
"=",
"str",
"(",
"field",
".",
"label",
")",
"# force ... | 38.545455 | 17.068182 |
def do_pickle_ontology(filename, g=None):
"""
from a valid filename, generate the graph instance and pickle it too
note: option to pass a pre-generated graph instance too
2015-09-17: added code to increase recursion limit if cPickle fails
see http://stackoverflow.com/questions/2134706/hitting-maximum-recursion-de... | [
"def",
"do_pickle_ontology",
"(",
"filename",
",",
"g",
"=",
"None",
")",
":",
"ONTOSPY_LOCAL_MODELS",
"=",
"get_home_location",
"(",
")",
"pickledpath",
"=",
"ONTOSPY_LOCAL_CACHE",
"+",
"\"/\"",
"+",
"filename",
"+",
"\".pickle\"",
"if",
"not",
"g",
":",
"g",... | 41.133333 | 23.533333 |
def __prepare_resource(data):
"""Prepare the resourcepart of the JID.
:Parameters:
- `data`: Resourcepart of the JID
:raise JIDError: if the resource name is too long.
:raise pyxmpp.xmppstringprep.StringprepError: if the
resourcepart fails Resourceprep preparati... | [
"def",
"__prepare_resource",
"(",
"data",
")",
":",
"if",
"not",
"data",
":",
"return",
"None",
"data",
"=",
"unicode",
"(",
"data",
")",
"try",
":",
"resource",
"=",
"RESOURCEPREP",
".",
"prepare",
"(",
"data",
")",
"except",
"StringprepError",
",",
"er... | 35.526316 | 16.157895 |
def _clean_rec_name(rec):
"""Clean illegal characters in input fasta file which cause problems downstream.
"""
out_id = []
for char in list(rec.id):
if char in ALLOWED_CONTIG_NAME_CHARS:
out_id.append(char)
else:
out_id.append("_")
rec.id = "".join(out_id)
... | [
"def",
"_clean_rec_name",
"(",
"rec",
")",
":",
"out_id",
"=",
"[",
"]",
"for",
"char",
"in",
"list",
"(",
"rec",
".",
"id",
")",
":",
"if",
"char",
"in",
"ALLOWED_CONTIG_NAME_CHARS",
":",
"out_id",
".",
"append",
"(",
"char",
")",
"else",
":",
"out_... | 28.75 | 13 |
def delete_acl_request(request):
"""Submission to remove an ACL."""
uuid_ = request.matchdict['uuid']
posted = request.json
permissions = [(x['uid'], x['permission'],) for x in posted]
with db_connect() as db_conn:
with db_conn.cursor() as cursor:
remove_acl(cursor, uuid_, permi... | [
"def",
"delete_acl_request",
"(",
"request",
")",
":",
"uuid_",
"=",
"request",
".",
"matchdict",
"[",
"'uuid'",
"]",
"posted",
"=",
"request",
".",
"json",
"permissions",
"=",
"[",
"(",
"x",
"[",
"'uid'",
"]",
",",
"x",
"[",
"'permission'",
"]",
",",
... | 29.692308 | 15.384615 |
def parallelize(mapfunc, workers=None):
'''
Parallelize the mapfunc with multithreading. mapfunc calls will be
partitioned by the provided list of arguments. Each item in the list
will represent one call's arguments. They can be tuples if the function
takes multiple arguments, but one-tupling is not... | [
"def",
"parallelize",
"(",
"mapfunc",
",",
"workers",
"=",
"None",
")",
":",
"workers",
"=",
"workers",
"if",
"workers",
"else",
"_get_default_workers",
"(",
")",
"def",
"wrapper",
"(",
"args_list",
")",
":",
"result",
"=",
"{",
"}",
"with",
"concurrent",
... | 37.617647 | 20.970588 |
def print_usage():
"""
Prints usage message.
"""
print('Usage: ' + os.path.basename(sys.argv[0]) + ' [options] dimacs-file')
print('Options:')
print(' -h, --help Show this message')
print(' -m, --model Print model')
print(' -s, --solver SAT solver... | [
"def",
"print_usage",
"(",
")",
":",
"print",
"(",
"'Usage: '",
"+",
"os",
".",
"path",
".",
"basename",
"(",
"sys",
".",
"argv",
"[",
"0",
"]",
")",
"+",
"' [options] dimacs-file'",
")",
"print",
"(",
"'Options:'",
")",
"print",
"(",
"' -h, --hel... | 37.916667 | 18.75 |
def covariance_matrix(self,x,y,names=None,cov=None):
"""build a pyemu.Cov instance from GeoStruct
Parameters
----------
x : (iterable of floats)
x-coordinate locations
y : (iterable of floats)
y-coordinate locations
names : (iterable of str)
... | [
"def",
"covariance_matrix",
"(",
"self",
",",
"x",
",",
"y",
",",
"names",
"=",
"None",
",",
"cov",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"x",
",",
"np",
".",
"ndarray",
")",
":",
"x",
"=",
"np",
".",
"array",
"(",
"x",
")",
... | 32.901639 | 19.540984 |
def notification_selected_sm_changed(self, model, prop_name, info):
"""If a new state machine is selected, make sure the tab is open"""
selected_state_machine_id = self.model.selected_state_machine_id
if selected_state_machine_id is None:
return
page_id = self.get_page_num(s... | [
"def",
"notification_selected_sm_changed",
"(",
"self",
",",
"model",
",",
"prop_name",
",",
"info",
")",
":",
"selected_state_machine_id",
"=",
"self",
".",
"model",
".",
"selected_state_machine_id",
"if",
"selected_state_machine_id",
"is",
"None",
":",
"return",
"... | 46.555556 | 23.925926 |
def imagetransformer_b12l_4h_b128_uncond_dr03_tpu():
"""TPU config for cifar 10."""
hparams = imagetransformer_bas8l_8h_big_uncond_dr03_imgnet()
update_hparams_for_tpu(hparams)
hparams.batch_size = 2
hparams.num_heads = 4 # heads are expensive on tpu
hparams.num_decoder_layers = 12
hparams.block_length ... | [
"def",
"imagetransformer_b12l_4h_b128_uncond_dr03_tpu",
"(",
")",
":",
"hparams",
"=",
"imagetransformer_bas8l_8h_big_uncond_dr03_imgnet",
"(",
")",
"update_hparams_for_tpu",
"(",
"hparams",
")",
"hparams",
".",
"batch_size",
"=",
"2",
"hparams",
".",
"num_heads",
"=",
... | 38 | 10 |
def options(self, route: str(), callback: object()):
"""
Binds a OPTIONS route with the given callback
:rtype: object
"""
self.__set_route('options', {route: callback})
return RouteMapping | [
"def",
"options",
"(",
"self",
",",
"route",
":",
"str",
"(",
")",
",",
"callback",
":",
"object",
"(",
")",
")",
":",
"self",
".",
"__set_route",
"(",
"'options'",
",",
"{",
"route",
":",
"callback",
"}",
")",
"return",
"RouteMapping"
] | 32.857143 | 10 |
def init_jvm(java_home=None,
jvm_dll=None,
jvm_maxmem=None,
jvm_classpath=None,
jvm_properties=None,
jvm_options=None,
config_file=None,
config=None):
"""
Creates a configured Java virtual machine which will be used by jp... | [
"def",
"init_jvm",
"(",
"java_home",
"=",
"None",
",",
"jvm_dll",
"=",
"None",
",",
"jvm_maxmem",
"=",
"None",
",",
"jvm_classpath",
"=",
"None",
",",
"jvm_properties",
"=",
"None",
",",
"jvm_options",
"=",
"None",
",",
"config_file",
"=",
"None",
",",
"... | 48.530612 | 26.816327 |
def run(scenario, magicc_version=6, **kwargs):
"""
Run a MAGICC scenario and return output data and (optionally) config parameters.
As a reminder, putting ``out_parameters=1`` will cause MAGICC to write out its
parameters into ``out/PARAMETERS.OUT`` and they will then be read into
``output.metadata... | [
"def",
"run",
"(",
"scenario",
",",
"magicc_version",
"=",
"6",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"magicc_version",
"==",
"6",
":",
"magicc_cls",
"=",
"MAGICC6",
"elif",
"magicc_version",
"==",
"7",
":",
"magicc_cls",
"=",
"MAGICC7",
"else",
":",
... | 29.02439 | 24.097561 |
def platform_data_dir():
"""
Returns path for user-specific data files
Returns:
PathLike : path to the data dir used by the current operating system
"""
if LINUX: # nocover
dpath_ = os.environ.get('XDG_DATA_HOME', '~/.local/share')
elif DARWIN: # nocover
dpath_ = '~/L... | [
"def",
"platform_data_dir",
"(",
")",
":",
"if",
"LINUX",
":",
"# nocover",
"dpath_",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'XDG_DATA_HOME'",
",",
"'~/.local/share'",
")",
"elif",
"DARWIN",
":",
"# nocover",
"dpath_",
"=",
"'~/Library/Application Support'... | 31.352941 | 16.411765 |
def __get_query_agg_cardinality(cls, field, agg_id=None):
"""
Create an es_dsl aggregation object for getting the approximate count of distinct values of a field.
:param field: field from which the get count of distinct values
:return: a tuple with the aggregation id and es_dsl aggregat... | [
"def",
"__get_query_agg_cardinality",
"(",
"cls",
",",
"field",
",",
"agg_id",
"=",
"None",
")",
":",
"if",
"not",
"agg_id",
":",
"agg_id",
"=",
"cls",
".",
"AGGREGATION_ID",
"query_agg",
"=",
"A",
"(",
"\"cardinality\"",
",",
"field",
"=",
"field",
",",
... | 42.8125 | 20.8125 |
def listBlockParents(self, block_name=""):
"""
list parents of a block
"""
if not block_name:
msg = " DBSBlock/listBlockParents. Block_name must be provided as a string or a list. \
No wildcards allowed in block_name/s."
dbsExceptionHandler('dbsExc... | [
"def",
"listBlockParents",
"(",
"self",
",",
"block_name",
"=",
"\"\"",
")",
":",
"if",
"not",
"block_name",
":",
"msg",
"=",
"\" DBSBlock/listBlockParents. Block_name must be provided as a string or a list. \\\n No wildcards allowed in block_name/s.\"",
"dbsExceptio... | 48.757576 | 23.060606 |
def rtgen_family(self, value):
"""Family setter."""
self.bytearray[self._get_slicers(0)] = bytearray(c_ubyte(value or 0)) | [
"def",
"rtgen_family",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"bytearray",
"[",
"self",
".",
"_get_slicers",
"(",
"0",
")",
"]",
"=",
"bytearray",
"(",
"c_ubyte",
"(",
"value",
"or",
"0",
")",
")"
] | 45 | 15.666667 |
def get_item(self, **kwargs):
""" Get collection item taking into account generated queryset
of parent view.
This method allows working with nested resources properly. Thus an item
returned by this method will belong to its parent view's queryset, thus
filtering out objects that... | [
"def",
"get_item",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"six",
".",
"callable",
"(",
"self",
".",
"context",
")",
":",
"self",
".",
"reload_context",
"(",
"es_based",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
"objects",
"=",
"sel... | 39.761905 | 20.666667 |
def move_right(self, keep_anchor=False, nb_chars=1):
"""
Moves the cursor on the right.
:param keep_anchor: True to keep anchor (to select text) or False to
move the anchor (no selection)
:param nb_chars: Number of characters to move.
"""
text_cursor = self._... | [
"def",
"move_right",
"(",
"self",
",",
"keep_anchor",
"=",
"False",
",",
"nb_chars",
"=",
"1",
")",
":",
"text_cursor",
"=",
"self",
".",
"_editor",
".",
"textCursor",
"(",
")",
"text_cursor",
".",
"movePosition",
"(",
"text_cursor",
".",
"Right",
",",
"... | 40.692308 | 12.692308 |
def datasets(self):
"""Distinct datasets (``dataset``) in :class:`.models.Entry`
Distinct datasets are SwissProt or/and TrEMBL
:return: all distinct dataset types
:rtype: list[str]
"""
r = self.session.query(distinct(models.Entry.dataset)).all()
return [x[0] for... | [
"def",
"datasets",
"(",
"self",
")",
":",
"r",
"=",
"self",
".",
"session",
".",
"query",
"(",
"distinct",
"(",
"models",
".",
"Entry",
".",
"dataset",
")",
")",
".",
"all",
"(",
")",
"return",
"[",
"x",
"[",
"0",
"]",
"for",
"x",
"in",
"r",
... | 31.9 | 16.8 |
def _apply_template(template, target, *, checkout, extra_context):
"""Apply a template to a temporary directory and then copy results to target."""
with tempfile.TemporaryDirectory() as tempdir:
repo_dir = cc_main.cookiecutter(
template,
checkout=checkout,
no_input=Tr... | [
"def",
"_apply_template",
"(",
"template",
",",
"target",
",",
"*",
",",
"checkout",
",",
"extra_context",
")",
":",
"with",
"tempfile",
".",
"TemporaryDirectory",
"(",
")",
"as",
"tempdir",
":",
"repo_dir",
"=",
"cc_main",
".",
"cookiecutter",
"(",
"templat... | 39.95 | 7.05 |
def _login(self, max_tries=2):
"""Logs in to Kindle Cloud Reader.
Args:
max_tries: The maximum number of login attempts that will be made.
Raises:
BrowserError: If method called when browser not at a signin URL.
LoginError: If login unsuccessful after `max_tries` attempts.
"""
i... | [
"def",
"_login",
"(",
"self",
",",
"max_tries",
"=",
"2",
")",
":",
"if",
"not",
"self",
".",
"current_url",
".",
"startswith",
"(",
"_KindleCloudReaderBrowser",
".",
"_SIGNIN_URL",
")",
":",
"raise",
"BrowserError",
"(",
"'Current url \"%s\" is not a signin url (... | 32.458333 | 21.770833 |
def _get_setup(self, result):
"""Internal method which process the results from the server."""
self.__devices = {}
if ('setup' not in result.keys() or
'devices' not in result['setup'].keys()):
raise Exception(
"Did not find device definition.")
... | [
"def",
"_get_setup",
"(",
"self",
",",
"result",
")",
":",
"self",
".",
"__devices",
"=",
"{",
"}",
"if",
"(",
"'setup'",
"not",
"in",
"result",
".",
"keys",
"(",
")",
"or",
"'devices'",
"not",
"in",
"result",
"[",
"'setup'",
"]",
".",
"keys",
"(",... | 37.2 | 15.866667 |
def _create_options(self, items):
"""Helper method to create options from list, or instance.
Applies preprocess method if available to create a uniform
output
"""
return OrderedDict(map(lambda x: (x.name, x),
coerce_to_list(items, self.preprocess))) | [
"def",
"_create_options",
"(",
"self",
",",
"items",
")",
":",
"return",
"OrderedDict",
"(",
"map",
"(",
"lambda",
"x",
":",
"(",
"x",
".",
"name",
",",
"x",
")",
",",
"coerce_to_list",
"(",
"items",
",",
"self",
".",
"preprocess",
")",
")",
")"
] | 38.75 | 17.375 |
def cmd_ip_geolocation(ip_address, verbose):
"""Get the geolocation of an IP adddress from https://ipapi.co/.
Example:
\b
$ habu.ip.geolocation 8.8.8.8
{
"ip": "8.8.8.8",
"city": "Mountain View",
...
"asn": "AS15169",
"org": "Google LLC"
}
"""
if... | [
"def",
"cmd_ip_geolocation",
"(",
"ip_address",
",",
"verbose",
")",
":",
"if",
"verbose",
":",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"logging",
".",
"INFO",
",",
"format",
"=",
"'%(message)s'",
")",
"print",
"(",
"\"Looking up %s...\"",
"%",
"ip... | 23.296296 | 22.592593 |
def active_path(context, pattern, css=None):
"""
Highlight menu item based on path.
Returns a css class if ``request.path`` is in given ``pattern``.
:param pattern:
Regex url pattern.
:param css:
Css class to be returned for highlighting. Return active if none set.
""... | [
"def",
"active_path",
"(",
"context",
",",
"pattern",
",",
"css",
"=",
"None",
")",
":",
"request",
"=",
"context",
"[",
"'request'",
"]",
"#pattern = \"^\" + pattern + \"$\"",
"if",
"re",
".",
"search",
"(",
"pattern",
",",
"request",
".",
"path",
")",
":... | 25.944444 | 18.055556 |
def prepare_encrypted_request(self, session, endpoint, message):
"""
Creates a prepared request to send to the server with an encrypted message
and correct headers
:param session: The handle of the session to prepare requests with
:param endpoint: The endpoint/server to prepare ... | [
"def",
"prepare_encrypted_request",
"(",
"self",
",",
"session",
",",
"endpoint",
",",
"message",
")",
":",
"host",
"=",
"urlsplit",
"(",
"endpoint",
")",
".",
"hostname",
"if",
"self",
".",
"protocol",
"==",
"'credssp'",
"and",
"len",
"(",
"message",
")",... | 50.354839 | 26.032258 |
def hpforest(self, data: ['SASdata', str] = None,
freq: str = None,
id: str = None,
input: [str, list, dict] = None,
save: str = None,
score: [str, bool, 'SASdata'] = True,
target: [str, list, dict] = None,
... | [
"def",
"hpforest",
"(",
"self",
",",
"data",
":",
"[",
"'SASdata'",
",",
"str",
"]",
"=",
"None",
",",
"freq",
":",
"str",
"=",
"None",
",",
"id",
":",
"str",
"=",
"None",
",",
"input",
":",
"[",
"str",
",",
"list",
",",
"dict",
"]",
"=",
"No... | 57.37037 | 28.481481 |
def from_charmm(cls, path, positions=None, forcefield=None, strict=True, **kwargs):
"""
Loads PSF Charmm structure from `path`. Requires `charmm_parameters`.
Parameters
----------
path : str
Path to PSF file
forcefield : list of str
Paths to Charm... | [
"def",
"from_charmm",
"(",
"cls",
",",
"path",
",",
"positions",
"=",
"None",
",",
"forcefield",
"=",
"None",
",",
"strict",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"psf",
"=",
"CharmmPsfFile",
"(",
"path",
")",
"if",
"strict",
"and",
"forcef... | 38.153846 | 19.923077 |
def init():
'''Initialise a WSGI application to be loaded by uWSGI.'''
# Load values from config file
config_file = os.path.realpath(os.path.join(os.getcwd(), 'swaggery.ini'))
config = configparser.RawConfigParser(allow_no_value=True)
config.read(config_file)
log_level = config.get('application'... | [
"def",
"init",
"(",
")",
":",
"# Load values from config file",
"config_file",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getcwd",
"(",
")",
",",
"'swaggery.ini'",
")",
")",
"config",
"=",
"configparser... | 45.882353 | 17.647059 |
def create(cls, session, record, imported=False, auto_reply=False):
"""Create a conversation.
Please note that conversation cannot be created with more than 100
threads, if attempted the API will respond with HTTP 412.
Args:
session (requests.sessions.Session): Authenticate... | [
"def",
"create",
"(",
"cls",
",",
"session",
",",
"record",
",",
"imported",
"=",
"False",
",",
"auto_reply",
"=",
"False",
")",
":",
"return",
"super",
"(",
"Conversations",
",",
"cls",
")",
".",
"create",
"(",
"session",
",",
"record",
",",
"imported... | 45.133333 | 25.133333 |
def index(self, value, start=None, stop=None):
"""
Return the index of the first occurence of *value*.
If *start* or *stop* are provided, return the smallest
index such that ``s[index] == value`` and ``start <= index < stop``.
"""
def index_trans(pipe):
len_se... | [
"def",
"index",
"(",
"self",
",",
"value",
",",
"start",
"=",
"None",
",",
"stop",
"=",
"None",
")",
":",
"def",
"index_trans",
"(",
"pipe",
")",
":",
"len_self",
",",
"normal_start",
"=",
"self",
".",
"_normalize_index",
"(",
"start",
"or",
"0",
","... | 40.947368 | 14.842105 |
def create_model(modelname, fields, indexes=None, basemodel=None, **props):
"""
Create model dynamically
:param fields: Just format like [
{'name':name, 'type':type, ...},
...
]
type should be a string, eg. 'str', '... | [
"def",
"create_model",
"(",
"modelname",
",",
"fields",
",",
"indexes",
"=",
"None",
",",
"basemodel",
"=",
"None",
",",
"*",
"*",
"props",
")",
":",
"assert",
"not",
"props",
"or",
"isinstance",
"(",
"props",
",",
"dict",
")",
"assert",
"not",
"indexe... | 31.103448 | 20.781609 |
def log_error(error, result):
"""Logs an error
"""
p = {'error': error, 'result':result}
_log(TYPE_CODES.ERROR, p) | [
"def",
"log_error",
"(",
"error",
",",
"result",
")",
":",
"p",
"=",
"{",
"'error'",
":",
"error",
",",
"'result'",
":",
"result",
"}",
"_log",
"(",
"TYPE_CODES",
".",
"ERROR",
",",
"p",
")"
] | 25.2 | 4.6 |
def prefix_indent(prefix, textblock, later_prefix=' '):
"""
Prefix and indent all lines in *textblock*.
*prefix* is a prefix string
*later_prefix* is used on all but the first line, if it is a single character
it will be repeated to match length of *prefix*
"""
textblock = te... | [
"def",
"prefix_indent",
"(",
"prefix",
",",
"textblock",
",",
"later_prefix",
"=",
"' '",
")",
":",
"textblock",
"=",
"textblock",
".",
"split",
"(",
"'\\n'",
")",
"line",
"=",
"prefix",
"+",
"textblock",
"[",
"0",
"]",
"+",
"'\\n'",
"if",
"len",
"(",
... | 34.470588 | 15.647059 |
async def is_object_synced_to_cn(self, client, pid):
"""Check if object with {pid} has successfully synced to the CN.
CNRead.describe() is used as it's a light-weight HTTP HEAD request.
This assumes that the call is being made over a connection that has been
authenticated and has read ... | [
"async",
"def",
"is_object_synced_to_cn",
"(",
"self",
",",
"client",
",",
"pid",
")",
":",
"try",
":",
"await",
"client",
".",
"describe",
"(",
"pid",
")",
"except",
"d1_common",
".",
"types",
".",
"exceptions",
".",
"DataONEException",
":",
"return",
"Fa... | 37.642857 | 24.142857 |
def cleanup():
"""Close all sockets at exit"""
for sck in list(Wdb._sockets):
try:
sck.close()
except Exception:
log.warn('Error in cleanup', exc_info=True) | [
"def",
"cleanup",
"(",
")",
":",
"for",
"sck",
"in",
"list",
"(",
"Wdb",
".",
"_sockets",
")",
":",
"try",
":",
"sck",
".",
"close",
"(",
")",
"except",
"Exception",
":",
"log",
".",
"warn",
"(",
"'Error in cleanup'",
",",
"exc_info",
"=",
"True",
... | 28.285714 | 15.285714 |
def create(self, properties):
"""
Create and configure a storage group.
The new storage group will be associated with the CPC identified by the
`cpc-uri` input property.
Authorization requirements:
* Object-access permission to the CPC that will be associated with
... | [
"def",
"create",
"(",
"self",
",",
"properties",
")",
":",
"if",
"properties",
"is",
"None",
":",
"properties",
"=",
"{",
"}",
"result",
"=",
"self",
".",
"session",
".",
"post",
"(",
"self",
".",
"_base_uri",
",",
"body",
"=",
"properties",
")",
"# ... | 36.02 | 21.5 |
def end(self, sql=None):
"""Commit the current transaction."""
self._transaction = False
try:
end = self._con.end
except AttributeError:
return self._con.query(sql or 'end')
else:
if sql:
return end(sql=sql)
else:
... | [
"def",
"end",
"(",
"self",
",",
"sql",
"=",
"None",
")",
":",
"self",
".",
"_transaction",
"=",
"False",
"try",
":",
"end",
"=",
"self",
".",
"_con",
".",
"end",
"except",
"AttributeError",
":",
"return",
"self",
".",
"_con",
".",
"query",
"(",
"sq... | 27.916667 | 13.833333 |
def get_arguments(args):
"""Parse the command line."""
usage = "%(prog)s [arguments] [image files]"
programs_str = ', '.join([prog.__name__ for prog in PROGRAMS])
description = "Uses "+programs_str+" if they are on the path."
parser = argparse.ArgumentParser(usage=usage, description=description)
... | [
"def",
"get_arguments",
"(",
"args",
")",
":",
"usage",
"=",
"\"%(prog)s [arguments] [image files]\"",
"programs_str",
"=",
"', '",
".",
"join",
"(",
"[",
"prog",
".",
"__name__",
"for",
"prog",
"in",
"PROGRAMS",
"]",
")",
"description",
"=",
"\"Uses \"",
"+",... | 59.541667 | 21.072917 |
def main():
"""
Main program entry point
"""
args = command_line()
# TODO: Decouple Book interface and implementation
query = Book(
title=args.title,
author=args.author,
max_results=args.max,
language_code=args.language,
fields=('title', 'authors', 'image... | [
"def",
"main",
"(",
")",
":",
"args",
"=",
"command_line",
"(",
")",
"# TODO: Decouple Book interface and implementation",
"query",
"=",
"Book",
"(",
"title",
"=",
"args",
".",
"title",
",",
"author",
"=",
"args",
".",
"author",
",",
"max_results",
"=",
"arg... | 27.64 | 20.44 |
def get_plugin_command(plugin_name, command_name, conn=None):
"""
get_specific_command function queries a specific CommandName
:param plugin_name: <str> PluginName
:param command_name: <str> CommandName
:return: <dict>
"""
commands = RPX.table(plugin_name).filter(
{COMMAND_NAME_KEY:... | [
"def",
"get_plugin_command",
"(",
"plugin_name",
",",
"command_name",
",",
"conn",
"=",
"None",
")",
":",
"commands",
"=",
"RPX",
".",
"table",
"(",
"plugin_name",
")",
".",
"filter",
"(",
"{",
"COMMAND_NAME_KEY",
":",
"command_name",
"}",
")",
".",
"run",... | 31.5 | 12.928571 |
def shutit_method_scope(func):
"""Notifies the ShutIt object whenever we call a shutit module method.
This allows setting values for the 'scope' of a function.
"""
def wrapper(self, shutit):
"""Wrapper to call a shutit module method, notifying the ShutIt object.
"""
ret = func(self, shutit)
return ret
retu... | [
"def",
"shutit_method_scope",
"(",
"func",
")",
":",
"def",
"wrapper",
"(",
"self",
",",
"shutit",
")",
":",
"\"\"\"Wrapper to call a shutit module method, notifying the ShutIt object.\n\t\t\"\"\"",
"ret",
"=",
"func",
"(",
"self",
",",
"shutit",
")",
"return",
"ret",... | 32.1 | 10.8 |
def convertloc(candsfile, candloc, memory_limit):
""" For given state and location that are too bulky, calculate new location given memory_limit. """
scan, segment, candint, dmind, dtind, beamnum = candloc
# set up state and find absolute integration of candidate
d0 = pickle.load(open(candsfile, 'r'))... | [
"def",
"convertloc",
"(",
"candsfile",
",",
"candloc",
",",
"memory_limit",
")",
":",
"scan",
",",
"segment",
",",
"candint",
",",
"dmind",
",",
"dtind",
",",
"beamnum",
"=",
"candloc",
"# set up state and find absolute integration of candidate",
"d0",
"=",
"pickl... | 39.829268 | 21.560976 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.