text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def get_languages(self):
"""
:calls: `GET /repos/:owner/:repo/languages <http://developer.github.com/v3/repos>`_
:rtype: dict of string to integer
"""
headers, data = self._requester.requestJsonAndCheck(
"GET",
self.url + "/languages"
)
ret... | [
"def",
"get_languages",
"(",
"self",
")",
":",
"headers",
",",
"data",
"=",
"self",
".",
"_requester",
".",
"requestJsonAndCheck",
"(",
"\"GET\"",
",",
"self",
".",
"url",
"+",
"\"/languages\"",
")",
"return",
"data"
] | 31.9 | 0.009146 |
def time_multi_coincidence(times, slide_step=0, slop=.003,
pivot='H1', fixed='L1'):
""" Find multi detector concidences.
Parameters
----------
times: dict of numpy.ndarrays
Dictionary keyed by ifo of the times of each single detector trigger.
slide_step: float
... | [
"def",
"time_multi_coincidence",
"(",
"times",
",",
"slide_step",
"=",
"0",
",",
"slop",
"=",
".003",
",",
"pivot",
"=",
"'H1'",
",",
"fixed",
"=",
"'L1'",
")",
":",
"# pivots are used to determine standard coincidence triggers, we then",
"# pair off additional detector... | 41.885057 | 0.001609 |
def troutslap(rest):
"Slap some(one|thing) with a fish"
slapee = rest
karma.Karma.store.change(slapee, -1)
return "/me slaps %s around a bit with a large trout" % slapee | [
"def",
"troutslap",
"(",
"rest",
")",
":",
"slapee",
"=",
"rest",
"karma",
".",
"Karma",
".",
"store",
".",
"change",
"(",
"slapee",
",",
"-",
"1",
")",
"return",
"\"/me slaps %s around a bit with a large trout\"",
"%",
"slapee"
] | 33.8 | 0.028902 |
def _GceMetadataRequest(relative_url, use_metadata_ip=False):
"""Request the given url from the GCE metadata service."""
if use_metadata_ip:
base_url = os.environ.get('GCE_METADATA_IP', '169.254.169.254')
else:
base_url = os.environ.get(
'GCE_METADATA_ROOT', 'metadata.google.inte... | [
"def",
"_GceMetadataRequest",
"(",
"relative_url",
",",
"use_metadata_ip",
"=",
"False",
")",
":",
"if",
"use_metadata_ip",
":",
"base_url",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'GCE_METADATA_IP'",
",",
"'169.254.169.254'",
")",
"else",
":",
"base_url",
... | 46.315789 | 0.001114 |
def _try_reduce(self) -> Tuple[List["HdlStatement"], bool]:
"""
Doc on parent class :meth:`HdlStatement._try_reduce`
"""
io_change = False
new_cases = []
for val, statements in self.cases:
_statements, rank_decrease, _io_change = self._try_reduce_list(
... | [
"def",
"_try_reduce",
"(",
"self",
")",
"->",
"Tuple",
"[",
"List",
"[",
"\"HdlStatement\"",
"]",
",",
"bool",
"]",
":",
"io_change",
"=",
"False",
"new_cases",
"=",
"[",
"]",
"for",
"val",
",",
"statements",
"in",
"self",
".",
"cases",
":",
"_statemen... | 33.891304 | 0.001247 |
def ls_handler(self, args):
'''Handler for ls command'''
if len(args) == 1:
self.pretty_print(self.s3handler().list_buckets())
return
self.validate('cmd|s3', args)
self.pretty_print(self.s3handler().s3walk(args[1])) | [
"def",
"ls_handler",
"(",
"self",
",",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"1",
":",
"self",
".",
"pretty_print",
"(",
"self",
".",
"s3handler",
"(",
")",
".",
"list_buckets",
"(",
")",
")",
"return",
"self",
".",
"validate",
"("... | 29.625 | 0.012295 |
def import_plugin(name):
"""Imports plugin python module"""
path = os.path.join("plugins", name + ".py")
try:
with open(path, 'rb') as f:
try:
plugin = imp.load_module(
"p_" + name, f, name + '.py',
('.py', 'rb', imp.PY_SOURCE)
... | [
"def",
"import_plugin",
"(",
"name",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"\"plugins\"",
",",
"name",
"+",
"\".py\"",
")",
"try",
":",
"with",
"open",
"(",
"path",
",",
"'rb'",
")",
"as",
"f",
":",
"try",
":",
"plugin",
"="... | 36.833333 | 0.001471 |
def create_parser(parser: argparse.ArgumentParser) -> None:
"""
Creates the parser by setting all the possible arguments
:param parser: The parser
"""
parser.add_argument("solidity_file", nargs="*")
commands = parser.add_argument_group("commands")
commands.add_argument("-g", "--graph", help... | [
"def",
"create_parser",
"(",
"parser",
":",
"argparse",
".",
"ArgumentParser",
")",
"->",
"None",
":",
"parser",
".",
"add_argument",
"(",
"\"solidity_file\"",
",",
"nargs",
"=",
"\"*\"",
")",
"commands",
"=",
"parser",
".",
"add_argument_group",
"(",
"\"comma... | 30.343915 | 0.00152 |
def UpdateFlows(self,
client_id_flow_id_pairs,
pending_termination=db.Database.unchanged,
cursor=None):
"""Updates flow objects in the database."""
if pending_termination == db.Database.unchanged:
return
serialized_termination = pending_terminati... | [
"def",
"UpdateFlows",
"(",
"self",
",",
"client_id_flow_id_pairs",
",",
"pending_termination",
"=",
"db",
".",
"Database",
".",
"unchanged",
",",
"cursor",
"=",
"None",
")",
":",
"if",
"pending_termination",
"==",
"db",
".",
"Database",
".",
"unchanged",
":",
... | 39.777778 | 0.00955 |
def _do_unjoin_packet(self, packet, ip, port):
"""
React to unjoin packet - remove a client from this server
:param packet: Packet from client that wants to join
:type packet: paps.si.app.message.APPJoinMessage
:param ip: Client ip address
:type ip: unicode
:para... | [
"def",
"_do_unjoin_packet",
"(",
"self",
",",
"packet",
",",
"ip",
",",
"port",
")",
":",
"self",
".",
"debug",
"(",
"\"()\"",
")",
"device_id",
"=",
"packet",
".",
"header",
".",
"device_id",
"if",
"device_id",
"<=",
"Id",
".",
"SERVER",
":",
"self",
... | 30.380952 | 0.002278 |
def get_cuda_visible_devices():
"""Get the device IDs in the CUDA_VISIBLE_DEVICES environment variable.
Returns:
if CUDA_VISIBLE_DEVICES is set, this returns a list of integers with
the IDs of the GPUs. If it is not set, this returns None.
"""
gpu_ids_str = os.environ.get("CUDA_VISI... | [
"def",
"get_cuda_visible_devices",
"(",
")",
":",
"gpu_ids_str",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"\"CUDA_VISIBLE_DEVICES\"",
",",
"None",
")",
"if",
"gpu_ids_str",
"is",
"None",
":",
"return",
"None",
"if",
"gpu_ids_str",
"==",
"\"\"",
":",
"retu... | 29.4375 | 0.002058 |
def ToHashArray(self):
"""
Turn the tree into a list of hashes.
Returns:
list:
"""
hashes = set()
MerkleTree.__DepthFirstSearch(self.Root, hashes)
return list(hashes) | [
"def",
"ToHashArray",
"(",
"self",
")",
":",
"hashes",
"=",
"set",
"(",
")",
"MerkleTree",
".",
"__DepthFirstSearch",
"(",
"self",
".",
"Root",
",",
"hashes",
")",
"return",
"list",
"(",
"hashes",
")"
] | 22.6 | 0.008511 |
def drop_database(self, name_or_database, session=None):
"""Drop a database.
Raises :class:`TypeError` if `name_or_database` is not an instance of
:class:`basestring` (:class:`str` in python 3) or
:class:`~pymongo.database.Database`.
:Parameters:
- `name_or_database`:... | [
"def",
"drop_database",
"(",
"self",
",",
"name_or_database",
",",
"session",
"=",
"None",
")",
":",
"name",
"=",
"name_or_database",
"if",
"isinstance",
"(",
"name",
",",
"database",
".",
"Database",
")",
":",
"name",
"=",
"name",
".",
"name",
"if",
"no... | 37.860465 | 0.001796 |
def parse_value_namedinstance(self, tup_tree):
"""
::
<!ELEMENT VALUE.NAMEDINSTANCE (INSTANCENAME, INSTANCE)>
Returns:
CIMInstance object with path set (without host or namespace).
"""
self.check_node(tup_tree, 'VALUE.NAMEDINSTANCE')
k = kids... | [
"def",
"parse_value_namedinstance",
"(",
"self",
",",
"tup_tree",
")",
":",
"self",
".",
"check_node",
"(",
"tup_tree",
",",
"'VALUE.NAMEDINSTANCE'",
")",
"k",
"=",
"kids",
"(",
"tup_tree",
")",
"if",
"len",
"(",
"k",
")",
"!=",
"2",
":",
"raise",
"CIMXM... | 30.615385 | 0.002436 |
def _make_f_expectation(self, expr):
"""
Calculates :math:`<F>` in eq. 12 (see Ale et al. 2013) to calculate :math:`<F>` for EACH VARIABLE combination.
:param expr: an expression
:return: a column vector. Each row correspond to an element of counter.
:rtype: :class:`sympy.Matrix... | [
"def",
"_make_f_expectation",
"(",
"self",
",",
"expr",
")",
":",
"# compute derivatives for EACH ENTRY in COUNTER",
"derives",
"=",
"sp",
".",
"Matrix",
"(",
"[",
"derive_expr_from_counter_entry",
"(",
"expr",
",",
"self",
".",
"__species",
",",
"tuple",
"(",
"c"... | 38.454545 | 0.008074 |
def send_dynamic_message(sender, message):
"""Send a dynamic message to the listeners.
Dynamic messages represents a progress. Usually it will be appended to
the previous messages.
.. versionadded:: 3.3
:param sender: The sender.
:type sender: object
:param message: An instance of our ri... | [
"def",
"send_dynamic_message",
"(",
"sender",
",",
"message",
")",
":",
"dispatcher",
".",
"send",
"(",
"signal",
"=",
"DYNAMIC_MESSAGE_SIGNAL",
",",
"sender",
"=",
"sender",
",",
"message",
"=",
"message",
")"
] | 25.157895 | 0.002016 |
def _get_column_boundaries(self):
'''Use the guessed ends to guess the boundaries of the plain
text columns.
'''
# Try to figure out the most common column boundaries.
ends = self._get_column_ends()
if not ends:
# If there aren't even any nontrivial sequences ... | [
"def",
"_get_column_boundaries",
"(",
"self",
")",
":",
"# Try to figure out the most common column boundaries.",
"ends",
"=",
"self",
".",
"_get_column_ends",
"(",
")",
"if",
"not",
"ends",
":",
"# If there aren't even any nontrivial sequences of whitespace",
"# dividing text,... | 39.473684 | 0.001301 |
def execute_and_reset(
expr, params=None, scope=None, aggcontext=None, **kwargs
):
"""Execute an expression against data that are bound to it. If no data
are bound, raise an Exception.
Notes
-----
The difference between this function and :func:`~ibis.pandas.core.execute`
is that this functi... | [
"def",
"execute_and_reset",
"(",
"expr",
",",
"params",
"=",
"None",
",",
"scope",
"=",
"None",
",",
"aggcontext",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"execute",
"(",
"expr",
",",
"params",
"=",
"params",
",",
"scope",
"=",... | 32.44898 | 0.000611 |
def is_empty(self):
"""
Test interval emptiness.
:return: True if interval is empty, False otherwise.
"""
return (
self._lower > self._upper or
(self._lower == self._upper and (self._left == OPEN or self._right == OPEN))
) | [
"def",
"is_empty",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"_lower",
">",
"self",
".",
"_upper",
"or",
"(",
"self",
".",
"_lower",
"==",
"self",
".",
"_upper",
"and",
"(",
"self",
".",
"_left",
"==",
"OPEN",
"or",
"self",
".",
"_right",
... | 28.6 | 0.010169 |
def booleanized(values, min_value, max_value, hysteresis=0):
"""
Returns True for each item in *values* between *min_value* and
*max_value*, and False otherwise. *hysteresis* can optionally be used to
add `hysteresis`_ which prevents the output value rapidly flipping when
the input value is fluctuat... | [
"def",
"booleanized",
"(",
"values",
",",
"min_value",
",",
"max_value",
",",
"hysteresis",
"=",
"0",
")",
":",
"values",
"=",
"_normalize",
"(",
"values",
")",
"if",
"min_value",
">=",
"max_value",
":",
"raise",
"ValueError",
"(",
"'min_value must be smaller ... | 36.885246 | 0.001732 |
def pick_free_port(hostname=REDIRECT_HOST, port=0):
""" Try to bind a port. Default=0 selects a free port. """
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind((hostname, port)) # port=0 finds an open port
except OSError as e:
log.warning("Could not bi... | [
"def",
"pick_free_port",
"(",
"hostname",
"=",
"REDIRECT_HOST",
",",
"port",
"=",
"0",
")",
":",
"import",
"socket",
"s",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"try",
":",
"s",
".",
"bind",... | 37.5 | 0.001626 |
def __update_upgrades_table(self, delta):
"""Add a new record into the upgrades information table about the
applied delta
Parameters
----------
delta: Delta
the applied delta file"""
query = """
INSERT INTO {} (
--id,
version,... | [
"def",
"__update_upgrades_table",
"(",
"self",
",",
"delta",
")",
":",
"query",
"=",
"\"\"\"\n INSERT INTO {} (\n --id,\n version,\n description,\n type,\n script,\n checksum,\n installed_by,\n --insta... | 24.135135 | 0.002153 |
def cached(self, TTL=60 * 24):
'''A decorator that will cache the output of the wrapped function. The
key used for the cache is the function name as well as the `*args` and
`**kwargs` passed to the function.
:param TTL: time to live in minutes
.. note:: For route caching, you s... | [
"def",
"cached",
"(",
"self",
",",
"TTL",
"=",
"60",
"*",
"24",
")",
":",
"def",
"decorating_function",
"(",
"function",
")",
":",
"# TODO test this method",
"storage",
"=",
"self",
".",
"get_storage",
"(",
"self",
".",
"_function_cache_name",
",",
"file_for... | 42.378378 | 0.00187 |
def _find_supported_challenge(authzr, responders):
"""
Find a challenge combination that consists of a single challenge that the
responder can satisfy.
:param ~acme.messages.AuthorizationResource auth: The authorization to
examine.
:type responder: List[`~txacme.interfaces.IResponder`]
... | [
"def",
"_find_supported_challenge",
"(",
"authzr",
",",
"responders",
")",
":",
"matches",
"=",
"[",
"(",
"responder",
",",
"challbs",
"[",
"0",
"]",
")",
"for",
"challbs",
"in",
"authzr",
".",
"body",
".",
"resolved_combinations",
"for",
"responder",
"in",
... | 34.296296 | 0.00105 |
def argv(*args, **opts):
"""
Produces an argument vector from its array of arguments and keyword
options. First, the options are unpacked. When the value is a ``bool``,
the option is passed without an argument if it is true and skipped if it
is ``false``. When the option is one of the flat built-in ... | [
"def",
"argv",
"(",
"*",
"args",
",",
"*",
"*",
"opts",
")",
":",
"spacer",
"=",
"[",
"\"--\"",
"]",
"if",
"opts",
".",
"get",
"(",
"\"__\"",
")",
"else",
"[",
"]",
"args",
"=",
"[",
"arg",
"(",
"_",
")",
"for",
"_",
"in",
"args",
"]",
"opt... | 55.153846 | 0.000685 |
def _get_template_dirs():
"""existing directories where to search for jinja2 templates. The order
is important. The first found template from the first found dir wins!"""
return filter(lambda x: os.path.exists(x), [
# user dir
os.path.join(os.path.expanduser('~'), '.py2pack', 'templates'),
... | [
"def",
"_get_template_dirs",
"(",
")",
":",
"return",
"filter",
"(",
"lambda",
"x",
":",
"os",
".",
"path",
".",
"exists",
"(",
"x",
")",
",",
"[",
"# user dir",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~'",... | 48.545455 | 0.001838 |
def get_spectrogram(self):
"""Calculate the spectrogram to be plotted
This exists as a separate method to allow subclasses to override
this and not the entire `get_plot` method, e.g. `Coherencegram`.
This method should not apply the normalisation from `args.norm`.
"""
a... | [
"def",
"get_spectrogram",
"(",
"self",
")",
":",
"args",
"=",
"self",
".",
"args",
"fftlength",
"=",
"float",
"(",
"args",
".",
"secpfft",
")",
"overlap",
"=",
"fftlength",
"*",
"args",
".",
"overlap",
"self",
".",
"log",
"(",
"2",
",",
"\"Calculating ... | 40.545455 | 0.00146 |
def create(cls, fpath):
"Creates a `Config` from `fpath`."
fpath = _expand_path(fpath)
assert(fpath.suffix == '.yml')
if fpath.exists(): return
fpath.parent.mkdir(parents=True, exist_ok=True)
with open(fpath, 'w') as yaml_file:
yaml.dump(cls.DEFAULT_CONFIG, ya... | [
"def",
"create",
"(",
"cls",
",",
"fpath",
")",
":",
"fpath",
"=",
"_expand_path",
"(",
"fpath",
")",
"assert",
"(",
"fpath",
".",
"suffix",
"==",
"'.yml'",
")",
"if",
"fpath",
".",
"exists",
"(",
")",
":",
"return",
"fpath",
".",
"parent",
".",
"m... | 43.375 | 0.008475 |
def get_used_in_func(node):
'''Get names, but ignore variables names to the left hand side
That is to say, in case of
a = b + 1
we consider b as "being accessed", while a is not.
'''
if isinstance(node, ast.FunctionDef):
return {node.name: get_accessed(node.body)}
names = {}
f... | [
"def",
"get_used_in_func",
"(",
"node",
")",
":",
"if",
"isinstance",
"(",
"node",
",",
"ast",
".",
"FunctionDef",
")",
":",
"return",
"{",
"node",
".",
"name",
":",
"get_accessed",
"(",
"node",
".",
"body",
")",
"}",
"names",
"=",
"{",
"}",
"for",
... | 34.083333 | 0.002381 |
def segment_midpoints_by_vertices(self, vertices):
"""
Add midpoints to any segment connected to the vertices in the
list / array provided.
"""
segments = set()
for vertex in vertices:
neighbours = self.identify_vertex_neighbours(vertex)
segments... | [
"def",
"segment_midpoints_by_vertices",
"(",
"self",
",",
"vertices",
")",
":",
"segments",
"=",
"set",
"(",
")",
"for",
"vertex",
"in",
"vertices",
":",
"neighbours",
"=",
"self",
".",
"identify_vertex_neighbours",
"(",
"vertex",
")",
"segments",
".",
"update... | 31.176471 | 0.010989 |
def screenshot(self, filename=None):
"""
Take screen snapshot
Args:
- filename: filename where save to, optional
Returns:
PIL.Image object
Raises:
TypeError, IOError
"""
if self.__keep_screen:
return self.__last_s... | [
"def",
"screenshot",
"(",
"self",
",",
"filename",
"=",
"None",
")",
":",
"if",
"self",
".",
"__keep_screen",
":",
"return",
"self",
".",
"__last_screen",
"try",
":",
"screen",
"=",
"self",
".",
"_take_screenshot",
"(",
")",
"except",
"IOError",
":",
"# ... | 28.107143 | 0.002457 |
def appendInputWithSimilarValues(inputs):
""" Creates an 'one-off' record for each record in the inputs. Appends new
records to the same inputs list.
"""
numInputs = len(inputs)
for i in xrange(numInputs):
input = inputs[i]
for j in xrange(len(input)-1):
if input[j] == 1 and input[j+1] == 0:
... | [
"def",
"appendInputWithSimilarValues",
"(",
"inputs",
")",
":",
"numInputs",
"=",
"len",
"(",
"inputs",
")",
"for",
"i",
"in",
"xrange",
"(",
"numInputs",
")",
":",
"input",
"=",
"inputs",
"[",
"i",
"]",
"for",
"j",
"in",
"xrange",
"(",
"len",
"(",
"... | 31.357143 | 0.011062 |
def interpolate(self, transform, transitions=None, Y=None):
"""Interpolate new data onto a transformation of the graph data
One of either transitions or Y should be provided
Parameters
----------
transform : array-like, shape=[n_samples, n_transform_features]
transiti... | [
"def",
"interpolate",
"(",
"self",
",",
"transform",
",",
"transitions",
"=",
"None",
",",
"Y",
"=",
"None",
")",
":",
"if",
"transitions",
"is",
"None",
":",
"if",
"Y",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Either `transitions` or `Y` must be pr... | 34 | 0.001589 |
def soft_kill(jid, state_id=None):
'''
Set up a state run to die before executing the given state id,
this instructs a running state to safely exit at a given
state id. This needs to pass in the jid of the running state.
If a state_id is not passed then the jid referenced will be safely exited
a... | [
"def",
"soft_kill",
"(",
"jid",
",",
"state_id",
"=",
"None",
")",
":",
"minion",
"=",
"salt",
".",
"minion",
".",
"MasterMinion",
"(",
"__opts__",
")",
"minion",
".",
"functions",
"[",
"'state.soft_kill'",
"]",
"(",
"jid",
",",
"state_id",
")"
] | 46 | 0.002132 |
def build_for_contour_tree(self, contour_tree, negate=False):
""" A helper function that will reduce duplication of data by
reusing the parent contour tree's parameters and data
"""
if self.debug:
tree_type = "Join"
if negate:
tree_type = "Spli... | [
"def",
"build_for_contour_tree",
"(",
"self",
",",
"contour_tree",
",",
"negate",
"=",
"False",
")",
":",
"if",
"self",
".",
"debug",
":",
"tree_type",
"=",
"\"Join\"",
"if",
"negate",
":",
"tree_type",
"=",
"\"Split\"",
"sys",
".",
"stdout",
".",
"write",... | 32.807692 | 0.002278 |
def write_file(environ, term='bash', out_dir=None, tree_dir=None):
''' Write a tree environment file
Loops over the tree environ and writes them out to a bash, tsch, or
modules file
Parameters:
environ (dict):
The tree dictionary environment
term (str):
The type... | [
"def",
"write_file",
"(",
"environ",
",",
"term",
"=",
"'bash'",
",",
"out_dir",
"=",
"None",
",",
"tree_dir",
"=",
"None",
")",
":",
"# get the proper name, header and file extension",
"name",
"=",
"environ",
"[",
"'default'",
"]",
"[",
"'name'",
"]",
"header... | 34.229167 | 0.001183 |
def _save_image(fig, filename, filetype='png', resolution=300):
"""
If filename is specified, saves the image
:param str filename:
Name of the file
:param str filetype:
Type of file
:param int resolution:
DPI resolution of the output figure
"""
if filename:
fi... | [
"def",
"_save_image",
"(",
"fig",
",",
"filename",
",",
"filetype",
"=",
"'png'",
",",
"resolution",
"=",
"300",
")",
":",
"if",
"filename",
":",
"filename",
",",
"filetype",
",",
"resolution",
"=",
"build_filename",
"(",
"filename",
",",
"filetype",
",",
... | 34.058824 | 0.001681 |
def inject_config(self, config, from_args):
"""
:param config:
:type config: list
:param from_args:
:type from_args: dict
"""
# First get required values from labelStore
runtime = self._get_runtime()
whitelist = self._get_whitelist()
#Run introspection on the libraries to retriev... | [
"def",
"inject_config",
"(",
"self",
",",
"config",
",",
"from_args",
")",
":",
"# First get required values from labelStore",
"runtime",
"=",
"self",
".",
"_get_runtime",
"(",
")",
"whitelist",
"=",
"self",
".",
"_get_whitelist",
"(",
")",
"#Run introspection on th... | 35.4 | 0.013201 |
def breakpoint(args):
"""
%prog breakpoint blastfile bedfile [options]
Identify breakpoints where collinearity ends. `blastfile` contains mapping
from markers (query) to scaffolds (subject). `bedfile` contains marker
locations in the related species.
"""
from jcvi.formats.blast import bed
... | [
"def",
"breakpoint",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"formats",
".",
"blast",
"import",
"bed",
"from",
"jcvi",
".",
"utils",
".",
"range",
"import",
"range_interleave",
"p",
"=",
"OptionParser",
"(",
"breakpoint",
".",
"__doc__",
")",
"p",
".... | 38.157895 | 0.000672 |
def knapsack(p, v, cmax):
"""Knapsack problem: select maximum value set of items if total size not more than capacity
:param p: table with size of items
:param v: table with value of items
:param cmax: capacity of bag
:requires: number of items non-zero
:returns: value optimal solution, list of... | [
"def",
"knapsack",
"(",
"p",
",",
"v",
",",
"cmax",
")",
":",
"n",
"=",
"len",
"(",
"p",
")",
"opt",
"=",
"[",
"[",
"0",
"]",
"*",
"(",
"cmax",
"+",
"1",
")",
"for",
"_",
"in",
"range",
"(",
"n",
"+",
"1",
")",
"]",
"sel",
"=",
"[",
"... | 37.176471 | 0.001542 |
def clean(args):
"""
%prog clean fastafile
Remove irregular chars in FASTA seqs.
"""
p = OptionParser(clean.__doc__)
p.add_option("--fancy", default=False, action="store_true",
help="Pretty print the sequence [default: %default]")
p.add_option("--canonical", default=False, ... | [
"def",
"clean",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"clean",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--fancy\"",
",",
"default",
"=",
"False",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Pretty print the sequen... | 28.939394 | 0.001013 |
def create_secret(
name,
namespace='default',
data=None,
source=None,
template=None,
saltenv='base',
**kwargs):
'''
Creates the kubernetes secret as defined by the user.
CLI Examples::
salt 'minion1' kubernetes.create_secret \
pas... | [
"def",
"create_secret",
"(",
"name",
",",
"namespace",
"=",
"'default'",
",",
"data",
"=",
"None",
",",
"source",
"=",
"None",
",",
"template",
"=",
"None",
",",
"saltenv",
"=",
"'base'",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"source",
":",
"data"... | 27.339623 | 0.000666 |
def WriteClientMetadata(self,
client_id,
certificate=None,
fleetspeak_enabled=None,
first_seen=None,
last_ping=None,
last_clock=None,
last... | [
"def",
"WriteClientMetadata",
"(",
"self",
",",
"client_id",
",",
"certificate",
"=",
"None",
",",
"fleetspeak_enabled",
"=",
"None",
",",
"first_seen",
"=",
"None",
",",
"last_ping",
"=",
"None",
",",
"last_clock",
"=",
"None",
",",
"last_ip",
"=",
"None",
... | 27.555556 | 0.016553 |
def ask_dir(self):
"""
dialogue box for choosing directory
"""
args ['directory'] = askdirectory(**self.dir_opt)
self.dir_text.set(args ['directory']) | [
"def",
"ask_dir",
"(",
"self",
")",
":",
"args",
"[",
"'directory'",
"]",
"=",
"askdirectory",
"(",
"*",
"*",
"self",
".",
"dir_opt",
")",
"self",
".",
"dir_text",
".",
"set",
"(",
"args",
"[",
"'directory'",
"]",
")"
] | 26 | 0.062112 |
def hierarchical_group_items(item_list, groupids_list):
"""
Generalization of group_item. Convert a flast list of ids into a heirarchical dictionary.
TODO: move to util_dict
Reference:
http://stackoverflow.com/questions/10193235/python-translate-a-table-to-a-hierarchical-dictionary
Args:
... | [
"def",
"hierarchical_group_items",
"(",
"item_list",
",",
"groupids_list",
")",
":",
"# Construct a defaultdict type with the appropriate number of levels",
"num_groups",
"=",
"len",
"(",
"groupids_list",
")",
"leaf_type",
"=",
"partial",
"(",
"defaultdict",
",",
"list",
... | 32.695122 | 0.000362 |
def serialize_example(transformed_json_data, features, feature_indices, target_name):
"""Makes an instance of data in libsvm format.
Args:
transformed_json_data: dict of transformed data.
features: features config.
feature_indices: output of feature_transforms.get_transformed_feature_indices()
Retur... | [
"def",
"serialize_example",
"(",
"transformed_json_data",
",",
"features",
",",
"feature_indices",
",",
"target_name",
")",
":",
"import",
"six",
"import",
"tensorflow",
"as",
"tf",
"from",
"trainer",
"import",
"feature_transforms",
"line",
"=",
"str",
"(",
"trans... | 42.966667 | 0.012898 |
def process_log_event(event, context):
"""Lambda Entrypoint - Log Subscriber
Format log events and relay to sentry (direct or sqs)
"""
init()
# Grab the actual error log payload
serialized = event['awslogs'].pop('data')
data = json.loads(zlib.decompress(
base64.b64decode(serialized)... | [
"def",
"process_log_event",
"(",
"event",
",",
"context",
")",
":",
"init",
"(",
")",
"# Grab the actual error log payload",
"serialized",
"=",
"event",
"[",
"'awslogs'",
"]",
".",
"pop",
"(",
"'data'",
")",
"data",
"=",
"json",
".",
"loads",
"(",
"zlib",
... | 33.05 | 0.001471 |
def assign_value(self, comp_def, value, src_ref):
"""
Used by the compiler for either local or dynamic prop assignments
This does the following:
- Check that the property is allowed in this component
- Check if the value being assigned is compatible
- Assign t... | [
"def",
"assign_value",
"(",
"self",
",",
"comp_def",
",",
"value",
",",
"src_ref",
")",
":",
"# Check if property is allowed in this component",
"if",
"type",
"(",
"comp_def",
")",
"not",
"in",
"self",
".",
"bindable_to",
":",
"self",
".",
"env",
".",
"msg",
... | 38.88 | 0.001004 |
def set_default_config(modules, params=None, yaml=None, filename=None,
config=None, validate=True):
"""Set up global configuration for tests and noninteractive tools.
`modules` is an iterable of
:class:`yakonfig.Configurable` objects, or anything
equivalently typed. This functio... | [
"def",
"set_default_config",
"(",
"modules",
",",
"params",
"=",
"None",
",",
"yaml",
"=",
"None",
",",
"filename",
"=",
"None",
",",
"config",
"=",
"None",
",",
"validate",
"=",
"True",
")",
":",
"if",
"params",
"is",
"None",
":",
"params",
"=",
"{"... | 41.5625 | 0.000294 |
def find_experiment_export(app_id):
"""Attempt to find a zipped export of an experiment with the ID provided
and return its path. Returns None if not found.
Search order:
1. local "data" subdirectory
2. user S3 bucket
3. Dallinger S3 bucket
"""
# Check locally first
cwd... | [
"def",
"find_experiment_export",
"(",
"app_id",
")",
":",
"# Check locally first",
"cwd",
"=",
"os",
".",
"getcwd",
"(",
")",
"data_filename",
"=",
"\"{}-data.zip\"",
".",
"format",
"(",
"app_id",
")",
"path_to_data",
"=",
"os",
".",
"path",
".",
"join",
"("... | 28.45 | 0.00085 |
def to_timestamp(dt, timestamp):
"""Convert datetime to google.protobuf.Timestamp.
Args:
dt: a timezone naive datetime.
timestamp: a google.protobuf.Timestamp to populate.
Raises:
TypeError: if a timezone aware datetime was provided.
"""
if dt.tzinfo:
# this is an "aware" datetime with an ex... | [
"def",
"to_timestamp",
"(",
"dt",
",",
"timestamp",
")",
":",
"if",
"dt",
".",
"tzinfo",
":",
"# this is an \"aware\" datetime with an explicit timezone. Throw an error.",
"raise",
"TypeError",
"(",
"'Cannot store a timezone aware datetime. '",
"'Convert to UTC and store the naiv... | 36 | 0.00846 |
def set_widgets(self):
"""Set widgets on the Field Mapping step."""
on_the_fly_metadata = {}
layer_purpose = self.parent.step_kw_purpose.selected_purpose()
on_the_fly_metadata['layer_purpose'] = layer_purpose['key']
if layer_purpose != layer_purpose_aggregation:
subca... | [
"def",
"set_widgets",
"(",
"self",
")",
":",
"on_the_fly_metadata",
"=",
"{",
"}",
"layer_purpose",
"=",
"self",
".",
"parent",
".",
"step_kw_purpose",
".",
"selected_purpose",
"(",
")",
"on_the_fly_metadata",
"[",
"'layer_purpose'",
"]",
"=",
"layer_purpose",
"... | 52.818182 | 0.001691 |
def connectAt(self, fromName, toName, position = None):
"""
Connects two layers by instantiating an instance of Connection
class. Allows a position number, indicating the ordering of
the connection.
"""
fromLayer = self.getLayer(fromName)
toLayer = self.getLayer... | [
"def",
"connectAt",
"(",
"self",
",",
"fromName",
",",
"toName",
",",
"position",
"=",
"None",
")",
":",
"fromLayer",
"=",
"self",
".",
"getLayer",
"(",
"fromName",
")",
"toLayer",
"=",
"self",
".",
"getLayer",
"(",
"toName",
")",
"if",
"self",
".",
... | 49.193548 | 0.009003 |
def get_cluster_labels(hdf5_file, N_processes):
"""
Returns
-------
cluster_centers_indices : array of shape (n_clusters,)
Indices of cluster centers
labels : array of shape (n_samples,)
Specify the label of the cluster to which each point has been assigned.
"""
wit... | [
"def",
"get_cluster_labels",
"(",
"hdf5_file",
",",
"N_processes",
")",
":",
"with",
"Worker",
".",
"hdf5_lock",
":",
"with",
"tables",
".",
"open_file",
"(",
"hdf5_file",
",",
"'r+'",
")",
"as",
"fileh",
":",
"A",
"=",
"fileh",
".",
"root",
".",
"aff_pr... | 33.570093 | 0.017036 |
def wrap(x):
"""
Wraps an element or integer type by serializing it and base64 encoding
the resulting bytes.
"""
# Detect the type so we can call the proper serialization routine
if isinstance(x, G1Element):
return _wrap(x, serializeG1)
elif isinstance(x, G2Element):
return... | [
"def",
"wrap",
"(",
"x",
")",
":",
"# Detect the type so we can call the proper serialization routine",
"if",
"isinstance",
"(",
"x",
",",
"G1Element",
")",
":",
"return",
"_wrap",
"(",
"x",
",",
"serializeG1",
")",
"elif",
"isinstance",
"(",
"x",
",",
"G2Elemen... | 28.153846 | 0.009247 |
def getUsrCfgFilesForPyPkg(pkgName):
""" See if the user has one of their own local .cfg files for this task,
such as might be created automatically during the save of a read-only
package, and return their names. """
# Get the python package and it's .cfg file
thePkg, theFile = findCfgFileFo... | [
"def",
"getUsrCfgFilesForPyPkg",
"(",
"pkgName",
")",
":",
"# Get the python package and it's .cfg file",
"thePkg",
",",
"theFile",
"=",
"findCfgFileForPkg",
"(",
"pkgName",
",",
"'.cfg'",
")",
"# See if the user has any of their own local .cfg files for this task",
"tname",
"=... | 53.3 | 0.001845 |
def get_bkg_qq_data(id=None, bkg_id=None):
"""Get data for a quantile-quantile plot of the background data and model.
*id*
The dataset id for which to get the data; defaults if unspecified.
*bkg_id*
The identifier of the background; defaults if unspecified.
Returns:
An ndarray of shap... | [
"def",
"get_bkg_qq_data",
"(",
"id",
"=",
"None",
",",
"bkg_id",
"=",
"None",
")",
":",
"bdata",
"=",
"ui",
".",
"get_bkg",
"(",
"id",
"=",
"id",
",",
"bkg_id",
"=",
"bkg_id",
")",
"kev",
"=",
"bdata",
".",
"get_x",
"(",
")",
"obs_data",
"=",
"bd... | 38.409091 | 0.001155 |
def members(name, ref):
""" List the members of a specific dimension or the distinct values of a
given attribute. """
cube = get_cube(name)
result = cube.members(ref, cuts=request.args.get('cut'),
order=request.args.get('order'),
page=request.args.get(... | [
"def",
"members",
"(",
"name",
",",
"ref",
")",
":",
"cube",
"=",
"get_cube",
"(",
"name",
")",
"result",
"=",
"cube",
".",
"members",
"(",
"ref",
",",
"cuts",
"=",
"request",
".",
"args",
".",
"get",
"(",
"'cut'",
")",
",",
"order",
"=",
"reques... | 44 | 0.002227 |
def origin(hosts):
"""
Return a function that returns a valid HTTP Origin or localhost
if none found.
"""
hosts = [urlsplit(h) for h in hosts]
def func(environ):
if 'ISSO_CORS_ORIGIN' in environ:
return environ['ISSO_CORS_ORIGIN']
if not hosts:
return "... | [
"def",
"origin",
"(",
"hosts",
")",
":",
"hosts",
"=",
"[",
"urlsplit",
"(",
"h",
")",
"for",
"h",
"in",
"hosts",
"]",
"def",
"func",
"(",
"environ",
")",
":",
"if",
"'ISSO_CORS_ORIGIN'",
"in",
"environ",
":",
"return",
"environ",
"[",
"'ISSO_CORS_ORIG... | 23.37037 | 0.001522 |
def models_list(self, api_url=None, offset=0, limit=-1, properties=None):
"""Get list of model resources from a SCO-API.
Parameters
----------
api_url : string, optional
Base Url of the SCO-API. Uses default API if argument not present.
offset : int, optional
... | [
"def",
"models_list",
"(",
"self",
",",
"api_url",
"=",
"None",
",",
"offset",
"=",
"0",
",",
"limit",
"=",
"-",
"1",
",",
"properties",
"=",
"None",
")",
":",
"# Get subject listing Url for given SCO-API and return the retrieved",
"# resource listing",
"return",
... | 35.25 | 0.001972 |
def read_table(fstream):
"""
Read a likwid table info from the text stream.
Args:
fstream: Likwid's filestream.
Returns (dict(str: str)):
A dict containing likwid's table info as key/value pairs.
"""
pos = fstream.tell()
line = fstream.readline().strip()
fragments = lin... | [
"def",
"read_table",
"(",
"fstream",
")",
":",
"pos",
"=",
"fstream",
".",
"tell",
"(",
")",
"line",
"=",
"fstream",
".",
"readline",
"(",
")",
".",
"strip",
"(",
")",
"fragments",
"=",
"line",
".",
"split",
"(",
"\",\"",
")",
"fragments",
"=",
"["... | 27.081081 | 0.000963 |
def ne(self, other, ranks=None):
"""
Compares the card against another card, ``other``, and checks whether
the card is not equal to ``other``, based on the given rank dict.
:arg Card other:
The second Card to compare.
:arg dict ranks:
The ranks to refer t... | [
"def",
"ne",
"(",
"self",
",",
"other",
",",
"ranks",
"=",
"None",
")",
":",
"ranks",
"=",
"ranks",
"or",
"DEFAULT_RANKS",
"if",
"isinstance",
"(",
"other",
",",
"Card",
")",
":",
"if",
"ranks",
".",
"get",
"(",
"\"suits\"",
")",
":",
"return",
"("... | 31.518519 | 0.002281 |
def get_nanopubstore_start_dt(url: str):
"""Get last start_dt recorded for getting new nanopub ID's"""
hostname = urllib.parse.urlsplit(url)[1]
start_dates_doc = state_mgmt.get(start_dates_doc_key)
if start_dates_doc and start_dates_doc.get("start_dates"):
date = [
dt["start_dt"]
... | [
"def",
"get_nanopubstore_start_dt",
"(",
"url",
":",
"str",
")",
":",
"hostname",
"=",
"urllib",
".",
"parse",
".",
"urlsplit",
"(",
"url",
")",
"[",
"1",
"]",
"start_dates_doc",
"=",
"state_mgmt",
".",
"get",
"(",
"start_dates_doc_key",
")",
"if",
"start_... | 33.470588 | 0.001709 |
def _z(self, x):
"""Standardize input `x` to a unit normal."""
with tf.name_scope("standardize"):
return (x - self.loc) / self.scale | [
"def",
"_z",
"(",
"self",
",",
"x",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"\"standardize\"",
")",
":",
"return",
"(",
"x",
"-",
"self",
".",
"loc",
")",
"/",
"self",
".",
"scale"
] | 35.75 | 0.013699 |
def hide(self, fromQtmacs: bool=False):
"""
Overloaded ``hide()`` function to avoid calling it
accidentally.
This method is a (weak) security mechanism to prevent
programmers from using the ``hide`` method as originally
intended by Qt, ie. to hide a window. However, in Q... | [
"def",
"hide",
"(",
"self",
",",
"fromQtmacs",
":",
"bool",
"=",
"False",
")",
":",
"if",
"not",
"fromQtmacs",
":",
"# Log a warning message if someone tries to call the",
"# native hide() method.",
"msg",
"=",
"(",
"'hide() command for applet <b>{}</b> ignored. Use '",
"... | 41.204082 | 0.001935 |
def run_script(self, filename, wdir, args, debug, post_mortem,
current_client, clear_variables):
"""Run script in current or dedicated client"""
norm = lambda text: remove_backslashes(to_text_string(text))
# Run Cython files in a dedicated console
is_cython = os... | [
"def",
"run_script",
"(",
"self",
",",
"filename",
",",
"wdir",
",",
"args",
",",
"debug",
",",
"post_mortem",
",",
"current_client",
",",
"clear_variables",
")",
":",
"norm",
"=",
"lambda",
"text",
":",
"remove_backslashes",
"(",
"to_text_string",
"(",
"tex... | 43.625 | 0.002179 |
def start(self):
"""Start performing the action."""
self.status = 'pending'
self.thing.action_notify(self)
self.perform_action()
self.finish() | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"status",
"=",
"'pending'",
"self",
".",
"thing",
".",
"action_notify",
"(",
"self",
")",
"self",
".",
"perform_action",
"(",
")",
"self",
".",
"finish",
"(",
")"
] | 29.5 | 0.010989 |
def populate_items(self, request):
'''populate and returns filtered items'''
self._items = self.get_items(request)
return self.items | [
"def",
"populate_items",
"(",
"self",
",",
"request",
")",
":",
"self",
".",
"_items",
"=",
"self",
".",
"get_items",
"(",
"request",
")",
"return",
"self",
".",
"items"
] | 38.25 | 0.012821 |
def send(self, url, data, headers):
"""
Spawn an async request to a remote webserver.
"""
eventlet.spawn(self._send_payload, (url, data, headers)) | [
"def",
"send",
"(",
"self",
",",
"url",
",",
"data",
",",
"headers",
")",
":",
"eventlet",
".",
"spawn",
"(",
"self",
".",
"_send_payload",
",",
"(",
"url",
",",
"data",
",",
"headers",
")",
")"
] | 34.8 | 0.011236 |
def _availableResultsFraction( self ):
"""Private method to return the fraction of results available, as a real number
between 0 and 1. This does not update the results fetched from the cluster.
:returns: the fraction of available results"""
tr = self.notebook().numberOfResults() + self... | [
"def",
"_availableResultsFraction",
"(",
"self",
")",
":",
"tr",
"=",
"self",
".",
"notebook",
"(",
")",
".",
"numberOfResults",
"(",
")",
"+",
"self",
".",
"notebook",
"(",
")",
".",
"numberOfPendingResults",
"(",
")",
"if",
"tr",
"==",
"0",
":",
"ret... | 46.8 | 0.014675 |
def get(self, *args, **kw):
"""Load the configuration if necessary and forward the call to the parent."""
if not self._loaded:
self.load_config()
return super(FedmsgConfig, self).get(*args, **kw) | [
"def",
"get",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"if",
"not",
"self",
".",
"_loaded",
":",
"self",
".",
"load_config",
"(",
")",
"return",
"super",
"(",
"FedmsgConfig",
",",
"self",
")",
".",
"get",
"(",
"*",
"args",
... | 45.4 | 0.012987 |
def set_identifier(self, uid):
"""
Sets unique id for this epub
:Args:
- uid: Value of unique identifier for this book
"""
self.uid = uid
self.set_unique_metadata('DC', 'identifier', self.uid, {'id': self.IDENTIFIER_ID}) | [
"def",
"set_identifier",
"(",
"self",
",",
"uid",
")",
":",
"self",
".",
"uid",
"=",
"uid",
"self",
".",
"set_unique_metadata",
"(",
"'DC'",
",",
"'identifier'",
",",
"self",
".",
"uid",
",",
"{",
"'id'",
":",
"self",
".",
"IDENTIFIER_ID",
"}",
")"
] | 24.636364 | 0.010676 |
def settings_and_attributes(self):
"""Return a combined dictionary of setting values and attribute values."""
attrs = self.setting_values()
attrs.update(self.__dict__)
skip = ["_instance_settings", "aliases"]
for a in skip:
del attrs[a]
return attrs | [
"def",
"settings_and_attributes",
"(",
"self",
")",
":",
"attrs",
"=",
"self",
".",
"setting_values",
"(",
")",
"attrs",
".",
"update",
"(",
"self",
".",
"__dict__",
")",
"skip",
"=",
"[",
"\"_instance_settings\"",
",",
"\"aliases\"",
"]",
"for",
"a",
"in"... | 37.75 | 0.009709 |
def mendelian_errors2(args):
"""
%prog mendelian_errors2 Trios.summary.csv
Plot Mendelian errors as calculated by mendelian(). File
`Trios.summary.csv` looks like:
Name,Motif,Inheritance,N_Correct,N_Error,N_missing,ErrorRate [N_Error / (N_Correct + N_Error))]
DM1,CTG,AD,790,12,0,1.5%
DM2,C... | [
"def",
"mendelian_errors2",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"mendelian_errors2",
".",
"__doc__",
")",
"opts",
",",
"args",
",",
"iopts",
"=",
"p",
".",
"set_image_options",
"(",
"args",
",",
"figsize",
"=",
"\"7x7\"",
",",
"format",
... | 31.304348 | 0.001795 |
def parseFile(filename):
"""parse an XML file and build a tree. Automatic support for
ZLIB/Compress compressed document is provided by default if
found at compile-time. """
ret = libxml2mod.xmlParseFile(filename)
if ret is None:raise parserError('xmlParseFile() failed')
return xmlDoc(_obj=r... | [
"def",
"parseFile",
"(",
"filename",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlParseFile",
"(",
"filename",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"parserError",
"(",
"'xmlParseFile() failed'",
")",
"return",
"xmlDoc",
"(",
"_obj",
"=",
"ret",
")... | 45.285714 | 0.009288 |
def print_param_values(self_):
"""Print the values of all this object's Parameters."""
self = self_.self
for name,val in self.param.get_param_values():
print('%s.%s = %s' % (self.name,name,val)) | [
"def",
"print_param_values",
"(",
"self_",
")",
":",
"self",
"=",
"self_",
".",
"self",
"for",
"name",
",",
"val",
"in",
"self",
".",
"param",
".",
"get_param_values",
"(",
")",
":",
"print",
"(",
"'%s.%s = %s'",
"%",
"(",
"self",
".",
"name",
",",
"... | 45.2 | 0.021739 |
def _exit_gracefully(self, signum, frame):
"""
Helper method to clean up DAG file processors to avoid leaving orphan processes.
"""
self.log.info("Exiting gracefully upon receiving signal %s", signum)
self.terminate()
self.end()
self.log.debug("Finished terminatin... | [
"def",
"_exit_gracefully",
"(",
"self",
",",
"signum",
",",
"frame",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"Exiting gracefully upon receiving signal %s\"",
",",
"signum",
")",
"self",
".",
"terminate",
"(",
")",
"self",
".",
"end",
"(",
")",
"s... | 39.777778 | 0.008197 |
def matchItem(self, item):
'''
[OPTIONAL] Attempts to find the specified item and returns an item
that describes the same object although it's specific properties
may be different. For example, a contact whose name is an
identical match, but whose telephone number has changed would
return the ma... | [
"def",
"matchItem",
"(",
"self",
",",
"item",
")",
":",
"for",
"match",
"in",
"self",
".",
"getAllItems",
"(",
")",
":",
"if",
"cmp",
"(",
"match",
",",
"item",
")",
"==",
"0",
":",
"return",
"match",
"return",
"None"
] | 40.59375 | 0.001504 |
def inspect_phone(self, gps_lat_long = [137.0000,100.0000], moving = False, move_dist_2_mn = 4, on_charge = True, screen_saver = False):
"""
FUNCTION STUB - TODO
The intention is to get data from the mobile in the format:
gps_lat = 137.000
gps_lng = 100.00... | [
"def",
"inspect_phone",
"(",
"self",
",",
"gps_lat_long",
"=",
"[",
"137.0000",
",",
"100.0000",
"]",
",",
"moving",
"=",
"False",
",",
"move_dist_2_mn",
"=",
"4",
",",
"on_charge",
"=",
"True",
",",
"screen_saver",
"=",
"False",
")",
":",
"self",
".",
... | 39.44186 | 0.011507 |
def receive_trial_result(self, parameter_id, parameters, value):
"""
Record an observation of the objective function
Parameters
----------
parameter_id : int
parameters : dict
value : dict/float
if value is dict, it should have "default" key.
... | [
"def",
"receive_trial_result",
"(",
"self",
",",
"parameter_id",
",",
"parameters",
",",
"value",
")",
":",
"reward",
"=",
"extract_scalar_reward",
"(",
"value",
")",
"# restore the paramsters contains '_index'",
"if",
"parameter_id",
"not",
"in",
"self",
".",
"tota... | 33.181818 | 0.001597 |
def build_extra_headers(request, proxyMode, orgaMode, currentOrga):
"""Build the list of extra headers"""
things_to_add = {}
# If in proxymode, add needed infos to headers
if proxyMode:
# User
for prop in settings.PIAPI_USERDATA:
if hasattr(request.user, prop):
... | [
"def",
"build_extra_headers",
"(",
"request",
",",
"proxyMode",
",",
"orgaMode",
",",
"currentOrga",
")",
":",
"things_to_add",
"=",
"{",
"}",
"# If in proxymode, add needed infos to headers",
"if",
"proxyMode",
":",
"# User",
"for",
"prop",
"in",
"settings",
".",
... | 40.205882 | 0.002143 |
def to_subject_id(s):
'''
to_subject_id(s) coerces the given string or number into an integer subject id. If s is not a
valid subejct id, raises an exception.
'''
if not pimms.is_number(s) and not pimms.is_str(s):
raise ValueError('invalid type for subject id: %s' % str(type(s)))
if pi... | [
"def",
"to_subject_id",
"(",
"s",
")",
":",
"if",
"not",
"pimms",
".",
"is_number",
"(",
"s",
")",
"and",
"not",
"pimms",
".",
"is_str",
"(",
"s",
")",
":",
"raise",
"ValueError",
"(",
"'invalid type for subject id: %s'",
"%",
"str",
"(",
"type",
"(",
... | 39.6 | 0.009868 |
def create_more_container_files(sourceDir, suffix, maxElements, containers, containers2):
"""Creates additional files for the individual MPL-containers."""
# Create files for each MPL-container with 20 to 'maxElements' elements
# which will be used during generation.
for container in containers:
... | [
"def",
"create_more_container_files",
"(",
"sourceDir",
",",
"suffix",
",",
"maxElements",
",",
"containers",
",",
"containers2",
")",
":",
"# Create files for each MPL-container with 20 to 'maxElements' elements",
"# which will be used during generation.",
"for",
"container",
"i... | 63.151515 | 0.012287 |
def logging_level(level):
"""
Temporarily modify param's logging level.
"""
level = level.upper()
levels = [DEBUG, INFO, WARNING, ERROR, CRITICAL, VERBOSE]
level_names = ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL', 'VERBOSE']
if level not in level_names:
raise Exception("Level ... | [
"def",
"logging_level",
"(",
"level",
")",
":",
"level",
"=",
"level",
".",
"upper",
"(",
")",
"levels",
"=",
"[",
"DEBUG",
",",
"INFO",
",",
"WARNING",
",",
"ERROR",
",",
"CRITICAL",
",",
"VERBOSE",
"]",
"level_names",
"=",
"[",
"'DEBUG'",
",",
"'IN... | 31.5 | 0.001712 |
def byte_str(s="", encoding="utf-8", input_encoding="utf-8", errors="strict"):
"""
Returns a byte string version of 's', encoded as specified in 'encoding'.
Accepts str & unicode objects, interpreting non-unicode strings as byte
strings encoded using the given input encoding.
"""
assert isinst... | [
"def",
"byte_str",
"(",
"s",
"=",
"\"\"",
",",
"encoding",
"=",
"\"utf-8\"",
",",
"input_encoding",
"=",
"\"utf-8\"",
",",
"errors",
"=",
"\"strict\"",
")",
":",
"assert",
"isinstance",
"(",
"s",
",",
"basestring",
")",
"if",
"isinstance",
"(",
"s",
",",... | 37.571429 | 0.001855 |
def add_logging_level(name, value, method_name=None):
''' Comprehensively adds a new logging level to the ``logging`` module and
the currently configured logging class.
Derived from: https://stackoverflow.com/a/35804945/450917
'''
if not method_name:
method_name = name.lower()
... | [
"def",
"add_logging_level",
"(",
"name",
",",
"value",
",",
"method_name",
"=",
"None",
")",
":",
"if",
"not",
"method_name",
":",
"method_name",
"=",
"name",
".",
"lower",
"(",
")",
"# set levels",
"logging",
".",
"addLevelName",
"(",
"value",
",",
"name"... | 37.866667 | 0.000858 |
def get_plan_from_dual(alpha, beta, C, regul):
"""
Retrieve optimal transportation plan from optimal dual potentials.
Parameters
----------
alpha: array, shape = len(a)
beta: array, shape = len(b)
Optimal dual potentials.
C: array, shape = len(a) x len(b)
Ground cost matrix.... | [
"def",
"get_plan_from_dual",
"(",
"alpha",
",",
"beta",
",",
"C",
",",
"regul",
")",
":",
"X",
"=",
"alpha",
"[",
":",
",",
"np",
".",
"newaxis",
"]",
"+",
"beta",
"-",
"C",
"return",
"regul",
".",
"delta_Omega",
"(",
"X",
")",
"[",
"1",
"]"
] | 26.952381 | 0.001706 |
def decode_lazy(rlp, sedes=None, **sedes_kwargs):
"""Decode an RLP encoded object in a lazy fashion.
If the encoded object is a bytestring, this function acts similar to
:func:`rlp.decode`. If it is a list however, a :class:`LazyList` is
returned instead. This object will decode the string lazily, avoi... | [
"def",
"decode_lazy",
"(",
"rlp",
",",
"sedes",
"=",
"None",
",",
"*",
"*",
"sedes_kwargs",
")",
":",
"item",
",",
"end",
"=",
"consume_item_lazy",
"(",
"rlp",
",",
"0",
")",
"if",
"end",
"!=",
"len",
"(",
"rlp",
")",
":",
"raise",
"DecodingError",
... | 46.5 | 0.001859 |
def set_sampling_strategies(self, filter, strategy_and_params):
"""Set sampling strategy for the sensors of all the group's clients.
Only sensors that match the specified filter are considered. See the
`KATCPResource.set_sampling_strategies` docstring for parameter
definitions and more ... | [
"def",
"set_sampling_strategies",
"(",
"self",
",",
"filter",
",",
"strategy_and_params",
")",
":",
"futures_dict",
"=",
"{",
"}",
"for",
"res_obj",
"in",
"self",
".",
"clients",
":",
"futures_dict",
"[",
"res_obj",
".",
"name",
"]",
"=",
"res_obj",
".",
"... | 45.4 | 0.002157 |
def close(self):
"""Close the pool by closing and removing all of the connections"""
for cid in list(self.connections.keys()):
self.remove(self.connections[cid].handle)
LOGGER.debug('Pool %s closed', self.id) | [
"def",
"close",
"(",
"self",
")",
":",
"for",
"cid",
"in",
"list",
"(",
"self",
".",
"connections",
".",
"keys",
"(",
")",
")",
":",
"self",
".",
"remove",
"(",
"self",
".",
"connections",
"[",
"cid",
"]",
".",
"handle",
")",
"LOGGER",
".",
"debu... | 48 | 0.008197 |
def calculate_solidity(labels,indexes=None):
"""Calculate the area of each label divided by the area of its convex hull
labels - a label matrix
indexes - the indexes of the labels to measure
"""
if indexes is not None:
""" Convert to compat 32bit integer """
indexes = np.array(i... | [
"def",
"calculate_solidity",
"(",
"labels",
",",
"indexes",
"=",
"None",
")",
":",
"if",
"indexes",
"is",
"not",
"None",
":",
"\"\"\" Convert to compat 32bit integer \"\"\"",
"indexes",
"=",
"np",
".",
"array",
"(",
"indexes",
",",
"dtype",
"=",
"np",
".",
"... | 41.416667 | 0.011811 |
def declare_dict(self):
"""Return declared sections, terms and synonyms as a dict"""
# Run the parser, if it has not been run yet.
if not self.root:
for _ in self: pass
return {
'sections': self._declared_sections,
'terms': self._declared_terms,
... | [
"def",
"declare_dict",
"(",
"self",
")",
":",
"# Run the parser, if it has not been run yet.",
"if",
"not",
"self",
".",
"root",
":",
"for",
"_",
"in",
"self",
":",
"pass",
"return",
"{",
"'sections'",
":",
"self",
".",
"_declared_sections",
",",
"'terms'",
":... | 32 | 0.008287 |
def Poll(generator=None, condition=None, interval=None, timeout=None):
"""Periodically calls generator function until a condition is satisfied."""
if not generator:
raise ValueError("generator has to be a lambda")
if not condition:
raise ValueError("condition has to be a lambda")
if interval is None:... | [
"def",
"Poll",
"(",
"generator",
"=",
"None",
",",
"condition",
"=",
"None",
",",
"interval",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"not",
"generator",
":",
"raise",
"ValueError",
"(",
"\"generator has to be a lambda\"",
")",
"if",
"not... | 27.115385 | 0.013699 |
def _get_bokeh_chart(self, x_field, y_field, chart_type,
label, opts, style, options={}, **kwargs):
"""
Get a Bokeh chart object
"""
if isinstance(x_field, list):
kdims = x_field
else:
kdims = [x_field]
if isinstance(y_fiel... | [
"def",
"_get_bokeh_chart",
"(",
"self",
",",
"x_field",
",",
"y_field",
",",
"chart_type",
",",
"label",
",",
"opts",
",",
"style",
",",
"options",
"=",
"{",
"}",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"x_field",
",",
"list",
")"... | 36.607143 | 0.002375 |
def _perform_version(self, version):
"""Inner method for version upgrade.
Not intended for standalone use. This method performs the actual
version upgrade with all the pre, post operations and addons upgrades.
:param version: The migration version to upgrade to
:type version: I... | [
"def",
"_perform_version",
"(",
"self",
",",
"version",
")",
":",
"if",
"version",
".",
"is_noop",
"(",
")",
":",
"self",
".",
"log",
"(",
"u'version {} is a noop'",
".",
"format",
"(",
"version",
".",
"number",
")",
")",
"else",
":",
"self",
".",
"log... | 43.103448 | 0.001565 |
def request(self,
method: str,
url: StrOrURL,
**kwargs: Any) -> '_RequestContextManager':
"""Perform HTTP request."""
return _RequestContextManager(self._request(method, url, **kwargs)) | [
"def",
"request",
"(",
"self",
",",
"method",
":",
"str",
",",
"url",
":",
"StrOrURL",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"'_RequestContextManager'",
":",
"return",
"_RequestContextManager",
"(",
"self",
".",
"_request",
"(",
"method",
",",
... | 40.666667 | 0.02008 |
def WriteToFD(self, fd):
"""Write out the updated configuration to the fd."""
if self.writeback:
self.writeback.SaveDataToFD(self.writeback_data, fd)
else:
raise RuntimeError("Attempting to write a configuration without a "
"writeback location.") | [
"def",
"WriteToFD",
"(",
"self",
",",
"fd",
")",
":",
"if",
"self",
".",
"writeback",
":",
"self",
".",
"writeback",
".",
"SaveDataToFD",
"(",
"self",
".",
"writeback_data",
",",
"fd",
")",
"else",
":",
"raise",
"RuntimeError",
"(",
"\"Attempting to write ... | 41.285714 | 0.010169 |
def update(self, language=values.unset, tagged_text=values.unset,
source_channel=values.unset):
"""
Update the SampleInstance
:param unicode language: The ISO language-country string that specifies the language used for the sample
:param unicode tagged_text: The text exam... | [
"def",
"update",
"(",
"self",
",",
"language",
"=",
"values",
".",
"unset",
",",
"tagged_text",
"=",
"values",
".",
"unset",
",",
"source_channel",
"=",
"values",
".",
"unset",
")",
":",
"return",
"self",
".",
"_proxy",
".",
"update",
"(",
"language",
... | 53.384615 | 0.009915 |
def hdf5_cache(filepath=None, parent=None, group=None, names=None, typed=False,
hashed_key=False, **h5dcreate_kwargs):
"""HDF5 cache decorator.
Parameters
----------
filepath : string, optional
Path to HDF5 file. If None a temporary file name will be used.
parent : string, op... | [
"def",
"hdf5_cache",
"(",
"filepath",
"=",
"None",
",",
"parent",
"=",
"None",
",",
"group",
"=",
"None",
",",
"names",
"=",
"None",
",",
"typed",
"=",
"False",
",",
"hashed_key",
"=",
"False",
",",
"*",
"*",
"h5dcreate_kwargs",
")",
":",
"# initialise... | 31.420168 | 0.000259 |
def call_functions_parallel(*worker_defs):
"""Call specified functions in parallel.
:param *worker_defs: Each positional argument can be either of
a function to be called or a tuple which consists of a function,
a list of positional arguments) and keyword arguments (optional).
If you ne... | [
"def",
"call_functions_parallel",
"(",
"*",
"worker_defs",
")",
":",
"# TODO(amotoki): Needs to figure out what max_workers can be specified.",
"# According to e0ne, the apache default configuration in devstack allows",
"# only 10 threads. What happens if max_worker=11 is specified?",
"max_work... | 50.272727 | 0.000591 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.