text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
async def getRowNodes(self, rows, rawprop, cmpf=None):
'''
Join a row generator into (row, Node()) tuples.
A row generator yields tuples of node buid, rawprop dict
Args:
rows: A generator of (layer_idx, (buid, ...)) tuples.
rawprop(str): "raw" propname e.g. if ... | [
"async",
"def",
"getRowNodes",
"(",
"self",
",",
"rows",
",",
"rawprop",
",",
"cmpf",
"=",
"None",
")",
":",
"count",
"=",
"0",
"async",
"for",
"origlayer",
",",
"row",
"in",
"rows",
":",
"count",
"+=",
"1",
"if",
"not",
"count",
"%",
"5",
":",
"... | 36.924242 | 0.001599 |
def automatic_gamma_density(structure, kppa):
"""
Returns an automatic Kpoint object based on a structure and a kpoint
density. Uses Gamma centered meshes always. For GW.
Algorithm:
Uses a simple approach scaling the number of divisions along each
reciprocal latt... | [
"def",
"automatic_gamma_density",
"(",
"structure",
",",
"kppa",
")",
":",
"latt",
"=",
"structure",
".",
"lattice",
"lengths",
"=",
"latt",
".",
"abc",
"ngrid",
"=",
"kppa",
"/",
"structure",
".",
"num_sites",
"mult",
"=",
"(",
"ngrid",
"*",
"lengths",
... | 33.972222 | 0.002385 |
def post_event_discount(self, id, discount_id, **data):
"""
POST /events/:id/discounts/:discount_id/
Updates a discount; returns the result as a :format:`discount` as the key ``discount``.
"""
return self.post("/events/{0}/discounts/{0}/".format(id,discount_id), data=dat... | [
"def",
"post_event_discount",
"(",
"self",
",",
"id",
",",
"discount_id",
",",
"*",
"*",
"data",
")",
":",
"return",
"self",
".",
"post",
"(",
"\"/events/{0}/discounts/{0}/\"",
".",
"format",
"(",
"id",
",",
"discount_id",
")",
",",
"data",
"=",
"data",
... | 45.142857 | 0.018634 |
def prepare(self, session, event):
"""Prepare phase for session.
:param session: sqlalchemy session
"""
if not event:
self.logger.warn("event empty!")
return
sp_key, sp_hkey = self._keygen(session)
def _pk(obj):
pk_values = tuple(get... | [
"def",
"prepare",
"(",
"self",
",",
"session",
",",
"event",
")",
":",
"if",
"not",
"event",
":",
"self",
".",
"logger",
".",
"warn",
"(",
"\"event empty!\"",
")",
"return",
"sp_key",
",",
"sp_hkey",
"=",
"self",
".",
"_keygen",
"(",
"session",
")",
... | 32 | 0.002092 |
def main(_):
"""Convert a file to examples."""
if FLAGS.subword_text_encoder_filename:
encoder = text_encoder.SubwordTextEncoder(
FLAGS.subword_text_encoder_filename)
elif FLAGS.token_text_encoder_filename:
encoder = text_encoder.TokenTextEncoder(FLAGS.token_text_encoder_filename)
elif FLAGS.byt... | [
"def",
"main",
"(",
"_",
")",
":",
"if",
"FLAGS",
".",
"subword_text_encoder_filename",
":",
"encoder",
"=",
"text_encoder",
".",
"SubwordTextEncoder",
"(",
"FLAGS",
".",
"subword_text_encoder_filename",
")",
"elif",
"FLAGS",
".",
"token_text_encoder_filename",
":",... | 41.76087 | 0.012716 |
def get(self, column, useMethod=True, **context):
"""
Returns the value for the column for this record.
:param column | <orb.Column> || <str>
default | <variant>
inflated | <bool>
:return <variant>
"""
# look... | [
"def",
"get",
"(",
"self",
",",
"column",
",",
"useMethod",
"=",
"True",
",",
"*",
"*",
"context",
")",
":",
"# look for shortcuts (dot-noted path)",
"if",
"isinstance",
"(",
"column",
",",
"(",
"str",
",",
"unicode",
")",
")",
"and",
"'.'",
"in",
"colum... | 39.301724 | 0.001712 |
def retry_on_exception(tries=6, delay=1, backoff=2, max_delay=32):
'''
Decorator for implementing exponential backoff for retrying on failures.
tries: Max number of tries to execute the wrapped function before failing.
delay: Delay time in seconds before the FIRST retry.
backoff: Multiplier to exte... | [
"def",
"retry_on_exception",
"(",
"tries",
"=",
"6",
",",
"delay",
"=",
"1",
",",
"backoff",
"=",
"2",
",",
"max_delay",
"=",
"32",
")",
":",
"tries",
"=",
"math",
".",
"floor",
"(",
"tries",
")",
"if",
"tries",
"<",
"1",
":",
"raise",
"ValueError"... | 42.702703 | 0.000619 |
def _wait_for_transfer_threads(self, terminate):
# type: (Uploader, bool) -> None
"""Wait for transfer threads
:param Uploader self: this
:param bool terminate: terminate threads
"""
if terminate:
self._upload_terminate = terminate
for thr in self._tra... | [
"def",
"_wait_for_transfer_threads",
"(",
"self",
",",
"terminate",
")",
":",
"# type: (Uploader, bool) -> None",
"if",
"terminate",
":",
"self",
".",
"_upload_terminate",
"=",
"terminate",
"for",
"thr",
"in",
"self",
".",
"_transfer_threads",
":",
"thr",
".",
"jo... | 34.8 | 0.008403 |
def confirm(statement):
"""Ask the user for confirmation about the specified statement.
Args:
statement (unicode): statement to ask the user confirmation about.
Returns:
bool: whether or not specified statement was confirmed.
"""
prompt = "{statement} [y/n]".format(statement=statem... | [
"def",
"confirm",
"(",
"statement",
")",
":",
"prompt",
"=",
"\"{statement} [y/n]\"",
".",
"format",
"(",
"statement",
"=",
"statement",
")",
"answer",
"=",
"_ask",
"(",
"prompt",
",",
"limited_to",
"=",
"[",
"\"yes\"",
",",
"\"no\"",
",",
"\"y\"",
",",
... | 35 | 0.00232 |
def remove_child(self, label):
"""
Removes node by label
"""
ind = None
for i,c in enumerate(self.children):
if c.label==label:
ind = i
if ind is None:
logging.warning('No child labeled {}.'.format(label))
return
... | [
"def",
"remove_child",
"(",
"self",
",",
"label",
")",
":",
"ind",
"=",
"None",
"for",
"i",
",",
"c",
"in",
"enumerate",
"(",
"self",
".",
"children",
")",
":",
"if",
"c",
".",
"label",
"==",
"label",
":",
"ind",
"=",
"i",
"if",
"ind",
"is",
"N... | 26 | 0.01061 |
def power_on(self, timeout_sec=TIMEOUT_SEC):
"""Power on Bluetooth."""
# Turn on bluetooth and wait for powered on event to be set.
self._powered_on.clear()
IOBluetoothPreferenceSetControllerPowerState(1)
if not self._powered_on.wait(timeout_sec):
raise RuntimeError('... | [
"def",
"power_on",
"(",
"self",
",",
"timeout_sec",
"=",
"TIMEOUT_SEC",
")",
":",
"# Turn on bluetooth and wait for powered on event to be set.",
"self",
".",
"_powered_on",
".",
"clear",
"(",
")",
"IOBluetoothPreferenceSetControllerPowerState",
"(",
"1",
")",
"if",
"no... | 52.142857 | 0.008086 |
def of_file(path: str, root_directory: str = None) -> dict:
"""
Returns a dictionary containing status information for the specified file
including when its name relative to the root directory, when it was last
modified and its size.
:param path:
The absolute path to the file for which the ... | [
"def",
"of_file",
"(",
"path",
":",
"str",
",",
"root_directory",
":",
"str",
"=",
"None",
")",
"->",
"dict",
":",
"slug",
"=",
"(",
"path",
"if",
"root_directory",
"is",
"None",
"else",
"path",
"[",
"len",
"(",
"root_directory",
")",
":",
"]",
".",
... | 31.35 | 0.000773 |
def report_ports(target, ports):
"""portscan a target and output a LaTeX table
report_ports(target, ports) -> string"""
ans, unans = sr(IP(dst=target) / TCP(dport=ports), timeout=5)
rep = "\\begin{tabular}{|r|l|l|}\n\\hline\n"
for s, r in ans:
if not r.haslayer(ICMP):
if r.payload.fl... | [
"def",
"report_ports",
"(",
"target",
",",
"ports",
")",
":",
"ans",
",",
"unans",
"=",
"sr",
"(",
"IP",
"(",
"dst",
"=",
"target",
")",
"/",
"TCP",
"(",
"dport",
"=",
"ports",
")",
",",
"timeout",
"=",
"5",
")",
"rep",
"=",
"\"\\\\begin{tabular}{|... | 42.95 | 0.001139 |
def parse_non_selinux(parts):
"""
Parse part of an ls output line that isn't selinux.
Args:
parts (list): A four element list of strings representing the initial
parts of an ls line after the permission bits. The parts are link
count, owner, group, and everything else.
... | [
"def",
"parse_non_selinux",
"(",
"parts",
")",
":",
"links",
",",
"owner",
",",
"group",
",",
"last",
"=",
"parts",
"result",
"=",
"{",
"\"links\"",
":",
"int",
"(",
"links",
")",
",",
"\"owner\"",
":",
"owner",
",",
"\"group\"",
":",
"group",
",",
"... | 32.790698 | 0.000689 |
def register_game(game_name, game_mode="NoFrameskip-v4"):
"""Create and register problems for the game.
Args:
game_name: str, one of the games in ATARI_GAMES, e.g. "bank_heist".
game_mode: the frame skip and sticky keys config.
Raises:
ValueError: if game_name or game_mode are wrong.
"""
if game... | [
"def",
"register_game",
"(",
"game_name",
",",
"game_mode",
"=",
"\"NoFrameskip-v4\"",
")",
":",
"if",
"game_name",
"not",
"in",
"ATARI_GAMES",
":",
"raise",
"ValueError",
"(",
"\"Game %s not in ATARI_GAMES\"",
"%",
"game_name",
")",
"if",
"game_mode",
"not",
"in"... | 39.473684 | 0.010417 |
def replace_whitespace(text, SAFE_SPACE='|<^>|', insert=True):
"""
Replace non-strippable whitepace in a string with a safe space
"""
if insert:
# replace whitespace with safe space chr
args = (' ', SAFE_SPACE)
else:
# replace safe space chr with whitespace
args = (SA... | [
"def",
"replace_whitespace",
"(",
"text",
",",
"SAFE_SPACE",
"=",
"'|<^>|'",
",",
"insert",
"=",
"True",
")",
":",
"if",
"insert",
":",
"# replace whitespace with safe space chr",
"args",
"=",
"(",
"' '",
",",
"SAFE_SPACE",
")",
"else",
":",
"# replace safe spac... | 32.846154 | 0.002278 |
def max_similarity(context_sentence: str, ambiguous_word: str, option="path",
lemma=True, context_is_lemmatized=False, pos=None, best=True) -> "wn.Synset":
"""
Perform WSD by maximizing the sum of maximum similarity between possible
synsets of all words in the context sentence and the pos... | [
"def",
"max_similarity",
"(",
"context_sentence",
":",
"str",
",",
"ambiguous_word",
":",
"str",
",",
"option",
"=",
"\"path\"",
",",
"lemma",
"=",
"True",
",",
"context_is_lemmatized",
"=",
"False",
",",
"pos",
"=",
"None",
",",
"best",
"=",
"True",
")",
... | 42.657143 | 0.009823 |
def tx_for_tx_hash(self, tx_hash):
"Get a Tx by its hash."
URL = self.api_domain + ("/rawtx/%s?format=hex" % b2h_rev(tx_hash))
tx = Tx.from_hex(urlopen(URL).read().decode("utf8"))
return tx | [
"def",
"tx_for_tx_hash",
"(",
"self",
",",
"tx_hash",
")",
":",
"URL",
"=",
"self",
".",
"api_domain",
"+",
"(",
"\"/rawtx/%s?format=hex\"",
"%",
"b2h_rev",
"(",
"tx_hash",
")",
")",
"tx",
"=",
"Tx",
".",
"from_hex",
"(",
"urlopen",
"(",
"URL",
")",
".... | 43.4 | 0.00905 |
def read_parquet(path, engine="auto", columns=None, **kwargs):
"""Load a parquet object from the file path, returning a DataFrame.
Args:
path: The filepath of the parquet file.
We only support local files for now.
engine: This argument doesn't do anything for now.
kwargs: ... | [
"def",
"read_parquet",
"(",
"path",
",",
"engine",
"=",
"\"auto\"",
",",
"columns",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"DataFrame",
"(",
"query_compiler",
"=",
"BaseFactory",
".",
"read_parquet",
"(",
"path",
"=",
"path",
",",
"col... | 36.214286 | 0.001923 |
def _on_message(channel, method, header, body):
"""
Invoked by pika when a message is delivered from RabbitMQ. The
channel is passed for your convenience. The basic_deliver object that
is passed in carries the exchange, routing key, delivery tag and
a redelivered flag for the message. The properties... | [
"def",
"_on_message",
"(",
"channel",
",",
"method",
",",
"header",
",",
"body",
")",
":",
"print",
"\"Message:\"",
"print",
"\"\\t%r\"",
"%",
"method",
"print",
"\"\\t%r\"",
"%",
"header",
"print",
"\"\\t%r\"",
"%",
"body",
"# Acknowledge message receipt",
"cha... | 37.75 | 0.001076 |
def get_kb_mappings(kb_name="", key="", value="", match_type="s", sortby="to",
limit=None):
"""Return a list of all mappings from the given kb, ordered by key.
If key given, give only those with left side (mapFrom) = key.
If value given, give only those with right side (mapTo) = value.
... | [
"def",
"get_kb_mappings",
"(",
"kb_name",
"=",
"\"\"",
",",
"key",
"=",
"\"\"",
",",
"value",
"=",
"\"\"",
",",
"match_type",
"=",
"\"s\"",
",",
"sortby",
"=",
"\"to\"",
",",
"limit",
"=",
"None",
")",
":",
"# query",
"query",
"=",
"db",
".",
"sessio... | 34.658537 | 0.000684 |
def standardize_table(cls, table):
'''
Extract objects from a Gaia DR2 table.
'''
# tidy up quantities, setting motions to 0 if poorly defined
for key in ['pmra', 'pmdec', 'parallax', 'radial_velocity']:
bad = table[key].mask
table[key][bad] = 0.0
... | [
"def",
"standardize_table",
"(",
"cls",
",",
"table",
")",
":",
"# tidy up quantities, setting motions to 0 if poorly defined",
"for",
"key",
"in",
"[",
"'pmra'",
",",
"'pmdec'",
",",
"'parallax'",
",",
"'radial_velocity'",
"]",
":",
"bad",
"=",
"table",
"[",
"key... | 40.584906 | 0.01044 |
def recRemoveTreeFormating(element):
"""Removes whitespace characters, which are leftovers from previous xml
formatting.
:param element: an instance of lxml.etree._Element
str.strip() is applied to the "text" and the "tail" attribute of the
element and recursively to all child elements.
"""
... | [
"def",
"recRemoveTreeFormating",
"(",
"element",
")",
":",
"children",
"=",
"element",
".",
"getchildren",
"(",
")",
"if",
"len",
"(",
"children",
")",
">",
"0",
":",
"for",
"child",
"in",
"children",
":",
"recRemoveTreeFormating",
"(",
"child",
")",
"if",... | 33.521739 | 0.001261 |
def list_gewesten(self, sort=1):
'''
List all `gewesten` in Belgium.
:param integer sort: What field to sort on.
:rtype: A :class`list` of class: `Gewest`.
'''
def creator():
res = crab_gateway_request(self.client, 'ListGewesten', sort)
tmp = {}
... | [
"def",
"list_gewesten",
"(",
"self",
",",
"sort",
"=",
"1",
")",
":",
"def",
"creator",
"(",
")",
":",
"res",
"=",
"crab_gateway_request",
"(",
"self",
".",
"client",
",",
"'ListGewesten'",
",",
"sort",
")",
"tmp",
"=",
"{",
"}",
"for",
"r",
"in",
... | 33 | 0.002103 |
def xAxisIsMajor(self):
'''
Returns True if the major axis is parallel to the X axis, boolean.
'''
return max(self.radius.x, self.radius.y) == self.radius.x | [
"def",
"xAxisIsMajor",
"(",
"self",
")",
":",
"return",
"max",
"(",
"self",
".",
"radius",
".",
"x",
",",
"self",
".",
"radius",
".",
"y",
")",
"==",
"self",
".",
"radius",
".",
"x"
] | 36.8 | 0.010638 |
def add_row(self, row):
"""Add a row to the table
Arguments:
row - row of data, should be a list with as many elements as the table
has fields"""
if self._field_names and len(row) != len(self._field_names):
raise Exception("Row has incorrect number of values, (act... | [
"def",
"add_row",
"(",
"self",
",",
"row",
")",
":",
"if",
"self",
".",
"_field_names",
"and",
"len",
"(",
"row",
")",
"!=",
"len",
"(",
"self",
".",
"_field_names",
")",
":",
"raise",
"Exception",
"(",
"\"Row has incorrect number of values, (actual) %d!=%d (e... | 37 | 0.013183 |
def p_navigation_step_2(self, p):
'''navigation_step : ARROW identifier LSQBR identifier DOT phrase RSQBR'''
p[0] = NavigationStepNode(key_letter=p[2],
rel_id=p[4],
phrase=p[6]) | [
"def",
"p_navigation_step_2",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"NavigationStepNode",
"(",
"key_letter",
"=",
"p",
"[",
"2",
"]",
",",
"rel_id",
"=",
"p",
"[",
"4",
"]",
",",
"phrase",
"=",
"p",
"[",
"6",
"]",
")"
] | 51.4 | 0.011494 |
def deep_encode(s, encoding='utf-8', errors='strict'):
"""Encode "DEEP" S using the codec registered for encoding."""
# encoding defaults to the default encoding. errors may be given to set
# a different error handling scheme. Default is 'strict' meaning
# that encoding errors raise
# a UnicodeEncod... | [
"def",
"deep_encode",
"(",
"s",
",",
"encoding",
"=",
"'utf-8'",
",",
"errors",
"=",
"'strict'",
")",
":",
"# encoding defaults to the default encoding. errors may be given to set",
"# a different error handling scheme. Default is 'strict' meaning",
"# that encoding errors raise",
... | 44.925926 | 0.000807 |
def _check_modes(self, modes):
"""Check that the image is in one of the given *modes*, raise an exception otherwise."""
if not isinstance(modes, (tuple, list, set)):
modes = [modes]
if self.mode not in modes:
raise ValueError("Image not in suitable mode, expected: %s, got... | [
"def",
"_check_modes",
"(",
"self",
",",
"modes",
")",
":",
"if",
"not",
"isinstance",
"(",
"modes",
",",
"(",
"tuple",
",",
"list",
",",
"set",
")",
")",
":",
"modes",
"=",
"[",
"modes",
"]",
"if",
"self",
".",
"mode",
"not",
"in",
"modes",
":",... | 57 | 0.011527 |
def command(name, nargs=0, complete=None, range=None, count=None, bang=False,
register=False, sync=False, allow_nested=False, eval=None):
"""Tag a function or plugin method as a Nvim command handler."""
def dec(f):
f._nvim_rpc_method_name = 'command:{}'.format(name)
f._nvim_rpc_sync ... | [
"def",
"command",
"(",
"name",
",",
"nargs",
"=",
"0",
",",
"complete",
"=",
"None",
",",
"range",
"=",
"None",
",",
"count",
"=",
"None",
",",
"bang",
"=",
"False",
",",
"register",
"=",
"False",
",",
"sync",
"=",
"False",
",",
"allow_nested",
"="... | 24.977273 | 0.000876 |
def _streaming_file_md5(file_path):
"""
Create and return a hex checksum using the MD5 sum of the passed in file.
This will stream the file, rather than load it all into memory.
:param file_path: full path to the file
:type file_path: string
:returns: a hex checksum
:rtype: string
"""
... | [
"def",
"_streaming_file_md5",
"(",
"file_path",
")",
":",
"md5",
"=",
"hashlib",
".",
"md5",
"(",
")",
"with",
"open",
"(",
"file_path",
",",
"'rb'",
")",
"as",
"f",
":",
"# iter needs an empty byte string for the returned iterator to halt at",
"# EOF",
"for",
"ch... | 34.294118 | 0.001669 |
def write_string_to_file(path, string, make_parents=False, backup_suffix=BACKUP_SUFFIX, encoding="utf8"):
"""
Write entire file with given string contents, atomically. Keeps backup by default.
"""
with atomic_output_file(path, make_parents=make_parents, backup_suffix=backup_suffix) as tmp_path:
with codecs.... | [
"def",
"write_string_to_file",
"(",
"path",
",",
"string",
",",
"make_parents",
"=",
"False",
",",
"backup_suffix",
"=",
"BACKUP_SUFFIX",
",",
"encoding",
"=",
"\"utf8\"",
")",
":",
"with",
"atomic_output_file",
"(",
"path",
",",
"make_parents",
"=",
"make_paren... | 54.428571 | 0.018088 |
def check_slas(metric):
"""
Check if all SLAs pass
:return: 0 (if all SLAs pass) or the number of SLAs failures
"""
if not hasattr(metric, 'sla_map'):
return
for metric_label in metric.sla_map.keys():
for sub_metric in metric.sla_map[metric_label].keys():
for stat_name in metric.sla_map[metric... | [
"def",
"check_slas",
"(",
"metric",
")",
":",
"if",
"not",
"hasattr",
"(",
"metric",
",",
"'sla_map'",
")",
":",
"return",
"for",
"metric_label",
"in",
"metric",
".",
"sla_map",
".",
"keys",
"(",
")",
":",
"for",
"sub_metric",
"in",
"metric",
".",
"sla... | 54.78125 | 0.011771 |
def _validate(self):
"""
Do the actual validation
"""
if self.strictness == 'off':
return self.report
handle_inconsistencies(self.page, self.strictness, self.strategy, self.report)
return self.report | [
"def",
"_validate",
"(",
"self",
")",
":",
"if",
"self",
".",
"strictness",
"==",
"'off'",
":",
"return",
"self",
".",
"report",
"handle_inconsistencies",
"(",
"self",
".",
"page",
",",
"self",
".",
"strictness",
",",
"self",
".",
"strategy",
",",
"self"... | 31.5 | 0.011583 |
def grid_arange(bounds, step):
"""
Return a grid from an (2,dimension) bounds with samples step distance apart.
Parameters
---------
bounds: (2,dimension) list of [[min x, min y, etc], [max x, max y, etc]]
step: float, or (dimension) floats, separation between points
Returns
-------
... | [
"def",
"grid_arange",
"(",
"bounds",
",",
"step",
")",
":",
"bounds",
"=",
"np",
".",
"asanyarray",
"(",
"bounds",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
"if",
"len",
"(",
"bounds",
")",
"!=",
"2",
":",
"raise",
"ValueError",
"(",
"'bounds mus... | 33.307692 | 0.002245 |
def create_class(self, data, options=None, **kwargs):
"""Return instance of class based on Go data
Data keys handled here:
_type
Set the object class
consts, types, vars, funcs
Recurse into :py:meth:`create_class` to create child object
... | [
"def",
"create_class",
"(",
"self",
",",
"data",
",",
"options",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"_type",
"=",
"kwargs",
".",
"get",
"(",
"\"_type\"",
")",
"obj_map",
"=",
"dict",
"(",
"(",
"cls",
".",
"type",
",",
"cls",
")",
"fo... | 39.117647 | 0.000978 |
def validate_password_reset(cls, code, new_password):
"""
Validates an unhashed code against a hashed code.
Once the code has been validated and confirmed
new_password will replace the old users password
"""
password_reset_model = \
PasswordResetModel.w... | [
"def",
"validate_password_reset",
"(",
"cls",
",",
"code",
",",
"new_password",
")",
":",
"password_reset_model",
"=",
"PasswordResetModel",
".",
"where_code",
"(",
"code",
")",
"if",
"password_reset_model",
"is",
"None",
":",
"return",
"None",
"jwt",
"=",
"JWT"... | 41.842105 | 0.00246 |
def pprint_thing(thing, _nest_lvl=0, escape_chars=None, default_escapes=False,
quote_strings=False, max_seq_items=None):
"""
This function is the sanctioned way of converting objects
to a unicode representation.
properly handles nested sequences containing unicode strings
(unicode(... | [
"def",
"pprint_thing",
"(",
"thing",
",",
"_nest_lvl",
"=",
"0",
",",
"escape_chars",
"=",
"None",
",",
"default_escapes",
"=",
"False",
",",
"quote_strings",
"=",
"False",
",",
"max_seq_items",
"=",
"None",
")",
":",
"def",
"as_escaped_unicode",
"(",
"thing... | 37.549296 | 0.000365 |
def convert_registers_to_float(registers):
"""
Convert two 16 Bit Registers to 32 Bit real value - Used to receive float values from Modbus (Modbus Registers are 16 Bit long)
registers: 16 Bit Registers
return: 32 bit value real
"""
b = bytearray(4)
b [0] = registers[0] & 0xff
b [1] = ... | [
"def",
"convert_registers_to_float",
"(",
"registers",
")",
":",
"b",
"=",
"bytearray",
"(",
"4",
")",
"b",
"[",
"0",
"]",
"=",
"registers",
"[",
"0",
"]",
"&",
"0xff",
"b",
"[",
"1",
"]",
"=",
"(",
"registers",
"[",
"0",
"]",
"&",
"0xff00",
")",... | 38.307692 | 0.021569 |
def json_to_string(value, null_string_repr='[]', trimable=False):
"""
Return a string representation of the specified JSON object.
@param value: a JSON object.
@param null_string_rep: the string representation of the null
object.
@return: a string representation of the specified JSON obje... | [
"def",
"json_to_string",
"(",
"value",
",",
"null_string_repr",
"=",
"'[]'",
",",
"trimable",
"=",
"False",
")",
":",
"return",
"null_string_repr",
"if",
"is_undefined",
"(",
"value",
")",
"else",
"obj",
".",
"jsonify",
"(",
"value",
",",
"trimable",
"=",
... | 32.538462 | 0.002299 |
def run_assembly(stmts, folder, pmcid, background_assertions=None):
'''Run assembly on a list of statements, for a given PMCID.'''
# Folder for index card output (scored submission)
indexcard_prefix = folder + '/index_cards/' + pmcid
# Folder for other outputs (for analysis, debugging)
otherout_pref... | [
"def",
"run_assembly",
"(",
"stmts",
",",
"folder",
",",
"pmcid",
",",
"background_assertions",
"=",
"None",
")",
":",
"# Folder for index card output (scored submission)",
"indexcard_prefix",
"=",
"folder",
"+",
"'/index_cards/'",
"+",
"pmcid",
"# Folder for other output... | 37.335938 | 0.000408 |
def merge(self, other):
# type: (TentativeType) -> None
"""
Merge two TentativeType instances
"""
for hashables in other.types_hashable:
self.add(hashables)
for non_hashbles in other.types:
self.add(non_hashbles) | [
"def",
"merge",
"(",
"self",
",",
"other",
")",
":",
"# type: (TentativeType) -> None",
"for",
"hashables",
"in",
"other",
".",
"types_hashable",
":",
"self",
".",
"add",
"(",
"hashables",
")",
"for",
"non_hashbles",
"in",
"other",
".",
"types",
":",
"self",... | 30.666667 | 0.010563 |
def by_water_area_in_sqmi(self,
lower=-1,
upper=2 ** 31,
zipcode_type=ZipcodeType.Standard,
sort_by=SimpleZipcode.water_area_in_sqmi.name,
ascending=False,
... | [
"def",
"by_water_area_in_sqmi",
"(",
"self",
",",
"lower",
"=",
"-",
"1",
",",
"upper",
"=",
"2",
"**",
"31",
",",
"zipcode_type",
"=",
"ZipcodeType",
".",
"Standard",
",",
"sort_by",
"=",
"SimpleZipcode",
".",
"water_area_in_sqmi",
".",
"name",
",",
"asce... | 41.625 | 0.011747 |
def network_set_autostart(name, state='on', **kwargs):
'''
Set the autostart flag on a virtual network so that the network
will start with the host system on reboot.
:param name: virtual network name
:param state: 'on' to auto start the network, anything else to mark the
virtual n... | [
"def",
"network_set_autostart",
"(",
"name",
",",
"state",
"=",
"'on'",
",",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"__get_conn",
"(",
"*",
"*",
"kwargs",
")",
"try",
":",
"net",
"=",
"conn",
".",
"networkLookupByName",
"(",
"name",
")",
"return",
... | 33.692308 | 0.00111 |
def update_preview(self, index=None, scheme_name=None):
"""
Update the color scheme of the preview editor and adds text.
Note
----
'index' is needed, because this is triggered by a signal that sends
the selected index.
"""
text = ('"""A string"""\n\n'
... | [
"def",
"update_preview",
"(",
"self",
",",
"index",
"=",
"None",
",",
"scheme_name",
"=",
"None",
")",
":",
"text",
"=",
"(",
"'\"\"\"A string\"\"\"\\n\\n'",
"'# A comment\\n\\n'",
"'# %% A cell\\n\\n'",
"'class Foo(object):\\n'",
"' def __init__(self):\\n'",
"' ... | 42.1 | 0.001548 |
def validate_args(args):
"""Validate provided arguments and act on --help."""
# Check correctness of similarity dataset names
for dataset_name in args.similarity_datasets:
if dataset_name.lower() not in map(
str.lower,
nlp.data.word_embedding_evaluation.word_similarit... | [
"def",
"validate_args",
"(",
"args",
")",
":",
"# Check correctness of similarity dataset names",
"for",
"dataset_name",
"in",
"args",
".",
"similarity_datasets",
":",
"if",
"dataset_name",
".",
"lower",
"(",
")",
"not",
"in",
"map",
"(",
"str",
".",
"lower",
",... | 44.294118 | 0.0013 |
def date(self,local=False):
""" Return the date object associated
:param local: if False [default] return UTC date. If True return localtz date
"""
return Date(self.get(local).date(),self.local_tz) | [
"def",
"date",
"(",
"self",
",",
"local",
"=",
"False",
")",
":",
"return",
"Date",
"(",
"self",
".",
"get",
"(",
"local",
")",
".",
"date",
"(",
")",
",",
"self",
".",
"local_tz",
")"
] | 45.8 | 0.021459 |
def reftrack_type_data(rt, role):
"""Return the data for the type (e.g. Asset, Alembic, Camera etc)
:param rt: the :class:`jukeboxcore.reftrack.Reftrack` holds the data
:type rt: :class:`jukeboxcore.reftrack.Reftrack`
:param role: item data role
:type role: QtCore.Qt.ItemDataRole
:returns: data... | [
"def",
"reftrack_type_data",
"(",
"rt",
",",
"role",
")",
":",
"if",
"role",
"==",
"QtCore",
".",
"Qt",
".",
"DisplayRole",
"or",
"role",
"==",
"QtCore",
".",
"Qt",
".",
"EditRole",
":",
"return",
"rt",
".",
"get_typ",
"(",
")",
"elif",
"role",
"==",... | 36.466667 | 0.001783 |
def _integerValue_to_int(value_str):
"""
Convert a value string that conforms to DSP0004 `integerValue`, into
the corresponding integer and return it. The returned value has Python
type `int`, or in Python 2, type `long` if needed.
Note that DSP0207 and DSP0004 only allow US-ASCII decimal digits. H... | [
"def",
"_integerValue_to_int",
"(",
"value_str",
")",
":",
"m",
"=",
"BINARY_VALUE",
".",
"match",
"(",
"value_str",
")",
"if",
"m",
":",
"value",
"=",
"int",
"(",
"m",
".",
"group",
"(",
"1",
")",
",",
"2",
")",
"elif",
"OCTAL_VALUE",
".",
"match",
... | 40.222222 | 0.000899 |
def constructor(
self,
name=None,
function=None,
return_type=None,
arg_types=None,
header_dir=None,
header_file=None,
recursive=None):
"""returns reference to constructor declaration, that is matched
defined ... | [
"def",
"constructor",
"(",
"self",
",",
"name",
"=",
"None",
",",
"function",
"=",
"None",
",",
"return_type",
"=",
"None",
",",
"arg_types",
"=",
"None",
",",
"header_dir",
"=",
"None",
",",
"header_file",
"=",
"None",
",",
"recursive",
"=",
"None",
"... | 32.416667 | 0.002497 |
def station_feed(self, *, num_songs=25, num_stations=4):
"""Generate stations.
Note:
A Google Music subscription is required.
Parameters:
num_songs (int, Optional): The total number of songs to return. Default: ``25``
num_stations (int, Optional): The number of stations to return when no station_infos ... | [
"def",
"station_feed",
"(",
"self",
",",
"*",
",",
"num_songs",
"=",
"25",
",",
"num_stations",
"=",
"4",
")",
":",
"response",
"=",
"self",
".",
"_call",
"(",
"mc_calls",
".",
"RadioStationFeed",
",",
"num_entries",
"=",
"num_songs",
",",
"num_stations",
... | 25.565217 | 0.034426 |
def _get_server(self):
"""
Get server to use for request.
Also process inactive server list, re-add them after given interval.
"""
with self._lock:
inactive_server_count = len(self._inactive_servers)
for i in range(inactive_server_count):
t... | [
"def",
"_get_server",
"(",
"self",
")",
":",
"with",
"self",
".",
"_lock",
":",
"inactive_server_count",
"=",
"len",
"(",
"self",
".",
"_inactive_servers",
")",
"for",
"i",
"in",
"range",
"(",
"inactive_server_count",
")",
":",
"try",
":",
"ts",
",",
"se... | 40.25 | 0.001516 |
def create_ngram_table(self, cardinality):
"""
Creates a table for n-gram of a give cardinality. The table name is
constructed from this parameter, for example for cardinality `2` there
will be a table `_2_gram` created.
Parameters
----------
cardinality : int
... | [
"def",
"create_ngram_table",
"(",
"self",
",",
"cardinality",
")",
":",
"query",
"=",
"\"CREATE TABLE IF NOT EXISTS _{0}_gram (\"",
".",
"format",
"(",
"cardinality",
")",
"unique",
"=",
"\"\"",
"for",
"i",
"in",
"reversed",
"(",
"range",
"(",
"cardinality",
")"... | 33.958333 | 0.002387 |
def _dryrun_cell(args, cell_body):
"""Implements the BigQuery cell magic used to dry run BQ queries.
The supported syntax is:
%%bq dryrun [-q|--sql <query identifier>]
[<YAML or JSON cell_body or inline SQL>]
Args:
args: the argument following '%bq dryrun'.
cell_body: optional contents of the cel... | [
"def",
"_dryrun_cell",
"(",
"args",
",",
"cell_body",
")",
":",
"query",
"=",
"_get_query_argument",
"(",
"args",
",",
"cell_body",
",",
"google",
".",
"datalab",
".",
"utils",
".",
"commands",
".",
"notebook_environment",
"(",
")",
")",
"if",
"args",
"[",... | 35.318182 | 0.010025 |
def configure_devel_job(
config_url, rosdistro_name, source_build_name,
repo_name, os_name, os_code_name, arch,
pull_request=False,
config=None, build_file=None,
index=None, dist_file=None, dist_cache=None,
jenkins=None, views=None,
is_disabled=False,
groo... | [
"def",
"configure_devel_job",
"(",
"config_url",
",",
"rosdistro_name",
",",
"source_build_name",
",",
"repo_name",
",",
"os_name",
",",
"os_code_name",
",",
"arch",
",",
"pull_request",
"=",
"False",
",",
"config",
"=",
"None",
",",
"build_file",
"=",
"None",
... | 40.43299 | 0.000249 |
def do_or_fake_filter( value, formatter ):
"""
call a faker if value is None
uses:
{{ myint|or_fake:'randomInt' }}
"""
if not value:
value = Faker.getGenerator().format( formatter )
return value | [
"def",
"do_or_fake_filter",
"(",
"value",
",",
"formatter",
")",
":",
"if",
"not",
"value",
":",
"value",
"=",
"Faker",
".",
"getGenerator",
"(",
")",
".",
"format",
"(",
"formatter",
")",
"return",
"value"
] | 20.545455 | 0.021186 |
def emit(self, record):
"""Save a logging.LogRecord to our test record.
Logs carry useful metadata such as the logger name and level information.
We capture this in a structured format in the test record to enable
filtering by client applications.
Args:
record: A logging.LogRecord to record.... | [
"def",
"emit",
"(",
"self",
",",
"record",
")",
":",
"try",
":",
"message",
"=",
"self",
".",
"format",
"(",
"record",
")",
"log_record",
"=",
"LogRecord",
"(",
"record",
".",
"levelno",
",",
"record",
".",
"name",
",",
"os",
".",
"path",
".",
"bas... | 34.6 | 0.008439 |
def run_sector(sector, C_in, eta_s, f, p_in, p_out, qed_order=1, qcd_order=1):
r"""Solve the WET RGE for a specific sector.
Parameters:
- sector: sector of interest
- C_in: dictionary of Wilson coefficients
- eta_s: ratio of $\alpha_s$ at input and output scale
- f: number of active quark flav... | [
"def",
"run_sector",
"(",
"sector",
",",
"C_in",
",",
"eta_s",
",",
"f",
",",
"p_in",
",",
"p_out",
",",
"qed_order",
"=",
"1",
",",
"qcd_order",
"=",
"1",
")",
":",
"Cdictout",
"=",
"OrderedDict",
"(",
")",
"classname",
"=",
"sectors",
"[",
"sector"... | 38.295455 | 0.001736 |
def check_type_and_size_of_param_list(param_list, expected_length):
"""
Ensure that param_list is a list with the expected length. Raises a helpful
ValueError if this is not the case.
"""
try:
assert isinstance(param_list, list)
assert len(param_list) == expected_length
except As... | [
"def",
"check_type_and_size_of_param_list",
"(",
"param_list",
",",
"expected_length",
")",
":",
"try",
":",
"assert",
"isinstance",
"(",
"param_list",
",",
"list",
")",
"assert",
"len",
"(",
"param_list",
")",
"==",
"expected_length",
"except",
"AssertionError",
... | 35.230769 | 0.002128 |
def calculate_acd(acd_structure, fpf):
"""
Determine the area under the cumulative distribution function of the active framework count, or ACD, of those
actives ranked better than the specified False Postive Fraction.
:param acd_structure: list [(id, best_score, best_query, status, fw smiles), ..., ]. A... | [
"def",
"calculate_acd",
"(",
"acd_structure",
",",
"fpf",
")",
":",
"# initialize variables",
"fw_dict",
"=",
"defaultdict",
"(",
"int",
")",
"# a count of the number of molecules that share a given framework",
"# loop over the molecules in acd_structure and count up the molecules co... | 48.481481 | 0.009738 |
def shift_path(script_name, path_info):
"""Return ('/a', '/b/c') -> ('b', '/a/b', 'c')."""
segment, rest = pop_path(path_info)
return (segment, join_uri(script_name.rstrip("/"), segment), rest.rstrip("/")) | [
"def",
"shift_path",
"(",
"script_name",
",",
"path_info",
")",
":",
"segment",
",",
"rest",
"=",
"pop_path",
"(",
"path_info",
")",
"return",
"(",
"segment",
",",
"join_uri",
"(",
"script_name",
".",
"rstrip",
"(",
"\"/\"",
")",
",",
"segment",
")",
","... | 53.5 | 0.009217 |
def describe(self, name=str(), **options):
""" Returns the **metadata** of a `Field` as an
:class:`ordered dictionary <collections.OrderedDict>`.
.. code-block:: python
metadata = {
'address': self.index.address,
'alignment': [self.alignment.byte_siz... | [
"def",
"describe",
"(",
"self",
",",
"name",
"=",
"str",
"(",
")",
",",
"*",
"*",
"options",
")",
":",
"metadata",
"=",
"{",
"'address'",
":",
"self",
".",
"index",
".",
"address",
",",
"'alignment'",
":",
"list",
"(",
"self",
".",
"alignment",
")"... | 39.444444 | 0.002062 |
def complete(self, flag_message="Complete", padding=None, force=False):
""" Log Level: :attr:COMPLETE
@flag_message: #str flags the message with the given text
using :func:flag
@padding: #str 'top', 'bottom' or 'all', adds a new line to the
specified area... | [
"def",
"complete",
"(",
"self",
",",
"flag_message",
"=",
"\"Complete\"",
",",
"padding",
"=",
"None",
",",
"force",
"=",
"False",
")",
":",
"if",
"self",
".",
"should_log",
"(",
"self",
".",
"COMPLETE",
")",
"or",
"force",
":",
"self",
".",
"_print_me... | 38.115385 | 0.001969 |
def Perc(poly, q, dist, sample=10000, **kws):
"""
Percentile function.
Note that this function is an empirical function that operates using Monte
Carlo sampling.
Args:
poly (Poly):
Polynomial of interest.
q (numpy.ndarray):
positions where percentiles are ta... | [
"def",
"Perc",
"(",
"poly",
",",
"q",
",",
"dist",
",",
"sample",
"=",
"10000",
",",
"*",
"*",
"kws",
")",
":",
"shape",
"=",
"poly",
".",
"shape",
"poly",
"=",
"polynomials",
".",
"flatten",
"(",
"poly",
")",
"q",
"=",
"numpy",
".",
"array",
"... | 29 | 0.002152 |
def openid_form(parser, token):
"""
Render OpenID form. Allows to pre set the provider::
{% openid_form "https://www.google.com/accounts/o8/id" %}
Also creates custom button URLs by concatenating all arguments
after the provider's URL
{% openid_form "https://www.google.com/accounts/o8/id" S... | [
"def",
"openid_form",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"get_bits",
"(",
"token",
")",
"if",
"len",
"(",
"bits",
")",
">",
"1",
":",
"return",
"FormNode",
"(",
"bits",
"[",
"0",
"]",
",",
"bits",
"[",
"1",
":",
"]",
")",
"if",... | 26.05 | 0.011111 |
def from_edf(fname):
"""
DataFrame constructor to open XBT EDF ASCII format.
Examples
--------
>>> from pathlib import Path
>>> import ctd
>>> data_path = Path(__file__).parents[1].joinpath("tests", "data")
>>> cast = ctd.from_edf(data_path.joinpath('XBT.EDF.gz'))
>>> ax = cast['tem... | [
"def",
"from_edf",
"(",
"fname",
")",
":",
"f",
"=",
"_read_file",
"(",
"fname",
")",
"header",
",",
"names",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"k",
",",
"line",
"in",
"enumerate",
"(",
"f",
".",
"readlines",
"(",
")",
")",
":",
"line",
"=",... | 30.040541 | 0.000871 |
def linked(base_dir: str, rr_id: str) -> str:
"""
Get, from the specified directory, the path to the tails file associated with
the input revocation registry identifier, or None for no such file.
:param base_dir: base directory for tails files, thereafter split by cred def id
:p... | [
"def",
"linked",
"(",
"base_dir",
":",
"str",
",",
"rr_id",
":",
"str",
")",
"->",
"str",
":",
"cd_id",
"=",
"rev_reg_id2cred_def_id",
"(",
"rr_id",
")",
"link",
"=",
"join",
"(",
"base_dir",
",",
"cd_id",
",",
"rr_id",
")",
"return",
"join",
"(",
"b... | 46.230769 | 0.008157 |
def load(self):
""" Read pref dict stored on disk. Overwriting current values. """
if VERBOSE_PREF:
print('[pref.load()]')
#if not os.path.exists(self._intern.fpath):
# msg = '[pref] fpath=%r does not exist' % (self._intern.fpath)
# return msg
... | [
"def",
"load",
"(",
"self",
")",
":",
"if",
"VERBOSE_PREF",
":",
"print",
"(",
"'[pref.load()]'",
")",
"#if not os.path.exists(self._intern.fpath):",
"# msg = '[pref] fpath=%r does not exist' % (self._intern.fpath)",
"# return msg",
"fpath",
"=",
"self",
".",
"get_fpath... | 39.444444 | 0.008249 |
def valuePop(ctxt):
"""Pops the top XPath object from the value stack """
if ctxt is None: ctxt__o = None
else: ctxt__o = ctxt._o
ret = libxml2mod.valuePop(ctxt__o)
return ret | [
"def",
"valuePop",
"(",
"ctxt",
")",
":",
"if",
"ctxt",
"is",
"None",
":",
"ctxt__o",
"=",
"None",
"else",
":",
"ctxt__o",
"=",
"ctxt",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"valuePop",
"(",
"ctxt__o",
")",
"return",
"ret"
] | 31.666667 | 0.015385 |
def get_valid_location(location):
"""Check if the given location represents a valid cellular component."""
# If we're given None, return None
if location is not None and cellular_components.get(location) is None:
loc = cellular_components_reverse.get(location)
if loc is None:
rai... | [
"def",
"get_valid_location",
"(",
"location",
")",
":",
"# If we're given None, return None",
"if",
"location",
"is",
"not",
"None",
"and",
"cellular_components",
".",
"get",
"(",
"location",
")",
"is",
"None",
":",
"loc",
"=",
"cellular_components_reverse",
".",
... | 40.1 | 0.002439 |
def _zoom(scale:uniform=1.0, row_pct:uniform=0.5, col_pct:uniform=0.5):
"Zoom image by `scale`. `row_pct`,`col_pct` select focal point of zoom."
s = 1-1/scale
col_c = s * (2*col_pct - 1)
row_c = s * (2*row_pct - 1)
return _get_zoom_mat(1/scale, 1/scale, col_c, row_c) | [
"def",
"_zoom",
"(",
"scale",
":",
"uniform",
"=",
"1.0",
",",
"row_pct",
":",
"uniform",
"=",
"0.5",
",",
"col_pct",
":",
"uniform",
"=",
"0.5",
")",
":",
"s",
"=",
"1",
"-",
"1",
"/",
"scale",
"col_c",
"=",
"s",
"*",
"(",
"2",
"*",
"col_pct",... | 47 | 0.034843 |
def SGg(self):
r'''Specific gravity of the gas phase of the chemical, [dimensionless].
The reference condition is air at 15.6 °C (60 °F) and 1 atm
(rho=1.223 kg/m^3). The definition for gases uses the compressibility
factor of the reference gas and the chemical both at the reference
... | [
"def",
"SGg",
"(",
"self",
")",
":",
"Vmg",
"=",
"self",
".",
"VolumeGas",
"(",
"T",
"=",
"288.70555555555552",
",",
"P",
"=",
"101325",
")",
"if",
"Vmg",
":",
"rho",
"=",
"Vm_to_rho",
"(",
"Vmg",
",",
"self",
".",
"MW",
")",
"return",
"SG",
"(",... | 40.941176 | 0.008427 |
def build_config(dataset, datasets_dir, phase, problem=None, output_dir='data/output'):
"""
root@d3m-example-pod:/# cat /input/185_baseball/test_config.json
{
"problem_schema": "/input/TEST/problem_TEST/problemDoc.json",
"problem_root": "/input/TEST/problem_TEST",
"dataset_schema": "/input... | [
"def",
"build_config",
"(",
"dataset",
",",
"datasets_dir",
",",
"phase",
",",
"problem",
"=",
"None",
",",
"output_dir",
"=",
"'data/output'",
")",
":",
"if",
"problem",
":",
"full_phase",
"=",
"phase",
"+",
"'_'",
"+",
"problem",
"else",
":",
"full_phase... | 38.960784 | 0.000982 |
def write_padding_bits(buff, version, length):
"""\
Writes padding bits if the data stream does not meet the codeword boundary.
:param buff: The byte buffer.
:param int length: Data stream length.
"""
# ISO/IEC 18004:2015(E) - 7.4.10 Bit stream to codeword conversion -- page 32
# [...]
... | [
"def",
"write_padding_bits",
"(",
"buff",
",",
"version",
",",
"length",
")",
":",
"# ISO/IEC 18004:2015(E) - 7.4.10 Bit stream to codeword conversion -- page 32",
"# [...]",
"# All codewords are 8 bits in length, except for the final data symbol",
"# character in Micro QR Code versions M1... | 48.705882 | 0.00237 |
def reg_event(self, flags):
"""
reg events
"""
command = const.CMD_REG_EVENT
command_string = pack ("I", flags)
cmd_response = self.__send_command(command, command_string)
if not cmd_response.get('status'):
raise ZKErrorResponse("cant' reg events %i" %... | [
"def",
"reg_event",
"(",
"self",
",",
"flags",
")",
":",
"command",
"=",
"const",
".",
"CMD_REG_EVENT",
"command_string",
"=",
"pack",
"(",
"\"I\"",
",",
"flags",
")",
"cmd_response",
"=",
"self",
".",
"__send_command",
"(",
"command",
",",
"command_string",... | 35.444444 | 0.009174 |
def list_objects(self, path='', relative=False, first_level=False,
max_request_entries=None):
"""
List objects.
Args:
path (str): Path or URL.
relative (bool): Path is relative to current root.
first_level (bool): It True, returns only fi... | [
"def",
"list_objects",
"(",
"self",
",",
"path",
"=",
"''",
",",
"relative",
"=",
"False",
",",
"first_level",
"=",
"False",
",",
"max_request_entries",
"=",
"None",
")",
":",
"entries",
"=",
"0",
"max_request_entries_arg",
"=",
"None",
"if",
"not",
"relat... | 32.016807 | 0.001018 |
def post(self, request, *args, **kwargs):
""" Handles POST requests. """
return self.lock(request, *args, **kwargs) | [
"def",
"post",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"lock",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 43 | 0.015267 |
def run_incremental(components=None, broker=None):
"""
Executes components in an order that satisfies their dependency
relationships. Disjoint subgraphs are executed one at a time and a broker
containing the results for each is yielded. If a broker is passed here, its
instances are used to seed the ... | [
"def",
"run_incremental",
"(",
"components",
"=",
"None",
",",
"broker",
"=",
"None",
")",
":",
"for",
"graph",
",",
"_broker",
"in",
"generate_incremental",
"(",
"components",
",",
"broker",
")",
":",
"yield",
"run",
"(",
"graph",
",",
"broker",
"=",
"_... | 47.952381 | 0.000974 |
def get_word_under_cursor_legacy(self):
"""
Returns the document word under cursor ( Using Qt legacy "QTextCursor.WordUnderCursor" ).
:return: Word under cursor.
:rtype: QString
"""
cursor = self.textCursor()
cursor.select(QTextCursor.WordUnderCursor)
re... | [
"def",
"get_word_under_cursor_legacy",
"(",
"self",
")",
":",
"cursor",
"=",
"self",
".",
"textCursor",
"(",
")",
"cursor",
".",
"select",
"(",
"QTextCursor",
".",
"WordUnderCursor",
")",
"return",
"cursor",
".",
"selectedText",
"(",
")"
] | 30.545455 | 0.008671 |
def deterministic(__func__=None, **kwds):
"""
Decorator function instantiating deterministic variables. Usage:
@deterministic
def B(parent_name = ., ...)
return baz(parent_name, ...)
@deterministic(trace = trace_object)
def B(parent_name = ., ...)
return baz(parent_name, ...)
... | [
"def",
"deterministic",
"(",
"__func__",
"=",
"None",
",",
"*",
"*",
"kwds",
")",
":",
"def",
"instantiate_n",
"(",
"__func__",
")",
":",
"junk",
",",
"parents",
"=",
"_extract",
"(",
"__func__",
",",
"kwds",
",",
"keys",
",",
"'Deterministic'",
",",
"... | 25.46875 | 0.001182 |
def copy_binder_files(app, exception):
"""Copy all Binder requirements and notebooks files."""
if exception is not None:
return
if app.builder.name not in ['html', 'readthedocs']:
return
gallery_conf = app.config.sphinx_gallery_conf
binder_conf = check_binder_conf(gallery_conf.get(... | [
"def",
"copy_binder_files",
"(",
"app",
",",
"exception",
")",
":",
"if",
"exception",
"is",
"not",
"None",
":",
"return",
"if",
"app",
".",
"builder",
".",
"name",
"not",
"in",
"[",
"'html'",
",",
"'readthedocs'",
"]",
":",
"return",
"gallery_conf",
"="... | 29.470588 | 0.001934 |
def delete_queue(name, region, opts=None, user=None):
'''
Deletes a queue in the region.
name
Name of the SQS queue to deletes
region
Name of the region to delete the queue from
opts : None
Any additional options to add to the command line
user : None
Run hg as... | [
"def",
"delete_queue",
"(",
"name",
",",
"region",
",",
"opts",
"=",
"None",
",",
"user",
"=",
"None",
")",
":",
"queues",
"=",
"list_queues",
"(",
"region",
",",
"opts",
",",
"user",
")",
"url_map",
"=",
"_parse_queue_list",
"(",
"queues",
")",
"log",... | 21.291667 | 0.000935 |
def p_relate_statement_2(self, p):
'''statement : RELATE instance_name TO instance_name ACROSS rel_id DOT phrase'''
p[0] = RelateNode(from_variable_name=p[2],
to_variable_name=p[4],
rel_id=p[6],
phrase=p[8]) | [
"def",
"p_relate_statement_2",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"RelateNode",
"(",
"from_variable_name",
"=",
"p",
"[",
"2",
"]",
",",
"to_variable_name",
"=",
"p",
"[",
"4",
"]",
",",
"rel_id",
"=",
"p",
"[",
"6",
"]",
"... | 49.333333 | 0.009967 |
def interjoint_paths(self):
"""
Returns paths between the adjacent critical points
in the skeleton, where a critical point is the set of
terminal and branch points.
"""
paths = []
for tree in self.components():
subpaths = self._single_tree_interjoint_paths(tree)
paths.extend(subp... | [
"def",
"interjoint_paths",
"(",
"self",
")",
":",
"paths",
"=",
"[",
"]",
"for",
"tree",
"in",
"self",
".",
"components",
"(",
")",
":",
"subpaths",
"=",
"self",
".",
"_single_tree_interjoint_paths",
"(",
"tree",
")",
"paths",
".",
"extend",
"(",
"subpat... | 27.666667 | 0.008746 |
def main():
"""Main."""
if len(sys.argv) > 1 and os.path.exists(sys.argv[1]):
try:
with open(sys.argv[1], 'r') as f:
user_name, password = f.read().strip().split(':')
git = Github(user_name, password)
password = None
except Exception:
... | [
"def",
"main",
"(",
")",
":",
"if",
"len",
"(",
"sys",
".",
"argv",
")",
">",
"1",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"sys",
".",
"argv",
"[",
"1",
"]",
")",
":",
"try",
":",
"with",
"open",
"(",
"sys",
".",
"argv",
"[",
"1",
"... | 26.73913 | 0.00157 |
def cli(sample, dry_run, limit, no_limit,
database_filename, template_filename, config_filename):
"""Command line interface."""
# pylint: disable=too-many-arguments
mailmerge.api.main(
sample=sample,
dry_run=dry_run,
limit=limit,
no_limit=no_limit,
database_fi... | [
"def",
"cli",
"(",
"sample",
",",
"dry_run",
",",
"limit",
",",
"no_limit",
",",
"database_filename",
",",
"template_filename",
",",
"config_filename",
")",
":",
"# pylint: disable=too-many-arguments",
"mailmerge",
".",
"api",
".",
"main",
"(",
"sample",
"=",
"s... | 32.692308 | 0.002288 |
def GetVmodlType(name):
""" Get type from vmodl name """
# If the input is already a type, just return
if isinstance(name, type):
return name
# Try to get type from vmodl type names table
typ = vmodlTypes.get(name)
if typ:
return typ
# Else get the type from the _wsdlTypeMap
isArr... | [
"def",
"GetVmodlType",
"(",
"name",
")",
":",
"# If the input is already a type, just return",
"if",
"isinstance",
"(",
"name",
",",
"type",
")",
":",
"return",
"name",
"# Try to get type from vmodl type names table",
"typ",
"=",
"vmodlTypes",
".",
"get",
"(",
"name",... | 23.08 | 0.036606 |
def set_object(cache, template, indexes, data):
"""Set an object in Redis using a pipeline.
Only sets the fields that are present in both the template and the data.
Arguments:
template: a dictionary containg the keys for the object and
template strings for the corresponding redis keys.... | [
"def",
"set_object",
"(",
"cache",
",",
"template",
",",
"indexes",
",",
"data",
")",
":",
"# TODO(mattmillr): Handle expiration times",
"with",
"cache",
"as",
"redis_connection",
":",
"pipe",
"=",
"redis_connection",
".",
"pipeline",
"(",
")",
"for",
"key",
"in... | 30.921053 | 0.000825 |
def set_var(var, value):
'''
Set a variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_var 'LINGUAS' 'en'
... | [
"def",
"set_var",
"(",
"var",
",",
"value",
")",
":",
"makeconf",
"=",
"_get_makeconf",
"(",
")",
"old_value",
"=",
"get_var",
"(",
"var",
")",
"# If var already in file, replace its value",
"if",
"old_value",
"is",
"not",
"None",
":",
"__salt__",
"[",
"'file.... | 23.275862 | 0.001422 |
def print_diff(diff, color=True):
"""Pretty printing for a diff, if color then we use a simple color scheme
(red for removed lines, green for added lines)."""
import colorama
if not diff:
return
if not color:
colorama.init = lambda autoreset: None
colorama.Fore.RED = ''
... | [
"def",
"print_diff",
"(",
"diff",
",",
"color",
"=",
"True",
")",
":",
"import",
"colorama",
"if",
"not",
"diff",
":",
"return",
"if",
"not",
"color",
":",
"colorama",
".",
"init",
"=",
"lambda",
"autoreset",
":",
"None",
"colorama",
".",
"Fore",
".",
... | 38.777778 | 0.002096 |
def has_fun_prop(f, k):
"""Test whether function `f` has property `k`.
We define properties as annotations added to a function throughout
the process of defining a function for verification, e.g. the
argument types. If `f` is an unannotated function, this returns
False. If `f` has the property na... | [
"def",
"has_fun_prop",
"(",
"f",
",",
"k",
")",
":",
"if",
"not",
"hasattr",
"(",
"f",
",",
"_FUN_PROPS",
")",
":",
"return",
"False",
"if",
"not",
"isinstance",
"(",
"getattr",
"(",
"f",
",",
"_FUN_PROPS",
")",
",",
"dict",
")",
":",
"return",
"Fa... | 35.444444 | 0.001527 |
def stack_reparameterization_layer(self, layer_size):
"""
Perform reparameterization trick for latent variables.
:param layer_size: the size of latent variable
"""
self.rep_layer = ReparameterizationLayer(layer_size, sample=self.sample)
self.stack_encoders(self.rep_layer) | [
"def",
"stack_reparameterization_layer",
"(",
"self",
",",
"layer_size",
")",
":",
"self",
".",
"rep_layer",
"=",
"ReparameterizationLayer",
"(",
"layer_size",
",",
"sample",
"=",
"self",
".",
"sample",
")",
"self",
".",
"stack_encoders",
"(",
"self",
".",
"re... | 44.857143 | 0.009375 |
def count_matrix(self):
# TODO: does this belong here or to the BHMM sampler, or in a subclass containing HMM with data?
"""Compute the transition count matrix from hidden state trajectory.
Returns
-------
C : numpy.array with shape (nstates,nstates)
C[i,j] is the nu... | [
"def",
"count_matrix",
"(",
"self",
")",
":",
"# TODO: does this belong here or to the BHMM sampler, or in a subclass containing HMM with data?",
"if",
"self",
".",
"hidden_state_trajectories",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"'HMM model does not have a hidden stat... | 35.73913 | 0.009479 |
def get_parquet_metadata(
self,
path='.'
):
"""
OUTPUT PARQUET METADATA COLUMNS
:param path: FOR INTERNAL USE
:return: LIST OF SchemaElement
"""
children = []
for name, child_schema in sort_using_key(self.more.items(), lambda p: p[0]):
... | [
"def",
"get_parquet_metadata",
"(",
"self",
",",
"path",
"=",
"'.'",
")",
":",
"children",
"=",
"[",
"]",
"for",
"name",
",",
"child_schema",
"in",
"sort_using_key",
"(",
"self",
".",
"more",
".",
"items",
"(",
")",
",",
"lambda",
"p",
":",
"p",
"[",... | 30.5 | 0.008834 |
def events():
'''Serve a JSON representation of events
'''
db = get_session()
upcoming_events = db.query(UpcomingEvent)\
.order_by(UpcomingEvent.start)
recorded_events = db.query(RecordedEvent)\
.order_by(RecordedEvent.start.desc())
result = [even... | [
"def",
"events",
"(",
")",
":",
"db",
"=",
"get_session",
"(",
")",
"upcoming_events",
"=",
"db",
".",
"query",
"(",
"UpcomingEvent",
")",
".",
"order_by",
"(",
"UpcomingEvent",
".",
"start",
")",
"recorded_events",
"=",
"db",
".",
"query",
"(",
"Recorde... | 37.75 | 0.002155 |
def get_uid(user=None):
'''
Get the uid for a given user name. If no user given, the current euid will
be returned. If the user does not exist, None will be returned. On systems
which do not support pwd or os.geteuid, None will be returned.
'''
if not HAS_PWD:
return None
elif user i... | [
"def",
"get_uid",
"(",
"user",
"=",
"None",
")",
":",
"if",
"not",
"HAS_PWD",
":",
"return",
"None",
"elif",
"user",
"is",
"None",
":",
"try",
":",
"return",
"os",
".",
"geteuid",
"(",
")",
"except",
"AttributeError",
":",
"return",
"None",
"else",
"... | 29.277778 | 0.001838 |
def from_dict(data, ctx):
"""
Instantiate a new PositionSide from a dict (generally from loading a
JSON response). The data used to instantiate the PositionSide is a
shallow copy of the dict passed in, with any complex child types
instantiated appropriately.
"""
... | [
"def",
"from_dict",
"(",
"data",
",",
"ctx",
")",
":",
"data",
"=",
"data",
".",
"copy",
"(",
")",
"if",
"data",
".",
"get",
"(",
"'units'",
")",
"is",
"not",
"None",
":",
"data",
"[",
"'units'",
"]",
"=",
"ctx",
".",
"convert_decimal_number",
"(",... | 31.468085 | 0.001967 |
def m(self, msg,
state=False, more=None, cmdd=None, critical=True, verbose=None):
'''
Mysterious mega method managing multiple meshed modules magically
.. note:: If this function is used, the code contains facepalms: ``m(``
* It is possible to just show a message, \
o... | [
"def",
"m",
"(",
"self",
",",
"msg",
",",
"state",
"=",
"False",
",",
"more",
"=",
"None",
",",
"cmdd",
"=",
"None",
",",
"critical",
"=",
"True",
",",
"verbose",
"=",
"None",
")",
":",
"if",
"verbose",
"is",
"None",
":",
"verbose",
"=",
"self",
... | 35.142857 | 0.001078 |
def loads(self, s):
"""
Deserializes a string representation of the object.
:param s: the string
"""
f = io.BytesIO(s)
return VaultUnpickler(self, f).load() | [
"def",
"loads",
"(",
"self",
",",
"s",
")",
":",
"f",
"=",
"io",
".",
"BytesIO",
"(",
"s",
")",
"return",
"VaultUnpickler",
"(",
"self",
",",
"f",
")",
".",
"load",
"(",
")"
] | 24.75 | 0.009756 |
def split_marker(marker, fg_id = 1, bg_id = 2):
"""
Splits an integer marker image into two binary image containing the foreground and
background markers respectively.
All encountered 1's are hereby treated as foreground, all 2's as background, all 0's
as neutral marker and all others are ignored.
... | [
"def",
"split_marker",
"(",
"marker",
",",
"fg_id",
"=",
"1",
",",
"bg_id",
"=",
"2",
")",
":",
"img_marker",
"=",
"scipy",
".",
"asarray",
"(",
"marker",
")",
"img_fgmarker",
"=",
"scipy",
".",
"zeros",
"(",
"img_marker",
".",
"shape",
",",
"scipy",
... | 33.645161 | 0.012116 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.