text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def transition(value, maximum, start, end):
""" Transition between two values.
:param value: Current iteration.
:param maximum: Maximum number of iterations.
:param start: Start value.
:param end: End value.
:returns: Transitional value.
"""
return round(start + (end - start) * value / ... | [
"def",
"transition",
"(",
"value",
",",
"maximum",
",",
"start",
",",
"end",
")",
":",
"return",
"round",
"(",
"start",
"+",
"(",
"end",
"-",
"start",
")",
"*",
"value",
"/",
"maximum",
",",
"2",
")"
] | 32.2 | 0.003021 |
def simxSetSphericalJointMatrix(clientID, jointHandle, matrix, operationMode):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
matrix = (ct.c_float*12)(*matrix)
return c_SetSphericalJointMatrix(clientID, jointHandle, matrix, operationMode) | [
"def",
"simxSetSphericalJointMatrix",
"(",
"clientID",
",",
"jointHandle",
",",
"matrix",
",",
"operationMode",
")",
":",
"matrix",
"=",
"(",
"ct",
".",
"c_float",
"*",
"12",
")",
"(",
"*",
"matrix",
")",
"return",
"c_SetSphericalJointMatrix",
"(",
"clientID",... | 50 | 0.009836 |
def readline(self, echo=None, prompt='', use_history=True):
"""Return a line of text, including the terminating LF
If echo is true always echo, if echo is false never echo
If echo is None follow the negotiated setting.
prompt is the current prompt to write (and rewrite if needed... | [
"def",
"readline",
"(",
"self",
",",
"echo",
"=",
"None",
",",
"prompt",
"=",
"''",
",",
"use_history",
"=",
"True",
")",
":",
"line",
"=",
"[",
"]",
"insptr",
"=",
"0",
"ansi",
"=",
"0",
"histptr",
"=",
"len",
"(",
"self",
".",
"history",
")",
... | 39.495575 | 0.00306 |
def yield_from_handle(self, tokens):
"""Process Python 3.3 yield from."""
internal_assert(len(tokens) == 1, "invalid yield from tokens", tokens)
if self.target_info < (3, 3):
return (
yield_from_var + " = " + tokens[0]
+ "\nfor " + yield_item_var + " i... | [
"def",
"yield_from_handle",
"(",
"self",
",",
"tokens",
")",
":",
"internal_assert",
"(",
"len",
"(",
"tokens",
")",
"==",
"1",
",",
"\"invalid yield from tokens\"",
",",
"tokens",
")",
"if",
"self",
".",
"target_info",
"<",
"(",
"3",
",",
"3",
")",
":",... | 44.454545 | 0.004008 |
def parse_html_urls(file_name, html_data):
'''
Returns a list of tuples in the form (url, file_name, line_number)
'''
try:
html = lxml.html.fromstring(html_data)
anchor_tags = html.cssselect('a')
for a in anchor_tags:
# A link was started but not finished, href with ... | [
"def",
"parse_html_urls",
"(",
"file_name",
",",
"html_data",
")",
":",
"try",
":",
"html",
"=",
"lxml",
".",
"html",
".",
"fromstring",
"(",
"html_data",
")",
"anchor_tags",
"=",
"html",
".",
"cssselect",
"(",
"'a'",
")",
"for",
"a",
"in",
"anchor_tags"... | 30.565217 | 0.002759 |
def is_valid_channel(self,
channel,
conda_url='https://conda.anaconda.org',
non_blocking=True):
"""Check if a conda channel is valid."""
logger.debug(str((channel, conda_url)))
if non_blocking:
method = self._... | [
"def",
"is_valid_channel",
"(",
"self",
",",
"channel",
",",
"conda_url",
"=",
"'https://conda.anaconda.org'",
",",
"non_blocking",
"=",
"True",
")",
":",
"logger",
".",
"debug",
"(",
"str",
"(",
"(",
"channel",
",",
"conda_url",
")",
")",
")",
"if",
"non_... | 43.545455 | 0.010225 |
def authenticate(url, account, key, by='name', expires=0, timestamp=None,
timeout=None, request_type="xml", admin_auth=False,
use_password=False, raise_on_error=False):
""" Authenticate to the Zimbra server
:param url: URL of Zimbra SOAP service
:param account: The accoun... | [
"def",
"authenticate",
"(",
"url",
",",
"account",
",",
"key",
",",
"by",
"=",
"'name'",
",",
"expires",
"=",
"0",
",",
"timestamp",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
"request_type",
"=",
"\"xml\"",
",",
"admin_auth",
"=",
"False",
",",
... | 26.028571 | 0.000352 |
def is_complete(self):
"""
Checks whether all descriptor fields are set.
If descriptor has at least one "*" or null field it is considered "incomplete"
:return: true if all descriptor fields are defined and false otherwise.
"""
return self._group != None and self._type !... | [
"def",
"is_complete",
"(",
"self",
")",
":",
"return",
"self",
".",
"_group",
"!=",
"None",
"and",
"self",
".",
"_type",
"!=",
"None",
"and",
"self",
".",
"_kind",
"!=",
"None",
"and",
"self",
".",
"_name",
"!=",
"None",
"and",
"self",
".",
"_version... | 44.888889 | 0.021845 |
def subsequent_calling_points(self):
"""
A list of CallingPoint objects.
This is the list of all subsequent calling points for the service,
including all associated services if the service splits into multiple
services.
"""
calling_points = list()
for cpl... | [
"def",
"subsequent_calling_points",
"(",
"self",
")",
":",
"calling_points",
"=",
"list",
"(",
")",
"for",
"cpl",
"in",
"self",
".",
"_subsequent_calling_point_lists",
":",
"calling_points",
"+=",
"cpl",
".",
"calling_points",
"return",
"calling_points"
] | 35.75 | 0.004545 |
def prioritized_iter(cls, flag_val, env_val, config_val, config_default_val,
hardcoded_val, default):
"""Yield the non-None values from highest-ranked to lowest, wrapped in RankedValue instances."""
if flag_val is not None:
yield RankedValue(cls.FLAG, flag_val)
if env_val is not... | [
"def",
"prioritized_iter",
"(",
"cls",
",",
"flag_val",
",",
"env_val",
",",
"config_val",
",",
"config_default_val",
",",
"hardcoded_val",
",",
"default",
")",
":",
"if",
"flag_val",
"is",
"not",
"None",
":",
"yield",
"RankedValue",
"(",
"cls",
".",
"FLAG",... | 48.142857 | 0.011645 |
def do_execute_direct(self, code: str, silent: bool = False) -> [str, dict]:
"""
This is the main method that takes code from the Jupyter cell and submits it to the SAS server
:param code: code from the cell
:param silent:
:return: str with either the log or list
"""
... | [
"def",
"do_execute_direct",
"(",
"self",
",",
"code",
":",
"str",
",",
"silent",
":",
"bool",
"=",
"False",
")",
"->",
"[",
"str",
",",
"dict",
"]",
":",
"if",
"not",
"code",
".",
"strip",
"(",
")",
":",
"return",
"{",
"'status'",
":",
"'ok'",
",... | 43.734694 | 0.004564 |
def cutout(im, n_holes, length):
""" Cut out n_holes number of square holes of size length in image at random locations. Holes may overlap. """
r,c,*_ = im.shape
mask = np.ones((r, c), np.int32)
for n in range(n_holes):
y = np.random.randint(0, r)
x = np.random.randint(0, c)
y1 ... | [
"def",
"cutout",
"(",
"im",
",",
"n_holes",
",",
"length",
")",
":",
"r",
",",
"c",
",",
"",
"*",
"_",
"=",
"im",
".",
"shape",
"mask",
"=",
"np",
".",
"ones",
"(",
"(",
"r",
",",
"c",
")",
",",
"np",
".",
"int32",
")",
"for",
"n",
"in",
... | 34.235294 | 0.011706 |
def dump_counts(self, out=sys.stdout, count_fn=len, colwidth=10):
"""Dump out the summary counts of entries in this pivot table as a tabular listing.
@param out: output stream to write to
@param count_fn: (default=len) function for computing value for each pivot cell
@param colw... | [
"def",
"dump_counts",
"(",
"self",
",",
"out",
"=",
"sys",
".",
"stdout",
",",
"count_fn",
"=",
"len",
",",
"colwidth",
"=",
"10",
")",
":",
"if",
"len",
"(",
"self",
".",
"_pivot_attrs",
")",
"==",
"1",
":",
"out",
".",
"write",
"(",
"\"Pivot: %s\... | 56.146341 | 0.003843 |
def add_child_gradebook(self, gradebook_id, child_id):
"""Adds a child to a gradebook.
arg: gradebook_id (osid.id.Id): the ``Id`` of a gradebook
arg: child_id (osid.id.Id): the ``Id`` of the new child
raise: AlreadyExists - ``gradebook_id`` is already a parent of
... | [
"def",
"add_child_gradebook",
"(",
"self",
",",
"gradebook_id",
",",
"child_id",
")",
":",
"# Implemented from template for",
"# osid.resource.BinHierarchyDesignSession.add_child_bin_template",
"if",
"self",
".",
"_catalog_session",
"is",
"not",
"None",
":",
"return",
"self... | 51.1 | 0.003842 |
def union(self, other):
"""Returns a new IntervalSet which represents the union of each of the intervals in this IntervalSet with each
of the intervals in the other IntervalSet
:param other: An IntervalSet to union with this one.
"""
result = IntervalSet()
for el in self:... | [
"def",
"union",
"(",
"self",
",",
"other",
")",
":",
"result",
"=",
"IntervalSet",
"(",
")",
"for",
"el",
"in",
"self",
":",
"result",
".",
"add",
"(",
"el",
")",
"for",
"el",
"in",
"other",
":",
"result",
".",
"add",
"(",
"el",
")",
"return",
... | 37.363636 | 0.007126 |
def add_network_to_dhcp_agent(self, dhcp_agent, body=None):
"""Adds a network to dhcp agent."""
return self.post((self.agent_path + self.DHCP_NETS) % dhcp_agent,
body=body) | [
"def",
"add_network_to_dhcp_agent",
"(",
"self",
",",
"dhcp_agent",
",",
"body",
"=",
"None",
")",
":",
"return",
"self",
".",
"post",
"(",
"(",
"self",
".",
"agent_path",
"+",
"self",
".",
"DHCP_NETS",
")",
"%",
"dhcp_agent",
",",
"body",
"=",
"body",
... | 52.5 | 0.00939 |
def set_connection_logging(self, loadbalancer, val):
"""
Sets the connection logging for the given load balancer.
"""
uri = "/loadbalancers/%s/connectionlogging" % utils.get_id(loadbalancer)
val = str(val).lower()
req_body = {"connectionLogging": {
"enable... | [
"def",
"set_connection_logging",
"(",
"self",
",",
"loadbalancer",
",",
"val",
")",
":",
"uri",
"=",
"\"/loadbalancers/%s/connectionlogging\"",
"%",
"utils",
".",
"get_id",
"(",
"loadbalancer",
")",
"val",
"=",
"str",
"(",
"val",
")",
".",
"lower",
"(",
")",... | 38 | 0.007009 |
def triads_inv(reference_labels, estimated_labels):
"""Score chords along triad (root, quality to #5, & bass) relationships.
Examples
--------
>>> (ref_intervals,
... ref_labels) = mir_eval.io.load_labeled_intervals('ref.lab')
>>> (est_intervals,
... est_labels) = mir_eval.io.load_labeled... | [
"def",
"triads_inv",
"(",
"reference_labels",
",",
"estimated_labels",
")",
":",
"validate",
"(",
"reference_labels",
",",
"estimated_labels",
")",
"ref_roots",
",",
"ref_semitones",
",",
"ref_bass",
"=",
"encode_many",
"(",
"reference_labels",
",",
"False",
")",
... | 38.276596 | 0.000542 |
def add_decrypt_chunk(
self, final_path, internal_fdstart, offsets, symkey, iv,
hmac_datafile):
# type: (CryptoOffload, str, int, blobxfer.models.download.Offsets,
# bytes, bytes, str) -> None
"""Add a chunk to decrypt
:param CryptoOffload self: this
... | [
"def",
"add_decrypt_chunk",
"(",
"self",
",",
"final_path",
",",
"internal_fdstart",
",",
"offsets",
",",
"symkey",
",",
"iv",
",",
"hmac_datafile",
")",
":",
"# type: (CryptoOffload, str, int, blobxfer.models.download.Offsets,",
"# bytes, bytes, str) -> None",
"self",... | 43.055556 | 0.005051 |
def make_figure_source_geom(extractors, what):
"""
Extract the geometry of a given sources
Example:
http://127.0.0.1:8800/v1/calc/30/extract/source_geom/1,2,3
"""
import matplotlib.pyplot as plt
fig = plt.figure()
[ex] = extractors
sitecol = ex.get('sitecol')
geom_by_src = vars(e... | [
"def",
"make_figure_source_geom",
"(",
"extractors",
",",
"what",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"fig",
"=",
"plt",
".",
"figure",
"(",
")",
"[",
"ex",
"]",
"=",
"extractors",
"sitecol",
"=",
"ex",
".",
"get",
"(",
"'site... | 30.333333 | 0.001522 |
def right(self, f, n=1):
"""return the nearest n features strictly to the right of a Feature f.
Overlapping features are not considered as to the right.
f: a Feature object
n: the number of features to return
"""
intervals = self.intervals[f.chrom]
ilen = len(int... | [
"def",
"right",
"(",
"self",
",",
"f",
",",
"n",
"=",
"1",
")",
":",
"intervals",
"=",
"self",
".",
"intervals",
"[",
"f",
".",
"chrom",
"]",
"ilen",
"=",
"len",
"(",
"intervals",
")",
"iright",
"=",
"binsearch_right_end",
"(",
"intervals",
",",
"f... | 34.636364 | 0.003831 |
def _find_append_zero_crossings(x, y):
r"""
Find and interpolate zero crossings.
Estimate the zero crossings of an x,y series and add estimated crossings to series,
returning a sorted array with no duplicate values.
Parameters
----------
x : `pint.Quantity`
x values of data
y :... | [
"def",
"_find_append_zero_crossings",
"(",
"x",
",",
"y",
")",
":",
"# Find and append crossings to the data",
"crossings",
"=",
"find_intersections",
"(",
"x",
"[",
"1",
":",
"]",
",",
"y",
"[",
"1",
":",
"]",
",",
"np",
".",
"zeros_like",
"(",
"y",
"[",
... | 24.945946 | 0.003128 |
def update(self):
"""Update |KInz| based on |HInz| and |LAI|.
>>> from hydpy.models.lland import *
>>> parameterstep('1d')
>>> nhru(2)
>>> hinz(0.2)
>>> lai.acker_jun = 1.0
>>> lai.vers_dec = 2.0
>>> derived.kinz.update()
>>> from hydpy import rou... | [
"def",
"update",
"(",
"self",
")",
":",
"con",
"=",
"self",
".",
"subpars",
".",
"pars",
".",
"control",
"self",
"(",
"con",
".",
"hinz",
"*",
"con",
".",
"lai",
")"
] | 27.666667 | 0.003883 |
def main():
"""
Entry point
"""
client_1 = MessageBot("verne", "Jules Verne")
client_1.start()
client_1.connect("127.0.0.1")
client_2 = MessageBot("adams", "Douglas Adams")
client_2.start()
client_2.connect("127.0.0.1")
herald_1 = Herald(client_1)
herald_1.start()
hera... | [
"def",
"main",
"(",
")",
":",
"client_1",
"=",
"MessageBot",
"(",
"\"verne\"",
",",
"\"Jules Verne\"",
")",
"client_1",
".",
"start",
"(",
")",
"client_1",
".",
"connect",
"(",
"\"127.0.0.1\"",
")",
"client_2",
"=",
"MessageBot",
"(",
"\"adams\"",
",",
"\"... | 21.322581 | 0.001447 |
def get_patient_pharmacies(self, patient_id,
patients_favorite_only='N'):
"""
invokes TouchWorksMagicConstants.ACTION_GET_ENCOUNTER_LIST_FOR_PATIENT action
:return: JSON response
"""
magic = self._magic_json(
action=TouchWorksMagicConsta... | [
"def",
"get_patient_pharmacies",
"(",
"self",
",",
"patient_id",
",",
"patients_favorite_only",
"=",
"'N'",
")",
":",
"magic",
"=",
"self",
".",
"_magic_json",
"(",
"action",
"=",
"TouchWorksMagicConstants",
".",
"ACTION_GET_PATIENT_PHARAMCIES",
",",
"patient_id",
"... | 43.5 | 0.007032 |
def format_runlog(runlog: List[Mapping[str, Any]]) -> str:
"""
Format a run log (return value of :py:meth:`simulate``) into a
human-readable string
:param runlog: The output of a call to :py:func:`simulate`
"""
to_ret = []
for command in runlog:
to_ret.append(
'\t' * com... | [
"def",
"format_runlog",
"(",
"runlog",
":",
"List",
"[",
"Mapping",
"[",
"str",
",",
"Any",
"]",
"]",
")",
"->",
"str",
":",
"to_ret",
"=",
"[",
"]",
"for",
"command",
"in",
"runlog",
":",
"to_ret",
".",
"append",
"(",
"'\\t'",
"*",
"command",
"[",... | 37.315789 | 0.002751 |
def to_JSON(self):
"""Dumps object fields into a JSON formatted string
:returns: the JSON string
"""
return json.dumps({"reference_time": self._reference_time,
"location": json.loads(self._location.to_JSON()),
"interval": self._int... | [
"def",
"to_JSON",
"(",
"self",
")",
":",
"return",
"json",
".",
"dumps",
"(",
"{",
"\"reference_time\"",
":",
"self",
".",
"_reference_time",
",",
"\"location\"",
":",
"json",
".",
"loads",
"(",
"self",
".",
"_location",
".",
"to_JSON",
"(",
")",
")",
... | 39.25 | 0.004149 |
def tiny_integer(self, column, auto_increment=False, unsigned=False):
"""
Create a new tiny integer column on the table.
:param column: The column
:type column: str
:type auto_increment: bool
:type unsigned: bool
:rtype: Fluent
"""
return self.... | [
"def",
"tiny_integer",
"(",
"self",
",",
"column",
",",
"auto_increment",
"=",
"False",
",",
"unsigned",
"=",
"False",
")",
":",
"return",
"self",
".",
"_add_column",
"(",
"'tiny_integer'",
",",
"column",
",",
"auto_increment",
"=",
"auto_increment",
",",
"u... | 28.375 | 0.004264 |
def _init_context(self, gene_seq):
"""Initializes attributes defining mutation contexts and their position.
The self.context2pos and self.pos2context dictionaries map from
sequence context to sequence position and sequence position to
sequence context, respectively. These attributes all... | [
"def",
"_init_context",
"(",
"self",
",",
"gene_seq",
")",
":",
"self",
".",
"context2pos",
",",
"self",
".",
"pos2context",
"=",
"{",
"}",
",",
"{",
"}",
"gene_len",
"=",
"len",
"(",
"gene_seq",
".",
"exon_seq",
")",
"# get length of CDS",
"five_ss_len",
... | 52.426471 | 0.001927 |
def get_groups_to_remove(self, current_roles, roles_to_remove):
"""get groups to remove from list of
roles to remove and current roles
"""
current_roles = set(current_roles)
ret = {}
roles_to_remove = set(roles_to_remove)
tmp = set([])
# get sub roles of ... | [
"def",
"get_groups_to_remove",
"(",
"self",
",",
"current_roles",
",",
"roles_to_remove",
")",
":",
"current_roles",
"=",
"set",
"(",
"current_roles",
")",
"ret",
"=",
"{",
"}",
"roles_to_remove",
"=",
"set",
"(",
"roles_to_remove",
")",
"tmp",
"=",
"set",
"... | 41.62963 | 0.001739 |
def port_add(self, dpid, port, mac):
"""
:returns: old port if learned. (this may be = port)
None otherwise
"""
old_port = self.mac_to_port[dpid].get(mac, None)
self.mac_to_port[dpid][mac] = port
if old_port is not None and old_port != port:
... | [
"def",
"port_add",
"(",
"self",
",",
"dpid",
",",
"port",
",",
"mac",
")",
":",
"old_port",
"=",
"self",
".",
"mac_to_port",
"[",
"dpid",
"]",
".",
"get",
"(",
"mac",
",",
"None",
")",
"self",
".",
"mac_to_port",
"[",
"dpid",
"]",
"[",
"mac",
"]"... | 32.846154 | 0.004556 |
def macf_period_find(
times,
mags,
errs,
fillgaps=0.0,
filterwindow=11,
forcetimebin=None,
maxlags=None,
maxacfpeaks=10,
smoothacf=21, # set for Kepler-type LCs, see details below
smoothfunc=_smooth_acf_savgol,
smoothfunckwargs=Non... | [
"def",
"macf_period_find",
"(",
"times",
",",
"mags",
",",
"errs",
",",
"fillgaps",
"=",
"0.0",
",",
"filterwindow",
"=",
"11",
",",
"forcetimebin",
"=",
"None",
",",
"maxlags",
"=",
"None",
",",
"maxacfpeaks",
"=",
"10",
",",
"smoothacf",
"=",
"21",
"... | 39.217742 | 0.004011 |
def find_equals_true_or_false(node):
"""Finds equals true or false"""
return (
isinstance(node, ast.Compare)
and len(node.ops) == 1
and isinstance(node.ops[0], ast.Eq)
and any(h.is_boolean(n) for n in node.comparators)
) | [
"def",
"find_equals_true_or_false",
"(",
"node",
")",
":",
"return",
"(",
"isinstance",
"(",
"node",
",",
"ast",
".",
"Compare",
")",
"and",
"len",
"(",
"node",
".",
"ops",
")",
"==",
"1",
"and",
"isinstance",
"(",
"node",
".",
"ops",
"[",
"0",
"]",
... | 32.125 | 0.003788 |
def add_row(self, data: list):
"""
Add a row of buttons each with their own callbacks to the
current widget. Each element in `data` will consist of a
label and a command.
:param data: a list of tuples of the form ('label', <callback>)
:return: None
"""
#... | [
"def",
"add_row",
"(",
"self",
",",
"data",
":",
"list",
")",
":",
"# validation",
"if",
"self",
".",
"headers",
"and",
"data",
":",
"if",
"len",
"(",
"self",
".",
"headers",
")",
"!=",
"len",
"(",
"data",
")",
":",
"raise",
"ValueError",
"offset",
... | 34.0625 | 0.001784 |
def resource(*args, loop=None, **kwargs):
"""
Create a resource service client by name using the default session.
See :py:meth:`aioboto3.session.Session.resource`.
"""
return _get_default_session(loop=loop).resource(*args, **kwargs) | [
"def",
"resource",
"(",
"*",
"args",
",",
"loop",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_get_default_session",
"(",
"loop",
"=",
"loop",
")",
".",
"resource",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 41.166667 | 0.003968 |
def get_lldp_tlv(self, port_name, is_ncb=True, is_nb=False):
"""Function to Query LLDP TLV on the interface. """
reply = None
if is_ncb:
reply = self.run_lldptool(["get-tlv", "-n", "-i", port_name,
"-g", "ncb"])
elif is_nb:
r... | [
"def",
"get_lldp_tlv",
"(",
"self",
",",
"port_name",
",",
"is_ncb",
"=",
"True",
",",
"is_nb",
"=",
"False",
")",
":",
"reply",
"=",
"None",
"if",
"is_ncb",
":",
"reply",
"=",
"self",
".",
"run_lldptool",
"(",
"[",
"\"get-tlv\"",
",",
"\"-n\"",
",",
... | 42.384615 | 0.003552 |
def _overlapOK(self, i, j, overlap=None):
"""
Return True if the given overlap between bucket indices i and j are
acceptable. If overlap is not specified, calculate it from the bucketMap
"""
if overlap is None:
overlap = self._countOverlapIndices(i, j)
if abs(i-j) < self.w:
if overla... | [
"def",
"_overlapOK",
"(",
"self",
",",
"i",
",",
"j",
",",
"overlap",
"=",
"None",
")",
":",
"if",
"overlap",
"is",
"None",
":",
"overlap",
"=",
"self",
".",
"_countOverlapIndices",
"(",
"i",
",",
"j",
")",
"if",
"abs",
"(",
"i",
"-",
"j",
")",
... | 28.411765 | 0.012024 |
def _attributeStrs(self):
"""
Return name=value, semi-colon-separated string for attributes,
including url-style quoting
"""
return ";".join([self._attributeStr(name)
for name in self.attributes.iterkeys()]) | [
"def",
"_attributeStrs",
"(",
"self",
")",
":",
"return",
"\";\"",
".",
"join",
"(",
"[",
"self",
".",
"_attributeStr",
"(",
"name",
")",
"for",
"name",
"in",
"self",
".",
"attributes",
".",
"iterkeys",
"(",
")",
"]",
")"
] | 38 | 0.007353 |
def _normalize_metadata(metadata):
"""Normalize metadata to improve match accuracy."""
metadata = str(metadata)
metadata = metadata.lower()
metadata = re.sub(r'\/\s*\d+', '', metadata) # Remove "/<totaltracks>" from track number.
metadata = re.sub(r'^0+([0-9]+)', r'\1', metadata) # Remove leading zero(s) from ... | [
"def",
"_normalize_metadata",
"(",
"metadata",
")",
":",
"metadata",
"=",
"str",
"(",
"metadata",
")",
"metadata",
"=",
"metadata",
".",
"lower",
"(",
")",
"metadata",
"=",
"re",
".",
"sub",
"(",
"r'\\/\\s*\\d+'",
",",
"''",
",",
"metadata",
")",
"# Remo... | 48.9375 | 0.02005 |
def _intern(
m: lmap.Map, sym: sym.Symbol, new_var: Var, force: bool = False
) -> lmap.Map:
"""Swap function used by intern to atomically intern a new variable in
the symbol mapping for this Namespace."""
var = m.entry(sym, None)
if var is None or force:
return m.... | [
"def",
"_intern",
"(",
"m",
":",
"lmap",
".",
"Map",
",",
"sym",
":",
"sym",
".",
"Symbol",
",",
"new_var",
":",
"Var",
",",
"force",
":",
"bool",
"=",
"False",
")",
"->",
"lmap",
".",
"Map",
":",
"var",
"=",
"m",
".",
"entry",
"(",
"sym",
",... | 38.666667 | 0.008427 |
def get_qubits(self, indices=True):
"""
Returns all of the qubit indices used in this program, including gate applications and
allocated qubits. e.g.
>>> p = Program()
>>> p.inst(("H", 1))
>>> p.get_qubits()
{1}
>>> q = p.alloc()
... | [
"def",
"get_qubits",
"(",
"self",
",",
"indices",
"=",
"True",
")",
":",
"qubits",
"=",
"set",
"(",
")",
"for",
"instr",
"in",
"self",
".",
"instructions",
":",
"if",
"isinstance",
"(",
"instr",
",",
"(",
"Gate",
",",
"Measurement",
")",
")",
":",
... | 32.875 | 0.003695 |
def deprovision(self, instance_id: str, details: DeprovisionDetails,
async_allowed: bool) -> DeprovisionServiceSpec:
"""
Further readings `CF Broker API#Deprovisioning <https://docs.cloudfoundry.org/services/api.html#deprovisioning>`_
:param instance_id: Instance id provided... | [
"def",
"deprovision",
"(",
"self",
",",
"instance_id",
":",
"str",
",",
"details",
":",
"DeprovisionDetails",
",",
"async_allowed",
":",
"bool",
")",
"->",
"DeprovisionServiceSpec",
":",
"raise",
"NotImplementedError",
"(",
")"
] | 51.692308 | 0.005848 |
def _is_valid_templates_dict(policy_templates_dict, schema=None):
"""
Is this a valid policy template dictionary
:param dict policy_templates_dict: Data to be validated
:param dict schema: Optional, dictionary containing JSON Schema representing policy template
:return: True, if... | [
"def",
"_is_valid_templates_dict",
"(",
"policy_templates_dict",
",",
"schema",
"=",
"None",
")",
":",
"if",
"not",
"schema",
":",
"schema",
"=",
"PolicyTemplatesProcessor",
".",
"_read_schema",
"(",
")",
"try",
":",
"jsonschema",
".",
"validate",
"(",
"policy_t... | 37.4 | 0.005215 |
def json(self, data):
"""Set the POST/PUT body content in JSON format for this request."""
if data is not None:
self._body = json.dumps(data)
self.add_header('Content-Type', 'application/json') | [
"def",
"json",
"(",
"self",
",",
"data",
")",
":",
"if",
"data",
"is",
"not",
"None",
":",
"self",
".",
"_body",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
"self",
".",
"add_header",
"(",
"'Content-Type'",
",",
"'application/json'",
")"
] | 45.8 | 0.008584 |
def get_policies_from_aws(client, scope='Local'):
"""Returns a list of all the policies currently applied to an AWS Account. Returns a list containing all the
policies for the specified scope
Args:
client (:obj:`boto3.session.Session`): A boto3 Session object
scope (`str... | [
"def",
"get_policies_from_aws",
"(",
"client",
",",
"scope",
"=",
"'Local'",
")",
":",
"done",
"=",
"False",
"marker",
"=",
"None",
"policies",
"=",
"[",
"]",
"while",
"not",
"done",
":",
"if",
"marker",
":",
"response",
"=",
"client",
".",
"list_policie... | 29.965517 | 0.003344 |
def getStreamNetworkAsGeoJson(self, session, withNodes=True):
"""
Retrieve the stream network geometry in GeoJSON format.
Args:
session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGIS enabled database
withNodes (bool, optional): Includ... | [
"def",
"getStreamNetworkAsGeoJson",
"(",
"self",
",",
"session",
",",
"withNodes",
"=",
"True",
")",
":",
"features_list",
"=",
"[",
"]",
"# Assemble link features",
"for",
"link",
"in",
"self",
".",
"streamLinks",
":",
"link_geoJson",
"=",
"link",
".",
"getAs... | 38.263158 | 0.001341 |
def periodrec_worker(task):
'''This is a parallel worker for running period-recovery.
Parameters
----------
task : tuple
This is used to pass args to the `periodicvar_recovery` function::
task[0] = period-finding result pickle to work on
task[1] = simbasedir
... | [
"def",
"periodrec_worker",
"(",
"task",
")",
":",
"pfpkl",
",",
"simbasedir",
",",
"period_tolerance",
"=",
"task",
"try",
":",
"return",
"periodicvar_recovery",
"(",
"pfpkl",
",",
"simbasedir",
",",
"period_tolerance",
"=",
"period_tolerance",
")",
"except",
"E... | 25.84375 | 0.002331 |
def addif(self, iname):
""" Add an interface to the bridge """
_runshell([brctlexe, 'addif', self.name, iname],
"Could not add interface %s to %s." % (iname, self.name)) | [
"def",
"addif",
"(",
"self",
",",
"iname",
")",
":",
"_runshell",
"(",
"[",
"brctlexe",
",",
"'addif'",
",",
"self",
".",
"name",
",",
"iname",
"]",
",",
"\"Could not add interface %s to %s.\"",
"%",
"(",
"iname",
",",
"self",
".",
"name",
")",
")"
] | 48.5 | 0.015228 |
def funnel(self, steps, timeframe=None, timezone=None, max_age=None, all_keys=False):
""" Performs a Funnel query
Returns an object containing the results for each step of the funnel.
:param steps: array of dictionaries, one for each step. example:
[{"event_collection":"signup","actor_... | [
"def",
"funnel",
"(",
"self",
",",
"steps",
",",
"timeframe",
"=",
"None",
",",
"timezone",
"=",
"None",
",",
"max_age",
"=",
"None",
",",
"all_keys",
"=",
"False",
")",
":",
"params",
"=",
"self",
".",
"get_params",
"(",
"steps",
"=",
"steps",
",",
... | 44.64 | 0.004386 |
def message_create(self, originator, recipients, body, params=None):
"""Create a new message."""
if params is None: params = {}
if type(recipients) == list:
recipients = ','.join(recipients)
params.update({'originator': originator, 'body': body, 'recipients': recipients})
... | [
"def",
"message_create",
"(",
"self",
",",
"originator",
",",
"recipients",
",",
"body",
",",
"params",
"=",
"None",
")",
":",
"if",
"params",
"is",
"None",
":",
"params",
"=",
"{",
"}",
"if",
"type",
"(",
"recipients",
")",
"==",
"list",
":",
"recip... | 47.75 | 0.010283 |
def run(items, background=None):
"""Detect copy number variations from batched set of samples using cn.mops.
"""
if not background: background = []
names = [tz.get_in(["rgnames", "sample"], x) for x in items + background]
work_bams = [x["align_bam"] for x in items + background]
if len(items + ba... | [
"def",
"run",
"(",
"items",
",",
"background",
"=",
"None",
")",
":",
"if",
"not",
"background",
":",
"background",
"=",
"[",
"]",
"names",
"=",
"[",
"tz",
".",
"get_in",
"(",
"[",
"\"rgnames\"",
",",
"\"sample\"",
"]",
",",
"x",
")",
"for",
"x",
... | 51.444444 | 0.00424 |
def route(rule=None, blueprint=None, defaults=None, endpoint=None,
is_member=False, methods=None, only_if=None, **rule_options):
"""
Decorator to set default route rules for a view function. The arguments this
function accepts are very similar to Flask's :meth:`~flask.Flask.route`,
however, th... | [
"def",
"route",
"(",
"rule",
"=",
"None",
",",
"blueprint",
"=",
"None",
",",
"defaults",
"=",
"None",
",",
"endpoint",
"=",
"None",
",",
"is_member",
"=",
"False",
",",
"methods",
"=",
"None",
",",
"only_if",
"=",
"None",
",",
"*",
"*",
"rule_option... | 41.641509 | 0.002213 |
def window(self, vec):
"""Apply a window to the coefficients defined by *vec*. *vec* must
have length *nmax* + 1. This is good way to filter the pattern by
windowing in the coefficient domain.
Example::
>>> vec = numpy.linspace(0, 1, c.nmax + 1)
>>> c.w... | [
"def",
"window",
"(",
"self",
",",
"vec",
")",
":",
"slce",
"=",
"slice",
"(",
"None",
",",
"None",
",",
"None",
")",
"self",
".",
"__setitem__",
"(",
"(",
"slce",
",",
"0",
")",
",",
"self",
".",
"__getitem__",
"(",
"(",
"slce",
",",
"0",
")",... | 34.92 | 0.005574 |
def analyzeOverlaps(activeCoincsFile, encodingsFile, dataset):
'''Mirror Image Visualization: Shows the encoding space juxtaposed against the
coincidence space. The encoding space is the bottom-up sensory encoding and
the coincidence space depicts the corresponding activation of coincidences in
the SP. Hence, t... | [
"def",
"analyzeOverlaps",
"(",
"activeCoincsFile",
",",
"encodingsFile",
",",
"dataset",
")",
":",
"lines",
"=",
"activeCoincsFile",
".",
"readlines",
"(",
")",
"inputs",
"=",
"encodingsFile",
".",
"readlines",
"(",
")",
"w",
"=",
"len",
"(",
"inputs",
"[",
... | 36.454545 | 0.028528 |
def docCopyNode(self, doc, extended):
"""Do a copy of the node to a given document. """
if doc is None: doc__o = None
else: doc__o = doc._o
ret = libxml2mod.xmlDocCopyNode(self._o, doc__o, extended)
if ret is None:raise treeError('xmlDocCopyNode() failed')
__tmp = xmlNode... | [
"def",
"docCopyNode",
"(",
"self",
",",
"doc",
",",
"extended",
")",
":",
"if",
"doc",
"is",
"None",
":",
"doc__o",
"=",
"None",
"else",
":",
"doc__o",
"=",
"doc",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"xmlDocCopyNode",
"(",
"self",
".",
"_o",
... | 43 | 0.017094 |
def deserialize(self, value, **kwargs):
"""Return a deserialized copy of the dict"""
kwargs.update({'trusted': kwargs.get('trusted', False)})
if self.deserializer is not None:
return self.deserializer(value, **kwargs)
if value is None:
return None
output_t... | [
"def",
"deserialize",
"(",
"self",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"update",
"(",
"{",
"'trusted'",
":",
"kwargs",
".",
"get",
"(",
"'trusted'",
",",
"False",
")",
"}",
")",
"if",
"self",
".",
"deserializer",
"is",
"... | 41.1 | 0.002378 |
def format_ascii(sensor_graph):
"""Format this sensor graph as a loadable ascii file format.
This includes commands to reset and clear previously stored
sensor graphs.
NB. This format does not include any required configuration
variables that were specified in this sensor graph, so you
should ... | [
"def",
"format_ascii",
"(",
"sensor_graph",
")",
":",
"cmdfile",
"=",
"CommandFile",
"(",
"\"Sensor Graph\"",
",",
"\"1.0\"",
")",
"# Clear any old sensor graph",
"cmdfile",
".",
"add",
"(",
"\"set_online\"",
",",
"False",
")",
"cmdfile",
".",
"add",
"(",
"\"cle... | 30.659574 | 0.002017 |
def hmsm_to_days(hour=0,min=0,sec=0,micro=0):
"""
Convert hours, minutes, seconds, and microseconds to fractional days.
Parameters
----------
hour : int, optional
Hour number. Defaults to 0.
min : int, optional
Minute number. Defaults to 0.
sec : int, optional
Seco... | [
"def",
"hmsm_to_days",
"(",
"hour",
"=",
"0",
",",
"min",
"=",
"0",
",",
"sec",
"=",
"0",
",",
"micro",
"=",
"0",
")",
":",
"days",
"=",
"sec",
"+",
"(",
"micro",
"/",
"1.e6",
")",
"days",
"=",
"min",
"+",
"(",
"days",
"/",
"60.",
")",
"day... | 17.75 | 0.005935 |
def _filter(msgdata, mailparser, mdfolder, mailfilters):
"""Filter msgdata by mailfilters"""
if mailfilters:
for f in mailfilters:
msg = mailparser.parse(StringIO(msgdata))
rule = f(msg, folder=mdfolder)
if rule:
yield rule
return | [
"def",
"_filter",
"(",
"msgdata",
",",
"mailparser",
",",
"mdfolder",
",",
"mailfilters",
")",
":",
"if",
"mailfilters",
":",
"for",
"f",
"in",
"mailfilters",
":",
"msg",
"=",
"mailparser",
".",
"parse",
"(",
"StringIO",
"(",
"msgdata",
")",
")",
"rule",... | 32.666667 | 0.003311 |
def delete_logstore(self, project_name, logstore_name):
""" delete log store
Unsuccessful opertaion will cause an LogException.
:type project_name: string
:param project_name: the Project name
:type logstore_name: string
:param logstore_name: the logstore name
... | [
"def",
"delete_logstore",
"(",
"self",
",",
"project_name",
",",
"logstore_name",
")",
":",
"headers",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"resource",
"=",
"\"/logstores/\"",
"+",
"logstore_name",
"(",
"resp",
",",
"header",
")",
"=",
"self",
".",
"_... | 33.526316 | 0.007634 |
def list_is_type(ls, t):
'''Assert that a list contains only elements of type t
Return True if list contains elements of type t
Raise TypeError if t is not a class
Raise TypeError if ls is not a list
Raise TypeError if ls contains non-t elements
:param ls: LIST
:param t: python class
'... | [
"def",
"list_is_type",
"(",
"ls",
",",
"t",
")",
":",
"if",
"not",
"isclass",
"(",
"t",
")",
":",
"raise",
"TypeError",
"(",
"\"{} is not a class\"",
".",
"format",
"(",
"t",
")",
")",
"elif",
"not",
"isinstance",
"(",
"ls",
",",
"list",
")",
":",
... | 33.15 | 0.001466 |
def _get_powercfg_minute_values(scheme, guid, subguid, safe_name):
'''
Returns the AC/DC values in an dict for a guid and subguid for a the given
scheme
'''
if scheme is None:
scheme = _get_current_scheme()
if __grains__['osrelease'] == '7':
cmd = 'powercfg /q {0} {1}'.format(sc... | [
"def",
"_get_powercfg_minute_values",
"(",
"scheme",
",",
"guid",
",",
"subguid",
",",
"safe_name",
")",
":",
"if",
"scheme",
"is",
"None",
":",
"scheme",
"=",
"_get_current_scheme",
"(",
")",
"if",
"__grains__",
"[",
"'osrelease'",
"]",
"==",
"'7'",
":",
... | 31.5 | 0.001185 |
def database_clone(targetcall, databasepath, complete=False):
"""
Checks to see if the database has already been downloaded. If not, runs the system call to
download the database, and writes stdout and stderr to the logfile
:param targetcall: system call to download, and possibly set-up ... | [
"def",
"database_clone",
"(",
"targetcall",
",",
"databasepath",
",",
"complete",
"=",
"False",
")",
":",
"# Create a file to store the logs; it will be used to determine if the database was downloaded and set-up",
"completefile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"... | 61.277778 | 0.00625 |
def pip(filename):
"""Parse pip reqs file and transform it to setuptools requirements."""
requirements = []
for line in open(join(ROOT, 'requirements', filename)):
line = line.strip()
if not line or '://' in line:
continue
match = RE_REQUIREMENT.match(line)
if mat... | [
"def",
"pip",
"(",
"filename",
")",
":",
"requirements",
"=",
"[",
"]",
"for",
"line",
"in",
"open",
"(",
"join",
"(",
"ROOT",
",",
"'requirements'",
",",
"filename",
")",
")",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"not",
"line",
... | 34.538462 | 0.002169 |
def fix(args):
"""
%prog fix ahrd.csv > ahrd.fixed.csv
Fix ugly names from Uniprot.
"""
p = OptionParser(fix.__doc__)
p.add_option("--ignore_sym_pat", default=False, action="store_true",
help="Do not fix names matching symbol patterns i.e." + \
" names beginning or ending with g... | [
"def",
"fix",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"fix",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--ignore_sym_pat\"",
",",
"default",
"=",
"False",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Do not fix names m... | 34.942857 | 0.008751 |
def computeDistortion(self, eEye, fU, fV):
"""
Gets the result of the distortion function for the specified eye and input UVs. UVs go from 0,0 in
the upper left of that eye's viewport and 1,1 in the lower right of that eye's viewport.
Returns true for success. Otherwise, returns false, ... | [
"def",
"computeDistortion",
"(",
"self",
",",
"eEye",
",",
"fU",
",",
"fV",
")",
":",
"fn",
"=",
"self",
".",
"function_table",
".",
"computeDistortion",
"pDistortionCoordinates",
"=",
"DistortionCoordinates_t",
"(",
")",
"result",
"=",
"fn",
"(",
"eEye",
",... | 53.454545 | 0.010033 |
def output(self, filename):
"""
Output the inheritance relation
_filename is not used
Args:
_filename(string)
"""
info = 'Inheritance\n'
if not self.contracts:
return
info += blue('Child_Contract -> ') + green('Im... | [
"def",
"output",
"(",
"self",
",",
"filename",
")",
":",
"info",
"=",
"'Inheritance\\n'",
"if",
"not",
"self",
".",
"contracts",
":",
"return",
"info",
"+=",
"blue",
"(",
"'Child_Contract -> '",
")",
"+",
"green",
"(",
"'Immediate_Base_Contracts'",
")",
"inf... | 42.138889 | 0.006443 |
def find_root(self):
"""Finds the index of the root node of the tree."""
self.find_parents()
index = 0
while len(self.vertices[index].parents)>0:
index = self.vertices[index].parents[0]
return index | [
"def",
"find_root",
"(",
"self",
")",
":",
"self",
".",
"find_parents",
"(",
")",
"index",
"=",
"0",
"while",
"len",
"(",
"self",
".",
"vertices",
"[",
"index",
"]",
".",
"parents",
")",
">",
"0",
":",
"index",
"=",
"self",
".",
"vertices",
"[",
... | 34.857143 | 0.012 |
def around_me_in(self, leaderboard_name, member, **options):
'''
Retrieve a page of leaders from the named leaderboard around a given member.
@param leaderboard_name [String] Name of the leaderboard.
@param member [String] Member name.
@param options [Hash] Options to be used wh... | [
"def",
"around_me_in",
"(",
"self",
",",
"leaderboard_name",
",",
"member",
",",
"*",
"*",
"options",
")",
":",
"reverse_rank_for_member",
"=",
"None",
"if",
"self",
".",
"order",
"==",
"self",
".",
"DESC",
":",
"reverse_rank_for_member",
"=",
"self",
".",
... | 38.131579 | 0.003365 |
def export(self, version, export_dir):
"""
Create prov entities and activities.
"""
atts = [
(PROV['type'], self.type),
(PROV['label'], self.label),
]
if version['num'] == "1.0.0":
atts += [
(NIDM_USER_SPECIFIED_THRESH... | [
"def",
"export",
"(",
"self",
",",
"version",
",",
"export_dir",
")",
":",
"atts",
"=",
"[",
"(",
"PROV",
"[",
"'type'",
"]",
",",
"self",
".",
"type",
")",
",",
"(",
"PROV",
"[",
"'label'",
"]",
",",
"self",
".",
"label",
")",
",",
"]",
"if",
... | 31.333333 | 0.002064 |
def local_datetime(utcdatetime, format=None, timezone=None):
"""
Return local datetime based on the timezone
It will automatically format the date.
To not format the date, set format=False
:param utcdatetime: Arrow or string
:param format: string of format or False
:param timezone: str... | [
"def",
"local_datetime",
"(",
"utcdatetime",
",",
"format",
"=",
"None",
",",
"timezone",
"=",
"None",
")",
":",
"if",
"utcdatetime",
"is",
"None",
":",
"return",
"None",
"timezone",
"=",
"timezone",
"or",
"config",
"(",
"\"DATETIME_TIMEZONE\"",
",",
"\"US/E... | 32.166667 | 0.003774 |
def level_order(tree, include_all=False):
""" Returns an iterator over the tree in level-order
If include_all is set to True, empty parts of the tree are filled
with dummy entries and the iterator becomes infinite. """
q = deque()
q.append(tree)
while q:
node = q.popleft()
yiel... | [
"def",
"level_order",
"(",
"tree",
",",
"include_all",
"=",
"False",
")",
":",
"q",
"=",
"deque",
"(",
")",
"q",
".",
"append",
"(",
"tree",
")",
"while",
"q",
":",
"node",
"=",
"q",
".",
"popleft",
"(",
")",
"yield",
"node",
"if",
"include_all",
... | 28.941176 | 0.001969 |
def releaseCompleteNetToMs(Cause_presence=0, Facility_presence=0,
UserUser_presence=0):
"""RELEASE COMPLETE Section 9.3.19.1"""
a = TpPd(pd=0x3)
b = MessageType(mesType=0x2a) # 00101010
packet = a / b
if Cause_presence is 1:
c = CauseHdr(ieiC=0x08, eightBitC=0x0)
... | [
"def",
"releaseCompleteNetToMs",
"(",
"Cause_presence",
"=",
"0",
",",
"Facility_presence",
"=",
"0",
",",
"UserUser_presence",
"=",
"0",
")",
":",
"a",
"=",
"TpPd",
"(",
"pd",
"=",
"0x3",
")",
"b",
"=",
"MessageType",
"(",
"mesType",
"=",
"0x2a",
")",
... | 35.625 | 0.001709 |
def get_logical_plan(cluster, environ, topology, role=None):
'''
Get the logical plan state of a topology in a cluster
:param cluster:
:param environ:
:param topology:
:param role:
:return:
'''
params = dict(cluster=cluster, environ=environ, topology=topology)
if role is not None:
params['role']... | [
"def",
"get_logical_plan",
"(",
"cluster",
",",
"environ",
",",
"topology",
",",
"role",
"=",
"None",
")",
":",
"params",
"=",
"dict",
"(",
"cluster",
"=",
"cluster",
",",
"environ",
"=",
"environ",
",",
"topology",
"=",
"topology",
")",
"if",
"role",
... | 31.466667 | 0.012346 |
def render_to_texture(self, data, texture, offset, size):
"""Render a SDF to a texture at a given offset and size
Parameters
----------
data : array
Must be 2D with type np.ubyte.
texture : instance of Texture2D
The texture to render to.
offset : ... | [
"def",
"render_to_texture",
"(",
"self",
",",
"data",
",",
"texture",
",",
"offset",
",",
"size",
")",
":",
"assert",
"isinstance",
"(",
"texture",
",",
"Texture2D",
")",
"set_state",
"(",
"blend",
"=",
"False",
",",
"depth_test",
"=",
"False",
")",
"# c... | 38.314286 | 0.002909 |
def linkify_h_by_hd(self, hosts):
"""Add dependency in host objects
:param hosts: hosts list
:type hosts: alignak.objects.host.Hosts
:return: None
"""
for hostdep in self:
# Only used for debugging purpose when loops are detected
setattr(hostdep, ... | [
"def",
"linkify_h_by_hd",
"(",
"self",
",",
"hosts",
")",
":",
"for",
"hostdep",
"in",
"self",
":",
"# Only used for debugging purpose when loops are detected",
"setattr",
"(",
"hostdep",
",",
"\"host_name_string\"",
",",
"\"undefined\"",
")",
"setattr",
"(",
"hostdep... | 47.558824 | 0.003636 |
def open_streaming_interface(self):
"""Called when someone opens a streaming interface to the device.
This method will automatically notify sensor_graph that there is a
streaming interface opened.
Returns:
list: A list of IOTileReport objects that should be sent out
... | [
"def",
"open_streaming_interface",
"(",
"self",
")",
":",
"super",
"(",
"ReferenceDevice",
",",
"self",
")",
".",
"open_streaming_interface",
"(",
")",
"self",
".",
"rpc",
"(",
"8",
",",
"rpcs",
".",
"SG_GRAPH_INPUT",
",",
"8",
",",
"streams",
".",
"COMM_T... | 33.533333 | 0.003868 |
def create_message(self):
"""Returns a message body to send in this email. Should be from email.mime.*"""
body = dedent("""\
Received exception {exception} on {queue} from worker {worker}:
{traceback}
Payload:
{payload}
""").format(exception=self._exception,
... | [
"def",
"create_message",
"(",
"self",
")",
":",
"body",
"=",
"dedent",
"(",
"\"\"\"\\\n Received exception {exception} on {queue} from worker {worker}:\n\n {traceback}\n\n Payload:\n {payload}\n\n \"\"\"",
")",
".",
"format",
"(",
"exception",
"=",
... | 27.666667 | 0.013592 |
def _from_specs(self, dims, spacing=(1.0,1.0,1.0), origin=(0.0, 0.0, 0.0)):
"""
Create VTK image data directly from numpy arrays. A uniform grid is
defined by the node spacings for each axis (uniform along each
individual axis) and the number of nodes on each axis. These are
rela... | [
"def",
"_from_specs",
"(",
"self",
",",
"dims",
",",
"spacing",
"=",
"(",
"1.0",
",",
"1.0",
",",
"1.0",
")",
",",
"origin",
"=",
"(",
"0.0",
",",
"0.0",
",",
"0.0",
")",
")",
":",
"xn",
",",
"yn",
",",
"zn",
"=",
"dims",
"[",
"0",
"]",
","... | 41.916667 | 0.005831 |
def policy_evaluation(pi, U, mdp, k=20):
"""Return an updated utility mapping U from each state in the MDP to its
utility, using an approximation (modified policy iteration)."""
R, T, gamma = mdp.R, mdp.T, mdp.gamma
for i in range(k):
for s in mdp.states:
U[s] = R(s) + gamma * sum([p... | [
"def",
"policy_evaluation",
"(",
"pi",
",",
"U",
",",
"mdp",
",",
"k",
"=",
"20",
")",
":",
"R",
",",
"T",
",",
"gamma",
"=",
"mdp",
".",
"R",
",",
"mdp",
".",
"T",
",",
"mdp",
".",
"gamma",
"for",
"i",
"in",
"range",
"(",
"k",
")",
":",
... | 45.375 | 0.002703 |
def encode(self, inputRow):
"""Encodes the given input row as a dict, with the
keys being the field names. This also adds in some meta fields:
'_category': The value from the category field (if any)
'_reset': True if the reset field was True (if any)
'_sequenceId': the value from the sequenceI... | [
"def",
"encode",
"(",
"self",
",",
"inputRow",
")",
":",
"# Create the return dict",
"result",
"=",
"dict",
"(",
"zip",
"(",
"self",
".",
"_fieldNames",
",",
"inputRow",
")",
")",
"# Add in the special fields",
"if",
"self",
".",
"_categoryFieldIndex",
"is",
"... | 34.070423 | 0.008839 |
def tangent_bundle(self):
"""The tangent bundle associated with `domain` using `partition`.
The tangent bundle of a space ``X`` of functions ``R^d --> F`` can be
interpreted as the space of vector-valued functions ``R^d --> F^d``.
This space can be identified with the power space ``X^d`... | [
"def",
"tangent_bundle",
"(",
"self",
")",
":",
"if",
"self",
".",
"ndim",
"==",
"0",
":",
"return",
"ProductSpace",
"(",
"field",
"=",
"self",
".",
"field",
")",
"else",
":",
"return",
"ProductSpace",
"(",
"self",
",",
"self",
".",
"ndim",
")"
] | 41.833333 | 0.003899 |
def create(self, validated_data):
""" This is a standard method called indirectly by calling
'save' on the serializer.
This method expects the 'parent_field' and 'parent_instance' to
be included in the Serializer context.
"""
if self.context.get('parent_field') \
... | [
"def",
"create",
"(",
"self",
",",
"validated_data",
")",
":",
"if",
"self",
".",
"context",
".",
"get",
"(",
"'parent_field'",
")",
"and",
"self",
".",
"context",
".",
"get",
"(",
"'parent_instance'",
")",
":",
"validated_data",
".",
"update",
"(",
"{",... | 38.8125 | 0.004717 |
def GetServiceDll(self, key):
"""Get the Service DLL for a service, if it exists.
Checks for a ServiceDLL for in the Parameters subkey of a service key in
the Registry.
Args:
key (dfwinreg.WinRegistryKey): a Windows Registry key.
Returns:
str: path of the service DLL or None.
"""
... | [
"def",
"GetServiceDll",
"(",
"self",
",",
"key",
")",
":",
"parameters_key",
"=",
"key",
".",
"GetSubkeyByName",
"(",
"'Parameters'",
")",
"if",
"not",
"parameters_key",
":",
"return",
"None",
"service_dll",
"=",
"parameters_key",
".",
"GetValueByName",
"(",
"... | 26 | 0.0053 |
def auto_zip_open(filepath, mode):
"""Convenience function for opening potentially-compressed files."""
if filepath.endswith('.gz'):
outfile = gzip.open(filepath, mode)
elif filepath.endswith('.bz2'):
outfile = bz2.BZ2File(filepath, mode)
else:
outfile = open(filepath, mode)
... | [
"def",
"auto_zip_open",
"(",
"filepath",
",",
"mode",
")",
":",
"if",
"filepath",
".",
"endswith",
"(",
"'.gz'",
")",
":",
"outfile",
"=",
"gzip",
".",
"open",
"(",
"filepath",
",",
"mode",
")",
"elif",
"filepath",
".",
"endswith",
"(",
"'.bz2'",
")",
... | 36.222222 | 0.002994 |
def change_note_duration(self, at, to):
"""Change the note duration at the given index to the given
duration."""
if valid_beat_duration(to):
diff = 0
for x in self.bar:
if diff != 0:
x[0][0] -= diff
if x[0] == at:
... | [
"def",
"change_note_duration",
"(",
"self",
",",
"at",
",",
"to",
")",
":",
"if",
"valid_beat_duration",
"(",
"to",
")",
":",
"diff",
"=",
"0",
"for",
"x",
"in",
"self",
".",
"bar",
":",
"if",
"diff",
"!=",
"0",
":",
"x",
"[",
"0",
"]",
"[",
"0... | 34.416667 | 0.004717 |
def user_absent(name, htpasswd_file=None, runas=None):
'''
Make sure the user is not in the specified htpasswd file
name
User name
htpasswd_file
Path to the htpasswd file
runas
The system user to run htpasswd command with
'''
ret = {'name': name,
'chang... | [
"def",
"user_absent",
"(",
"name",
",",
"htpasswd_file",
"=",
"None",
",",
"runas",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'comment'",
":",
"''",
",",
"'result'",
":",
"None",
"}",
"exi... | 26.5 | 0.001654 |
def parse_simple_duration(duration):
"""
Attepmt to parse an ISO8601 formatted duration, using a naive calculation.
Accepts a ``duration`` which must be an ISO8601 formatted string, and
assumes 365 days in a year and 30 days in a month for the calculation.
Returns a ``datetime.timedelta`` object.
... | [
"def",
"parse_simple_duration",
"(",
"duration",
")",
":",
"elements",
"=",
"_parse_duration_string",
"(",
"_clean",
"(",
"duration",
")",
")",
"if",
"not",
"elements",
":",
"raise",
"ParseError",
"(",
")",
"return",
"_timedelta_from_elements",
"(",
"elements",
... | 31 | 0.002088 |
def construct_rest_of_worlds_mapping(self, excluded, fp=None):
"""Construct topo mapping file for ``excluded``.
``excluded`` must be a **dictionary** of {"rest-of-world label": ["names", "of", "excluded", "locations"]}``.
Topo mapping has the data format:
.. code-block:: python
... | [
"def",
"construct_rest_of_worlds_mapping",
"(",
"self",
",",
"excluded",
",",
"fp",
"=",
"None",
")",
":",
"metadata",
"=",
"{",
"'filename'",
":",
"'faces.gpkg'",
",",
"'field'",
":",
"'id'",
",",
"'sha256'",
":",
"sha256",
"(",
"self",
".",
"faces_fp",
"... | 34.95 | 0.003479 |
def has_aligned_reads(align_bam, region=None):
"""Check if the aligned BAM file has any reads in the region.
region can be a chromosome string ("chr22"),
a tuple region (("chr22", 1, 100)) or a file of regions.
"""
import pybedtools
if region is not None:
if isinstance(region, six.strin... | [
"def",
"has_aligned_reads",
"(",
"align_bam",
",",
"region",
"=",
"None",
")",
":",
"import",
"pybedtools",
"if",
"region",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"region",
",",
"six",
".",
"string_types",
")",
"and",
"os",
".",
"path",
".",
... | 38.692308 | 0.00194 |
def map_volume_to_sdc(self, volumeObj, sdcObj=None, allowMultipleMappings=False, **kwargs):
"""
Map a Volume to SDC
:param volumeObj: ScaleIO Volume object
:param sdcObj: ScaleIO SDC object
:param allowMultipleMappings: True to allow more than one SDC to be mapped to volume
... | [
"def",
"map_volume_to_sdc",
"(",
"self",
",",
"volumeObj",
",",
"sdcObj",
"=",
"None",
",",
"allowMultipleMappings",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"conn",
".",
"connection",
".",
"_check_login",
"(",
")",
"if",
"kwargs",
"... | 51.421053 | 0.007035 |
def invoke(self, args, kwargs):
"""
Send the required soap message to invoke the specified method
@param args: A list of args for the method invoked.
@type args: list
@param kwargs: Named (keyword) args for the method invoked.
@type kwargs: dict
@return: The resul... | [
"def",
"invoke",
"(",
"self",
",",
"args",
",",
"kwargs",
")",
":",
"simulation",
"=",
"kwargs",
"[",
"self",
".",
"injkey",
"]",
"msg",
"=",
"simulation",
".",
"get",
"(",
"'msg'",
")",
"reply",
"=",
"simulation",
".",
"get",
"(",
"'reply'",
")",
... | 39.043478 | 0.002174 |
def saveTargetsToFile(self, filename):
"""
Deprecated.
"""
fp = open(filename, 'w')
for target in self.targets:
vec = self.replacePatterns(target)
for item in vec:
fp.write("%f " % item)
fp.write("\n") | [
"def",
"saveTargetsToFile",
"(",
"self",
",",
"filename",
")",
":",
"fp",
"=",
"open",
"(",
"filename",
",",
"'w'",
")",
"for",
"target",
"in",
"self",
".",
"targets",
":",
"vec",
"=",
"self",
".",
"replacePatterns",
"(",
"target",
")",
"for",
"item",
... | 28.4 | 0.006826 |
def finder(self, figsize=(7,7), **kwargs):
'''
Plot a finder chart. This *does* create a new figure.
'''
try:
center = self.meta['center']
radius = self.meta['radius']
except KeyError:
return self.allskyfinder(**kwargs)
plt.figure(fig... | [
"def",
"finder",
"(",
"self",
",",
"figsize",
"=",
"(",
"7",
",",
"7",
")",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"center",
"=",
"self",
".",
"meta",
"[",
"'center'",
"]",
"radius",
"=",
"self",
".",
"meta",
"[",
"'radius'",
"]",
"exce... | 35.318182 | 0.008772 |
def time_to_number(self, time):
"""
Converts a time instance to a corresponding float value.
"""
if not isinstance(time, datetime.time):
raise TypeError(time)
return ((time.second / 60.0 + time.minute) / 60.0 + time.hour) / 24.0 | [
"def",
"time_to_number",
"(",
"self",
",",
"time",
")",
":",
"if",
"not",
"isinstance",
"(",
"time",
",",
"datetime",
".",
"time",
")",
":",
"raise",
"TypeError",
"(",
"time",
")",
"return",
"(",
"(",
"time",
".",
"second",
"/",
"60.0",
"+",
"time",
... | 39.142857 | 0.007143 |
def TP2(dv, u, jac=False):
'''Demo problem 2 for horsetail matching, takes two input vectors of size 2
and returns just the qoi if jac is False or the qoi and its gradient if jac
is True'''
y = dv[0]/2.
z = dv[1]/2. + 12
q = 0.25*((y**2 + z**2)/10 + 5*u[0]*u[1] - z*u[1]**2) + 0.2*z*u[1]**3 + 7
... | [
"def",
"TP2",
"(",
"dv",
",",
"u",
",",
"jac",
"=",
"False",
")",
":",
"y",
"=",
"dv",
"[",
"0",
"]",
"/",
"2.",
"z",
"=",
"dv",
"[",
"1",
"]",
"/",
"2.",
"+",
"12",
"q",
"=",
"0.25",
"*",
"(",
"(",
"y",
"**",
"2",
"+",
"z",
"**",
"... | 31.8 | 0.008147 |
def _process_command(self, command, name=None):
"""Process ``make_ndx`` command and return name and temp index file."""
self._command_counter += 1
if name is None:
name = "CMD{0:03d}".format(self._command_counter)
# Need to build it with two make_ndx calls because I cannot... | [
"def",
"_process_command",
"(",
"self",
",",
"command",
",",
"name",
"=",
"None",
")",
":",
"self",
".",
"_command_counter",
"+=",
"1",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"\"CMD{0:03d}\"",
".",
"format",
"(",
"self",
".",
"_command_counter",
"... | 49.2 | 0.009302 |
def issuer(self, value):
"""
An asn1crypto.x509.Certificate object of the issuer. Used to populate
both the issuer field, but also the authority key identifier extension.
"""
is_oscrypto = isinstance(value, asymmetric.Certificate)
if not isinstance(value, x509.Certificat... | [
"def",
"issuer",
"(",
"self",
",",
"value",
")",
":",
"is_oscrypto",
"=",
"isinstance",
"(",
"value",
",",
"asymmetric",
".",
"Certificate",
")",
"if",
"not",
"isinstance",
"(",
"value",
",",
"x509",
".",
"Certificate",
")",
"and",
"not",
"is_oscrypto",
... | 35.08 | 0.00222 |
def empy_hankel(ftype, zsrc, zrec, res, freqtime, depth=None, aniso=None,
epermH=None, epermV=None, mpermH=None, mpermV=None,
htarg=None, verblhs=0, verbrhs=0):
r"""Numerical transform pair with empymod.
All parameters except ``ftype``, ``verblhs``, and ``verbrhs`` correspond to... | [
"def",
"empy_hankel",
"(",
"ftype",
",",
"zsrc",
",",
"zrec",
",",
"res",
",",
"freqtime",
",",
"depth",
"=",
"None",
",",
"aniso",
"=",
"None",
",",
"epermH",
"=",
"None",
",",
"epermV",
"=",
"None",
",",
"mpermH",
"=",
"None",
",",
"mpermV",
"=",... | 32 | 0.000361 |
def _handle_bugged_tarfile(self, destination, skip_top_level):
"""
Handle tar file that tarfile library mistakenly reports as invalid.
Happens with tar files created on FAT systems. See:
http://stackoverflow.com/questions/25552162/tarfile-readerror-file-could-not-be-opened-successfully
... | [
"def",
"_handle_bugged_tarfile",
"(",
"self",
",",
"destination",
",",
"skip_top_level",
")",
":",
"args",
"=",
"[",
"'tar'",
",",
"'-xzf'",
",",
"self",
".",
"destination",
",",
"'-C'",
",",
"destination",
"]",
"if",
"skip_top_level",
":",
"args",
".",
"e... | 50.6 | 0.003883 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.