text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def incoming_args(self, nodeid):
"""
Return the arguments that target *nodeid*.
Valid arguments include regular variable arguments and scopal
(label-selecting or HCONS) arguments. MOD/EQ
links and intrinsic arguments are not included.
Args:
nodeid: the nodei... | [
"def",
"incoming_args",
"(",
"self",
",",
"nodeid",
")",
":",
"_vars",
"=",
"self",
".",
"_vars",
"ep",
"=",
"self",
".",
"_eps",
"[",
"nodeid",
"]",
"lbl",
"=",
"ep",
"[",
"2",
"]",
"iv",
"=",
"ep",
"[",
"3",
"]",
".",
"get",
"(",
"IVARG_ROLE"... | 36.815789 | 15.131579 |
def process(self):
"""Construct and start a new File hunt.
Raises:
RuntimeError: if no items specified for collection.
"""
hunt = self.grr_api.Hunt(self.hunt_id).Get()
self.state.output = self.collect_hunt_results(hunt) | [
"def",
"process",
"(",
"self",
")",
":",
"hunt",
"=",
"self",
".",
"grr_api",
".",
"Hunt",
"(",
"self",
".",
"hunt_id",
")",
".",
"Get",
"(",
")",
"self",
".",
"state",
".",
"output",
"=",
"self",
".",
"collect_hunt_results",
"(",
"hunt",
")"
] | 29.875 | 16.375 |
def standard(model, **kwargs):
"""
Create standard model of molecular evolution.
Parameters
----------
model : str
Model to create. See list of available models below
**kwargs:
Key word arguments to be passed to the model
**Available ... | [
"def",
"standard",
"(",
"model",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
"nuc_models",
"import",
"JC69",
",",
"K80",
",",
"F81",
",",
"HKY85",
",",
"T92",
",",
"TN93",
"from",
".",
"aa_models",
"import",
"JTT92",
"if",
"model",
".",
"lower",
... | 36.439716 | 31.588652 |
def add_document(self, item_uri, name, metadata,
content=None, docurl=None, file=None,
displaydoc=False, preferName=False,
contrib_id=None):
"""Add a document to an existing item
:param item_uri: the URI that references the item
:ty... | [
"def",
"add_document",
"(",
"self",
",",
"item_uri",
",",
"name",
",",
"metadata",
",",
"content",
"=",
"None",
",",
"docurl",
"=",
"None",
",",
"file",
"=",
"None",
",",
"displaydoc",
"=",
"False",
",",
"preferName",
"=",
"False",
",",
"contrib_id",
"... | 34.725 | 23 |
def main(self, *directories):
"""
The actual logic that runs the linters
"""
if not self.git and len(directories) == 0:
print ("ERROR: At least one directory must be provided (or the "
"--git-precommit flag must be passed.\n")
self.help()
... | [
"def",
"main",
"(",
"self",
",",
"*",
"directories",
")",
":",
"if",
"not",
"self",
".",
"git",
"and",
"len",
"(",
"directories",
")",
"==",
"0",
":",
"print",
"(",
"\"ERROR: At least one directory must be provided (or the \"",
"\"--git-precommit flag must be passed... | 39 | 20.135135 |
def toplevel_packages():
""" Get package list, without sub-packages.
"""
packages = set(easy.options.setup.packages)
for pkg in list(packages):
packages -= set(p for p in packages if str(p).startswith(pkg + '.'))
return list(sorted(packages)) | [
"def",
"toplevel_packages",
"(",
")",
":",
"packages",
"=",
"set",
"(",
"easy",
".",
"options",
".",
"setup",
".",
"packages",
")",
"for",
"pkg",
"in",
"list",
"(",
"packages",
")",
":",
"packages",
"-=",
"set",
"(",
"p",
"for",
"p",
"in",
"packages"... | 37.714286 | 10.857143 |
def main_photo(self):
"""Return user's main photo."""
if not self._main_photo:
self._main_photo = self.photos_factory()
return self._main_photo | [
"def",
"main_photo",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_main_photo",
":",
"self",
".",
"_main_photo",
"=",
"self",
".",
"photos_factory",
"(",
")",
"return",
"self",
".",
"_main_photo"
] | 35 | 9.6 |
def read(self, pin):
""" Read the pin state of an input pin.
Make sure you put the pin in input modus with the IODIR* register or direction_* attribute first.
:Example:
>>> expander = MCP23017I2C(gw)
>>> # Read the logic level on pin B3
>>> expander.read('B3')
F... | [
"def",
"read",
"(",
"self",
",",
"pin",
")",
":",
"port",
",",
"pin",
"=",
"self",
".",
"pin_to_port",
"(",
"pin",
")",
"self",
".",
"i2c_write",
"(",
"[",
"0x12",
"+",
"port",
"]",
")",
"raw",
"=",
"self",
".",
"i2c_read",
"(",
"1",
")",
"valu... | 32.5 | 16.409091 |
def _characteristics_discovered(self, service):
"""Called when GATT characteristics have been discovered."""
# Characteristics for the specified service were discovered. Update
# set of discovered services and signal when all have been discovered.
self._discovered_services.add(service)
... | [
"def",
"_characteristics_discovered",
"(",
"self",
",",
"service",
")",
":",
"# Characteristics for the specified service were discovered. Update",
"# set of discovered services and signal when all have been discovered.",
"self",
".",
"_discovered_services",
".",
"add",
"(",
"servic... | 60.777778 | 19 |
def write_haxis_pdb(self, filename='helical_axis.pdb', step_range=False, step=None, write_smooth_axis=True, write_orig_axis=False, write_curv=False, scale_curv=1):
"""To write trajectory of helcial-axis as a PDB format file.
Both local helical axis and global (smoothed) axis can be written to PDB file.... | [
"def",
"write_haxis_pdb",
"(",
"self",
",",
"filename",
"=",
"'helical_axis.pdb'",
",",
"step_range",
"=",
"False",
",",
"step",
"=",
"None",
",",
"write_smooth_axis",
"=",
"True",
",",
"write_orig_axis",
"=",
"False",
",",
"write_curv",
"=",
"False",
",",
"... | 39.928571 | 25.935065 |
def detect_ts(df, max_anoms=0.10, direction='pos',
alpha=0.05, only_last=None, threshold=None,
e_value=False, longterm=False,
piecewise_median_period_weeks=2, plot=False,
y_log=False, xlabel = '', ylabel = 'count',
title=None, verbose=False):
"""... | [
"def",
"detect_ts",
"(",
"df",
",",
"max_anoms",
"=",
"0.10",
",",
"direction",
"=",
"'pos'",
",",
"alpha",
"=",
"0.05",
",",
"only_last",
"=",
"None",
",",
"threshold",
"=",
"None",
",",
"e_value",
"=",
"False",
",",
"longterm",
"=",
"False",
",",
"... | 38.45625 | 24.4125 |
def get_fields(catalog, filter_in=None, filter_out=None, meta_field=None,
only_time_series=False, distribution_identifier=None):
"""Devuelve lista de campos del catálogo o de uno de sus metadatos.
Args:
catalog (dict, str or DataJson): Representación externa/interna de un
cat... | [
"def",
"get_fields",
"(",
"catalog",
",",
"filter_in",
"=",
"None",
",",
"filter_out",
"=",
"None",
",",
"meta_field",
"=",
"None",
",",
"only_time_series",
"=",
"False",
",",
"distribution_identifier",
"=",
"None",
")",
":",
"filter_in",
"=",
"filter_in",
"... | 44.907895 | 21.644737 |
def trades(self, symbol='btcusd', since=0, limit_trades=50,
include_breaks=0):
"""
Send a request to get all public trades, return the response.
Arguments:
symbol -- currency symbol (default 'btcusd')
since -- only return trades after this unix timestamp (default ... | [
"def",
"trades",
"(",
"self",
",",
"symbol",
"=",
"'btcusd'",
",",
"since",
"=",
"0",
",",
"limit_trades",
"=",
"50",
",",
"include_breaks",
"=",
"0",
")",
":",
"url",
"=",
"self",
".",
"base_url",
"+",
"'/v1/trades/'",
"+",
"symbol",
"params",
"=",
... | 37 | 18.473684 |
def create_folder(self, name, parent_folder_id=0):
"""Create a folder
If the folder exists, a BoxError will be raised.
Args:
folder_id (int): Name of the folder.
parent_folder_id (int): ID of the folder where to create the new one.
Returns:
dict. R... | [
"def",
"create_folder",
"(",
"self",
",",
"name",
",",
"parent_folder_id",
"=",
"0",
")",
":",
"return",
"self",
".",
"__request",
"(",
"\"POST\"",
",",
"\"folders\"",
",",
"data",
"=",
"{",
"\"name\"",
":",
"name",
",",
"\"parent\"",
":",
"{",
"\"id\"",... | 31.913043 | 25.086957 |
def convert_value_to_standard_unit(value, symbol='i'):
# type: (Text, Text) -> float
"""
Converts between any two standard units of iota.
:param value:
Value (affixed) to convert. For example: '1.618 Mi'.
:param symbol:
Unit symbol of iota to convert to. For example: 'Gi'.
:re... | [
"def",
"convert_value_to_standard_unit",
"(",
"value",
",",
"symbol",
"=",
"'i'",
")",
":",
"# type: (Text, Text) -> float",
"try",
":",
"# Get input value",
"value_tuple",
"=",
"value",
".",
"split",
"(",
")",
"amount",
"=",
"float",
"(",
"value_tuple",
"[",
"0... | 27.727273 | 19.136364 |
def RecurseKeys(self):
"""Recurses the subkeys starting with the key.
Yields:
WinRegistryKey: Windows Registry key.
"""
yield self
for subkey in self.GetSubkeys():
for key in subkey.RecurseKeys():
yield key | [
"def",
"RecurseKeys",
"(",
"self",
")",
":",
"yield",
"self",
"for",
"subkey",
"in",
"self",
".",
"GetSubkeys",
"(",
")",
":",
"for",
"key",
"in",
"subkey",
".",
"RecurseKeys",
"(",
")",
":",
"yield",
"key"
] | 23.8 | 14.5 |
def _execute_cell_code(self, row, col, grid):
"""Executes cell code"""
key = row, col, grid.current_table
grid.code_array[key]
grid.ForceRefresh() | [
"def",
"_execute_cell_code",
"(",
"self",
",",
"row",
",",
"col",
",",
"grid",
")",
":",
"key",
"=",
"row",
",",
"col",
",",
"grid",
".",
"current_table",
"grid",
".",
"code_array",
"[",
"key",
"]",
"grid",
".",
"ForceRefresh",
"(",
")"
] | 24.857143 | 16 |
def check_answer(self, task_input, language):
"""
Verify the answers in task_input. Returns six values
1st: True the input is **currently** valid. (may become invalid after running the code), False else
2nd: True if the input needs to be run in the VM, False else
... | [
"def",
"check_answer",
"(",
"self",
",",
"task_input",
",",
"language",
")",
":",
"valid",
"=",
"True",
"need_launch",
"=",
"False",
"main_message",
"=",
"[",
"]",
"problem_messages",
"=",
"{",
"}",
"error_count",
"=",
"0",
"multiple_choice_error_count",
"=",
... | 56.172414 | 25.344828 |
def stddev_samples(data, xcol, ycollist, delta=1.0):
"""Create a sample list that contains the mean and standard deviation of the original list. Each element in the returned list contains following values: [MEAN, STDDEV, MEAN - STDDEV*delta, MEAN + STDDEV*delta].
>>> chart_data.stddev_samples([ [1, 10, 15, 12, 15]... | [
"def",
"stddev_samples",
"(",
"data",
",",
"xcol",
",",
"ycollist",
",",
"delta",
"=",
"1.0",
")",
":",
"out",
"=",
"[",
"]",
"numcol",
"=",
"len",
"(",
"ycollist",
")",
"try",
":",
"for",
"elem",
"in",
"data",
":",
"total",
"=",
"0",
"for",
"col... | 48 | 30.52 |
def get_merkle_proof(self, tx_hash: str, is_full: bool = False) -> dict:
"""
This interface is used to get the corresponding merkle proof based on the specified hexadecimal hash value.
:param tx_hash: an hexadecimal transaction hash value.
:param is_full:
:return: the merkle pro... | [
"def",
"get_merkle_proof",
"(",
"self",
",",
"tx_hash",
":",
"str",
",",
"is_full",
":",
"bool",
"=",
"False",
")",
"->",
"dict",
":",
"payload",
"=",
"self",
".",
"generate_json_rpc_payload",
"(",
"RpcMethod",
".",
"GET_MERKLE_PROOF",
",",
"[",
"tx_hash",
... | 43.615385 | 23.153846 |
def list(self, product, store_view=None, identifierType=None):
"""
Retrieve product image list
:param product: ID or SKU of product
:param store_view: Code or ID of store view
:param identifierType: Defines whether the product or SKU value is
passe... | [
"def",
"list",
"(",
"self",
",",
"product",
",",
"store_view",
"=",
"None",
",",
"identifierType",
"=",
"None",
")",
":",
"return",
"self",
".",
"call",
"(",
"'catalog_product_attribute_media.list'",
",",
"[",
"product",
",",
"store_view",
",",
"identifierType... | 38.769231 | 17.384615 |
def _netstat_sunos():
'''
Return netstat information for SunOS flavors
'''
log.warning('User and program not (yet) supported on SunOS')
ret = []
for addr_family in ('inet', 'inet6'):
# Lookup TCP connections
cmd = 'netstat -f {0} -P tcp -an | tail +5'.format(addr_family)
... | [
"def",
"_netstat_sunos",
"(",
")",
":",
"log",
".",
"warning",
"(",
"'User and program not (yet) supported on SunOS'",
")",
"ret",
"=",
"[",
"]",
"for",
"addr_family",
"in",
"(",
"'inet'",
",",
"'inet6'",
")",
":",
"# Lookup TCP connections",
"cmd",
"=",
"'netst... | 37.419355 | 17.032258 |
def _clean_dict(row):
"""
Transform empty strings values of dict `row` to None.
"""
row_cleaned = {}
for key, val in row.items():
if val is None or val == '':
row_cleaned[key] = None
else:
row_cleaned[key] = val
return row_cleaned | [
"def",
"_clean_dict",
"(",
"row",
")",
":",
"row_cleaned",
"=",
"{",
"}",
"for",
"key",
",",
"val",
"in",
"row",
".",
"items",
"(",
")",
":",
"if",
"val",
"is",
"None",
"or",
"val",
"==",
"''",
":",
"row_cleaned",
"[",
"key",
"]",
"=",
"None",
... | 25.818182 | 11.272727 |
def branchlist2branches(data, commdct, branchlist):
"""get branches from the branchlist"""
objkey = 'BranchList'.upper()
theobjects = data.dt[objkey]
fieldlists = []
objnames = [obj[1] for obj in theobjects]
for theobject in theobjects:
fieldlists.append(list(range(2, len(theobject))))
... | [
"def",
"branchlist2branches",
"(",
"data",
",",
"commdct",
",",
"branchlist",
")",
":",
"objkey",
"=",
"'BranchList'",
".",
"upper",
"(",
")",
"theobjects",
"=",
"data",
".",
"dt",
"[",
"objkey",
"]",
"fieldlists",
"=",
"[",
"]",
"objnames",
"=",
"[",
... | 42.416667 | 12.083333 |
def stop(self):
"""
The client stop method. If the client is currently connected
stop the thread and disconnect. Publish the disconnected
message if clean shutdown.
"""
# self.loop.call_soon_threadsafe(self.loop.stop)
# self.loop.stop()
# self._longPoll.ca... | [
"def",
"stop",
"(",
"self",
")",
":",
"# self.loop.call_soon_threadsafe(self.loop.stop)",
"# self.loop.stop()",
"# self._longPoll.cancel()",
"# self._shortPoll.cancel()",
"if",
"self",
".",
"connected",
":",
"LOGGER",
".",
"info",
"(",
"'Disconnecting from MQTT... {}:{}'",
".... | 43.3 | 19.7 |
def _wrap_data(data: Union[str, bytes]):
"""
Wraps data into the right event.
"""
MsgType = TextMessage if isinstance(data, str) else BytesMessage
return MsgType(data=data, frame_finished=True, message_finished=True) | [
"def",
"_wrap_data",
"(",
"data",
":",
"Union",
"[",
"str",
",",
"bytes",
"]",
")",
":",
"MsgType",
"=",
"TextMessage",
"if",
"isinstance",
"(",
"data",
",",
"str",
")",
"else",
"BytesMessage",
"return",
"MsgType",
"(",
"data",
"=",
"data",
",",
"frame... | 41.833333 | 11.5 |
def totext(self) ->str:
"""
return blob content from StorageBlobModel instance to a string. Parameters are:
"""
sreturn = ''
if self.properties.content_settings.content_encoding is None:
raise AzureStorageWrapException(self, 'can not convert blob {!s} to text because... | [
"def",
"totext",
"(",
"self",
")",
"->",
"str",
":",
"sreturn",
"=",
"''",
"if",
"self",
".",
"properties",
".",
"content_settings",
".",
"content_encoding",
"is",
"None",
":",
"raise",
"AzureStorageWrapException",
"(",
"self",
",",
"'can not convert blob {!s} t... | 45.545455 | 32.909091 |
def encodeIntoArray(self, x, output):
""" See method description in base.py """
if x is not None and not isinstance(x, numbers.Number):
raise TypeError(
"Expected a scalar input but got input of type %s" % type(x))
# Get the bucket index to use
bucketIdx = self.getBucketIndices(x)[0]
... | [
"def",
"encodeIntoArray",
"(",
"self",
",",
"x",
",",
"output",
")",
":",
"if",
"x",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"x",
",",
"numbers",
".",
"Number",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected a scalar input but got input of ty... | 35.5 | 20.142857 |
def backend_fields(self, fields):
'''Return a two elements tuple containing a list
of fields names and a list of field attribute names.'''
dfields = self.dfields
processed = set()
names = []
atts = []
pkname = self.pkname()
for name in fields:
... | [
"def",
"backend_fields",
"(",
"self",
",",
"fields",
")",
":",
"dfields",
"=",
"self",
".",
"dfields",
"processed",
"=",
"set",
"(",
")",
"names",
"=",
"[",
"]",
"atts",
"=",
"[",
"]",
"pkname",
"=",
"self",
".",
"pkname",
"(",
")",
"for",
"name",
... | 37.72 | 10.44 |
def get_verbatim(key, **kwargs):
'''
Gets a verbatim occurrence record without any interpretation
:param key: [int] A GBIF occurrence key
:return: A dictionary, of results
Usage::
from pygbif import occurrences
occurrences.get_verbatim(key = 1258202889)
occurrences.get_ve... | [
"def",
"get_verbatim",
"(",
"key",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"gbif_baseurl",
"+",
"'occurrence/'",
"+",
"str",
"(",
"key",
")",
"+",
"'/verbatim'",
"out",
"=",
"gbif_GET",
"(",
"url",
",",
"{",
"}",
",",
"*",
"*",
"kwargs",
")"... | 27.944444 | 20.944444 |
def VEXTRACTF128(cpu, dest, src, offset):
"""Extract Packed Floating-Point Values
Extracts 128-bits of packed floating-point values from the source
operand (second operand) at an 128-bit offset from imm8[0] into the
destination operand (first operand). The destination may be either an
... | [
"def",
"VEXTRACTF128",
"(",
"cpu",
",",
"dest",
",",
"src",
",",
"offset",
")",
":",
"offset",
"=",
"offset",
".",
"read",
"(",
")",
"dest",
".",
"write",
"(",
"Operators",
".",
"EXTRACT",
"(",
"src",
".",
"read",
"(",
")",
",",
"offset",
"*",
"1... | 48.8 | 21 |
def auto_stratify(scores, **kwargs):
"""Generate Strata instance automatically
Parameters
----------
scores : array-like, shape=(n_items,)
ordered array of scores which quantify the classifier confidence for
the items in the pool. High scores indicate a high confidence that
the ... | [
"def",
"auto_stratify",
"(",
"scores",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'stratification_method'",
"in",
"kwargs",
":",
"method",
"=",
"kwargs",
"[",
"'stratification_method'",
"]",
"else",
":",
"method",
"=",
"'cum_sqrt_F'",
"if",
"'stratification_n_str... | 34.121212 | 20.606061 |
def virt_env(self):
"""
Getter for this instance's virt env, creates it if needed
Returns:
lago.virt.VirtEnv: virt env instance used by this prefix
"""
if self._virt_env is None:
self._virt_env = self._create_virt_env()
return self._virt_env | [
"def",
"virt_env",
"(",
"self",
")",
":",
"if",
"self",
".",
"_virt_env",
"is",
"None",
":",
"self",
".",
"_virt_env",
"=",
"self",
".",
"_create_virt_env",
"(",
")",
"return",
"self",
".",
"_virt_env"
] | 30.5 | 16.7 |
def remove_destinations(self, server_id, destination_paths):
# pylint: disable=line-too-long
"""
Remove listener destinations from a WBEM server, by deleting the
listener destination instances in the server.
The listener destinations must be owned or permanent (i.e. not static).... | [
"def",
"remove_destinations",
"(",
"self",
",",
"server_id",
",",
"destination_paths",
")",
":",
"# pylint: disable=line-too-long",
"# noqa: E501",
"# Validate server_id",
"server",
"=",
"self",
".",
"_get_server",
"(",
"server_id",
")",
"conn_id",
"=",
"server",
".",... | 39.737705 | 23.540984 |
def show_linkinfo_output_show_link_info_linkinfo_version(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_linkinfo = ET.Element("show_linkinfo")
config = show_linkinfo
output = ET.SubElement(show_linkinfo, "output")
show_link_info = E... | [
"def",
"show_linkinfo_output_show_link_info_linkinfo_version",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"show_linkinfo",
"=",
"ET",
".",
"Element",
"(",
"\"show_linkinfo\"",
")",
"config",
"=",
... | 48.733333 | 19.6 |
def get_all_params(self, session=None):
"""Return the parameters in a list of array."""
_params = []
for p in self.all_params:
if session is None:
_params.append(p.eval())
else:
_params.append(session.run(p))
return _params | [
"def",
"get_all_params",
"(",
"self",
",",
"session",
"=",
"None",
")",
":",
"_params",
"=",
"[",
"]",
"for",
"p",
"in",
"self",
".",
"all_params",
":",
"if",
"session",
"is",
"None",
":",
"_params",
".",
"append",
"(",
"p",
".",
"eval",
"(",
")",
... | 33.666667 | 9.333333 |
def add_secondary_ip(self, ip_address, interface=1):
"""Adds an IP address as a secondary IP address
:param ip_address: String IP address to add as a secondary IP
:param interface: Integer associated to the interface/device number
:return: None
:raises: AWSAPIError, EC2UtilError... | [
"def",
"add_secondary_ip",
"(",
"self",
",",
"ip_address",
",",
"interface",
"=",
"1",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"self",
".",
"cls_logger",
"+",
"'.add_secondary_ip'",
")",
"# Get the ENI ID",
"eni_id",
"=",
"self",
".",
"get_en... | 38.794872 | 18.025641 |
def bulk(iterable, index=INDEX_NAME, doc_type=DOC_TYPE, action='index'):
"""
Wrapper of elasticsearch's bulk method
Converts an interable of models to document operations and submits them to
Elasticsearch. Returns a count of operations when done.
https://elasticsearch-py.readthedocs.io/en/master/... | [
"def",
"bulk",
"(",
"iterable",
",",
"index",
"=",
"INDEX_NAME",
",",
"doc_type",
"=",
"DOC_TYPE",
",",
"action",
"=",
"'index'",
")",
":",
"actions",
"=",
"compact",
"(",
"dict_to_op",
"(",
"to_dict",
"(",
"model",
")",
",",
"index_name",
"=",
"INDEX_NA... | 32 | 23.666667 |
def expand_item(self, item, open_all=True):
"""Display a node as expanded
:param item: The item to show expanded
:param open_all: Whether all child nodes should be recursively
expanded.
"""
self.expand_row(self._view_path_for(item), open_all) | [
"def",
"expand_item",
"(",
"self",
",",
"item",
",",
"open_all",
"=",
"True",
")",
":",
"self",
".",
"expand_row",
"(",
"self",
".",
"_view_path_for",
"(",
"item",
")",
",",
"open_all",
")"
] | 37.625 | 13.125 |
def generic_div(a, b):
"""Simple function to divide two numbers"""
logger.debug('Called generic_div({}, {})'.format(a, b))
return a / b | [
"def",
"generic_div",
"(",
"a",
",",
"b",
")",
":",
"logger",
".",
"debug",
"(",
"'Called generic_div({}, {})'",
".",
"format",
"(",
"a",
",",
"b",
")",
")",
"return",
"a",
"/",
"b"
] | 36 | 15.25 |
def reset_socat(use_sudo=False):
"""
Finds and closes all processes of `socat`.
:param use_sudo: Use `sudo` command. As Docker-Fabric does not run `socat` with `sudo`, this is by default set to
``False``. Setting it to ``True`` could unintentionally remove instances from other users.
:type use_su... | [
"def",
"reset_socat",
"(",
"use_sudo",
"=",
"False",
")",
":",
"output",
"=",
"stdout_result",
"(",
"'ps -o pid -C socat'",
",",
"quiet",
"=",
"True",
")",
"pids",
"=",
"output",
".",
"split",
"(",
"'\\n'",
")",
"[",
"1",
":",
"]",
"puts",
"(",
"\"Remo... | 45.153846 | 21.615385 |
async def async_enqueue_download(self, resource):
'''
Enqueue the download of the given foreign resource.
'''
worker = self.pick_sticky(resource.url_string)
await worker.enqueue(enums.Task.DOWNLOAD, (resource,)) | [
"async",
"def",
"async_enqueue_download",
"(",
"self",
",",
"resource",
")",
":",
"worker",
"=",
"self",
".",
"pick_sticky",
"(",
"resource",
".",
"url_string",
")",
"await",
"worker",
".",
"enqueue",
"(",
"enums",
".",
"Task",
".",
"DOWNLOAD",
",",
"(",
... | 41 | 20.333333 |
def certify_dict(
value, schema=None, allow_extra=False, required=True, key_certifier=None, value_certifier=None,
include_collections=False,
):
"""
Certifies a dictionary, checking it against an optional schema.
The schema should be a dictionary, with keys corresponding to the expected keys in `val... | [
"def",
"certify_dict",
"(",
"value",
",",
"schema",
"=",
"None",
",",
"allow_extra",
"=",
"False",
",",
"required",
"=",
"True",
",",
"key_certifier",
"=",
"None",
",",
"value_certifier",
"=",
"None",
",",
"include_collections",
"=",
"False",
",",
")",
":"... | 30.948052 | 19.12987 |
def repair_duplicate_names(self):
"""
Prior to 1101.1.1, pmxbot would incorrectly create new karma records
for individuals with multiple names.
This routine corrects those records.
"""
for name in self._all_names():
cur = self.db.find({'names': name})
main_doc = next(cur)
for duplicate in cur:
... | [
"def",
"repair_duplicate_names",
"(",
"self",
")",
":",
"for",
"name",
"in",
"self",
".",
"_all_names",
"(",
")",
":",
"cur",
"=",
"self",
".",
"db",
".",
"find",
"(",
"{",
"'names'",
":",
"name",
"}",
")",
"main_doc",
"=",
"next",
"(",
"cur",
")",... | 30.647059 | 10.882353 |
def _straight_line_vertices(adjacency_mat, node_coords, directed=False):
"""
Generate the vertices for straight lines between nodes.
If it is a directed graph, it also generates the vertices which can be
passed to an :class:`ArrowVisual`.
Parameters
----------
adjacency_mat : array
... | [
"def",
"_straight_line_vertices",
"(",
"adjacency_mat",
",",
"node_coords",
",",
"directed",
"=",
"False",
")",
":",
"if",
"not",
"issparse",
"(",
"adjacency_mat",
")",
":",
"adjacency_mat",
"=",
"np",
".",
"asarray",
"(",
"adjacency_mat",
",",
"float",
")",
... | 32.047619 | 22.333333 |
def prepare_data(self):
"""Prepare widget data for template."""
result = {}
for field in self.fields:
data = self.data.get(field.name)
result[field.name] = field.prepare_data(data)
return result | [
"def",
"prepare_data",
"(",
"self",
")",
":",
"result",
"=",
"{",
"}",
"for",
"field",
"in",
"self",
".",
"fields",
":",
"data",
"=",
"self",
".",
"data",
".",
"get",
"(",
"field",
".",
"name",
")",
"result",
"[",
"field",
".",
"name",
"]",
"=",
... | 27.111111 | 18.333333 |
def agent_path(cls, project, agent):
"""Return a fully-qualified agent string."""
return google.api_core.path_template.expand(
'projects/{project}/agents/{agent}',
project=project,
agent=agent,
) | [
"def",
"agent_path",
"(",
"cls",
",",
"project",
",",
"agent",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"'projects/{project}/agents/{agent}'",
",",
"project",
"=",
"project",
",",
"agent",
"=",
"agent",
",",
")... | 35.571429 | 11.857143 |
def get_fsapi_endpoint(self):
"""Parse the fsapi endpoint from the device url."""
endpoint = yield from self.__session.get(self.fsapi_device_url, timeout = self.timeout)
text = yield from endpoint.text(encoding='utf-8')
doc = objectify.fromstring(text)
return doc.webfsapi.text | [
"def",
"get_fsapi_endpoint",
"(",
"self",
")",
":",
"endpoint",
"=",
"yield",
"from",
"self",
".",
"__session",
".",
"get",
"(",
"self",
".",
"fsapi_device_url",
",",
"timeout",
"=",
"self",
".",
"timeout",
")",
"text",
"=",
"yield",
"from",
"endpoint",
... | 52 | 15.166667 |
def get_jids():
'''
Return a list of all job ids
'''
serv = _get_serv(ret=None)
jids = _get_list(serv, 'jids')
loads = serv.get_multi(jids) # {jid: load, jid: load, ...}
ret = {}
for jid, load in six.iteritems(loads):
ret[jid] = salt.utils.jid.format_jid_instance(jid, salt.utils... | [
"def",
"get_jids",
"(",
")",
":",
"serv",
"=",
"_get_serv",
"(",
"ret",
"=",
"None",
")",
"jids",
"=",
"_get_list",
"(",
"serv",
",",
"'jids'",
")",
"loads",
"=",
"serv",
".",
"get_multi",
"(",
"jids",
")",
"# {jid: load, jid: load, ...}",
"ret",
"=",
... | 31.181818 | 21.909091 |
def parse_token(self, token):
"""
Obtain a user from a signed token.
"""
try:
data = self.unsign(token)
except signing.SignatureExpired:
logger.debug("Expired token: %s", token)
return
except signing.BadSignature:
logger.de... | [
"def",
"parse_token",
"(",
"self",
",",
"token",
")",
":",
"try",
":",
"data",
"=",
"self",
".",
"unsign",
"(",
"token",
")",
"except",
"signing",
".",
"SignatureExpired",
":",
"logger",
".",
"debug",
"(",
"\"Expired token: %s\"",
",",
"token",
")",
"ret... | 32.735294 | 14.794118 |
def get_inputs_for_state(self, state):
"""Retrieves all input data of a state. If several data flows are connected to an input port the
most current data is used for the specific input port.
:param state: the state of which the input data is determined
:return: the input data of the tar... | [
"def",
"get_inputs_for_state",
"(",
"self",
",",
"state",
")",
":",
"result_dict",
"=",
"{",
"}",
"tmp_dict",
"=",
"self",
".",
"get_default_input_values_for_state",
"(",
"state",
")",
"result_dict",
".",
"update",
"(",
"tmp_dict",
")",
"for",
"input_port_key",
... | 48.645161 | 26.354839 |
def set_value(self, name, value, ignore_error=False, block_user_signals=False):
"""
Sets the variable of the supplied name to the supplied value.
Setting block_user_signals=True will temporarily block the widget from
sending any signals when setting the value.
"""
# firs... | [
"def",
"set_value",
"(",
"self",
",",
"name",
",",
"value",
",",
"ignore_error",
"=",
"False",
",",
"block_user_signals",
"=",
"False",
")",
":",
"# first clean up the name",
"name",
"=",
"self",
".",
"_clean_up_name",
"(",
"name",
")",
"# If we're supposed to, ... | 37.914286 | 23.4 |
def connect(self):
""" Connects to the device and starts the read thread """
self.serial = serial.Serial(port=self.port, baudrate=self.baudrate, timeout=self.timeout)
# Start read thread
self.alive = True
self.rxThread = threading.Thread(target=self._readLoop)
... | [
"def",
"connect",
"(",
"self",
")",
":",
"self",
".",
"serial",
"=",
"serial",
".",
"Serial",
"(",
"port",
"=",
"self",
".",
"port",
",",
"baudrate",
"=",
"self",
".",
"baudrate",
",",
"timeout",
"=",
"self",
".",
"timeout",
")",
"# Start read thread",... | 47 | 18.125 |
def _mute(self):
""" mute vlc """
if self.muted:
self._sendCommand("volume {}\n".format(self.actual_volume))
if logger.isEnabledFor(logging.DEBUG):
logger.debug('VLC unmuted: {0} ({1}%)'.format(self.actual_volume, int(100 * self.actual_volume / self.max_volume)))... | [
"def",
"_mute",
"(",
"self",
")",
":",
"if",
"self",
".",
"muted",
":",
"self",
".",
"_sendCommand",
"(",
"\"volume {}\\n\"",
".",
"format",
"(",
"self",
".",
"actual_volume",
")",
")",
"if",
"logger",
".",
"isEnabledFor",
"(",
"logging",
".",
"DEBUG",
... | 41.769231 | 20.692308 |
def list_teams(profile="github", ignore_cache=False):
'''
Lists all teams with the organization.
profile
The name of the profile configuration to use. Defaults to ``github``.
ignore_cache
Bypasses the use of cached teams.
CLI Example:
.. code-block:: bash
salt mymini... | [
"def",
"list_teams",
"(",
"profile",
"=",
"\"github\"",
",",
"ignore_cache",
"=",
"False",
")",
":",
"key",
"=",
"'github.{0}:teams'",
".",
"format",
"(",
"_get_config_value",
"(",
"profile",
",",
"'org_name'",
")",
")",
"if",
"key",
"not",
"in",
"__context_... | 30.818182 | 21.045455 |
def model_creation_opt(dicCnfg, aryMdlParams, strPathHrf=None, varRat=None,
lgcPrint=True):
"""
Create or load pRF model time courses.
Parameters
----------
dicCnfg : dict
Dictionary containing config parameters.
aryMdlParams : numpy arrays
x, y and sigma ... | [
"def",
"model_creation_opt",
"(",
"dicCnfg",
",",
"aryMdlParams",
",",
"strPathHrf",
"=",
"None",
",",
"varRat",
"=",
"None",
",",
"lgcPrint",
"=",
"True",
")",
":",
"# *************************************************************************",
"# *** Load parameters from c... | 44.686131 | 25.883212 |
def object_properties_count(self, o):
""" returns the number of user browsable properties of an object. """
o_type = type(o)
if isinstance(o, (dict, list, tuple, set)):
return len(o)
elif isinstance(o, (type(None), bool, float,
str, int,
... | [
"def",
"object_properties_count",
"(",
"self",
",",
"o",
")",
":",
"o_type",
"=",
"type",
"(",
"o",
")",
"if",
"isinstance",
"(",
"o",
",",
"(",
"dict",
",",
"list",
",",
"tuple",
",",
"set",
")",
")",
":",
"return",
"len",
"(",
"o",
")",
"elif",... | 48.162791 | 19.674419 |
def receive(self, msg):
'''
The message received from the queue specify a method of the
class the actor represents. This invokes it. If the
communication is an ASK, sends the result back
to the channel included in the message as an
ASKRESPONSE.
If it is a FUTURE,... | [
"def",
"receive",
"(",
"self",
",",
"msg",
")",
":",
"if",
"msg",
"[",
"TYPE",
"]",
"==",
"TELL",
"and",
"msg",
"[",
"METHOD",
"]",
"==",
"'stop'",
":",
"self",
".",
"running",
"=",
"False",
"self",
".",
"future_manager",
".",
"stop",
"(",
")",
"... | 35.517241 | 16.689655 |
def fraction_correct_values(indices, x_values, y_values, x_cutoff = 1.0, y_cutoff = 1.0, ignore_null_values = False):
'''
An approximation to the metric used in the Kellogg et al. paper: "The fraction correct is defined as the number of mutations categorized correctly divided by the total number of mutations in... | [
"def",
"fraction_correct_values",
"(",
"indices",
",",
"x_values",
",",
"y_values",
",",
"x_cutoff",
"=",
"1.0",
",",
"y_cutoff",
"=",
"1.0",
",",
"ignore_null_values",
"=",
"False",
")",
":",
"num_points",
"=",
"len",
"(",
"indices",
")",
"assert",
"(",
"... | 53.363636 | 35.727273 |
def run_script(self, script_name, keys=None, args=None):
"""
Execute a walrus script with the given arguments.
:param script_name: The base name of the script to execute.
:param list keys: Keys referenced by the script.
:param list args: Arguments passed in to the script.
... | [
"def",
"run_script",
"(",
"self",
",",
"script_name",
",",
"keys",
"=",
"None",
",",
"args",
"=",
"None",
")",
":",
"return",
"self",
".",
"_scripts",
"[",
"script_name",
"]",
"(",
"keys",
",",
"args",
")"
] | 40.428571 | 18.142857 |
def get_strike(self):
"""
Compute strike of each surface element and return area-weighted average
value (in range ``[0, 360]``) using formula from:
http://en.wikipedia.org/wiki/Mean_of_circular_quantities
Note that the original formula has been adapted to compute a weighted
... | [
"def",
"get_strike",
"(",
"self",
")",
":",
"areas",
"=",
"self",
".",
"_get_areas",
"(",
")",
"strikes",
"=",
"numpy",
".",
"array",
"(",
"[",
"surf",
".",
"get_strike",
"(",
")",
"for",
"surf",
"in",
"self",
".",
"surfaces",
"]",
")",
"v1",
"=",
... | 40 | 21.888889 |
def _invert(color, **kwargs):
""" Returns the inverse (negative) of a color.
The red, green, and blue values are inverted, while the opacity is left alone.
"""
col = ColorValue(color)
args = [
255.0 - col.value[0],
255.0 - col.value[1],
255.0 - col.value[2],
col.v... | [
"def",
"_invert",
"(",
"color",
",",
"*",
"*",
"kwargs",
")",
":",
"col",
"=",
"ColorValue",
"(",
"color",
")",
"args",
"=",
"[",
"255.0",
"-",
"col",
".",
"value",
"[",
"0",
"]",
",",
"255.0",
"-",
"col",
".",
"value",
"[",
"1",
"]",
",",
"2... | 28.769231 | 16.538462 |
def types(self):
"""A tuple containing the value types for this Slot.
The Python equivalent of the CLIPS deftemplate-slot-types function.
"""
data = clips.data.DataObject(self._env)
lib.EnvDeftemplateSlotTypes(
self._env, self._tpl, self._name, data.byref)
... | [
"def",
"types",
"(",
"self",
")",
":",
"data",
"=",
"clips",
".",
"data",
".",
"DataObject",
"(",
"self",
".",
"_env",
")",
"lib",
".",
"EnvDeftemplateSlotTypes",
"(",
"self",
".",
"_env",
",",
"self",
".",
"_tpl",
",",
"self",
".",
"_name",
",",
"... | 31.166667 | 23.25 |
def get_preference(self, pref_name):
""" Gets a single named preference
:returns: the value, typed to str/bool/int/float regarding its content.
"""
resp = self.request_single('GetPrefs', {'pref': {'name': pref_name}})
return utils.auto_type(resp['_content']) | [
"def",
"get_preference",
"(",
"self",
",",
"pref_name",
")",
":",
"resp",
"=",
"self",
".",
"request_single",
"(",
"'GetPrefs'",
",",
"{",
"'pref'",
":",
"{",
"'name'",
":",
"pref_name",
"}",
"}",
")",
"return",
"utils",
".",
"auto_type",
"(",
"resp",
... | 41.857143 | 18.285714 |
def norm(self, x):
"""Calculate the array-weighted norm of an element.
Parameters
----------
x : `ProductSpaceElement`
Element whose norm is calculated.
Returns
-------
norm : float
The norm of the provided element.
"""
if... | [
"def",
"norm",
"(",
"self",
",",
"x",
")",
":",
"if",
"self",
".",
"exponent",
"==",
"2.0",
":",
"norm_squared",
"=",
"self",
".",
"inner",
"(",
"x",
",",
"x",
")",
".",
"real",
"# TODO: optimize?!",
"return",
"np",
".",
"sqrt",
"(",
"norm_squared",
... | 31.36 | 18.48 |
def rmdir(self, tid):
"""
Directory removal. ``YTActions`` object under `tid` is told to clean all data, and then it is deleted.
Parameters
----------
tid : str
Path to file. Original `path` argument is converted to tuple identifier by ``_pathdec`` decorator.
... | [
"def",
"rmdir",
"(",
"self",
",",
"tid",
")",
":",
"pt",
"=",
"self",
".",
"PathType",
".",
"get",
"(",
"tid",
")",
"if",
"pt",
"is",
"self",
".",
"PathType",
".",
"main",
":",
"raise",
"FuseOSError",
"(",
"errno",
".",
"EINVAL",
")",
"elif",
"pt... | 26.576923 | 23.115385 |
def get_metric(self, timestamp):
"""Get a metric including all current time series.
Get a :class:`opencensus.metrics.export.metric.Metric` with one
:class:`opencensus.metrics.export.time_series.TimeSeries` for each
set of label values with a recorded measurement. Each `TimeSeries`
... | [
"def",
"get_metric",
"(",
"self",
",",
"timestamp",
")",
":",
"if",
"not",
"self",
".",
"points",
":",
"return",
"None",
"with",
"self",
".",
"_points_lock",
":",
"ts_list",
"=",
"get_timeseries_list",
"(",
"self",
".",
"points",
",",
"timestamp",
")",
"... | 42.6 | 23.85 |
def shorten_name(name, char_limit, side='right'):
"""Shorten `name` if it is longer than `char_limit`.
If `side` == "right" then the right side of the name is shortened;
if "left" then the left side is shortened.
In either case, the suffix of the name is preserved.
"""
# TODO: A more elegant way... | [
"def",
"shorten_name",
"(",
"name",
",",
"char_limit",
",",
"side",
"=",
"'right'",
")",
":",
"# TODO: A more elegant way to do this?",
"if",
"char_limit",
"is",
"not",
"None",
"and",
"len",
"(",
"name",
")",
">",
"char_limit",
":",
"info",
"=",
"get_fileinfo"... | 38.793103 | 12.482759 |
def process(self, username, password, remember=True):
"""
Process a login request
@type username: str
@type password: str
@param remember: Save the login session to disk
@type remember: bool
@raise BadLoginException: Login request failed
@... | [
"def",
"process",
"(",
"self",
",",
"username",
",",
"password",
",",
"remember",
"=",
"True",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'Processing login request'",
")",
"self",
".",
"browser",
".",
"open",
"(",
"self",
".",
"LOGIN_URL",
")",
... | 37.765957 | 18.106383 |
def software_breakpoint_set(self, addr, thumb=False, arm=False, flash=False, ram=False):
"""Sets a software breakpoint at the specified address.
If ``thumb`` is ``True``, the breakpoint is set in THUMB-mode, while if
``arm`` is ``True``, the breakpoint is set in ARM-mode, otherwise a
no... | [
"def",
"software_breakpoint_set",
"(",
"self",
",",
"addr",
",",
"thumb",
"=",
"False",
",",
"arm",
"=",
"False",
",",
"flash",
"=",
"False",
",",
"ram",
"=",
"False",
")",
":",
"if",
"flash",
"and",
"not",
"ram",
":",
"flags",
"=",
"enums",
".",
"... | 41.288889 | 25.066667 |
def add_ref(self, reftype, data):
"""Add a reference and returns the identifier."""
ref = (reftype, data)
try:
index = self.refs.index(ref)
except ValueError:
self.refs.append(ref)
index = len(self.refs) - 1
return str(index) | [
"def",
"add_ref",
"(",
"self",
",",
"reftype",
",",
"data",
")",
":",
"ref",
"=",
"(",
"reftype",
",",
"data",
")",
"try",
":",
"index",
"=",
"self",
".",
"refs",
".",
"index",
"(",
"ref",
")",
"except",
"ValueError",
":",
"self",
".",
"refs",
".... | 32.555556 | 9.333333 |
def get_bitcoind( new_bitcoind_opts=None, reset=False, new=False ):
"""
Get or instantiate our bitcoind client.
Optionally re-set the bitcoind options.
"""
global bitcoind
if reset:
bitcoind = None
elif not new and bitcoind is not None:
return bitcoind
if new or bitcoind is None:... | [
"def",
"get_bitcoind",
"(",
"new_bitcoind_opts",
"=",
"None",
",",
"reset",
"=",
"False",
",",
"new",
"=",
"False",
")",
":",
"global",
"bitcoind",
"if",
"reset",
":",
"bitcoind",
"=",
"None",
"elif",
"not",
"new",
"and",
"bitcoind",
"is",
"not",
"None",... | 24.102564 | 19.128205 |
def download(self,
url,
dest_path=None):
"""
:param url:
:type url: str
:param dest_path:
:type dest_path: str
"""
if os.path.exists(dest_path):
os.remove(dest_path)
resp = get(url, stream=True)
size =... | [
"def",
"download",
"(",
"self",
",",
"url",
",",
"dest_path",
"=",
"None",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"dest_path",
")",
":",
"os",
".",
"remove",
"(",
"dest_path",
")",
"resp",
"=",
"get",
"(",
"url",
",",
"stream",
"=... | 33.607143 | 14.392857 |
def unindex_item(self, item):
"""
Un-index an item from our name_to_item dict.
:param item: the item to un-index
:type item: alignak.objects.item.Item
:return: None
"""
name_property = getattr(self.__class__, "name_property", None)
if name_property is None... | [
"def",
"unindex_item",
"(",
"self",
",",
"item",
")",
":",
"name_property",
"=",
"getattr",
"(",
"self",
".",
"__class__",
",",
"\"name_property\"",
",",
"None",
")",
"if",
"name_property",
"is",
"None",
":",
"return",
"name",
"=",
"getattr",
"(",
"item",
... | 33.071429 | 11.071429 |
def _reduce_method(cls, func):
"""
Return a wrapped function for injecting numpy methods.
see ops.inject_coarsen_methods
"""
def wrapped_func(self, **kwargs):
from .dataarray import DataArray
reduced = self.obj.variable.coarsen(
self.windo... | [
"def",
"_reduce_method",
"(",
"cls",
",",
"func",
")",
":",
"def",
"wrapped_func",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
"dataarray",
"import",
"DataArray",
"reduced",
"=",
"self",
".",
"obj",
".",
"variable",
".",
"coarsen",
"("... | 37.791667 | 13.708333 |
def get(self, namespace, key):
"""Get a specific configuration item"""
cfg = self.dbconfig.get(key, namespace, as_object=True)
return self.make_response({
'message': None,
'config': cfg
}) | [
"def",
"get",
"(",
"self",
",",
"namespace",
",",
"key",
")",
":",
"cfg",
"=",
"self",
".",
"dbconfig",
".",
"get",
"(",
"key",
",",
"namespace",
",",
"as_object",
"=",
"True",
")",
"return",
"self",
".",
"make_response",
"(",
"{",
"'message'",
":",
... | 34 | 13.571429 |
def get_file_list(opts):
"""
Returns a list containing file paths of requested files to be parsed
using AnchorHub options.
:param opts: Namespace containing AnchorHub options, usually created from
command line arguments
:return: a list of absolute string file paths of files that should be
... | [
"def",
"get_file_list",
"(",
"opts",
")",
":",
"if",
"opts",
".",
"is_dir",
":",
"# Input is a directory, get a list of files",
"return",
"get_files",
"(",
"opts",
".",
"abs_input",
",",
"opts",
".",
"extensions",
",",
"exclude",
"=",
"[",
"opts",
".",
"abs_ou... | 35.3 | 18.7 |
def compile(expr, params=None):
"""
Force compilation of expression as though it were an expression depending
on Clickhouse. Note you can also call expr.compile()
Returns
-------
compiled : string
"""
from ibis.clickhouse.compiler import to_sql
return to_sql(expr, dialect.make_cont... | [
"def",
"compile",
"(",
"expr",
",",
"params",
"=",
"None",
")",
":",
"from",
"ibis",
".",
"clickhouse",
".",
"compiler",
"import",
"to_sql",
"return",
"to_sql",
"(",
"expr",
",",
"dialect",
".",
"make_context",
"(",
"params",
"=",
"params",
")",
")"
] | 27.333333 | 20.5 |
def send_notification_batch(self, notifications, topic=None, priority=NotificationPriority.Immediate,
expiration=None, collapse_id=None):
"""
Send a notification to a list of tokens in batch. Instead of sending a synchronous request
for each token, send multiple r... | [
"def",
"send_notification_batch",
"(",
"self",
",",
"notifications",
",",
"topic",
"=",
"None",
",",
"priority",
"=",
"NotificationPriority",
".",
"Immediate",
",",
"expiration",
"=",
"None",
",",
"collapse_id",
"=",
"None",
")",
":",
"notification_iterator",
"=... | 61.42 | 34.34 |
def v(*args, **kwargs):
'''
print the name = values of any passed in variables
this prints out the passed in name, the value, and the file:line where the v()
method was called so you can easily find it and remove it later
example --
foo = 1
bar = [1, 2, 3]
out.v(foo, bar)
... | [
"def",
"v",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"args",
":",
"raise",
"ValueError",
"(",
"\"you didn't pass any arguments to print out\"",
")",
"with",
"Reflect",
".",
"context",
"(",
"args",
",",
"*",
"*",
"kwargs",
")",
"a... | 23.125 | 25.5625 |
def get(self, **url_params):
"""
Makes the HTTP GET to the url.
"""
if url_params:
self.http_method_args["params"].update(url_params)
return self.http_method("GET") | [
"def",
"get",
"(",
"self",
",",
"*",
"*",
"url_params",
")",
":",
"if",
"url_params",
":",
"self",
".",
"http_method_args",
"[",
"\"params\"",
"]",
".",
"update",
"(",
"url_params",
")",
"return",
"self",
".",
"http_method",
"(",
"\"GET\"",
")"
] | 30 | 8 |
def request_time(self, req):
"""Return the current time in ms since the Unix Epoch."""
r = time.time()
self._time_result.set_value(r)
return ("ok", r) | [
"def",
"request_time",
"(",
"self",
",",
"req",
")",
":",
"r",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"_time_result",
".",
"set_value",
"(",
"r",
")",
"return",
"(",
"\"ok\"",
",",
"r",
")"
] | 35.6 | 9.4 |
def _get_parallel_regions(data):
"""Retrieve regions to run in parallel, putting longest intervals first.
"""
callable_regions = tz.get_in(["config", "algorithm", "callable_regions"], data)
if not callable_regions:
raise ValueError("Did not find any callable regions for sample: %s\n"
... | [
"def",
"_get_parallel_regions",
"(",
"data",
")",
":",
"callable_regions",
"=",
"tz",
".",
"get_in",
"(",
"[",
"\"config\"",
",",
"\"algorithm\"",
",",
"\"callable_regions\"",
"]",
",",
"data",
")",
"if",
"not",
"callable_regions",
":",
"raise",
"ValueError",
... | 62.692308 | 28.923077 |
def p_try_statement_1(self, p):
"""try_statement : TRY block catch"""
p[0] = ast.Try(statements=p[2], catch=p[3]) | [
"def",
"p_try_statement_1",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"ast",
".",
"Try",
"(",
"statements",
"=",
"p",
"[",
"2",
"]",
",",
"catch",
"=",
"p",
"[",
"3",
"]",
")"
] | 42.333333 | 6.666667 |
def stage(self, fileobj, creds=None, callback=None):
"""Stages data in a Mapbox-owned S3 bucket
If creds are not provided, temporary credentials will be
generated using the Mapbox API.
Parameters
----------
fileobj: file object or filename
A Python file obje... | [
"def",
"stage",
"(",
"self",
",",
"fileobj",
",",
"creds",
"=",
"None",
",",
"callback",
"=",
"None",
")",
":",
"if",
"not",
"hasattr",
"(",
"fileobj",
",",
"'read'",
")",
":",
"fileobj",
"=",
"open",
"(",
"fileobj",
",",
"'rb'",
")",
"if",
"not",
... | 30.292683 | 18.658537 |
def highs(self, *args):
"""
Generator yielding only the high tides.
Arguments:
see Tide.extrema()
"""
for t in ifilter(lambda e: e[2] == 'H', self.extrema(*args)):
yield t | [
"def",
"highs",
"(",
"self",
",",
"*",
"args",
")",
":",
"for",
"t",
"in",
"ifilter",
"(",
"lambda",
"e",
":",
"e",
"[",
"2",
"]",
"==",
"'H'",
",",
"self",
".",
"extrema",
"(",
"*",
"args",
")",
")",
":",
"yield",
"t"
] | 22.375 | 14.875 |
def _set_get_arp(self, v, load=False):
"""
Setter method for get_arp, mapped from YANG variable /brocade_arp_rpc/get_arp (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_get_arp is considered as a private
method. Backends looking to populate this variable should... | [
"def",
"_set_get_arp",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base",... | 63.851852 | 29.851852 |
def parse(self, buf: memoryview, params: Params) \
-> Tuple[Command, memoryview]:
"""Parse the given bytes into a command. The basic syntax is a tag
string, a command name, possibly some arguments, and then an endline.
If the command has a complete structure but cannot be parsed, an
... | [
"def",
"parse",
"(",
"self",
",",
"buf",
":",
"memoryview",
",",
"params",
":",
"Params",
")",
"->",
"Tuple",
"[",
"Command",
",",
"memoryview",
"]",
":",
"try",
":",
"tag",
",",
"buf",
"=",
"Tag",
".",
"parse",
"(",
"buf",
",",
"params",
")",
"e... | 39.405405 | 14.783784 |
def _sentinel_parse_scene_id(sceneid):
"""Parse Sentinel-2 scene id.
Attributes
----------
sceneid : str
Sentinel-2 sceneid.
Returns
-------
out : dict
dictionary with metadata constructed from the sceneid.
e.g:
_sentinel_parse_scene_id('S2A_tile_20170323_0... | [
"def",
"_sentinel_parse_scene_id",
"(",
"sceneid",
")",
":",
"if",
"not",
"re",
".",
"match",
"(",
"\"^S2[AB]_tile_[0-9]{8}_[0-9]{2}[A-Z]{3}_[0-9]$\"",
",",
"sceneid",
")",
":",
"raise",
"InvalidSentinelSceneId",
"(",
"\"Could not match {}\"",
".",
"format",
"(",
"sce... | 25.085714 | 20.342857 |
def upload_local_file(self, local_file_path, file_obj=None):
"""Create a Stored File and upload it's data. This is a one part do it all type method. Here is what
it does:
1. "Discover" information about the file (mime-type, size)
2. Create the stored file object in slick
... | [
"def",
"upload_local_file",
"(",
"self",
",",
"local_file_path",
",",
"file_obj",
"=",
"None",
")",
":",
"if",
"file_obj",
"is",
"None",
"and",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"local_file_path",
")",
":",
"return",
"storedfile",
"=",
"StoredF... | 46.642857 | 16.321429 |
def base_argparser(argv=()):
"""Initial parser that can set values for the rest of the parsing process.
"""
global verbose
verbose = _not_verbose
_p = argparse.ArgumentParser(add_help=False)
_p.add_argument('--debug', action='store_true', help="turn on all the show and verbose options (mainly f... | [
"def",
"base_argparser",
"(",
"argv",
"=",
"(",
")",
")",
":",
"global",
"verbose",
"verbose",
"=",
"_not_verbose",
"_p",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"add_help",
"=",
"False",
")",
"_p",
".",
"add_argument",
"(",
"'--debug'",
",",
"action"... | 38.529412 | 25.088235 |
def use_mock(self, mock, *args, **kwarg):
"""
Context manager or decorator in order to use a coroutine as mock of service
endpoint in a test.
:param mock: Coroutine to use as mock. It should behave like :meth:`~ClientSession.request`.
:type mock: coroutine
:param service... | [
"def",
"use_mock",
"(",
"self",
",",
"mock",
",",
"*",
"args",
",",
"*",
"*",
"kwarg",
")",
":",
"return",
"UseMockDefinition",
"(",
"mock",
",",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwarg",
")"
] | 47 | 23.8 |
def force_new_dynamic_value(self_, name): # pylint: disable-msg=E0213
"""
Force a new value to be generated for the dynamic attribute
name, and return it.
If name is not dynamic, its current value is returned
(i.e. equivalent to getattr(name).
"""
cls_or_slf = se... | [
"def",
"force_new_dynamic_value",
"(",
"self_",
",",
"name",
")",
":",
"# pylint: disable-msg=E0213",
"cls_or_slf",
"=",
"self_",
".",
"self_or_cls",
"param_obj",
"=",
"cls_or_slf",
".",
"param",
".",
"objects",
"(",
"'existing'",
")",
".",
"get",
"(",
"name",
... | 31.083333 | 16.75 |
def transcribe_file(self, file_path, clip_length=10, compress=True):
'''
a method to transcribe the text from an audio file
EXAMPLE: https://github.com/dannguyen/watson-word-watcher
:param file_path: string with path to audio file on localhost
:para... | [
"def",
"transcribe_file",
"(",
"self",
",",
"file_path",
",",
"clip_length",
"=",
"10",
",",
"compress",
"=",
"True",
")",
":",
"title",
"=",
"'%s.transcribe_file'",
"%",
"self",
".",
"__class__",
".",
"__name__",
"# validate inputs\r",
"input_fields",
"=",
"{... | 37.504587 | 20.513761 |
def get_vulnerability_functions_04(fname):
"""
Parse the vulnerability model in NRML 0.4 format.
:param fname:
path of the vulnerability file
:returns:
a dictionary imt, taxonomy -> vulnerability function + vset
"""
categories = dict(assetCategory=set(), lossCategory=set(),
... | [
"def",
"get_vulnerability_functions_04",
"(",
"fname",
")",
":",
"categories",
"=",
"dict",
"(",
"assetCategory",
"=",
"set",
"(",
")",
",",
"lossCategory",
"=",
"set",
"(",
")",
",",
"vulnerabilitySetID",
"=",
"set",
"(",
")",
")",
"imts",
"=",
"set",
"... | 44.55102 | 15.612245 |
def _create(cls, configuration=None, remoteckan=None, **kwargs):
# type: (Optional['Configuration'], Optional[ckanapi.RemoteCKAN], Any) -> str
"""
Create HDX configuration
Args:
configuration (Optional[Configuration]): Configuration instance. Defaults to setting one up from ... | [
"def",
"_create",
"(",
"cls",
",",
"configuration",
"=",
"None",
",",
"remoteckan",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# type: (Optional['Configuration'], Optional[ckanapi.RemoteCKAN], Any) -> str",
"kwargs",
"=",
"cls",
".",
"_environment_variables",
"(... | 62.911765 | 36.323529 |
def list(self, pattern='*'):
"""Returns a list of groups that match the filters.
Args:
pattern: An optional pattern to filter the groups based on their display
name. This can include Unix shell-style wildcards. E.g.
``"Production*"``.
Returns:
A list of Group objects that m... | [
"def",
"list",
"(",
"self",
",",
"pattern",
"=",
"'*'",
")",
":",
"if",
"self",
".",
"_group_dict",
"is",
"None",
":",
"self",
".",
"_group_dict",
"=",
"collections",
".",
"OrderedDict",
"(",
"(",
"group",
".",
"id",
",",
"group",
")",
"for",
"group"... | 35.294118 | 21.176471 |
def saveAsTable(self, name, format=None, mode=None, partitionBy=None, **options):
"""Saves the content of the :class:`DataFrame` as the specified table.
In the case the table already exists, behavior of this function depends on the
save mode, specified by the `mode` function (default to throwin... | [
"def",
"saveAsTable",
"(",
"self",
",",
"name",
",",
"format",
"=",
"None",
",",
"mode",
"=",
"None",
",",
"partitionBy",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"self",
".",
"mode",
"(",
"mode",
")",
".",
"options",
"(",
"*",
"*",
"opti... | 49.615385 | 21.115385 |
def get_pool(cls) -> Pool:
"""
Yields:
existing db connection pool
"""
if len(cls._connection_params) < 5:
raise ConnectionError('Please call SQLStore.connect before calling this method')
if not cls._pool:
cls._pool = yield from create_pool(**c... | [
"def",
"get_pool",
"(",
"cls",
")",
"->",
"Pool",
":",
"if",
"len",
"(",
"cls",
".",
"_connection_params",
")",
"<",
"5",
":",
"raise",
"ConnectionError",
"(",
"'Please call SQLStore.connect before calling this method'",
")",
"if",
"not",
"cls",
".",
"_pool",
... | 35.8 | 15.8 |
def waitForNextState( self ):
'''After each command has been sent we wait for the observation to change as expected and a frame.'''
# wait for the observation position to have changed
print('Waiting for observation...', end=' ')
while True:
world_state = self.agent_host.peekW... | [
"def",
"waitForNextState",
"(",
"self",
")",
":",
"# wait for the observation position to have changed",
"print",
"(",
"'Waiting for observation...'",
",",
"end",
"=",
"' '",
")",
"while",
"True",
":",
"world_state",
"=",
"self",
".",
"agent_host",
".",
"peekWorldStat... | 53.285714 | 22.047619 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.