text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def get_meta_lang(self):
"""\
Extract content language from meta
"""
# we have a lang attribute in html
attr = self.parser.getAttribute(self.article.doc, attr='lang')
if attr is None:
# look up for a Content-Language in meta
items = [
... | [
"def",
"get_meta_lang",
"(",
"self",
")",
":",
"# we have a lang attribute in html",
"attr",
"=",
"self",
".",
"parser",
".",
"getAttribute",
"(",
"self",
".",
"article",
".",
"doc",
",",
"attr",
"=",
"'lang'",
")",
"if",
"attr",
"is",
"None",
":",
"# look... | 34.583333 | 18.625 |
def _image_gradients(self, input_csvlines, label, image_column_name):
"""Compute gradients from prob of label to image. Used by integrated gradients (probe)."""
with tf.Graph().as_default() as g, tf.Session() as sess:
logging_level = tf.logging.get_verbosity()
try:
... | [
"def",
"_image_gradients",
"(",
"self",
",",
"input_csvlines",
",",
"label",
",",
"image_column_name",
")",
":",
"with",
"tf",
".",
"Graph",
"(",
")",
".",
"as_default",
"(",
")",
"as",
"g",
",",
"tf",
".",
"Session",
"(",
")",
"as",
"sess",
":",
"lo... | 50.0625 | 27.4375 |
def createEditor(self, delegate, parent, option):
""" Creates a FloatCtiEditor.
For the parameters see the AbstractCti constructor documentation.
"""
return FloatCtiEditor(self, delegate, parent=parent) | [
"def",
"createEditor",
"(",
"self",
",",
"delegate",
",",
"parent",
",",
"option",
")",
":",
"return",
"FloatCtiEditor",
"(",
"self",
",",
"delegate",
",",
"parent",
"=",
"parent",
")"
] | 46.8 | 13.2 |
def call_actions(
self,
service_name,
actions,
expansions=None,
raise_job_errors=True,
raise_action_errors=True,
timeout=None,
**kwargs
):
"""
Build and send a single job request with one or more actions.
Returns a list of acti... | [
"def",
"call_actions",
"(",
"self",
",",
"service_name",
",",
"actions",
",",
"expansions",
"=",
"None",
",",
"raise_job_errors",
"=",
"True",
",",
"raise_action_errors",
"=",
"True",
",",
"timeout",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return"... | 47.583333 | 29.216667 |
def make_process_header(self, slug, typ, version, source_uri, description, inputs):
"""Generate a process definition header.
:param str slug: process' slug
:param str typ: process' type
:param str version: process' version
:param str source_uri: url to the process definition
... | [
"def",
"make_process_header",
"(",
"self",
",",
"slug",
",",
"typ",
",",
"version",
",",
"source_uri",
",",
"description",
",",
"inputs",
")",
":",
"node",
"=",
"addnodes",
".",
"desc",
"(",
")",
"signode",
"=",
"addnodes",
".",
"desc_signature",
"(",
"s... | 38.155556 | 23.066667 |
def clear(self, ts=None):
"""Clear all session in prepare phase.
:param ts: timestamp used locate the namespace
"""
sp_key = "%s:session_prepare" % self.namespace(ts or int(time.time()))
return self.r.delete(sp_key) | [
"def",
"clear",
"(",
"self",
",",
"ts",
"=",
"None",
")",
":",
"sp_key",
"=",
"\"%s:session_prepare\"",
"%",
"self",
".",
"namespace",
"(",
"ts",
"or",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
")",
"return",
"self",
".",
"r",
".",
"delete",
... | 35.714286 | 15.857143 |
def is_prefix(pre_path, path):
"""Return True if pre_path is a path-prefix of path."""
pre_path = pre_path.strip('.')
path = path.strip('.')
return not pre_path or path.startswith(pre_path + '.') | [
"def",
"is_prefix",
"(",
"pre_path",
",",
"path",
")",
":",
"pre_path",
"=",
"pre_path",
".",
"strip",
"(",
"'.'",
")",
"path",
"=",
"path",
".",
"strip",
"(",
"'.'",
")",
"return",
"not",
"pre_path",
"or",
"path",
".",
"startswith",
"(",
"pre_path",
... | 41.4 | 9.6 |
def delete_classification_node(self, project, structure_group, path=None, reclassify_id=None):
"""DeleteClassificationNode.
Delete an existing classification node.
:param str project: Project ID or project name
:param TreeStructureGroup structure_group: Structure group of the classificat... | [
"def",
"delete_classification_node",
"(",
"self",
",",
"project",
",",
"structure_group",
",",
"path",
"=",
"None",
",",
"reclassify_id",
"=",
"None",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"project",
"is",
"not",
"None",
":",
"route_values",
"[",
... | 57.521739 | 24 |
def get_undefined_annotations(graph: BELGraph) -> Set[str]:
"""Get all annotations that aren't actually defined.
:return: The set of all undefined annotations
"""
return {
exc.annotation
for _, exc, _ in graph.warnings
if isinstance(exc, UndefinedAnnotationWarning)
} | [
"def",
"get_undefined_annotations",
"(",
"graph",
":",
"BELGraph",
")",
"->",
"Set",
"[",
"str",
"]",
":",
"return",
"{",
"exc",
".",
"annotation",
"for",
"_",
",",
"exc",
",",
"_",
"in",
"graph",
".",
"warnings",
"if",
"isinstance",
"(",
"exc",
",",
... | 30.7 | 16 |
def split(pattern, string, maxsplit=0, flags=0):
"""Split the source string by the occurrences of the pattern,
returning a list containing the resulting substrings."""
return _compile(pattern, flags).split(string, maxsplit) | [
"def",
"split",
"(",
"pattern",
",",
"string",
",",
"maxsplit",
"=",
"0",
",",
"flags",
"=",
"0",
")",
":",
"return",
"_compile",
"(",
"pattern",
",",
"flags",
")",
".",
"split",
"(",
"string",
",",
"maxsplit",
")"
] | 58 | 6.75 |
def get_factors(self, unique_R, inds, centers, widths):
"""Calculate factors based on centers and widths
Parameters
----------
unique_R : a list of array,
Each element contains unique value in one dimension of
scanner coordinate matrix R.
inds : a list ... | [
"def",
"get_factors",
"(",
"self",
",",
"unique_R",
",",
"inds",
",",
"centers",
",",
"widths",
")",
":",
"F",
"=",
"np",
".",
"zeros",
"(",
"(",
"len",
"(",
"inds",
"[",
"0",
"]",
")",
",",
"self",
".",
"K",
")",
")",
"tfa_extension",
".",
"fa... | 24.209302 | 21.255814 |
async def get_version(self, tp, params):
"""
Loads version from the stream / version database
# TODO: instance vs. tp.
:param tp:
:param params:
:return:
"""
tw = TypeWrapper(tp, params)
if not tw.is_versioned():
# self.registry.set_tr... | [
"async",
"def",
"get_version",
"(",
"self",
",",
"tp",
",",
"params",
")",
":",
"tw",
"=",
"TypeWrapper",
"(",
"tp",
",",
"params",
")",
"if",
"not",
"tw",
".",
"is_versioned",
"(",
")",
":",
"# self.registry.set_tr()",
"return",
"TypeWrapper",
".",
"ELE... | 30.807692 | 16.115385 |
def label_clusters(image, min_cluster_size=50, min_thresh=1e-6, max_thresh=1, fully_connected=False):
"""
This will give a unique ID to each connected
component 1 through N of size > min_cluster_size
ANTsR function: `labelClusters`
Arguments
---------
image : ANTsImage
input imag... | [
"def",
"label_clusters",
"(",
"image",
",",
"min_cluster_size",
"=",
"50",
",",
"min_thresh",
"=",
"1e-6",
",",
"max_thresh",
"=",
"1",
",",
"fully_connected",
"=",
"False",
")",
":",
"dim",
"=",
"image",
".",
"dimension",
"clust",
"=",
"threshold_image",
... | 28.813953 | 21.093023 |
def train_local(self, closest_point, label_vector_description=None, N=None,
pivot=True, **kwargs):
"""
Train the model in a Cannon-like fashion using the grid points as labels
and the intensities as normalsied rest-frame fluxes within some local
regime.
"""
lv = ... | [
"def",
"train_local",
"(",
"self",
",",
"closest_point",
",",
"label_vector_description",
"=",
"None",
",",
"N",
"=",
"None",
",",
"pivot",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"lv",
"=",
"self",
".",
"_cannon_label_vector",
"if",
"label_vector_... | 43.242424 | 26.030303 |
def identical_blocks(self):
"""
:return A list of all block matches that appear to be identical
"""
identical_blocks = []
for (func_a, func_b) in self.function_matches:
identical_blocks.extend(self.get_function_diff(func_a, func_b).identical_blocks)
return ide... | [
"def",
"identical_blocks",
"(",
"self",
")",
":",
"identical_blocks",
"=",
"[",
"]",
"for",
"(",
"func_a",
",",
"func_b",
")",
"in",
"self",
".",
"function_matches",
":",
"identical_blocks",
".",
"extend",
"(",
"self",
".",
"get_function_diff",
"(",
"func_a"... | 40.75 | 16.25 |
def show_vpnservice(self, vpnservice, **_params):
"""Fetches information of a specific VPN service."""
return self.get(self.vpnservice_path % (vpnservice), params=_params) | [
"def",
"show_vpnservice",
"(",
"self",
",",
"vpnservice",
",",
"*",
"*",
"_params",
")",
":",
"return",
"self",
".",
"get",
"(",
"self",
".",
"vpnservice_path",
"%",
"(",
"vpnservice",
")",
",",
"params",
"=",
"_params",
")"
] | 61.666667 | 15 |
def get_rendering_cache_key(placeholder_name, contentitem):
"""
Return a cache key for the content item output.
.. seealso::
The :func:`ContentItem.clear_cache() <fluent_contents.models.ContentItem.clear_cache>` function
can be used to remove the cache keys of a retrieved object.
"""
... | [
"def",
"get_rendering_cache_key",
"(",
"placeholder_name",
",",
"contentitem",
")",
":",
"if",
"not",
"contentitem",
".",
"pk",
":",
"return",
"None",
"return",
"\"contentitem.@{0}.{1}.{2}\"",
".",
"format",
"(",
"placeholder_name",
",",
"contentitem",
".",
"plugin"... | 36.0625 | 23.8125 |
def listen(self):
"""Server-side cookie exchange
This method reads datagrams from the socket and initiates cookie
exchange, upon whose successful conclusion one can then proceed to
the accept method. Alternatively, accept can be called directly, in
which case it will call this m... | [
"def",
"listen",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"_listening\"",
")",
":",
"raise",
"InvalidSocketError",
"(",
"\"listen called on non-listening socket\"",
")",
"self",
".",
"_pending_peer_address",
"=",
"None",
"try",
":",
"pe... | 43.666667 | 21.84 |
def abu_flux_chart(self, cycle, ilabel=True, imlabel=True,
imagic=False, boxstable=True, lbound=(-12,0),
plotaxis=[0,0,0,0], which_flux=None, prange=None,
profile='charged', show=True):
'''
Plots an abundance and flux chart
Pa... | [
"def",
"abu_flux_chart",
"(",
"self",
",",
"cycle",
",",
"ilabel",
"=",
"True",
",",
"imlabel",
"=",
"True",
",",
"imagic",
"=",
"False",
",",
"boxstable",
"=",
"True",
",",
"lbound",
"=",
"(",
"-",
"12",
",",
"0",
")",
",",
"plotaxis",
"=",
"[",
... | 35.857765 | 18.522496 |
def reshape(self, shape: tf.TensorShape) -> 'TensorFluent':
'''Returns a TensorFluent for the reshape operation with given `shape`.
Args:
shape: The output's shape.
Returns:
A TensorFluent wrapping the reshape operation.
'''
t = tf.reshape(self.tensor, s... | [
"def",
"reshape",
"(",
"self",
",",
"shape",
":",
"tf",
".",
"TensorShape",
")",
"->",
"'TensorFluent'",
":",
"t",
"=",
"tf",
".",
"reshape",
"(",
"self",
".",
"tensor",
",",
"shape",
")",
"scope",
"=",
"self",
".",
"scope",
".",
"as_list",
"(",
")... | 32.923077 | 20.615385 |
def parse(string, language=None):
"""
Return a solution to the equation in the input string.
"""
if language:
string = replace_word_tokens(string, language)
tokens = tokenize(string)
postfix = to_postfix(tokens)
return evaluate_postfix(postfix) | [
"def",
"parse",
"(",
"string",
",",
"language",
"=",
"None",
")",
":",
"if",
"language",
":",
"string",
"=",
"replace_word_tokens",
"(",
"string",
",",
"language",
")",
"tokens",
"=",
"tokenize",
"(",
"string",
")",
"postfix",
"=",
"to_postfix",
"(",
"to... | 24.727273 | 15.090909 |
def tagMap(self):
""""Return a :class:`~pyasn1.type.tagmap.TagMap` object mapping
ASN.1 tags to ASN.1 objects contained within callee.
"""
try:
return self._tagMap
except AttributeError:
self._tagMap = tagmap.TagMap(
{self.tagSet: self... | [
"def",
"tagMap",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_tagMap",
"except",
"AttributeError",
":",
"self",
".",
"_tagMap",
"=",
"tagmap",
".",
"TagMap",
"(",
"{",
"self",
".",
"tagSet",
":",
"self",
"}",
",",
"{",
"eoo",
".",
"e... | 29 | 16.866667 |
def render_config(config: Config, indent: str = "") -> str:
"""
Pretty-print a config in sort-of-JSON+comments.
"""
# Add four spaces to the indent.
new_indent = indent + " "
return "".join([
# opening brace + newline
"{\n",
# "type": "...", (if present)
... | [
"def",
"render_config",
"(",
"config",
":",
"Config",
",",
"indent",
":",
"str",
"=",
"\"\"",
")",
"->",
"str",
":",
"# Add four spaces to the indent.",
"new_indent",
"=",
"indent",
"+",
"\" \"",
"return",
"\"\"",
".",
"join",
"(",
"[",
"# opening brace + n... | 31.611111 | 15.833333 |
def chunks(self, size=32, alignment=1):
"""Iterate over all segments and return chunks of the data aligned as
given by `alignment`. `size` must be a multiple of
`alignment`. Each chunk is returned as a named two-tuple of
its address and data.
"""
if (size % alignment) !... | [
"def",
"chunks",
"(",
"self",
",",
"size",
"=",
"32",
",",
"alignment",
"=",
"1",
")",
":",
"if",
"(",
"size",
"%",
"alignment",
")",
"!=",
"0",
":",
"raise",
"Error",
"(",
"'size {} is not a multiple of alignment {}'",
".",
"format",
"(",
"size",
",",
... | 33.823529 | 17.117647 |
def combine_duplicate_stmts(stmts):
"""Combine evidence from duplicate Statements.
Statements are deemed to be duplicates if they have the same key
returned by the `matches_key()` method of the Statement class. This
generally means that statements must be identical in terms of their
... | [
"def",
"combine_duplicate_stmts",
"(",
"stmts",
")",
":",
"# Helper function to get a list of evidence matches keys",
"def",
"_ev_keys",
"(",
"sts",
")",
":",
"ev_keys",
"=",
"[",
"]",
"for",
"stmt",
"in",
"sts",
":",
"for",
"ev",
"in",
"stmt",
".",
"evidence",
... | 46.714286 | 19.604396 |
def projects(self):
"""*All child projects of this taskpaper object*
**Usage:**
Given a taskpaper document object (`doc`), to get a list of the project objects found within the document use:
.. code-block:: python
docProjects = doc.projects
The sa... | [
"def",
"projects",
"(",
"self",
")",
":",
"return",
"self",
".",
"_get_object",
"(",
"regex",
"=",
"re",
".",
"compile",
"(",
"r'((?<=\\n)|(?<=^))(?P<title>(?!\\[Searches\\]|- )\\S.*?:(?!\\S)) *(?P<tagString>( *?@[^(\\s]+(\\([^)]*\\))?)+)?(?P<content>(\\n(( |\\t)+\\S.*)|\\n( |\\t)*... | 33.708333 | 28.25 |
def log_uniform(low, high, size:Optional[List[int]]=None)->FloatOrTensor:
"Draw 1 or shape=`size` random floats from uniform dist: min=log(`low`), max=log(`high`)."
res = uniform(log(low), log(high), size)
return exp(res) if size is None else res.exp_() | [
"def",
"log_uniform",
"(",
"low",
",",
"high",
",",
"size",
":",
"Optional",
"[",
"List",
"[",
"int",
"]",
"]",
"=",
"None",
")",
"->",
"FloatOrTensor",
":",
"res",
"=",
"uniform",
"(",
"log",
"(",
"low",
")",
",",
"log",
"(",
"high",
")",
",",
... | 65.5 | 25.5 |
def get_selections(self):
"""Get current model selection status in state machine selection (filtered according the purpose of the widget)
and tree selection of the widget"""
sm_selection, sm_filtered_selected_model_set = self.get_state_machine_selection()
tree_selection, selected_model_l... | [
"def",
"get_selections",
"(",
"self",
")",
":",
"sm_selection",
",",
"sm_filtered_selected_model_set",
"=",
"self",
".",
"get_state_machine_selection",
"(",
")",
"tree_selection",
",",
"selected_model_list",
"=",
"self",
".",
"get_view_selection",
"(",
")",
"return",
... | 73.833333 | 25.166667 |
def vn(x):
"""
value or none, returns none if x is an empty list
"""
if x == []:
return None
if isinstance(x, list):
return '|'.join(x)
if isinstance(x, datetime):
return x.isoformat()
return x | [
"def",
"vn",
"(",
"x",
")",
":",
"if",
"x",
"==",
"[",
"]",
":",
"return",
"None",
"if",
"isinstance",
"(",
"x",
",",
"list",
")",
":",
"return",
"'|'",
".",
"join",
"(",
"x",
")",
"if",
"isinstance",
"(",
"x",
",",
"datetime",
")",
":",
"ret... | 17.818182 | 17.454545 |
def get_upcoming_events_within_the_current_week(self):
'''Returns the events from the calendar for the next days_to_look_ahead days.'''
now = datetime.now(tz=self.timezone) # timezone?
start_time = datetime(year=now.year, month=now.month, day=now.day, hour=now.hour, minute=now.minute, second=now... | [
"def",
"get_upcoming_events_within_the_current_week",
"(",
"self",
")",
":",
"now",
"=",
"datetime",
".",
"now",
"(",
"tz",
"=",
"self",
".",
"timezone",
")",
"# timezone?",
"start_time",
"=",
"datetime",
"(",
"year",
"=",
"now",
".",
"year",
",",
"month",
... | 73.3 | 33.7 |
async def get(self, key, *, dc=None, watch=None, consistency=None):
"""Returns the specified key
Parameters:
key (str): Key to fetch
watch (Blocking): Do a blocking query
consistency (Consistency): Force consistency
Returns:
ObjectMeta: where valu... | [
"async",
"def",
"get",
"(",
"self",
",",
"key",
",",
"*",
",",
"dc",
"=",
"None",
",",
"watch",
"=",
"None",
",",
"consistency",
"=",
"None",
")",
":",
"response",
"=",
"await",
"self",
".",
"_read",
"(",
"key",
",",
"dc",
"=",
"dc",
",",
"watc... | 38.176471 | 21.215686 |
def discrete(self):
"""
Set sequence to be discrete.
:rtype: Column
:Example:
>>> # Table schema is create table test(f1 double, f2 string)
>>> # Original continuity: f1=CONTINUOUS, f2=CONTINUOUS
>>> # Now we want to set ``f1`` and ``f2`` into continuous
... | [
"def",
"discrete",
"(",
"self",
")",
":",
"field_name",
"=",
"self",
".",
"name",
"new_df",
"=",
"copy_df",
"(",
"self",
")",
"new_df",
".",
"_perform_operation",
"(",
"op",
".",
"FieldContinuityOperation",
"(",
"{",
"field_name",
":",
"False",
"}",
")",
... | 30.529412 | 20.411765 |
def on_release_key(key, callback, suppress=False):
"""
Invokes `callback` for KEY_UP event related to the given key. For details see `hook`.
"""
return hook_key(key, lambda e: e.event_type == KEY_DOWN or callback(e), suppress=suppress) | [
"def",
"on_release_key",
"(",
"key",
",",
"callback",
",",
"suppress",
"=",
"False",
")",
":",
"return",
"hook_key",
"(",
"key",
",",
"lambda",
"e",
":",
"e",
".",
"event_type",
"==",
"KEY_DOWN",
"or",
"callback",
"(",
"e",
")",
",",
"suppress",
"=",
... | 49.4 | 22.6 |
def _format_linedata(linedata, indent, indent_width):
"""Format specific linedata into a pleasant layout.
"linedata" is a list of 2-tuples of the form:
(<item-display-string>, <item-docstring>)
"indent" is a string to use for one level of indentation
"indent_width" is a number o... | [
"def",
"_format_linedata",
"(",
"linedata",
",",
"indent",
",",
"indent_width",
")",
":",
"lines",
"=",
"[",
"]",
"WIDTH",
"=",
"78",
"-",
"indent_width",
"SPACING",
"=",
"2",
"NAME_WIDTH_LOWER_BOUND",
"=",
"13",
"NAME_WIDTH_UPPER_BOUND",
"=",
"30",
"NAME_WIDT... | 36.636364 | 14.393939 |
def rename(blocks, scope, stype):
""" Rename all sub-blocks moved under another
block. (mixins)
Args:
lst (list): block list
scope (object): Scope object
"""
for p in blocks:
if isinstance(p, stype):
p.tokens[0].parse(scope)
if p.tokens[1]:
... | [
"def",
"rename",
"(",
"blocks",
",",
"scope",
",",
"stype",
")",
":",
"for",
"p",
"in",
"blocks",
":",
"if",
"isinstance",
"(",
"p",
",",
"stype",
")",
":",
"p",
".",
"tokens",
"[",
"0",
"]",
".",
"parse",
"(",
"scope",
")",
"if",
"p",
".",
"... | 29.933333 | 10.066667 |
def filter_bam(job, job_vars):
"""
Performs filtering on the transcriptome bam
job_vars: tuple Tuple of dictionaries: input_args and ids
"""
input_args, ids = job_vars
work_dir = job.fileStore.getLocalTempDir()
cores = input_args['cpu_count']
sudo = input_args['sudo']
# I/O
... | [
"def",
"filter_bam",
"(",
"job",
",",
"job_vars",
")",
":",
"input_args",
",",
"ids",
"=",
"job_vars",
"work_dir",
"=",
"job",
".",
"fileStore",
".",
"getLocalTempDir",
"(",
")",
"cores",
"=",
"input_args",
"[",
"'cpu_count'",
"]",
"sudo",
"=",
"input_args... | 41.346154 | 18.730769 |
def unescape(text):
"""
Removes HTML or XML character references and entities from a text string.
:param text: The HTML (or XML) source text.
:return: The plain text, as a Unicode string, if necessary.
"""
def fixup(m):
text = m.group(0)
if text[:2] == "&#":
# charac... | [
"def",
"unescape",
"(",
"text",
")",
":",
"def",
"fixup",
"(",
"m",
")",
":",
"text",
"=",
"m",
".",
"group",
"(",
"0",
")",
"if",
"text",
"[",
":",
"2",
"]",
"==",
"\"&#\"",
":",
"# character reference",
"try",
":",
"if",
"text",
"[",
":",
"3"... | 29.62963 | 17.111111 |
def officialPriceWS(symbols=None, on_data=None):
'''https://iextrading.com/developer/docs/#official-price'''
symbols = _strToList(symbols)
sendinit = ({'symbols': symbols, 'channels': ['official-price']},)
return _stream(_wsURL('deep'), sendinit, on_data) | [
"def",
"officialPriceWS",
"(",
"symbols",
"=",
"None",
",",
"on_data",
"=",
"None",
")",
":",
"symbols",
"=",
"_strToList",
"(",
"symbols",
")",
"sendinit",
"=",
"(",
"{",
"'symbols'",
":",
"symbols",
",",
"'channels'",
":",
"[",
"'official-price'",
"]",
... | 53.4 | 16.2 |
def create_from_cellranger(indir: str, outdir: str = None, genome: str = None) -> str:
"""
Create a .loom file from 10X Genomics cellranger output
Args:
indir (str): path to the cellranger output folder (the one that contains 'outs')
outdir (str): output folder wher the new loom file should be saved (default to... | [
"def",
"create_from_cellranger",
"(",
"indir",
":",
"str",
",",
"outdir",
":",
"str",
"=",
"None",
",",
"genome",
":",
"str",
"=",
"None",
")",
"->",
"str",
":",
"if",
"outdir",
"is",
"None",
":",
"outdir",
"=",
"indir",
"sampleid",
"=",
"os",
".",
... | 49.086207 | 29.913793 |
async def patch_register(self, register: Dict, request: 'Request'):
"""
Store all options in the "choices" sub-register. We store both the
text and the potential intent, in order to match both regular
quick reply clicks but also the user typing stuff on his keyboard that
matches ... | [
"async",
"def",
"patch_register",
"(",
"self",
",",
"register",
":",
"Dict",
",",
"request",
":",
"'Request'",
")",
":",
"register",
"[",
"'choices'",
"]",
"=",
"{",
"o",
".",
"slug",
":",
"{",
"'intent'",
":",
"o",
".",
"intent",
".",
"key",
"if",
... | 38.764706 | 21.117647 |
def firmware_download_input_protocol_type_ftp_protocol_ftp_file(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
firmware_download = ET.Element("firmware_download")
config = firmware_download
input = ET.SubElement(firmware_download, "input")
... | [
"def",
"firmware_download_input_protocol_type_ftp_protocol_ftp_file",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"firmware_download",
"=",
"ET",
".",
"Element",
"(",
"\"firmware_download\"",
")",
"c... | 43.4 | 14 |
def is_present(self, locator, search_object=None):
"""
Determines whether an element is present on the page, retrying once if unable to locate
@type locator: webdriverwrapper.support.locator.Locator
@param locator: the locator or css string used to query... | [
"def",
"is_present",
"(",
"self",
",",
"locator",
",",
"search_object",
"=",
"None",
")",
":",
"all_elements",
"=",
"self",
".",
"_find_immediately",
"(",
"locator",
",",
"search_object",
"=",
"search_object",
")",
"if",
"all_elements",
"is",
"not",
"None",
... | 48.5 | 29.625 |
def dfs_present(path):
'''
Check if a file or directory is present on the distributed FS.
CLI Example:
.. code-block:: bash
salt '*' hadoop.dfs_present /some_random_file
Returns True if the file is present
'''
cmd_return = _hadoop_cmd('dfs', 'stat', path)
match = 'No such fil... | [
"def",
"dfs_present",
"(",
"path",
")",
":",
"cmd_return",
"=",
"_hadoop_cmd",
"(",
"'dfs'",
",",
"'stat'",
",",
"path",
")",
"match",
"=",
"'No such file or directory'",
"return",
"False",
"if",
"match",
"in",
"cmd_return",
"else",
"True"
] | 24.733333 | 22.866667 |
def get_maintenance_response(request):
"""
Return a '503 Service Unavailable' maintenance response.
"""
if settings.MAINTENANCE_MODE_REDIRECT_URL:
return redirect(settings.MAINTENANCE_MODE_REDIRECT_URL)
context = {}
if settings.MAINTENANCE_MODE_GET_TEMPLATE_CONTEXT:
try:
... | [
"def",
"get_maintenance_response",
"(",
"request",
")",
":",
"if",
"settings",
".",
"MAINTENANCE_MODE_REDIRECT_URL",
":",
"return",
"redirect",
"(",
"settings",
".",
"MAINTENANCE_MODE_REDIRECT_URL",
")",
"context",
"=",
"{",
"}",
"if",
"settings",
".",
"MAINTENANCE_... | 34.5 | 19.75 |
def download_google_images(path:PathOrStr, search_term:str, size:str='>400*300', n_images:int=10, format:str='jpg',
max_workers:int=defaults.cpus, timeout:int=4) -> FilePathList:
"""
Search for `n_images` images on Google, matching `search_term` and `size` requirements,
download ... | [
"def",
"download_google_images",
"(",
"path",
":",
"PathOrStr",
",",
"search_term",
":",
"str",
",",
"size",
":",
"str",
"=",
"'>400*300'",
",",
"n_images",
":",
"int",
"=",
"10",
",",
"format",
":",
"str",
"=",
"'jpg'",
",",
"max_workers",
":",
"int",
... | 71.5 | 36.642857 |
def round(cls, x: 'TensorFluent') -> 'TensorFluent':
'''Returns a TensorFluent for the round function.
Args:
x: The input fluent.
Returns:
A TensorFluent wrapping the round function.
'''
return cls._unary_op(x, tf.round, tf.float32) | [
"def",
"round",
"(",
"cls",
",",
"x",
":",
"'TensorFluent'",
")",
"->",
"'TensorFluent'",
":",
"return",
"cls",
".",
"_unary_op",
"(",
"x",
",",
"tf",
".",
"round",
",",
"tf",
".",
"float32",
")"
] | 28.9 | 22.5 |
def add_or_update(uid, post_data):
'''
Add or update the data by the given ID of post.
'''
catinfo = MCategory.get_by_uid(uid)
if catinfo:
MCategory.update(uid, post_data)
else:
TabTag.create(
uid=uid,
name=post_data... | [
"def",
"add_or_update",
"(",
"uid",
",",
"post_data",
")",
":",
"catinfo",
"=",
"MCategory",
".",
"get_by_uid",
"(",
"uid",
")",
"if",
"catinfo",
":",
"MCategory",
".",
"update",
"(",
"uid",
",",
"post_data",
")",
"else",
":",
"TabTag",
".",
"create",
... | 31.647059 | 14.705882 |
def arg_bool(name, default=False):
""" Fetch a query argument, as a boolean. """
v = request.args.get(name, '')
if not len(v):
return default
return v in BOOL_TRUISH | [
"def",
"arg_bool",
"(",
"name",
",",
"default",
"=",
"False",
")",
":",
"v",
"=",
"request",
".",
"args",
".",
"get",
"(",
"name",
",",
"''",
")",
"if",
"not",
"len",
"(",
"v",
")",
":",
"return",
"default",
"return",
"v",
"in",
"BOOL_TRUISH"
] | 30.666667 | 10.833333 |
def ensure_type(val, dtype, ndim, name, length=None, can_be_none=False, shape=None,
warn_on_cast=True, add_newaxis_on_deficient_ndim=False):
"""Typecheck the size, shape and dtype of a numpy array, with optional
casting.
Parameters
----------
val : {np.ndaraay, None}
The arr... | [
"def",
"ensure_type",
"(",
"val",
",",
"dtype",
",",
"ndim",
",",
"name",
",",
"length",
"=",
"None",
",",
"can_be_none",
"=",
"False",
",",
"shape",
"=",
"None",
",",
"warn_on_cast",
"=",
"True",
",",
"add_newaxis_on_deficient_ndim",
"=",
"False",
")",
... | 42.191919 | 23.676768 |
def parse_subtags(subtags, expect=EXTLANG):
"""
Parse everything that comes after the language tag: scripts, regions,
variants, and assorted extensions.
"""
# We parse the parts of a language code recursively: each step of
# language code parsing handles one component of the code, recurses
#... | [
"def",
"parse_subtags",
"(",
"subtags",
",",
"expect",
"=",
"EXTLANG",
")",
":",
"# We parse the parts of a language code recursively: each step of",
"# language code parsing handles one component of the code, recurses",
"# to handle the rest of the code, and adds what it found onto the",
... | 39.128205 | 23.299145 |
def setup_logging(logfile, print_log_location=True, debug=False):
'''
Set up logging using the built-in ``logging`` package.
A stream handler is added to all logs, so that logs at or above
``logging.INFO`` level are printed to screen as well as written
to the log file.
Arguments:
logf... | [
"def",
"setup_logging",
"(",
"logfile",
",",
"print_log_location",
"=",
"True",
",",
"debug",
"=",
"False",
")",
":",
"log_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"logfile",
")",
"make_dir",
"(",
"log_dir",
")",
"fmt",
"=",
"'[%(levelname)s] %(n... | 37.72973 | 20.324324 |
def loadWeights(self, filename, mode='pickle'):
"""
Loads weights from a file in pickle, plain, or tlearn mode.
"""
# modes: pickle, plain/conx, tlearn
if mode == 'pickle':
import pickle
fp = open(filename, "r")
mylist = pickle.load(fp)
... | [
"def",
"loadWeights",
"(",
"self",
",",
"filename",
",",
"mode",
"=",
"'pickle'",
")",
":",
"# modes: pickle, plain/conx, tlearn",
"if",
"mode",
"==",
"'pickle'",
":",
"import",
"pickle",
"fp",
"=",
"open",
"(",
"filename",
",",
"\"r\"",
")",
"mylist",
"=",
... | 46.794872 | 14.350427 |
def is_link_inline(cls, tag, attribute):
'''Return whether the link is likely to be inline object.'''
if tag in cls.TAG_ATTRIBUTES \
and attribute in cls.TAG_ATTRIBUTES[tag]:
attr_flags = cls.TAG_ATTRIBUTES[tag][attribute]
return attr_flags & cls.ATTR_INLINE
r... | [
"def",
"is_link_inline",
"(",
"cls",
",",
"tag",
",",
"attribute",
")",
":",
"if",
"tag",
"in",
"cls",
".",
"TAG_ATTRIBUTES",
"and",
"attribute",
"in",
"cls",
".",
"TAG_ATTRIBUTES",
"[",
"tag",
"]",
":",
"attr_flags",
"=",
"cls",
".",
"TAG_ATTRIBUTES",
"... | 42.25 | 14.25 |
def is_edge_highlighted(graph: BELGraph, u, v, k) -> bool:
"""Returns if the given edge is highlighted.
:param graph: A BEL graph
:return: Does the edge contain highlight information?
:rtype: bool
"""
return EDGE_HIGHLIGHT in graph[u][v][k] | [
"def",
"is_edge_highlighted",
"(",
"graph",
":",
"BELGraph",
",",
"u",
",",
"v",
",",
"k",
")",
"->",
"bool",
":",
"return",
"EDGE_HIGHLIGHT",
"in",
"graph",
"[",
"u",
"]",
"[",
"v",
"]",
"[",
"k",
"]"
] | 32.75 | 13.625 |
def register(self, typ):
""" register a plugin """
# should be able to combine class/instance namespace, and inherit from either
# would need to store meta or rely on copy ctor
def _func(cls):
if typ in self._class:
raise ValueError("duplicated type name '%s'"... | [
"def",
"register",
"(",
"self",
",",
"typ",
")",
":",
"# should be able to combine class/instance namespace, and inherit from either",
"# would need to store meta or rely on copy ctor",
"def",
"_func",
"(",
"cls",
")",
":",
"if",
"typ",
"in",
"self",
".",
"_class",
":",
... | 39.090909 | 16.090909 |
def params_section(thing, doc, header_level):
"""
Generate markdown for Parameters section.
Parameters
----------
thing : functuon
Function to produce parameters from
doc : dict
Dict from numpydoc
header_level : int
Number of `#`s to use for header
Returns
-... | [
"def",
"params_section",
"(",
"thing",
",",
"doc",
",",
"header_level",
")",
":",
"lines",
"=",
"[",
"]",
"class_doc",
"=",
"doc",
"[",
"\"Parameters\"",
"]",
"return",
"type_list",
"(",
"inspect",
".",
"signature",
"(",
"thing",
")",
",",
"class_doc",
"... | 21.076923 | 18.384615 |
def submit(self, command, blocksize, job_name="parsl.auto"):
''' Submits the command onto an Local Resource Manager job of blocksize parallel elements.
Submit returns an ID that corresponds to the task that was just submitted.
If tasks_per_node < 1:
1/tasks_per_node is provisioned... | [
"def",
"submit",
"(",
"self",
",",
"command",
",",
"blocksize",
",",
"job_name",
"=",
"\"parsl.auto\"",
")",
":",
"job_name",
"=",
"\"{0}.{1}\"",
".",
"format",
"(",
"job_name",
",",
"time",
".",
"time",
"(",
")",
")",
"# Set script path",
"script_path",
"... | 35.825 | 30.075 |
def filtered_search(
self,
id_list: List,
negated_classes: List,
limit: Optional[int] = 100,
taxon_filter: Optional[int] = None,
category_filter: Optional[str] = None,
method: Optional[SimAlgorithm] = SimAlgorithm.PHENODIGM) -> SimResul... | [
"def",
"filtered_search",
"(",
"self",
",",
"id_list",
":",
"List",
",",
"negated_classes",
":",
"List",
",",
"limit",
":",
"Optional",
"[",
"int",
"]",
"=",
"100",
",",
"taxon_filter",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"category_filter... | 47.555556 | 22.777778 |
def do_scan_results(sk, if_index, driver_id, results):
"""Retrieve the results of a successful scan (SSIDs and data about them).
This function does not require root privileges. It eventually calls a callback that actually decodes data about
SSIDs but this function kicks that off.
May exit the program ... | [
"def",
"do_scan_results",
"(",
"sk",
",",
"if_index",
",",
"driver_id",
",",
"results",
")",
":",
"msg",
"=",
"nlmsg_alloc",
"(",
")",
"genlmsg_put",
"(",
"msg",
",",
"0",
",",
"0",
",",
"driver_id",
",",
"0",
",",
"NLM_F_DUMP",
",",
"nl80211",
".",
... | 45.714286 | 26 |
def parse_line(p_string):
"""
Parses a single line as can be encountered in a todo.txt file.
First checks whether the standard elements are present, such as priority,
creation date, completeness check and the completion date.
Then the rest of the analyzed for any occurrences of contexts, projects o... | [
"def",
"parse_line",
"(",
"p_string",
")",
":",
"result",
"=",
"{",
"'completed'",
":",
"False",
",",
"'completionDate'",
":",
"None",
",",
"'priority'",
":",
"None",
",",
"'creationDate'",
":",
"None",
",",
"'text'",
":",
"\"\"",
",",
"'projects'",
":",
... | 27.8375 | 22.2125 |
def do_execute(self):
"""
The actual execution of the actor.
:return: None if successful, otherwise error message
:rtype: str
"""
expr = str(self.resolve_option("expression"))
expr = expr.replace("{X}", str(self.input.payload))
self._output.append(Token(e... | [
"def",
"do_execute",
"(",
"self",
")",
":",
"expr",
"=",
"str",
"(",
"self",
".",
"resolve_option",
"(",
"\"expression\"",
")",
")",
"expr",
"=",
"expr",
".",
"replace",
"(",
"\"{X}\"",
",",
"str",
"(",
"self",
".",
"input",
".",
"payload",
")",
")",... | 31 | 14.636364 |
def remove_container(self, container, v=False, link=False, force=False):
"""
Remove a container. Similar to the ``docker rm`` command.
Args:
container (str): The container to remove
v (bool): Remove the volumes associated with the container
link (bool): Remov... | [
"def",
"remove_container",
"(",
"self",
",",
"container",
",",
"v",
"=",
"False",
",",
"link",
"=",
"False",
",",
"force",
"=",
"False",
")",
":",
"params",
"=",
"{",
"'v'",
":",
"v",
",",
"'link'",
":",
"link",
",",
"'force'",
":",
"force",
"}",
... | 37.714286 | 20.285714 |
def count_variants_barplot(data):
""" Return HTML for the Variant Counts barplot """
keys = OrderedDict()
keys['snps'] = {'name': 'SNPs'}
keys['mnps'] = {'name': 'MNPs'}
keys['insertions'] = {'name': 'Insertions'}
keys['deletions'] = {'name': 'Deletions'}
keys['complex'] = {'name': 'Complex'... | [
"def",
"count_variants_barplot",
"(",
"data",
")",
":",
"keys",
"=",
"OrderedDict",
"(",
")",
"keys",
"[",
"'snps'",
"]",
"=",
"{",
"'name'",
":",
"'SNPs'",
"}",
"keys",
"[",
"'mnps'",
"]",
"=",
"{",
"'name'",
":",
"'MNPs'",
"}",
"keys",
"[",
"'inser... | 36.052632 | 10.578947 |
def _nextSequence(cls, name=None):
"""Return a new sequence number for insertion in self._sqlTable.
Note that if your sequences are not named
tablename_primarykey_seq (ie. for table 'blapp' with primary
key 'john_id', sequence name blapp_john_id_seq) you must give
the full se... | [
"def",
"_nextSequence",
"(",
"cls",
",",
"name",
"=",
"None",
")",
":",
"if",
"not",
"name",
":",
"name",
"=",
"cls",
".",
"_sqlSequence",
"if",
"not",
"name",
":",
"# Assume it's tablename_primarykey_seq",
"if",
"len",
"(",
"cls",
".",
"_sqlPrimary",
")",... | 42.954545 | 16.454545 |
def _get_tmaster_with_watch(self, topologyName, callback, isWatching):
"""
Helper function to get pplan with
a callback. The future watch is placed
only if isWatching is True.
"""
path = self.get_tmaster_path(topologyName)
if isWatching:
LOG.info("Adding data watch for path: " + path)
... | [
"def",
"_get_tmaster_with_watch",
"(",
"self",
",",
"topologyName",
",",
"callback",
",",
"isWatching",
")",
":",
"path",
"=",
"self",
".",
"get_tmaster_path",
"(",
"topologyName",
")",
"if",
"isWatching",
":",
"LOG",
".",
"info",
"(",
"\"Adding data watch for p... | 31.92 | 13.52 |
def quaternion_from_euler(ai, aj, ak, axes='sxyz'):
"""Return quaternion from Euler angles and axis sequence.
ai, aj, ak : Euler's roll, pitch and yaw angles
axes : One of 24 axis sequences as string or encoded tuple
>>> q = quaternion_from_euler(1, 2, 3, 'ryxz')
>>> np.allclose(q, [0.435953, 0.31... | [
"def",
"quaternion_from_euler",
"(",
"ai",
",",
"aj",
",",
"ak",
",",
"axes",
"=",
"'sxyz'",
")",
":",
"try",
":",
"firstaxis",
",",
"parity",
",",
"repetition",
",",
"frame",
"=",
"_AXES2TUPLE",
"[",
"axes",
".",
"lower",
"(",
")",
"]",
"except",
"(... | 23.472727 | 20.745455 |
def make_input(self,
seq_idx: int,
word_vec_prev: mx.sym.Symbol,
decoder_state: mx.sym.Symbol) -> AttentionInput:
"""
Returns AttentionInput to be fed into the attend callable returned by the on() method.
:param seq_idx: Decoder time step... | [
"def",
"make_input",
"(",
"self",
",",
"seq_idx",
":",
"int",
",",
"word_vec_prev",
":",
"mx",
".",
"sym",
".",
"Symbol",
",",
"decoder_state",
":",
"mx",
".",
"sym",
".",
"Symbol",
")",
"->",
"AttentionInput",
":",
"query",
"=",
"decoder_state",
"if",
... | 45.555556 | 18.666667 |
def resolve_xref(self, env, fromdocname, builder,
typ, target, node, contnode):
# type: (BuildEnvironment, unicode, Builder, unicode, unicode, nodes.Node, nodes.Node) -> nodes.Node # NOQA
"""Resolve the pending_xref *node* with the given *typ* and *target*.
This method sho... | [
"def",
"resolve_xref",
"(",
"self",
",",
"env",
",",
"fromdocname",
",",
"builder",
",",
"typ",
",",
"target",
",",
"node",
",",
"contnode",
")",
":",
"# type: (BuildEnvironment, unicode, Builder, unicode, unicode, nodes.Node, nodes.Node) -> nodes.Node # NOQA",
"for",
"f... | 52.5 | 27.9 |
def GetMessages(self, formatter_mediator, event):
"""Determines the formatted message strings for an event object.
Args:
formatter_mediator (FormatterMediator): mediates the interactions
between formatters and other components, such as storage and Windows
EventLog resources.
eve... | [
"def",
"GetMessages",
"(",
"self",
",",
"formatter_mediator",
",",
"event",
")",
":",
"if",
"self",
".",
"DATA_TYPE",
"!=",
"event",
".",
"data_type",
":",
"raise",
"errors",
".",
"WrongFormatter",
"(",
"'Unsupported data type: {0:s}.'",
".",
"format",
"(",
"e... | 37.854167 | 24.083333 |
def catsimPopulation(tag, mc_source_id_start=1, n=5000, n_chunk=100, config='simulate_population.yaml'):
"""
n = Number of satellites to simulation
n_chunk = Number of satellites in a file chunk
"""
assert mc_source_id_start >= 1, "Starting mc_source_id must be >= 1"
assert n % n_chunk == 0, "... | [
"def",
"catsimPopulation",
"(",
"tag",
",",
"mc_source_id_start",
"=",
"1",
",",
"n",
"=",
"5000",
",",
"n_chunk",
"=",
"100",
",",
"config",
"=",
"'simulate_population.yaml'",
")",
":",
"assert",
"mc_source_id_start",
">=",
"1",
",",
"\"Starting mc_source_id mu... | 56.260101 | 29.734848 |
def handle(self, *args, **options):
"""Call sync_subscriber on Subscribers without customers associated to them."""
qs = get_subscriber_model().objects.filter(djstripe_customers__isnull=True)
count = 0
total = qs.count()
for subscriber in qs:
count += 1
perc = int(round(100 * (float(count) / float(total... | [
"def",
"handle",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"options",
")",
":",
"qs",
"=",
"get_subscriber_model",
"(",
")",
".",
"objects",
".",
"filter",
"(",
"djstripe_customers__isnull",
"=",
"True",
")",
"count",
"=",
"0",
"total",
"=",
"qs",
... | 33.357143 | 20.428571 |
def _setup_conn_old(**kwargs):
'''
Setup kubernetes API connection singleton the old way
'''
host = __salt__['config.option']('kubernetes.api_url',
'http://localhost:8080')
username = __salt__['config.option']('kubernetes.user')
password = __salt__['config.op... | [
"def",
"_setup_conn_old",
"(",
"*",
"*",
"kwargs",
")",
":",
"host",
"=",
"__salt__",
"[",
"'config.option'",
"]",
"(",
"'kubernetes.api_url'",
",",
"'http://localhost:8080'",
")",
"username",
"=",
"__salt__",
"[",
"'config.option'",
"]",
"(",
"'kubernetes.user'",... | 41.541667 | 24.347222 |
def handle_json_GET_routepatterns(self, params):
"""Given a route_id generate a list of patterns of the route. For each
pattern include some basic information and a few sample trips."""
schedule = self.server.schedule
route = schedule.GetRoute(params.get('route', None))
if not route:
self.send... | [
"def",
"handle_json_GET_routepatterns",
"(",
"self",
",",
"params",
")",
":",
"schedule",
"=",
"self",
".",
"server",
".",
"schedule",
"route",
"=",
"schedule",
".",
"GetRoute",
"(",
"params",
".",
"get",
"(",
"'route'",
",",
"None",
")",
")",
"if",
"not... | 35.859155 | 20.915493 |
def _find_codopant(target, oxidation_state, allowed_elements=None):
"""
Finds the element from "allowed elements" that (i) possesses the desired
"oxidation state" and (ii) is closest in ionic radius to the target specie
Args:
target: (Specie) provides target ionic radius.
oxidation_stat... | [
"def",
"_find_codopant",
"(",
"target",
",",
"oxidation_state",
",",
"allowed_elements",
"=",
"None",
")",
":",
"ref_radius",
"=",
"target",
".",
"ionic_radius",
"candidates",
"=",
"[",
"]",
"symbols",
"=",
"allowed_elements",
"or",
"[",
"el",
".",
"symbol",
... | 36.689655 | 19.655172 |
def sg_summary_loss(tensor, prefix='losses', name=None):
r"""Register `tensor` to summary report as `loss`
Args:
tensor: A `Tensor` to log as loss
prefix: A `string`. A prefix to display in the tensor board web UI.
name: A `string`. A name to display in the tensor board web UI.
Returns:
... | [
"def",
"sg_summary_loss",
"(",
"tensor",
",",
"prefix",
"=",
"'losses'",
",",
"name",
"=",
"None",
")",
":",
"# defaults",
"prefix",
"=",
"''",
"if",
"prefix",
"is",
"None",
"else",
"prefix",
"+",
"'/'",
"# summary name",
"name",
"=",
"prefix",
"+",
"_pr... | 32.555556 | 20.222222 |
def _call(self, cmd, get_output):
"""Calls a command through the SSH connection.
Remote stderr gets printed to this program's stderr. Output is captured
and may be returned.
"""
server_err = self.server_logger()
chan = self.get_client().get_transport().open_session()
... | [
"def",
"_call",
"(",
"self",
",",
"cmd",
",",
"get_output",
")",
":",
"server_err",
"=",
"self",
".",
"server_logger",
"(",
")",
"chan",
"=",
"self",
".",
"get_client",
"(",
")",
".",
"get_transport",
"(",
")",
".",
"open_session",
"(",
")",
"try",
"... | 37.314286 | 13.057143 |
def add_record(self, record_in):
"""
Add a new record. Strip quotes from around strings.
This will over-write if the key already exists, except
for COMMENT and HISTORY fields
parameters
-----------
record:
The record, either a dict or a header card ... | [
"def",
"add_record",
"(",
"self",
",",
"record_in",
")",
":",
"if",
"(",
"isinstance",
"(",
"record_in",
",",
"dict",
")",
"and",
"'name'",
"in",
"record_in",
"and",
"'value'",
"in",
"record_in",
")",
":",
"record",
"=",
"{",
"}",
"record",
".",
"updat... | 33.452381 | 15.97619 |
def send_badge_messages(self, badge_award):
"""
If the Badge class defines a message, send it to the user who was just
awarded the badge.
"""
user_message = getattr(badge_award.badge, "user_message", None)
if callable(user_message):
message = user_message(badg... | [
"def",
"send_badge_messages",
"(",
"self",
",",
"badge_award",
")",
":",
"user_message",
"=",
"getattr",
"(",
"badge_award",
".",
"badge",
",",
"\"user_message\"",
",",
"None",
")",
"if",
"callable",
"(",
"user_message",
")",
":",
"message",
"=",
"user_message... | 38.583333 | 13.75 |
def repeat(mode):
"""Change repeat mode of current player."""
message = command(protobuf.CommandInfo_pb2.ChangeShuffleMode)
send_command = message.inner()
send_command.options.externalPlayerCommand = True
send_command.options.repeatMode = mode
return message | [
"def",
"repeat",
"(",
"mode",
")",
":",
"message",
"=",
"command",
"(",
"protobuf",
".",
"CommandInfo_pb2",
".",
"ChangeShuffleMode",
")",
"send_command",
"=",
"message",
".",
"inner",
"(",
")",
"send_command",
".",
"options",
".",
"externalPlayerCommand",
"="... | 39.428571 | 13 |
def is_python_binding_installed(self):
"""Check if the Python binding has already installed.
Consider below cases.
- pip command is not installed.
- The installed RPM Python binding does not have information
showed as a result of pip list.
"""
is_installed = Fa... | [
"def",
"is_python_binding_installed",
"(",
"self",
")",
":",
"is_installed",
"=",
"False",
"is_install_error",
"=",
"False",
"try",
":",
"is_installed",
"=",
"self",
".",
"is_python_binding_installed_on_pip",
"(",
")",
"except",
"InstallError",
":",
"# Consider a case... | 35.958333 | 15.291667 |
def update_pool(self, pool, body=None):
"""Updates a load balancer pool."""
return self.put(self.pool_path % (pool), body=body) | [
"def",
"update_pool",
"(",
"self",
",",
"pool",
",",
"body",
"=",
"None",
")",
":",
"return",
"self",
".",
"put",
"(",
"self",
".",
"pool_path",
"%",
"(",
"pool",
")",
",",
"body",
"=",
"body",
")"
] | 47 | 6.666667 |
def apply_obb(self):
"""
Transform the current path so that its OBB is axis aligned
and OBB center is at the origin.
"""
if len(self.root) == 1:
matrix, bounds = polygons.polygon_obb(
self.polygons_closed[self.root[0]])
self.apply_transform... | [
"def",
"apply_obb",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"root",
")",
"==",
"1",
":",
"matrix",
",",
"bounds",
"=",
"polygons",
".",
"polygon_obb",
"(",
"self",
".",
"polygons_closed",
"[",
"self",
".",
"root",
"[",
"0",
"]",
"]",
... | 35.666667 | 12.333333 |
def url_quote(url):
"""Ensure url is valid"""
try:
return quote(url, safe=URL_SAFE)
except KeyError:
return quote(encode(url), safe=URL_SAFE) | [
"def",
"url_quote",
"(",
"url",
")",
":",
"try",
":",
"return",
"quote",
"(",
"url",
",",
"safe",
"=",
"URL_SAFE",
")",
"except",
"KeyError",
":",
"return",
"quote",
"(",
"encode",
"(",
"url",
")",
",",
"safe",
"=",
"URL_SAFE",
")"
] | 27.333333 | 13.5 |
def close(self):
'''Stop running timers.'''
if self._call_later_handle:
self._call_later_handle.cancel()
self._running = False | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_call_later_handle",
":",
"self",
".",
"_call_later_handle",
".",
"cancel",
"(",
")",
"self",
".",
"_running",
"=",
"False"
] | 26.333333 | 15 |
def nodes(self):
"""
Return a list of child nodes of this engine. This can be
used to iterate to obtain access to node level operations
::
>>> print(list(engine.nodes))
[Node(name=myfirewall node 1)]
>>> engine.nodes.get(0)
Node(na... | [
"def",
"nodes",
"(",
"self",
")",
":",
"resource",
"=",
"sub_collection",
"(",
"self",
".",
"get_relation",
"(",
"'nodes'",
")",
",",
"Node",
")",
"resource",
".",
"_load_from_engine",
"(",
"self",
",",
"'nodes'",
")",
"return",
"resource"
] | 29.761905 | 13.571429 |
def opener(mode='r'):
"""Factory for creating file objects
Keyword Arguments:
- mode -- A string indicating how the file is to be opened. Accepts the
same values as the builtin open() function.
- bufsize -- The file's desired buffer size. Accepts the same values as
the b... | [
"def",
"opener",
"(",
"mode",
"=",
"'r'",
")",
":",
"def",
"open_file",
"(",
"f",
")",
":",
"if",
"f",
"is",
"sys",
".",
"stdout",
"or",
"f",
"is",
"sys",
".",
"stdin",
":",
"return",
"f",
"elif",
"f",
"==",
"'-'",
":",
"return",
"sys",
".",
... | 31.043478 | 17.695652 |
def activate():
'''Activate an existing user (validate their email confirmation)'''
email = click.prompt('Email')
user = User.objects(email=email).first()
if not user:
exit_with_error('Invalid user')
if user.confirmed_at is not None:
exit_with_error('User email address already confir... | [
"def",
"activate",
"(",
")",
":",
"email",
"=",
"click",
".",
"prompt",
"(",
"'Email'",
")",
"user",
"=",
"User",
".",
"objects",
"(",
"email",
"=",
"email",
")",
".",
"first",
"(",
")",
"if",
"not",
"user",
":",
"exit_with_error",
"(",
"'Invalid use... | 35.833333 | 14.333333 |
def getSpec(cls):
"""
Return the Spec for ApicalTMPairRegion
"""
spec = {
"description": ApicalTMPairRegion.__doc__,
"singleNodeOnly": True,
"inputs": {
"activeColumns": {
"description": ("An array of 0's and 1's representing the active "
"m... | [
"def",
"getSpec",
"(",
"cls",
")",
":",
"spec",
"=",
"{",
"\"description\"",
":",
"ApicalTMPairRegion",
".",
"__doc__",
",",
"\"singleNodeOnly\"",
":",
"True",
",",
"\"inputs\"",
":",
"{",
"\"activeColumns\"",
":",
"{",
"\"description\"",
":",
"(",
"\"An array... | 34.113971 | 18.716912 |
def unscored_nodes_iter(self) -> BaseEntity:
"""Iterate over all nodes without a score."""
for node, data in self.graph.nodes(data=True):
if self.tag not in data:
yield node | [
"def",
"unscored_nodes_iter",
"(",
"self",
")",
"->",
"BaseEntity",
":",
"for",
"node",
",",
"data",
"in",
"self",
".",
"graph",
".",
"nodes",
"(",
"data",
"=",
"True",
")",
":",
"if",
"self",
".",
"tag",
"not",
"in",
"data",
":",
"yield",
"node"
] | 42.6 | 7.2 |
def cli_tempurl(context, method, path, seconds=None, use_container=False):
"""
Generates a TempURL and sends that to the context.io_manager's
stdout.
See :py:mod:`swiftly.cli.tempurl` for context usage information.
See :py:class:`CLITempURL` for more information.
:param context: The :py:class... | [
"def",
"cli_tempurl",
"(",
"context",
",",
"method",
",",
"path",
",",
"seconds",
"=",
"None",
",",
"use_container",
"=",
"False",
")",
":",
"with",
"contextlib",
".",
"nested",
"(",
"context",
".",
"io_manager",
".",
"with_stdout",
"(",
")",
",",
"conte... | 40.06 | 17.46 |
def add_schema(self, schema):
"""
Merge in a JSON schema. This can be a ``dict`` or another
``SchemaBuilder``
:param schema: a JSON Schema
.. note::
There is no schema validation. If you pass in a bad schema,
you might get back a bad schema.
"""
... | [
"def",
"add_schema",
"(",
"self",
",",
"schema",
")",
":",
"if",
"isinstance",
"(",
"schema",
",",
"SchemaBuilder",
")",
":",
"schema_uri",
"=",
"schema",
".",
"schema_uri",
"schema",
"=",
"schema",
".",
"to_schema",
"(",
")",
"if",
"schema_uri",
"is",
"... | 33.083333 | 12.75 |
def create_objects_from_iterables(obj, args: dict, iterables: Dict[str, Any], formatting_options: Dict[str, Any], key_index_name: str = "KeyIndex") -> Tuple[Any, Dict[str, Any], dict]:
""" Create objects for each set of values based on the given arguments.
The iterable values are available under a key index ``... | [
"def",
"create_objects_from_iterables",
"(",
"obj",
",",
"args",
":",
"dict",
",",
"iterables",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"formatting_options",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"key_index_name",
":",
"str",
"=",
"\"KeyI... | 51.552083 | 31.114583 |
def pointTo(agent_host, ob, target_pitch, target_yaw, threshold):
'''Steer towards the target pitch/yaw, return True when within the given tolerance threshold.'''
pitch = ob.get(u'Pitch', 0)
yaw = ob.get(u'Yaw', 0)
delta_yaw = angvel(target_yaw, yaw, 50.0)
delta_pitch = angvel(target_pitch, pitch, 5... | [
"def",
"pointTo",
"(",
"agent_host",
",",
"ob",
",",
"target_pitch",
",",
"target_yaw",
",",
"threshold",
")",
":",
"pitch",
"=",
"ob",
".",
"get",
"(",
"u'Pitch'",
",",
"0",
")",
"yaw",
"=",
"ob",
".",
"get",
"(",
"u'Yaw'",
",",
"0",
")",
"delta_y... | 47 | 17.307692 |
def get_event(self, *etypes, timeout=None):
"""
Return a single event object or block until an event is
received and return it.
- etypes(str): If defined, Slack event type(s) not matching
the filter will be ignored. See https://api.slack.com/events for
a listing of... | [
"def",
"get_event",
"(",
"self",
",",
"*",
"etypes",
",",
"timeout",
"=",
"None",
")",
":",
"self",
".",
"_validate_etypes",
"(",
"*",
"etypes",
")",
"start",
"=",
"time",
".",
"time",
"(",
")",
"e",
"=",
"self",
".",
"_eventq",
".",
"get",
"(",
... | 37.16 | 16.28 |
def save_hash(self, location, basedir, ext=None):
"""
Save response body into file with special path
builded from hash. That allows to lower number of files
per directory.
:param location: URL of file or something else. It is
used to build the SHA1 hash.
:par... | [
"def",
"save_hash",
"(",
"self",
",",
"location",
",",
"basedir",
",",
"ext",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"location",
",",
"six",
".",
"text_type",
")",
":",
"location",
"=",
"location",
".",
"encode",
"(",
"'utf-8'",
")",
"rel_path... | 38.575 | 17.375 |
def targets(tgt, tgt_type='range', **kwargs):
'''
Return the targets from a range query
'''
r = seco.range.Range(__opts__['range_server'])
log.debug('Range connection to \'%s\' established', __opts__['range_server'])
hosts = []
try:
log.debug('Querying range for \'%s\'', tgt)
... | [
"def",
"targets",
"(",
"tgt",
",",
"tgt_type",
"=",
"'range'",
",",
"*",
"*",
"kwargs",
")",
":",
"r",
"=",
"seco",
".",
"range",
".",
"Range",
"(",
"__opts__",
"[",
"'range_server'",
"]",
")",
"log",
".",
"debug",
"(",
"'Range connection to \\'%s\\' est... | 31.125 | 23.75 |
def measured_voltage(self):
"""
The measured voltage that the battery is supplying (in microvolts)
"""
self._measured_voltage, value = self.get_attr_int(self._measured_voltage, 'voltage_now')
return value | [
"def",
"measured_voltage",
"(",
"self",
")",
":",
"self",
".",
"_measured_voltage",
",",
"value",
"=",
"self",
".",
"get_attr_int",
"(",
"self",
".",
"_measured_voltage",
",",
"'voltage_now'",
")",
"return",
"value"
] | 39.833333 | 20.5 |
def delete(self, cascade=False, delete_shares=False):
"""
Deletes the video.
"""
if self.id:
self.connection.post('delete_video', video_id=self.id,
cascade=cascade, delete_shares=delete_shares)
self.id = None | [
"def",
"delete",
"(",
"self",
",",
"cascade",
"=",
"False",
",",
"delete_shares",
"=",
"False",
")",
":",
"if",
"self",
".",
"id",
":",
"self",
".",
"connection",
".",
"post",
"(",
"'delete_video'",
",",
"video_id",
"=",
"self",
".",
"id",
",",
"casc... | 34.125 | 13.625 |
def pop(self, identifier, default=None):
"""Pop a node of the AttrTree using its path string.
Args:
identifier: Path string of the node to return
default: Value to return if no node is found
Returns:
The node that was removed from the AttrTree
"""
... | [
"def",
"pop",
"(",
"self",
",",
"identifier",
",",
"default",
"=",
"None",
")",
":",
"if",
"identifier",
"in",
"self",
".",
"children",
":",
"item",
"=",
"self",
"[",
"identifier",
"]",
"self",
".",
"__delitem__",
"(",
"identifier",
")",
"return",
"ite... | 30.25 | 15.1875 |
def create_shortcuts(self):
"""Create shortcuts for this widget."""
# Configurable
copyfig = config_shortcut(self.copy_figure, context='plots',
name='copy', parent=self)
prevfig = config_shortcut(self.go_previous_thumbnail, context='plots',
... | [
"def",
"create_shortcuts",
"(",
"self",
")",
":",
"# Configurable",
"copyfig",
"=",
"config_shortcut",
"(",
"self",
".",
"copy_figure",
",",
"context",
"=",
"'plots'",
",",
"name",
"=",
"'copy'",
",",
"parent",
"=",
"self",
")",
"prevfig",
"=",
"config_short... | 50.272727 | 22.545455 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.