text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def inner_join_impl(other, sequence):
"""
Implementation for part of join_impl
:param other: other sequence to join with
:param sequence: first sequence to join with
:return: joined sequence
"""
seq_dict = {}
for element in sequence:
seq_dict[element[0]] = element[1]
seq_kv =... | [
"def",
"inner_join_impl",
"(",
"other",
",",
"sequence",
")",
":",
"seq_dict",
"=",
"{",
"}",
"for",
"element",
"in",
"sequence",
":",
"seq_dict",
"[",
"element",
"[",
"0",
"]",
"]",
"=",
"element",
"[",
"1",
"]",
"seq_kv",
"=",
"seq_dict",
"other_kv",... | 31.944444 | 10.944444 |
def remove_citation_metadata(graph):
"""Remove the metadata associated with a citation.
Best practice is to add this information programmatically.
"""
for u, v, k in graph.edges(keys=True):
if CITATION not in graph[u][v][k]:
continue
for key in list(graph[u][v][k][CITATION])... | [
"def",
"remove_citation_metadata",
"(",
"graph",
")",
":",
"for",
"u",
",",
"v",
",",
"k",
"in",
"graph",
".",
"edges",
"(",
"keys",
"=",
"True",
")",
":",
"if",
"CITATION",
"not",
"in",
"graph",
"[",
"u",
"]",
"[",
"v",
"]",
"[",
"k",
"]",
":"... | 37.090909 | 10.454545 |
def get_as_string(self, s3_path, encoding='utf-8'):
"""
Get the contents of an object stored in S3 as string.
:param s3_path: URL for target S3 location
:param encoding: Encoding to decode bytes to string
:return: File contents as a string
"""
content = self.get_... | [
"def",
"get_as_string",
"(",
"self",
",",
"s3_path",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"content",
"=",
"self",
".",
"get_as_bytes",
"(",
"s3_path",
")",
"return",
"content",
".",
"decode",
"(",
"encoding",
")"
] | 36.8 | 10.8 |
def svd_entropy(X, Tau, DE, W=None):
"""Compute SVD Entropy from either two cases below:
1. a time series X, with lag tau and embedding dimension dE (default)
2. a list, W, of normalized singular values of a matrix (if W is provided,
recommend to speed up.)
If W is None, the function will do as fol... | [
"def",
"svd_entropy",
"(",
"X",
",",
"Tau",
",",
"DE",
",",
"W",
"=",
"None",
")",
":",
"if",
"W",
"is",
"None",
":",
"Y",
"=",
"embed_seq",
"(",
"X",
",",
"Tau",
",",
"DE",
")",
"W",
"=",
"numpy",
".",
"linalg",
".",
"svd",
"(",
"Y",
",",
... | 33.787879 | 22.818182 |
def biopax_process_pc_neighborhood():
"""Process PathwayCommons neighborhood, return INDRA Statements."""
if request.method == 'OPTIONS':
return {}
response = request.body.read().decode('utf-8')
body = json.loads(response)
genes = body.get('genes')
bp = biopax.process_pc_neighborhood(gen... | [
"def",
"biopax_process_pc_neighborhood",
"(",
")",
":",
"if",
"request",
".",
"method",
"==",
"'OPTIONS'",
":",
"return",
"{",
"}",
"response",
"=",
"request",
".",
"body",
".",
"read",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"body",
"=",
"json",
... | 38.555556 | 8.444444 |
def dump_requestdriver_cookies_into_webdriver(requestdriver, webdriverwrapper, handle_sub_domain=True):
"""Adds all cookies in the RequestDriver session to Webdriver
@type requestdriver: RequestDriver
@param requestdriver: RequestDriver with cookies
@type webdriverwrapper: WebDriverWrapper
@param w... | [
"def",
"dump_requestdriver_cookies_into_webdriver",
"(",
"requestdriver",
",",
"webdriverwrapper",
",",
"handle_sub_domain",
"=",
"True",
")",
":",
"driver_hostname",
"=",
"urlparse",
"(",
"webdriverwrapper",
".",
"current_url",
"(",
")",
")",
".",
"netloc",
"for",
... | 44.634146 | 21.219512 |
def generate_scan_parameter_description(scan_parameters):
'''Generate scan parameter dictionary. This is the only way to dynamically create table with dictionary, cannot be done with tables.IsDescription
Parameters
----------
scan_parameters : list, tuple
List of scan parameters names (strings)... | [
"def",
"generate_scan_parameter_description",
"(",
"scan_parameters",
")",
":",
"table_description",
"=",
"np",
".",
"dtype",
"(",
"[",
"(",
"key",
",",
"tb",
".",
"Int32Col",
"(",
"pos",
"=",
"idx",
")",
")",
"for",
"idx",
",",
"key",
"in",
"enumerate",
... | 39.157895 | 38.105263 |
def compare_version(a, b): # Ignore PyDocStyleBear
"""Compare two version strings.
:param a: str
:param b: str
:return: -1 / 0 / 1
"""
def _range(q):
"""Convert a version string to array of integers.
"1.2.3" -> [1, 2, 3]
:param q: str
:return: List[int]
... | [
"def",
"compare_version",
"(",
"a",
",",
"b",
")",
":",
"# Ignore PyDocStyleBear",
"def",
"_range",
"(",
"q",
")",
":",
"\"\"\"Convert a version string to array of integers.\n\n \"1.2.3\" -> [1, 2, 3]\n\n :param q: str\n :return: List[int]\n \"\"\"",
"r",
... | 24.327273 | 17.836364 |
def address_to_coords(self, address):
"""Convert address to coordinates"""
base_coords = self.BASE_COORDS[self.region]
get_cord = self.COORD_SERVERS[self.region]
url_options = {
"q": address,
"lang": "eng",
"origin": "livemap",
"lat": base... | [
"def",
"address_to_coords",
"(",
"self",
",",
"address",
")",
":",
"base_coords",
"=",
"self",
".",
"BASE_COORDS",
"[",
"self",
".",
"region",
"]",
"get_cord",
"=",
"self",
".",
"COORD_SERVERS",
"[",
"self",
".",
"region",
"]",
"url_options",
"=",
"{",
"... | 47.038462 | 22.5 |
def get_trips(
feed: "Feed", date: Optional[str] = None, time: Optional[str] = None
) -> DataFrame:
"""
Return a subset of ``feed.trips``.
Parameters
----------
feed : Feed
date : string
YYYYMMDD date string
time : string
HH:MM:SS time string, possibly with HH > 23
... | [
"def",
"get_trips",
"(",
"feed",
":",
"\"Feed\"",
",",
"date",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"time",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"DataFrame",
":",
"if",
"feed",
".",
"trips",
"is",
"None",
"or",
... | 26.528302 | 20.264151 |
def by_tag_id(self,tag_id):
'''Return all the semantic tag related to the given tag id
:returns: a semantic tag or None
:rtype: list of ckan.model.semantictag.SemanticTag object
'''
query = meta.Session.query(TagSemanticTag).filter(TagSemanticTag.tag_id==tag_id)
return query.first() | [
"def",
"by_tag_id",
"(",
"self",
",",
"tag_id",
")",
":",
"query",
"=",
"meta",
".",
"Session",
".",
"query",
"(",
"TagSemanticTag",
")",
".",
"filter",
"(",
"TagSemanticTag",
".",
"tag_id",
"==",
"tag_id",
")",
"return",
"query",
".",
"first",
"(",
")... | 32.111111 | 25.888889 |
def load_plugins(self, plugin_dirs=None, quiet=True):
"""
Load plugins in `sys.path` and :attr:`plugin_dirs`
Parameters
----------
plugin_dirs : list or tuple of string, optional
A list or tuple of plugin directory path
quiet : bool, optional
If T... | [
"def",
"load_plugins",
"(",
"self",
",",
"plugin_dirs",
"=",
"None",
",",
"quiet",
"=",
"True",
")",
":",
"from",
"pkg_resources",
"import",
"working_set",
"from",
"pkg_resources",
"import",
"iter_entry_points",
"from",
"pkg_resources",
"import",
"Environment",
"i... | 35.707317 | 17.365854 |
def run_until_shutdown(self):
''' Run the Bokeh Server until shutdown is requested by the user,
either via a Keyboard interrupt (Ctrl-C) or SIGTERM.
Calling this method will start the Tornado ``IOLoop`` and block
all execution in the calling process.
Returns:
None
... | [
"def",
"run_until_shutdown",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_started",
":",
"self",
".",
"start",
"(",
")",
"# Install shutdown hooks",
"atexit",
".",
"register",
"(",
"self",
".",
"_atexit",
")",
"signal",
".",
"signal",
"(",
"signal",
... | 30.380952 | 20.095238 |
def max_placeable_height_on_deck(self, placeable):
"""
:param placeable:
:return: Calibrated height of container in mm from
deck as the reference point
"""
offset = placeable.top()[1]
placeable_coordinate = add(
pose_tracker.absolute(
s... | [
"def",
"max_placeable_height_on_deck",
"(",
"self",
",",
"placeable",
")",
":",
"offset",
"=",
"placeable",
".",
"top",
"(",
")",
"[",
"1",
"]",
"placeable_coordinate",
"=",
"add",
"(",
"pose_tracker",
".",
"absolute",
"(",
"self",
".",
"poses",
",",
"plac... | 33.625 | 13.625 |
def _hammer_function_precompute(self,x0, L, Min, model):
"""
Pre-computes the parameters of a penalizer centered at x0.
"""
if x0 is None: return None, None
if len(x0.shape)==1: x0 = x0[None,:]
m = model.predict(x0)[0]
pred = model.predict(x0)[1].copy()
pr... | [
"def",
"_hammer_function_precompute",
"(",
"self",
",",
"x0",
",",
"L",
",",
"Min",
",",
"model",
")",
":",
"if",
"x0",
"is",
"None",
":",
"return",
"None",
",",
"None",
"if",
"len",
"(",
"x0",
".",
"shape",
")",
"==",
"1",
":",
"x0",
"=",
"x0",
... | 32.266667 | 10.266667 |
def _is_range_request_processable(self, environ):
"""Return ``True`` if `Range` header is present and if underlying
resource is considered unchanged when compared with `If-Range` header.
"""
return (
"HTTP_IF_RANGE" not in environ
or not is_resource_modified(
... | [
"def",
"_is_range_request_processable",
"(",
"self",
",",
"environ",
")",
":",
"return",
"(",
"\"HTTP_IF_RANGE\"",
"not",
"in",
"environ",
"or",
"not",
"is_resource_modified",
"(",
"environ",
",",
"self",
".",
"headers",
".",
"get",
"(",
"\"etag\"",
")",
",",
... | 38.071429 | 10.785714 |
def tags_getListUserPopular(user_id='', count=''):
"""Gets the popular tags for a user in dictionary form tag=>count"""
method = 'flickr.tags.getListUserPopular'
auth = user_id == ''
data = _doget(method, auth=auth, user_id=user_id)
result = {}
if isinstance(data.rsp.tags.tag, list):
for... | [
"def",
"tags_getListUserPopular",
"(",
"user_id",
"=",
"''",
",",
"count",
"=",
"''",
")",
":",
"method",
"=",
"'flickr.tags.getListUserPopular'",
"auth",
"=",
"user_id",
"==",
"''",
"data",
"=",
"_doget",
"(",
"method",
",",
"auth",
"=",
"auth",
",",
"use... | 39.083333 | 12.75 |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'name') and self.name is not None:
_dict['name'] = self.name
if hasattr(self, 'role') and self.role is not None:
_dict['role'] = self.role
return _dict | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'name'",
")",
"and",
"self",
".",
"name",
"is",
"not",
"None",
":",
"_dict",
"[",
"'name'",
"]",
"=",
"self",
".",
"name",
"if",
"hasattr",
"(",... | 39 | 13.375 |
def parse_xml_report(cls, conf, path):
"""Parse the ivy xml report corresponding to the name passed to ivy.
:API: public
:param string conf: the ivy conf name (e.g. "default")
:param string path: The path to the ivy report file.
:returns: The info in the xml report.
:rtype: :class:`IvyInfo`
... | [
"def",
"parse_xml_report",
"(",
"cls",
",",
"conf",
",",
"path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"raise",
"cls",
".",
"IvyResolveReportError",
"(",
"'Missing expected ivy output file {}'",
".",
"format",
"(",
... | 39.3 | 19.525 |
def metadataContributer(self):
"""gets the metadata featurelayer object"""
if self._metaFL is None:
fl = FeatureService(url=self._metadataURL,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
self._metaFS = fl
... | [
"def",
"metadataContributer",
"(",
"self",
")",
":",
"if",
"self",
".",
"_metaFL",
"is",
"None",
":",
"fl",
"=",
"FeatureService",
"(",
"url",
"=",
"self",
".",
"_metadataURL",
",",
"proxy_url",
"=",
"self",
".",
"_proxy_url",
",",
"proxy_port",
"=",
"se... | 42.125 | 11.25 |
def purge_items(app, env, docname):
"""
Clean, if existing, ``item`` entries in ``traceability_all_items``
environment variable, for all the source docs being purged.
This function should be triggered upon ``env-purge-doc`` event.
"""
keys = list(env.traceability_all_items.keys())
for key ... | [
"def",
"purge_items",
"(",
"app",
",",
"env",
",",
"docname",
")",
":",
"keys",
"=",
"list",
"(",
"env",
".",
"traceability_all_items",
".",
"keys",
"(",
")",
")",
"for",
"key",
"in",
"keys",
":",
"if",
"env",
".",
"traceability_all_items",
"[",
"key",... | 35.916667 | 18.916667 |
def get_tag_value(x, key):
"""Get a value from tag"""
if x is None:
return ''
result = [y['Value'] for y in x if y['Key'] == key]
if result:
return result[0]
return '' | [
"def",
"get_tag_value",
"(",
"x",
",",
"key",
")",
":",
"if",
"x",
"is",
"None",
":",
"return",
"''",
"result",
"=",
"[",
"y",
"[",
"'Value'",
"]",
"for",
"y",
"in",
"x",
"if",
"y",
"[",
"'Key'",
"]",
"==",
"key",
"]",
"if",
"result",
":",
"r... | 24.5 | 18 |
def get_schedules_for_season(self, season, season_type="REG"):
"""
Game schedule for a specified season.
"""
try:
season = int(season)
if season_type not in ["REG", "PRE", "POST"]:
raise ValueError
except (ValueError, TypeError):
... | [
"def",
"get_schedules_for_season",
"(",
"self",
",",
"season",
",",
"season_type",
"=",
"\"REG\"",
")",
":",
"try",
":",
"season",
"=",
"int",
"(",
"season",
")",
"if",
"season_type",
"not",
"in",
"[",
"\"REG\"",
",",
"\"PRE\"",
",",
"\"POST\"",
"]",
":"... | 38.357143 | 17.357143 |
def load_grid_data(file_list, data_type="binary", sort=True, delim=" "):
"""
Loads data from one or multiple grid_task files.
Arguments:
file_list - either a string or a list of strings indicating files to
load data from. Files are assumed to be in grid_task.dat
... | [
"def",
"load_grid_data",
"(",
"file_list",
",",
"data_type",
"=",
"\"binary\"",
",",
"sort",
"=",
"True",
",",
"delim",
"=",
"\" \"",
")",
":",
"# If there's only one file, we pretend it's a list",
"if",
"not",
"type",
"(",
"file_list",
")",
"is",
"list",
":",
... | 38.183333 | 20.35 |
def predict(self, test_data, **kwargs):
"""
Adjust new input by the values in the training data
"""
if test_data.shape[1]!=self.data.shape[1]:
raise Exception("Test data has different number of columns than training data.")
for i in xrange(0,test_data.shape[1]):
... | [
"def",
"predict",
"(",
"self",
",",
"test_data",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"test_data",
".",
"shape",
"[",
"1",
"]",
"!=",
"self",
".",
"data",
".",
"shape",
"[",
"1",
"]",
":",
"raise",
"Exception",
"(",
"\"Test data has different numbe... | 48 | 16.363636 |
def one_vertical_total_stress(self, z_c):
"""
Determine the vertical total stress at a single depth z_c.
:param z_c: depth from surface
"""
total_stress = 0.0
depths = self.depths
end = 0
for layer_int in range(1, len(depths) + 1):
l_index = l... | [
"def",
"one_vertical_total_stress",
"(",
"self",
",",
"z_c",
")",
":",
"total_stress",
"=",
"0.0",
"depths",
"=",
"self",
".",
"depths",
"end",
"=",
"0",
"for",
"layer_int",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"depths",
")",
"+",
"1",
")",
":",... | 42.088235 | 20.5 |
def getFeatureID(self, location):
"""
Returns the feature index associated with the provided location.
In the case of a sphere, it is always the same if the location is valid.
"""
if not self.contains(location):
return self.EMPTY_FEATURE
return self.SPHERICAL_SURFACE | [
"def",
"getFeatureID",
"(",
"self",
",",
"location",
")",
":",
"if",
"not",
"self",
".",
"contains",
"(",
"location",
")",
":",
"return",
"self",
".",
"EMPTY_FEATURE",
"return",
"self",
".",
"SPHERICAL_SURFACE"
] | 29 | 17.2 |
def choices(self):
"""Menu options for new configuration files
"""
print("| {0}K{1}{2}eep the old and .new files, no changes".format(
self.red, self.endc, self.br))
print("| {0}O{1}{2}verwrite all old configuration files with new "
"ones".format(self.red, self.e... | [
"def",
"choices",
"(",
"self",
")",
":",
"print",
"(",
"\"| {0}K{1}{2}eep the old and .new files, no changes\"",
".",
"format",
"(",
"self",
".",
"red",
",",
"self",
".",
"endc",
",",
"self",
".",
"br",
")",
")",
"print",
"(",
"\"| {0}O{1}{2}verwrite all old con... | 41.035714 | 16.392857 |
def recv_match(self, condition=None, type=None, blocking=False):
'''recv the next message that matches the given condition
type can be a string or a list of strings'''
if type is not None and not isinstance(type, list):
type = [type]
while True:
m = self.recv_msg(... | [
"def",
"recv_match",
"(",
"self",
",",
"condition",
"=",
"None",
",",
"type",
"=",
"None",
",",
"blocking",
"=",
"False",
")",
":",
"if",
"type",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"type",
",",
"list",
")",
":",
"type",
"=",
"[",... | 40.571429 | 18.428571 |
def get_failing_line(xml_string, exc_msg):
"""
Extract the failing line from the XML string, as indicated by the
line/column information in the exception message.
Returns a tuple (lineno, colno, new_pos, line), where lineno and colno
and marker_pos may be None.
"""
max_before = 500 # max c... | [
"def",
"get_failing_line",
"(",
"xml_string",
",",
"exc_msg",
")",
":",
"max_before",
"=",
"500",
"# max characters before reported position",
"max_after",
"=",
"500",
"# max characters after reported position",
"max_unknown",
"=",
"1000",
"# max characters when position cannot... | 45.033333 | 16.233333 |
def _calc_CI(
sampler,
modelidx=0,
confs=[3, 1],
last_step=False,
e_range=None,
e_npoints=100,
threads=None,
):
"""Calculate confidence interval.
"""
from scipy import stats
# If we are computing the samples for the confidence intervals, we need at
# least one sample to ... | [
"def",
"_calc_CI",
"(",
"sampler",
",",
"modelidx",
"=",
"0",
",",
"confs",
"=",
"[",
"3",
",",
"1",
"]",
",",
"last_step",
"=",
"False",
",",
"e_range",
"=",
"None",
",",
"e_npoints",
"=",
"100",
",",
"threads",
"=",
"None",
",",
")",
":",
"from... | 30.938462 | 19.307692 |
def rename(self, new_name):
"""
Rename an image
"""
return self.get_data(
"images/%s" % self.id,
type=PUT,
params={"name": new_name}
) | [
"def",
"rename",
"(",
"self",
",",
"new_name",
")",
":",
"return",
"self",
".",
"get_data",
"(",
"\"images/%s\"",
"%",
"self",
".",
"id",
",",
"type",
"=",
"PUT",
",",
"params",
"=",
"{",
"\"name\"",
":",
"new_name",
"}",
")"
] | 22.888889 | 10.666667 |
def create_client(storage_account, timeout, proxy):
# type: (blobxfer.operations.azure.StorageAccount,
# blobxfer.models.options.Timeout,
# blobxfer.models.options.HttpProxy) -> FileService
"""Create file client
:param blobxfer.operations.azure.StorageAccount storage_account:
s... | [
"def",
"create_client",
"(",
"storage_account",
",",
"timeout",
",",
"proxy",
")",
":",
"# type: (blobxfer.operations.azure.StorageAccount,",
"# blobxfer.models.options.Timeout,",
"# blobxfer.models.options.HttpProxy) -> FileService",
"if",
"storage_account",
".",
"is_s... | 41 | 12.941176 |
def _pfp__set_value(self, new_val):
"""Set the value, potentially converting an unsigned
value to a signed one (and visa versa)"""
if self._pfp__frozen:
raise errors.UnmodifiableConst()
if isinstance(new_val, IntBase):
# will automatically convert correctly betwe... | [
"def",
"_pfp__set_value",
"(",
"self",
",",
"new_val",
")",
":",
"if",
"self",
".",
"_pfp__frozen",
":",
"raise",
"errors",
".",
"UnmodifiableConst",
"(",
")",
"if",
"isinstance",
"(",
"new_val",
",",
"IntBase",
")",
":",
"# will automatically convert correctly ... | 31.023256 | 12.302326 |
def _read_buffer(self, data_in):
"""Process the socket buffer, and direct the data to the appropriate
channel.
:rtype: bytes
"""
while data_in:
data_in, channel_id, frame_in = self._handle_amqp_frame(data_in)
if frame_in is None:
break
... | [
"def",
"_read_buffer",
"(",
"self",
",",
"data_in",
")",
":",
"while",
"data_in",
":",
"data_in",
",",
"channel_id",
",",
"frame_in",
"=",
"self",
".",
"_handle_amqp_frame",
"(",
"data_in",
")",
"if",
"frame_in",
"is",
"None",
":",
"break",
"self",
".",
... | 29.368421 | 18.789474 |
def mktemp(self, container: Container) -> str:
"""
Generates a temporary file for a given container.
Returns:
the path to the temporary file inside the given container.
"""
r = self.__api.post('containers/{}/tempfile'.format(container.uid))
if r.status_code =... | [
"def",
"mktemp",
"(",
"self",
",",
"container",
":",
"Container",
")",
"->",
"str",
":",
"r",
"=",
"self",
".",
"__api",
".",
"post",
"(",
"'containers/{}/tempfile'",
".",
"format",
"(",
"container",
".",
"uid",
")",
")",
"if",
"r",
".",
"status_code",... | 35.636364 | 16.363636 |
def places_autocomplete_query(client, input_text, offset=None, location=None,
radius=None, language=None):
"""
Returns Place predictions given a textual search query, such as
"pizza near New York", and optional geographic bounds.
:param input_text: The text query on which ... | [
"def",
"places_autocomplete_query",
"(",
"client",
",",
"input_text",
",",
"offset",
"=",
"None",
",",
"location",
"=",
"None",
",",
"radius",
"=",
"None",
",",
"language",
"=",
"None",
")",
":",
"return",
"_autocomplete",
"(",
"client",
",",
"\"query\"",
... | 40.25 | 24.75 |
def build_rdn(self):
"""
Build the Relative Distinguished Name for this entry.
"""
bits = []
for field in self._meta.fields:
if field.db_column and field.primary_key:
bits.append("%s=%s" % (field.db_column,
getatt... | [
"def",
"build_rdn",
"(",
"self",
")",
":",
"bits",
"=",
"[",
"]",
"for",
"field",
"in",
"self",
".",
"_meta",
".",
"fields",
":",
"if",
"field",
".",
"db_column",
"and",
"field",
".",
"primary_key",
":",
"bits",
".",
"append",
"(",
"\"%s=%s\"",
"%",
... | 37.666667 | 14.166667 |
def add_gene(self, gene):
"""Add the information of a gene
This adds a gene dict to variant['genes']
Args:
gene (dict): A gene dictionary
"""
logger.debug("Adding gene {0} to variant {1}".format(
gene, self['variant_id']))
self['gene... | [
"def",
"add_gene",
"(",
"self",
",",
"gene",
")",
":",
"logger",
".",
"debug",
"(",
"\"Adding gene {0} to variant {1}\"",
".",
"format",
"(",
"gene",
",",
"self",
"[",
"'variant_id'",
"]",
")",
")",
"self",
"[",
"'genes'",
"]",
".",
"append",
"(",
"gene"... | 27.083333 | 17.166667 |
def do_restart(self, line):
"""
Attempt to restart the bot.
"""
self.bot._frame = 0
self.bot._namespace.clear()
self.bot._namespace.update(self.bot._initial_namespace) | [
"def",
"do_restart",
"(",
"self",
",",
"line",
")",
":",
"self",
".",
"bot",
".",
"_frame",
"=",
"0",
"self",
".",
"bot",
".",
"_namespace",
".",
"clear",
"(",
")",
"self",
".",
"bot",
".",
"_namespace",
".",
"update",
"(",
"self",
".",
"bot",
".... | 29.857143 | 8.428571 |
def nulldata_script(data: bytes) -> NulldataScript:
'''create nulldata (OP_return) script'''
stack = StackData.from_bytes(data)
return NulldataScript(stack) | [
"def",
"nulldata_script",
"(",
"data",
":",
"bytes",
")",
"->",
"NulldataScript",
":",
"stack",
"=",
"StackData",
".",
"from_bytes",
"(",
"data",
")",
"return",
"NulldataScript",
"(",
"stack",
")"
] | 33 | 13 |
def simple_signatures(ambiguous_word: str, pos: str = None, lemma=True, stem=False,
hyperhypo=True, stop=True, from_cache=True) -> dict:
"""
Returns a synsets_signatures dictionary that includes signature words of a
sense from its:
(i) definition
(ii) example sentences
(i... | [
"def",
"simple_signatures",
"(",
"ambiguous_word",
":",
"str",
",",
"pos",
":",
"str",
"=",
"None",
",",
"lemma",
"=",
"True",
",",
"stem",
"=",
"False",
",",
"hyperhypo",
"=",
"True",
",",
"stop",
"=",
"True",
",",
"from_cache",
"=",
"True",
")",
"-... | 44.722222 | 21.166667 |
def parse_extras(self):
# type: () -> None
"""
Parse extras from *self.line* and set them on the current object
:returns: Nothing
:rtype: None
"""
extras = None
if "@" in self.line or self.is_vcs or self.is_url:
line = "{0}".format(self.line)
... | [
"def",
"parse_extras",
"(",
"self",
")",
":",
"# type: () -> None",
"extras",
"=",
"None",
"if",
"\"@\"",
"in",
"self",
".",
"line",
"or",
"self",
".",
"is_vcs",
"or",
"self",
".",
"is_url",
":",
"line",
"=",
"\"{0}\"",
".",
"format",
"(",
"self",
".",... | 37.666667 | 17.121212 |
def current(self, fields=None):
"""Returns dict of current values for all tracked fields"""
if fields is None:
deferred_fields = self.deferred_fields
if deferred_fields:
fields = [
field for field in self.fields
if field not... | [
"def",
"current",
"(",
"self",
",",
"fields",
"=",
"None",
")",
":",
"if",
"fields",
"is",
"None",
":",
"deferred_fields",
"=",
"self",
".",
"deferred_fields",
"if",
"deferred_fields",
":",
"fields",
"=",
"[",
"field",
"for",
"field",
"in",
"self",
".",
... | 35.923077 | 14.769231 |
def take_nd(self, indexer, axis=0, new_mgr_locs=None, fill_tuple=None):
"""
Take values according to indexer and return them as a block.
"""
if fill_tuple is None:
fill_value = None
else:
fill_value = fill_tuple[0]
# axis doesn't matter; we are re... | [
"def",
"take_nd",
"(",
"self",
",",
"indexer",
",",
"axis",
"=",
"0",
",",
"new_mgr_locs",
"=",
"None",
",",
"fill_tuple",
"=",
"None",
")",
":",
"if",
"fill_tuple",
"is",
"None",
":",
"fill_value",
"=",
"None",
"else",
":",
"fill_value",
"=",
"fill_tu... | 38.136364 | 19.954545 |
def freeze(self, no_etag=False):
"""Call this method if you want to make your response object ready for
pickeling. This buffers the generator if there is one. This also
sets the etag unless `no_etag` is set to `True`.
"""
if not no_etag:
self.add_etag()
supe... | [
"def",
"freeze",
"(",
"self",
",",
"no_etag",
"=",
"False",
")",
":",
"if",
"not",
"no_etag",
":",
"self",
".",
"add_etag",
"(",
")",
"super",
"(",
"ETagResponseMixin",
",",
"self",
")",
".",
"freeze",
"(",
")"
] | 43.5 | 11.875 |
def process_model(model):
"""Returns a BiopaxProcessor for a BioPAX model object.
Parameters
----------
model : org.biopax.paxtools.model.Model
A BioPAX model object.
Returns
-------
bp : BiopaxProcessor
A BiopaxProcessor containing the obtained BioPAX model in bp.model.
... | [
"def",
"process_model",
"(",
"model",
")",
":",
"bp",
"=",
"BiopaxProcessor",
"(",
"model",
")",
"bp",
".",
"get_modifications",
"(",
")",
"bp",
".",
"get_regulate_activities",
"(",
")",
"bp",
".",
"get_regulate_amounts",
"(",
")",
"bp",
".",
"get_activity_m... | 24.708333 | 17.875 |
def pillar_refresh(self, force_refresh=False, notify=False):
'''
Refresh the pillar
'''
if self.connected:
log.debug('Refreshing pillar. Notify: %s', notify)
async_pillar = salt.pillar.get_async_pillar(
self.opts,
self.opts['grains'... | [
"def",
"pillar_refresh",
"(",
"self",
",",
"force_refresh",
"=",
"False",
",",
"notify",
"=",
"False",
")",
":",
"if",
"self",
".",
"connected",
":",
"log",
".",
"debug",
"(",
"'Refreshing pillar. Notify: %s'",
",",
"notify",
")",
"async_pillar",
"=",
"salt"... | 42.37037 | 19.111111 |
async def oauth2_request(
self,
url: str,
access_token: str = None,
post_args: Dict[str, Any] = None,
**args: Any
) -> Any:
"""Fetches the given URL auth an OAuth2 access token.
If the request is a POST, ``post_args`` should be provided. Query
string ... | [
"async",
"def",
"oauth2_request",
"(",
"self",
",",
"url",
":",
"str",
",",
"access_token",
":",
"str",
"=",
"None",
",",
"post_args",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
"=",
"None",
",",
"*",
"*",
"args",
":",
"Any",
")",
"->",
"Any",
":"... | 33.363636 | 21.036364 |
def choropleth(self, *args, **kwargs):
"""Call the Choropleth class with the same arguments.
This method may be deleted after a year from now (Nov 2018).
"""
warnings.warn(
'The choropleth method has been deprecated. Instead use the new '
'Choropleth class, whic... | [
"def",
"choropleth",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"warnings",
".",
"warn",
"(",
"'The choropleth method has been deprecated. Instead use the new '",
"'Choropleth class, which has the same arguments. See the example '",
"'notebook \\'GeoJSON... | 42.846154 | 19.769231 |
def basis(start, stop=None, dim=1, sort="G", cross_truncation=1.):
"""
Create an N-dimensional unit polynomial basis.
Args:
start (int, numpy.ndarray):
the minimum polynomial to include. If int is provided, set as
lowest total order. If array of int, set as lower order alon... | [
"def",
"basis",
"(",
"start",
",",
"stop",
"=",
"None",
",",
"dim",
"=",
"1",
",",
"sort",
"=",
"\"G\"",
",",
"cross_truncation",
"=",
"1.",
")",
":",
"if",
"stop",
"is",
"None",
":",
"start",
",",
"stop",
"=",
"numpy",
".",
"array",
"(",
"0",
... | 32.216867 | 18.698795 |
def order_target_value(id_or_ins, cash_amount, price=None, style=None):
"""
买入/卖出并且自动调整该证券的仓位到一个目标价值。
加仓时,cash_amount 代表现有持仓的价值加上即将花费(包含税费)的现金的总价值。
减仓时,cash_amount 代表调整仓位的目标价至。
需要注意,如果资金不足,该API将不会创建发送订单。
:param id_or_ins: 下单标的物
:type id_or_ins: :class:`~Instrument` object | `str` | List[:c... | [
"def",
"order_target_value",
"(",
"id_or_ins",
",",
"cash_amount",
",",
"price",
"=",
"None",
",",
"style",
"=",
"None",
")",
":",
"order_book_id",
"=",
"assure_stock_order_book_id",
"(",
"id_or_ins",
")",
"account",
"=",
"Environment",
".",
"get_instance",
"(",... | 33.232558 | 25.744186 |
def stage_subset(self, *files_to_add: str):
"""
Stages a subset of files
:param files_to_add: files to stage
:type files_to_add: str
"""
LOGGER.info('staging files: %s', files_to_add)
self.repo.git.add(*files_to_add, A=True) | [
"def",
"stage_subset",
"(",
"self",
",",
"*",
"files_to_add",
":",
"str",
")",
":",
"LOGGER",
".",
"info",
"(",
"'staging files: %s'",
",",
"files_to_add",
")",
"self",
".",
"repo",
".",
"git",
".",
"add",
"(",
"*",
"files_to_add",
",",
"A",
"=",
"True... | 30.333333 | 9.444444 |
def remove_handler(self, handler: Handler, group: int = 0):
"""Removes a previously-added update handler.
Make sure to provide the right group that the handler was added in. You can use
the return value of the :meth:`add_handler` method, a tuple of (handler, group), and
pass it directly... | [
"def",
"remove_handler",
"(",
"self",
",",
"handler",
":",
"Handler",
",",
"group",
":",
"int",
"=",
"0",
")",
":",
"if",
"isinstance",
"(",
"handler",
",",
"DisconnectHandler",
")",
":",
"self",
".",
"disconnect_handler",
"=",
"None",
"else",
":",
"self... | 37.277778 | 19.833333 |
def set_topological_dag_upstreams(dag, ops, op_runs, runs_by_ops):
"""Set the upstream runs for the operation runs in the dag following the topological sort."""
sorted_ops = dags.sort_topologically(dag=dag)
for op_id in sorted_ops:
op_run_id = runs_by_ops[op_id]
op_run = op_runs[op_run_id]
... | [
"def",
"set_topological_dag_upstreams",
"(",
"dag",
",",
"ops",
",",
"op_runs",
",",
"runs_by_ops",
")",
":",
"sorted_ops",
"=",
"dags",
".",
"sort_topologically",
"(",
"dag",
"=",
"dag",
")",
"for",
"op_id",
"in",
"sorted_ops",
":",
"op_run_id",
"=",
"runs_... | 52.428571 | 9.714286 |
def uealite(
word,
max_word_length=20,
max_acro_length=8,
return_rule_no=False,
var='standard',
):
"""Return UEA-Lite stem.
This is a wrapper for :py:meth:`UEALite.stem`.
Parameters
----------
word : str
The word to stem
max_word_length : int
The maximum wor... | [
"def",
"uealite",
"(",
"word",
",",
"max_word_length",
"=",
"20",
",",
"max_acro_length",
"=",
"8",
",",
"return_rule_no",
"=",
"False",
",",
"var",
"=",
"'standard'",
",",
")",
":",
"return",
"UEALite",
"(",
")",
".",
"stem",
"(",
"word",
",",
"max_wo... | 20.102041 | 22.122449 |
def renew_local_branch(branch, start_point, remote=False):
"""Make a new local branch from that start_point
start_point is a git "commit-ish", e.g branch, tag, commit
If a local branch already exists it is removed
If remote is true then push the new branch to origin
"""
if branch in branches()... | [
"def",
"renew_local_branch",
"(",
"branch",
",",
"start_point",
",",
"remote",
"=",
"False",
")",
":",
"if",
"branch",
"in",
"branches",
"(",
")",
":",
"checkout",
"(",
"start_point",
")",
"delete",
"(",
"branch",
",",
"force",
"=",
"True",
",",
"remote"... | 33 | 16.933333 |
def build_mock_repository(conn_, file_path_list, verbose):
"""
Build the mock repository from the file_path list and fake connection
instance. This allows both mof files and python files to be used to
build the repository.
If verbose is True, it displays the respository after it is build as
mo... | [
"def",
"build_mock_repository",
"(",
"conn_",
",",
"file_path_list",
",",
"verbose",
")",
":",
"for",
"file_path",
"in",
"file_path_list",
":",
"ext",
"=",
"_os",
".",
"path",
".",
"splitext",
"(",
"file_path",
")",
"[",
"1",
"]",
"if",
"not",
"_os",
"."... | 41.410256 | 20.230769 |
def iter_modules(path=None, prefix=''):
"""Yields (module_loader, name, ispkg) for all submodules on path,
or, if path is None, all top-level modules on sys.path.
'path' should be either None or a list of paths to look for
modules in.
'prefix' is a string to output on the front of every module nam... | [
"def",
"iter_modules",
"(",
"path",
"=",
"None",
",",
"prefix",
"=",
"''",
")",
":",
"if",
"path",
"is",
"None",
":",
"importers",
"=",
"iter_importers",
"(",
")",
"else",
":",
"importers",
"=",
"map",
"(",
"get_importer",
",",
"path",
")",
"yielded",
... | 29.363636 | 18.954545 |
def workers():
"""Show information on salactus workers. (slow)"""
counter = Counter()
for w in Worker.all(connection=worker.connection):
for q in w.queues:
counter[q.name] += 1
import pprint
pprint.pprint(dict(counter)) | [
"def",
"workers",
"(",
")",
":",
"counter",
"=",
"Counter",
"(",
")",
"for",
"w",
"in",
"Worker",
".",
"all",
"(",
"connection",
"=",
"worker",
".",
"connection",
")",
":",
"for",
"q",
"in",
"w",
".",
"queues",
":",
"counter",
"[",
"q",
".",
"nam... | 31.5 | 13.75 |
def informed_consent(self):
"""Create a URL for the user to give their consent through"""
if self.typeable_handle is None:
consent_url = [self.config['server']['server_url'],
"/get_initial_consent?username="]
consent_url.append(urlsafe_b64encode(self.us... | [
"def",
"informed_consent",
"(",
"self",
")",
":",
"if",
"self",
".",
"typeable_handle",
"is",
"None",
":",
"consent_url",
"=",
"[",
"self",
".",
"config",
"[",
"'server'",
"]",
"[",
"'server_url'",
"]",
",",
"\"/get_initial_consent?username=\"",
"]",
"consent_... | 45.9375 | 16 |
def send_buffered_messages(self):
"""Send messages in out_stream to the Stream Manager"""
while not self.out_stream.is_empty() and self._stmgr_client.is_registered:
tuple_set = self.out_stream.poll()
if isinstance(tuple_set, tuple_pb2.HeronTupleSet):
tuple_set.src_task_id = self.my_pplan_hel... | [
"def",
"send_buffered_messages",
"(",
"self",
")",
":",
"while",
"not",
"self",
".",
"out_stream",
".",
"is_empty",
"(",
")",
"and",
"self",
".",
"_stmgr_client",
".",
"is_registered",
":",
"tuple_set",
"=",
"self",
".",
"out_stream",
".",
"poll",
"(",
")"... | 55.75 | 15.125 |
def set_column_prop(self, prop, values, repeat="up"):
"""
Specify the properties of the columns
:param values:
:param repeat: if 'up' then duplicate up the structure
:return:
"""
values = np.array(values)
if repeat == "up":
assert len(values.s... | [
"def",
"set_column_prop",
"(",
"self",
",",
"prop",
",",
"values",
",",
"repeat",
"=",
"\"up\"",
")",
":",
"values",
"=",
"np",
".",
"array",
"(",
"values",
")",
"if",
"repeat",
"==",
"\"up\"",
":",
"assert",
"len",
"(",
"values",
".",
"shape",
")",
... | 37.631579 | 14.368421 |
def create(cls, user, **kwargs):
"""If parent resource is not an editable state, should not be able to create."""
parent_id = kwargs.get(cls.parent_resource.resource_type + '_id')
try:
parent = yield cls.parent_resource.get(parent_id)
except couch.NotFound:
msg = ... | [
"def",
"create",
"(",
"cls",
",",
"user",
",",
"*",
"*",
"kwargs",
")",
":",
"parent_id",
"=",
"kwargs",
".",
"get",
"(",
"cls",
".",
"parent_resource",
".",
"resource_type",
"+",
"'_id'",
")",
"try",
":",
"parent",
"=",
"yield",
"cls",
".",
"parent_... | 40.526316 | 19.684211 |
def lint(context):
"""Looks for errors in source code of your blog"""
config = context.obj
try:
run('flake8 {dir} --exclude={exclude}'.format(
dir=config['CWD'],
exclude=','.join(EXCLUDE),
))
except SubprocessError:
context.exit(1) | [
"def",
"lint",
"(",
"context",
")",
":",
"config",
"=",
"context",
".",
"obj",
"try",
":",
"run",
"(",
"'flake8 {dir} --exclude={exclude}'",
".",
"format",
"(",
"dir",
"=",
"config",
"[",
"'CWD'",
"]",
",",
"exclude",
"=",
"','",
".",
"join",
"(",
"EXC... | 26 | 17.818182 |
def set_metric_by_day(self, unique_identifier, metric, date, count, sync_agg=True, update_counter=True):
"""
Sets the count for the ``metric`` for ``unique_identifier``.
You must specify a ``date`` for the ``count`` to be set on. Useful for resetting a metric count to 0 or decrementing a metric.... | [
"def",
"set_metric_by_day",
"(",
"self",
",",
"unique_identifier",
",",
"metric",
",",
"date",
",",
"count",
",",
"sync_agg",
"=",
"True",
",",
"update_counter",
"=",
"True",
")",
":",
"metric",
"=",
"[",
"metric",
"]",
"if",
"isinstance",
"(",
"metric",
... | 60.611111 | 41 |
def xception_exit(inputs):
"""Xception exit flow."""
with tf.variable_scope("xception_exit"):
x = inputs
x_shape = x.get_shape().as_list()
if x_shape[1] is None or x_shape[2] is None:
length_float = tf.to_float(tf.shape(x)[1])
length_float *= tf.to_float(tf.shape(x)[2])
spatial_dim_flo... | [
"def",
"xception_exit",
"(",
"inputs",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"\"xception_exit\"",
")",
":",
"x",
"=",
"inputs",
"x_shape",
"=",
"x",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"if",
"x_shape",
"[",
"1",
"]",
"... | 43.952381 | 15.904762 |
def __prepare_usertexts(self):
"""Replace user-type text fields that start with "py3o." with genshi
instructions.
"""
field_expr = "//text:user-field-get[starts-with(@text:name, 'py3o.')]"
for content_tree in self.content_trees:
for userfield in content_tree.xpath(... | [
"def",
"__prepare_usertexts",
"(",
"self",
")",
":",
"field_expr",
"=",
"\"//text:user-field-get[starts-with(@text:name, 'py3o.')]\"",
"for",
"content_tree",
"in",
"self",
".",
"content_trees",
":",
"for",
"userfield",
"in",
"content_tree",
".",
"xpath",
"(",
"field_exp... | 36.814815 | 19.864198 |
def logarithmic_interpolation_extrapolation(df, target_height):
r"""
Logarithmic inter- or extrapolates between the values of a data frame.
This function can be used for the inter-/extrapolation of the wind speed if
it is available at two or more different heights, to approximate
the value at hub h... | [
"def",
"logarithmic_interpolation_extrapolation",
"(",
"df",
",",
"target_height",
")",
":",
"# find closest heights",
"heights_sorted",
"=",
"df",
".",
"columns",
"[",
"sorted",
"(",
"range",
"(",
"len",
"(",
"df",
".",
"columns",
")",
")",
",",
"key",
"=",
... | 39.867925 | 26.566038 |
def nextSolarEclipse(date):
""" Returns the Datetime of the maximum phase of the
next global solar eclipse.
"""
eclipse = swe.solarEclipseGlobal(date.jd, backward=False)
return Datetime.fromJD(eclipse['maximum'], date.utcoffset) | [
"def",
"nextSolarEclipse",
"(",
"date",
")",
":",
"eclipse",
"=",
"swe",
".",
"solarEclipseGlobal",
"(",
"date",
".",
"jd",
",",
"backward",
"=",
"False",
")",
"return",
"Datetime",
".",
"fromJD",
"(",
"eclipse",
"[",
"'maximum'",
"]",
",",
"date",
".",
... | 30.375 | 18.25 |
def get_environment(self):
"""Return environment details."""
environment = junos_views.junos_environment_table(self.device)
routing_engine = junos_views.junos_routing_engine_table(self.device)
temperature_thresholds = junos_views.junos_temperature_thresholds(self.device)
power_su... | [
"def",
"get_environment",
"(",
"self",
")",
":",
"environment",
"=",
"junos_views",
".",
"junos_environment_table",
"(",
"self",
".",
"device",
")",
"routing_engine",
"=",
"junos_views",
".",
"junos_routing_engine_table",
"(",
"self",
".",
"device",
")",
"temperat... | 48.797619 | 23.220238 |
def metric_data(
self, id, names, values=None, from_dt=None, to_dt=None,
summarize=False):
"""
This API endpoint returns a list of values for each of the requested
metrics. The list of available metrics can be returned using the Metric
Name API endpoint.
... | [
"def",
"metric_data",
"(",
"self",
",",
"id",
",",
"names",
",",
"values",
"=",
"None",
",",
"from_dt",
"=",
"None",
",",
"to_dt",
"=",
"None",
",",
"summarize",
"=",
"False",
")",
":",
"params",
"=",
"[",
"'from={0}'",
".",
"format",
"(",
"from_dt",... | 32.052632 | 21.236842 |
def render_constants():
"""render generated constant files from templates"""
generate_file("constant_enums.pxi", cython_enums, pjoin(root, 'zmq', 'backend', 'cython'))
generate_file("constants.pxi", constants_pyx, pjoin(root, 'zmq', 'backend', 'cython'))
generate_file("zmq_constants.h", ifndefs, pjoin(r... | [
"def",
"render_constants",
"(",
")",
":",
"generate_file",
"(",
"\"constant_enums.pxi\"",
",",
"cython_enums",
",",
"pjoin",
"(",
"root",
",",
"'zmq'",
",",
"'backend'",
",",
"'cython'",
")",
")",
"generate_file",
"(",
"\"constants.pxi\"",
",",
"constants_pyx",
... | 67.4 | 31 |
def plot_labels(labels, lattice=None, coords_are_cartesian=False, ax=None,
**kwargs):
"""
Adds labels to a matplotlib Axes
Args:
labels: dict containing the label as a key and the coordinates as value.
lattice: Lattice object used to convert from reciprocal to cartesian coor... | [
"def",
"plot_labels",
"(",
"labels",
",",
"lattice",
"=",
"None",
",",
"coords_are_cartesian",
"=",
"False",
",",
"ax",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ax",
",",
"fig",
",",
"plt",
"=",
"get_ax3d_fig_plt",
"(",
"ax",
")",
"if",
"\"co... | 34.825 | 20.075 |
def row(self):
"""Returns current data row: MyDBRow object, or None"""
ret = None
i = self.tableWidget.currentRow()
if i >= 0:
ret = self._data[i]
return ret | [
"def",
"row",
"(",
"self",
")",
":",
"ret",
"=",
"None",
"i",
"=",
"self",
".",
"tableWidget",
".",
"currentRow",
"(",
")",
"if",
"i",
">=",
"0",
":",
"ret",
"=",
"self",
".",
"_data",
"[",
"i",
"]",
"return",
"ret"
] | 29.857143 | 14.142857 |
def _from_dict(cls, _dict):
"""Initialize a Collection object from a json dictionary."""
args = {}
if 'collection_id' in _dict:
args['collection_id'] = _dict.get('collection_id')
if 'name' in _dict:
args['name'] = _dict.get('name')
if 'description' in _dic... | [
"def",
"_from_dict",
"(",
"cls",
",",
"_dict",
")",
":",
"args",
"=",
"{",
"}",
"if",
"'collection_id'",
"in",
"_dict",
":",
"args",
"[",
"'collection_id'",
"]",
"=",
"_dict",
".",
"get",
"(",
"'collection_id'",
")",
"if",
"'name'",
"in",
"_dict",
":",... | 44.78125 | 12.03125 |
def close_debt_position(self, symbol, account=None):
""" Close a debt position and reclaim the collateral
:param str symbol: Symbol to close debt position for
:raises ValueError: if symbol has no open call position
"""
if not account:
if "default_account" in ... | [
"def",
"close_debt_position",
"(",
"self",
",",
"symbol",
",",
"account",
"=",
"None",
")",
":",
"if",
"not",
"account",
":",
"if",
"\"default_account\"",
"in",
"self",
".",
"blockchain",
".",
"config",
":",
"account",
"=",
"self",
".",
"blockchain",
".",
... | 43.305556 | 18.444444 |
def list(self, **params):
"""
Retrieve all lead unqualified reasons
Returns all lead unqualified reasons available to the user according to the parameters provided
:calls: ``get /lead_unqualified_reasons``
:param dict params: (optional) Search options.
:return: List of ... | [
"def",
"list",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"_",
",",
"_",
",",
"lead_unqualified_reasons",
"=",
"self",
".",
"http_client",
".",
"get",
"(",
"\"/lead_unqualified_reasons\"",
",",
"params",
"=",
"params",
")",
"return",
"lead_unqualified_r... | 42.142857 | 28.571429 |
def terminate(self, *, force: bool=False, timeout: float=30.0,
step: float=1.0) -> None:
'''Stop all scheduled and/or executing tasks, first by asking nicely,
and then by waiting up to `timeout` seconds before forcefully stopping
the asyncio event loop.'''
if isinstanc... | [
"def",
"terminate",
"(",
"self",
",",
"*",
",",
"force",
":",
"bool",
"=",
"False",
",",
"timeout",
":",
"float",
"=",
"30.0",
",",
"step",
":",
"float",
"=",
"1.0",
")",
"->",
"None",
":",
"if",
"isinstance",
"(",
"self",
".",
"monitor",
",",
"a... | 40.470588 | 21.764706 |
def _print(self, ms, style="TIP"):
""" abstraction for managing color printing """
styles1 = {'IMPORTANT': Style.BRIGHT,
'TIP': Style.DIM,
'URI': Style.BRIGHT,
'TEXT': Fore.GREEN,
'MAGENTA': Fore.MAGENTA,
'BLU... | [
"def",
"_print",
"(",
"self",
",",
"ms",
",",
"style",
"=",
"\"TIP\"",
")",
":",
"styles1",
"=",
"{",
"'IMPORTANT'",
":",
"Style",
".",
"BRIGHT",
",",
"'TIP'",
":",
"Style",
".",
"DIM",
",",
"'URI'",
":",
"Style",
".",
"BRIGHT",
",",
"'TEXT'",
":",... | 37.75 | 8.6875 |
def get_array_for_fit(observables: dict, track_pt_bin: int, jet_pt_bin: int) -> histogram.Histogram1D:
""" Get a Histogram1D associated with the selected jet and track pt bins.
This is often used to retrieve data for fitting.
Args:
observables (dict): The observables from which the hist should be ... | [
"def",
"get_array_for_fit",
"(",
"observables",
":",
"dict",
",",
"track_pt_bin",
":",
"int",
",",
"jet_pt_bin",
":",
"int",
")",
"->",
"histogram",
".",
"Histogram1D",
":",
"for",
"name",
",",
"observable",
"in",
"observables",
".",
"items",
"(",
")",
":"... | 47.736842 | 29.421053 |
def pop_all(self):
"""Preserve the context stack by transferring it to a new instance."""
new_stack = type(self)()
new_stack._exit_callbacks = self._exit_callbacks
self._exit_callbacks = deque()
return new_stack | [
"def",
"pop_all",
"(",
"self",
")",
":",
"new_stack",
"=",
"type",
"(",
"self",
")",
"(",
")",
"new_stack",
".",
"_exit_callbacks",
"=",
"self",
".",
"_exit_callbacks",
"self",
".",
"_exit_callbacks",
"=",
"deque",
"(",
")",
"return",
"new_stack"
] | 41 | 10.666667 |
def inatoms(self, reverse=False):
"""Yield the singleton for every non-member."""
if reverse:
return filterfalse(self.__and__, reversed(self._atoms))
return filterfalse(self.__and__, self._atoms) | [
"def",
"inatoms",
"(",
"self",
",",
"reverse",
"=",
"False",
")",
":",
"if",
"reverse",
":",
"return",
"filterfalse",
"(",
"self",
".",
"__and__",
",",
"reversed",
"(",
"self",
".",
"_atoms",
")",
")",
"return",
"filterfalse",
"(",
"self",
".",
"__and_... | 45.4 | 13.6 |
def value(self):
"""Returns the value of this Slot."""
if hasattr(self, '_value_decoded'):
return self._value_decoded
if self.value_blob is not None:
encoded_value = self.value_blob.open().read()
else:
encoded_value = self.value_text
self._value_decoded = json.loads(encoded_value... | [
"def",
"value",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_value_decoded'",
")",
":",
"return",
"self",
".",
"_value_decoded",
"if",
"self",
".",
"value_blob",
"is",
"not",
"None",
":",
"encoded_value",
"=",
"self",
".",
"value_blob",
"... | 30.25 | 17.166667 |
def mean_se(series, mult=1):
"""
Calculate mean and standard errors on either side
"""
m = np.mean(series)
se = mult * np.sqrt(np.var(series) / len(series))
return pd.DataFrame({'y': [m],
'ymin': m-se,
'ymax': m+se}) | [
"def",
"mean_se",
"(",
"series",
",",
"mult",
"=",
"1",
")",
":",
"m",
"=",
"np",
".",
"mean",
"(",
"series",
")",
"se",
"=",
"mult",
"*",
"np",
".",
"sqrt",
"(",
"np",
".",
"var",
"(",
"series",
")",
"/",
"len",
"(",
"series",
")",
")",
"r... | 31.333333 | 7.111111 |
def do_attribute_query(self, entityid, subject_id,
attribute=None, sp_name_qualifier=None,
name_qualifier=None, nameid_format=None,
real_id=None, consent=None, extensions=None,
sign=False, binding=BINDING_SOAP, n... | [
"def",
"do_attribute_query",
"(",
"self",
",",
"entityid",
",",
"subject_id",
",",
"attribute",
"=",
"None",
",",
"sp_name_qualifier",
"=",
"None",
",",
"name_qualifier",
"=",
"None",
",",
"nameid_format",
"=",
"None",
",",
"real_id",
"=",
"None",
",",
"cons... | 49.447761 | 22.044776 |
def run(bam_file, data, out_dir):
"""Create several log files"""
m = {"base": None, "secondary": []}
m.update(_mirbase_stats(data, out_dir))
m["secondary"].append(_seqcluster_stats(data, out_dir)) | [
"def",
"run",
"(",
"bam_file",
",",
"data",
",",
"out_dir",
")",
":",
"m",
"=",
"{",
"\"base\"",
":",
"None",
",",
"\"secondary\"",
":",
"[",
"]",
"}",
"m",
".",
"update",
"(",
"_mirbase_stats",
"(",
"data",
",",
"out_dir",
")",
")",
"m",
"[",
"\... | 41.6 | 6 |
def _design_poll(self, name, mode, oldres, timeout=5, use_devmode=False):
"""
Poll for an 'async' action to be complete.
:param string name: The name of the design document
:param string mode: One of ``add`` or ``del`` to indicate whether
we should check for addition or delet... | [
"def",
"_design_poll",
"(",
"self",
",",
"name",
",",
"mode",
",",
"oldres",
",",
"timeout",
"=",
"5",
",",
"use_devmode",
"=",
"False",
")",
":",
"if",
"not",
"timeout",
":",
"return",
"True",
"if",
"timeout",
"<",
"0",
":",
"raise",
"ArgumentError",
... | 34.5 | 19.934783 |
def account_xdr_object(self):
"""Create PublicKey XDR object via public key bytes.
:return: Serialized XDR of PublicKey type.
"""
return Xdr.types.PublicKey(Xdr.const.KEY_TYPE_ED25519,
self.verifying_key.to_bytes()) | [
"def",
"account_xdr_object",
"(",
"self",
")",
":",
"return",
"Xdr",
".",
"types",
".",
"PublicKey",
"(",
"Xdr",
".",
"const",
".",
"KEY_TYPE_ED25519",
",",
"self",
".",
"verifying_key",
".",
"to_bytes",
"(",
")",
")"
] | 39.571429 | 15.428571 |
def obfuscate_unique(tokens, index, replace, replacement, *args):
"""
If the token string (a unique value anywhere) inside *tokens[index]*
matches *replace*, return *replacement*.
.. note::
This function is only for replacing absolutely unique ocurrences of
*replace* (where we don't ha... | [
"def",
"obfuscate_unique",
"(",
"tokens",
",",
"index",
",",
"replace",
",",
"replacement",
",",
"*",
"args",
")",
":",
"def",
"return_replacement",
"(",
"replacement",
")",
":",
"UNIQUE_REPLACEMENTS",
"[",
"replacement",
"]",
"=",
"replace",
"return",
"replac... | 34.45 | 16.45 |
def ex_call(func, args):
"""A function-call expression with only positional parameters. The
function may be an expression or the name of a function. Each
argument may be an expression or a value to be used as a literal.
"""
if isinstance(func, str):
func = ex_rvalue(func)
args = list(ar... | [
"def",
"ex_call",
"(",
"func",
",",
"args",
")",
":",
"if",
"isinstance",
"(",
"func",
",",
"str",
")",
":",
"func",
"=",
"ex_rvalue",
"(",
"func",
")",
"args",
"=",
"list",
"(",
"args",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"args",
... | 33.352941 | 14.823529 |
def check_match(self, name):
"""
Check if a release version matches any of the specificed patterns.
Parameters
==========
name: str
Release name
Returns
=======
bool:
True if it matches, False otherwise.
"""
return... | [
"def",
"check_match",
"(",
"self",
",",
"name",
")",
":",
"return",
"any",
"(",
"pattern",
".",
"match",
"(",
"name",
")",
"for",
"pattern",
"in",
"self",
".",
"patterns",
")"
] | 24 | 21.466667 |
async def get_self_info(self, get_self_info_request):
"""Return info about the current user."""
response = hangouts_pb2.GetSelfInfoResponse()
await self._pb_request('contacts/getselfinfo',
get_self_info_request, response)
return response | [
"async",
"def",
"get_self_info",
"(",
"self",
",",
"get_self_info_request",
")",
":",
"response",
"=",
"hangouts_pb2",
".",
"GetSelfInfoResponse",
"(",
")",
"await",
"self",
".",
"_pb_request",
"(",
"'contacts/getselfinfo'",
",",
"get_self_info_request",
",",
"respo... | 49.166667 | 13.333333 |
def _find_free_location(self, free_locations, required_sectors=1, preferred=None):
"""
Given a list of booleans, find a list of <required_sectors> consecutive True values.
If no such list is found, return length(free_locations).
Assumes first two values are always False.
"""
... | [
"def",
"_find_free_location",
"(",
"self",
",",
"free_locations",
",",
"required_sectors",
"=",
"1",
",",
"preferred",
"=",
"None",
")",
":",
"# check preferred (current) location",
"if",
"preferred",
"and",
"all",
"(",
"free_locations",
"[",
"preferred",
":",
"pr... | 45.863636 | 22.318182 |
def cleanup_subprocesses():
"""On python exit: find possibly running subprocesses and kill them."""
# pylint: disable=redefined-outer-name, reimported
# atexit functions tends to loose global imports sometimes so reimport
# everything what is needed again here:
import os
import errno
from mi... | [
"def",
"cleanup_subprocesses",
"(",
")",
":",
"# pylint: disable=redefined-outer-name, reimported",
"# atexit functions tends to loose global imports sometimes so reimport",
"# everything what is needed again here:",
"import",
"os",
"import",
"errno",
"from",
"mirakuru",
".",
"base_env... | 38.470588 | 16.411765 |
def rundata(self, strjson):
"""POST JSON data object to server"""
d = json.loads(strjson)
return self.api.data.post(d) | [
"def",
"rundata",
"(",
"self",
",",
"strjson",
")",
":",
"d",
"=",
"json",
".",
"loads",
"(",
"strjson",
")",
"return",
"self",
".",
"api",
".",
"data",
".",
"post",
"(",
"d",
")"
] | 27.8 | 13.2 |
def parse_version_output(out):
"""
Parses the output of 'docker version --format="{{json .}}"'. Essentially just returns the parsed JSON string,
like the Docker API does. Fields are slightly different however.
:param out: CLI output.
:type out: unicode | str
:return: Parsed result.
:rtype: ... | [
"def",
"parse_version_output",
"(",
"out",
")",
":",
"parsed",
"=",
"json",
".",
"loads",
"(",
"out",
",",
"encoding",
"=",
"'utf-8'",
")",
"if",
"parsed",
":",
"return",
"parsed",
".",
"get",
"(",
"'Client'",
",",
"{",
"}",
")",
"return",
"{",
"}"
] | 31.071429 | 19.5 |
def is_one_edit(s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if len(s) > len(t):
return is_one_edit(t, s)
if len(t) - len(s) > 1 or t == s:
return False
for i in range(len(s)):
if s[i] != t[i]:
return s[i+1:] == t[i+1:] or s[i:] == t[i+1:]
... | [
"def",
"is_one_edit",
"(",
"s",
",",
"t",
")",
":",
"if",
"len",
"(",
"s",
")",
">",
"len",
"(",
"t",
")",
":",
"return",
"is_one_edit",
"(",
"t",
",",
"s",
")",
"if",
"len",
"(",
"t",
")",
"-",
"len",
"(",
"s",
")",
">",
"1",
"or",
"t",
... | 22.785714 | 14.928571 |
def availability_sets_list_available_sizes(name, resource_group, **kwargs): # pylint: disable=invalid-name
'''
.. versionadded:: 2019.2.0
List all available virtual machine sizes that can be used to
to create a new virtual machine in an existing availability set.
:param name: The availability set... | [
"def",
"availability_sets_list_available_sizes",
"(",
"name",
",",
"resource_group",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=invalid-name",
"result",
"=",
"{",
"}",
"compconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'compute'",
",",... | 31.486486 | 26.567568 |
def get_obj_class(self, obj_type):
""" Returns the object class based on parent and object types.
In most cases the object class can be derived from object type alone but sometimes the
same object type name is used for different object types so the parent (or even
grandparent) type is r... | [
"def",
"get_obj_class",
"(",
"self",
",",
"obj_type",
")",
":",
"if",
"obj_type",
"in",
"IxnObject",
".",
"str_2_class",
":",
"if",
"type",
"(",
"IxnObject",
".",
"str_2_class",
"[",
"obj_type",
"]",
")",
"is",
"dict",
":",
"if",
"self",
".",
"obj_type",... | 54.045455 | 29 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.