text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def calculate_leapdays(init_date, final_date):
"""Currently unsupported, it only works for differences in years."""
leap_days = (final_date.year - 1) // 4 - (init_date.year - 1) // 4
leap_days -= (final_date.year - 1) // 100 - (init_date.year - 1) // 100
leap_days += (final_date.year - 1) // 400 - (ini... | [
"def",
"calculate_leapdays",
"(",
"init_date",
",",
"final_date",
")",
":",
"leap_days",
"=",
"(",
"final_date",
".",
"year",
"-",
"1",
")",
"//",
"4",
"-",
"(",
"init_date",
".",
"year",
"-",
"1",
")",
"//",
"4",
"leap_days",
"-=",
"(",
"final_date",
... | 45.6 | 26.4 |
def on_event_pre(self, e: Event) -> None:
"""Set values set on browser before calling event listeners."""
super().on_event_pre(e)
ct_msg = e.init.get('currentTarget', dict())
if e.type in ('input', 'change'):
self._set_attribute('value', ct_msg.get('value'))
_sele... | [
"def",
"on_event_pre",
"(",
"self",
",",
"e",
":",
"Event",
")",
"->",
"None",
":",
"super",
"(",
")",
".",
"on_event_pre",
"(",
"e",
")",
"ct_msg",
"=",
"e",
".",
"init",
".",
"get",
"(",
"'currentTarget'",
",",
"dict",
"(",
")",
")",
"if",
"e",... | 47.142857 | 9.5 |
def timedelta2period(duration):
"""Convert timedelta to different formats."""
seconds = duration.seconds
minutes = (seconds % 3600) // 60
seconds = (seconds % 60)
return '{0:0>2}:{1:0>2}'.format(minutes, seconds) | [
"def",
"timedelta2period",
"(",
"duration",
")",
":",
"seconds",
"=",
"duration",
".",
"seconds",
"minutes",
"=",
"(",
"seconds",
"%",
"3600",
")",
"//",
"60",
"seconds",
"=",
"(",
"seconds",
"%",
"60",
")",
"return",
"'{0:0>2}:{1:0>2}'",
".",
"format",
... | 37.833333 | 8 |
def main():
"""
Continues to validate patterns until it encounters EOF within a pattern
file or Ctrl-C is pressed by the user.
"""
parser = argparse.ArgumentParser(description='Validate STIX Patterns.')
parser.add_argument('-f', '--file',
help="Specify this arg to read pa... | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Validate STIX Patterns.'",
")",
"parser",
".",
"add_argument",
"(",
"'-f'",
",",
"'--file'",
",",
"help",
"=",
"\"Specify this arg to read patterns from a file... | 32.391304 | 20.043478 |
def switch_delete_record_for_userid(self, userid):
"""Remove userid switch record from switch table."""
with get_network_conn() as conn:
conn.execute("DELETE FROM switch WHERE userid=?",
(userid,))
LOG.debug("Switch record for user %s is removed from "
... | [
"def",
"switch_delete_record_for_userid",
"(",
"self",
",",
"userid",
")",
":",
"with",
"get_network_conn",
"(",
")",
"as",
"conn",
":",
"conn",
".",
"execute",
"(",
"\"DELETE FROM switch WHERE userid=?\"",
",",
"(",
"userid",
",",
")",
")",
"LOG",
".",
"debug... | 51.142857 | 9.714286 |
def make_transaction_frame(transactions):
"""
Formats a transaction DataFrame.
Parameters
----------
transactions : pd.DataFrame
Contains improperly formatted transactional data.
Returns
-------
df : pd.DataFrame
Daily transaction volume and dollar ammount.
- S... | [
"def",
"make_transaction_frame",
"(",
"transactions",
")",
":",
"transaction_list",
"=",
"[",
"]",
"for",
"dt",
"in",
"transactions",
".",
"index",
":",
"txns",
"=",
"transactions",
".",
"loc",
"[",
"dt",
"]",
"if",
"len",
"(",
"txns",
")",
"==",
"0",
... | 26.433333 | 18.5 |
def _find_listeners():
"""Find GPIB listeners.
"""
for i in range(31):
try:
if gpib.listener(BOARD, i) and gpib.ask(BOARD, 1) != i:
yield i
except gpib.GpibError as e:
logger.debug("GPIB error in _find_listeners(): %s", repr(e)) | [
"def",
"_find_listeners",
"(",
")",
":",
"for",
"i",
"in",
"range",
"(",
"31",
")",
":",
"try",
":",
"if",
"gpib",
".",
"listener",
"(",
"BOARD",
",",
"i",
")",
"and",
"gpib",
".",
"ask",
"(",
"BOARD",
",",
"1",
")",
"!=",
"i",
":",
"yield",
... | 32 | 16 |
def handle_connection(stream):
'''
Handle a connection.
The server operates a request/response cycle, so it performs a synchronous
loop:
1) Read data from network into wsproto
2) Get next wsproto event
3) Handle event
4) Send data from wsproto to network
:param stream: a socket st... | [
"def",
"handle_connection",
"(",
"stream",
")",
":",
"ws",
"=",
"WSConnection",
"(",
"ConnectionType",
".",
"SERVER",
")",
"# events is a generator that yields websocket event objects. Usually you",
"# would say `for event in ws.events()`, but the synchronous nature of this",
"# serv... | 36.31746 | 19.079365 |
def append(self, sc):
"""
Add scale 'sc' and remove any previous
scales that cover the same aesthetics
"""
ae = sc.aesthetics[0]
cover_ae = self.find(ae)
if any(cover_ae):
warn(_TPL_DUPLICATE_SCALE.format(ae), PlotnineWarning)
idx = cover_a... | [
"def",
"append",
"(",
"self",
",",
"sc",
")",
":",
"ae",
"=",
"sc",
".",
"aesthetics",
"[",
"0",
"]",
"cover_ae",
"=",
"self",
".",
"find",
"(",
"ae",
")",
"if",
"any",
"(",
"cover_ae",
")",
":",
"warn",
"(",
"_TPL_DUPLICATE_SCALE",
".",
"format",
... | 32.846154 | 9.769231 |
def remove_temporary_source(self):
"""Remove the source files from this requirement, if they are marked
for deletion"""
if self.source_dir and os.path.exists(
os.path.join(self.source_dir, PIP_DELETE_MARKER_FILENAME)):
logger.debug('Removing source in %s', self.source... | [
"def",
"remove_temporary_source",
"(",
"self",
")",
":",
"if",
"self",
".",
"source_dir",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"source_dir",
",",
"PIP_DELETE_MARKER_FILENAME",
")",
")",
":",
"log... | 48.454545 | 11.454545 |
def post(self, url, access_token=None, **kwargs):
"""
使用 POST 方法向微信服务器发出请求
:param url: 请求地址
:param access_token: access token 值, 如果初始化时传入 conf 会自动获取, 如果没有传入则请提供此值
:param kwargs: 附加数据
:return: 微信服务器响应的 JSON 数据
"""
return self.request(
method="po... | [
"def",
"post",
"(",
"self",
",",
"url",
",",
"access_token",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"request",
"(",
"method",
"=",
"\"post\"",
",",
"url",
"=",
"url",
",",
"access_token",
"=",
"access_token",
",",
"*",... | 28.714286 | 13.857143 |
def pad_length(s):
"""
Appends characters to the end of the string to increase the string length per
IBM Globalization Design Guideline A3: UI Expansion.
https://www-01.ibm.com/software/globalization/guidelines/a3.html
:param s: String to pad.
:returns: Padded string.
"""
padding_chars... | [
"def",
"pad_length",
"(",
"s",
")",
":",
"padding_chars",
"=",
"[",
"u'\\ufe4e'",
",",
"# ﹎: CENTRELINE LOW LINE",
"u'\\u040d'",
",",
"# Ѝ: CYRILLIC CAPITAL LETTER I WITH GRAVE",
"u'\\u05d0'",
",",
"# א: HEBREW LETTER ALEF",
"u'\\u01c6'",
",",
"# dž: LATIN SMALL LETTER DZ WITH... | 38.317073 | 16.658537 |
def loaddeposit(sources, depid):
"""Load deposit.
Usage:
invenio dumps loaddeposit ~/data/deposit_dump_*.json
invenio dumps loaddeposit -d 12345 ~/data/deposit_dump_*.json
"""
from .tasks.deposit import load_deposit
if depid is not None:
def pred(dep):
return int... | [
"def",
"loaddeposit",
"(",
"sources",
",",
"depid",
")",
":",
"from",
".",
"tasks",
".",
"deposit",
"import",
"load_deposit",
"if",
"depid",
"is",
"not",
"None",
":",
"def",
"pred",
"(",
"dep",
")",
":",
"return",
"int",
"(",
"dep",
"[",
"\"_p\"",
"]... | 33.071429 | 17.142857 |
def xpathNextFollowing(self, cur):
"""Traversal function for the "following" direction The
following axis contains all nodes in the same document as
the context node that are after the context node in
document order, excluding any descendants and excluding
attribute nodes... | [
"def",
"xpathNextFollowing",
"(",
"self",
",",
"cur",
")",
":",
"if",
"cur",
"is",
"None",
":",
"cur__o",
"=",
"None",
"else",
":",
"cur__o",
"=",
"cur",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"xmlXPathNextFollowing",
"(",
"self",
".",
"_o",
",",
... | 49.615385 | 15.692308 |
def neighbors(self, node_id):
"""Find all the nodes where there is an edge from the specified node to that node.
Returns a list of node ids."""
node = self.get_node(node_id)
return [self.get_edge(edge_id)['vertices'][1] for edge_id in node['edges']] | [
"def",
"neighbors",
"(",
"self",
",",
"node_id",
")",
":",
"node",
"=",
"self",
".",
"get_node",
"(",
"node_id",
")",
"return",
"[",
"self",
".",
"get_edge",
"(",
"edge_id",
")",
"[",
"'vertices'",
"]",
"[",
"1",
"]",
"for",
"edge_id",
"in",
"node",
... | 55.4 | 11.4 |
def init_state_from_encoder(self, encoder_outputs, encoder_valid_length=None):
"""Initialize the state from the encoder outputs.
Parameters
----------
encoder_outputs : list
encoder_valid_length : NDArray or None
Returns
-------
decoder_states : list
... | [
"def",
"init_state_from_encoder",
"(",
"self",
",",
"encoder_outputs",
",",
"encoder_valid_length",
"=",
"None",
")",
":",
"mem_value",
"=",
"encoder_outputs",
"decoder_states",
"=",
"[",
"mem_value",
"]",
"mem_length",
"=",
"mem_value",
".",
"shape",
"[",
"1",
... | 35.392857 | 14.607143 |
def kernel_matrix(svm_model, original_X):
if (svm_model.svm_kernel == 'polynomial_kernel' or svm_model.svm_kernel == 'soft_polynomial_kernel'):
K = (svm_model.zeta + svm_model.gamma * np.dot(original_X, original_X.T)) ** svm_model.Q
elif (svm_model.svm_kernel == 'gaussian_kernel' or svm_mod... | [
"def",
"kernel_matrix",
"(",
"svm_model",
",",
"original_X",
")",
":",
"if",
"(",
"svm_model",
".",
"svm_kernel",
"==",
"'polynomial_kernel'",
"or",
"svm_model",
".",
"svm_kernel",
"==",
"'soft_polynomial_kernel'",
")",
":",
"K",
"=",
"(",
"svm_model",
".",
"z... | 55.1 | 39.3 |
def MAC(self,days,rev = 0):
""" Comparing yesterday price is high, low or equal.
return ↑,↓ or -
與前一天 days 日收盤價移動平均比較
rev = 0
回傳 ↑,↓ or -
rev = 1
回傳 1,-1 or 0
"""
yesterday = self.raw_data[:]
yesterday.pop()
yes_MA = float(sum(yesterday[-days:]) / ... | [
"def",
"MAC",
"(",
"self",
",",
"days",
",",
"rev",
"=",
"0",
")",
":",
"yesterday",
"=",
"self",
".",
"raw_data",
"[",
":",
"]",
"yesterday",
".",
"pop",
"(",
")",
"yes_MA",
"=",
"float",
"(",
"sum",
"(",
"yesterday",
"[",
"-",
"days",
":",
"]... | 26.133333 | 15.266667 |
def group_values(self, group_name):
"""Return all distinct group values for given group."""
group_index = self.groups.index(group_name)
values = []
for key in self.data_keys:
if key[group_index] not in values:
values.append(key[group_index])
return val... | [
"def",
"group_values",
"(",
"self",
",",
"group_name",
")",
":",
"group_index",
"=",
"self",
".",
"groups",
".",
"index",
"(",
"group_name",
")",
"values",
"=",
"[",
"]",
"for",
"key",
"in",
"self",
".",
"data_keys",
":",
"if",
"key",
"[",
"group_index... | 39.5 | 9.375 |
def authenticate(self, driver):
"""Authenticate using the Console Server protocol specific FSM."""
# 0 1 2 3
events = [driver.username_re, driver.password_re, self.device.prompt_re, driver.rommon_re,
... | [
"def",
"authenticate",
"(",
"self",
",",
"driver",
")",
":",
"# 0 1 2 3",
"events",
"=",
"[",
"driver",
".",
"username_re",
",",
"driver",
".",
"password_re",
",",
"self",
".",
"device",
"."... | 66.5 | 33.884615 |
def _set_port_security(self, v, load=False):
"""
Setter method for port_security, mapped from YANG variable /interface/ethernet/switchport/port_security (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_port_security is considered as a private
method. Backe... | [
"def",
"_set_port_security",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"... | 75.291667 | 36.416667 |
def reformat_meta(self):
"""Collect the meta data information in a more user friendly format.
Function looks through the meta data, collecting the channel related information into a
dataframe and moving it into the _channels_ key.
"""
meta = self.annotation # For shorthand (pas... | [
"def",
"reformat_meta",
"(",
"self",
")",
":",
"meta",
"=",
"self",
".",
"annotation",
"# For shorthand (passed by reference)",
"channel_properties",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"meta",
".",
"items",
"(",
")",
":",
"if",
"key",
"[",
":... | 38.102564 | 20.282051 |
def change_owner(ctx, owner, uuid):
"""Changes the ownership of objects"""
objects = ctx.obj['objects']
database = ctx.obj['db']
if uuid is True:
owner_filter = {'uuid': owner}
else:
owner_filter = {'name': owner}
owner = database.objectmodels['user'].find_one(owner_filter)
... | [
"def",
"change_owner",
"(",
"ctx",
",",
"owner",
",",
"uuid",
")",
":",
"objects",
"=",
"ctx",
".",
"obj",
"[",
"'objects'",
"]",
"database",
"=",
"ctx",
".",
"obj",
"[",
"'db'",
"]",
"if",
"uuid",
"is",
"True",
":",
"owner_filter",
"=",
"{",
"'uui... | 22.333333 | 20.047619 |
def branch(self):
'''
:param branch:
Checks out specified branch (tracking if it exists on remote).
If set to ``None``, 'master' will be checked out
:returns:
The current branch
(This could also be 'master (Detatched-Head)' - Be warned)
'''... | [
"def",
"branch",
"(",
"self",
")",
":",
"branch",
"=",
"self",
".",
"_get_branch",
"(",
")",
".",
"get",
"(",
"'stdout'",
")",
"if",
"branch",
":",
"return",
"''",
".",
"join",
"(",
"[",
"b",
"for",
"b",
"in",
"branch",
"if",
"'*'",
"in",
"b",
... | 32.733333 | 20.6 |
def cmd_status(opts):
"""Print status of containers and networks
"""
config = load_config(opts.config)
b = get_blockade(config, opts)
containers = b.status()
print_containers(containers, opts.json) | [
"def",
"cmd_status",
"(",
"opts",
")",
":",
"config",
"=",
"load_config",
"(",
"opts",
".",
"config",
")",
"b",
"=",
"get_blockade",
"(",
"config",
",",
"opts",
")",
"containers",
"=",
"b",
".",
"status",
"(",
")",
"print_containers",
"(",
"containers",
... | 30.714286 | 6.285714 |
def hide_routemap_holder_route_map_action_rm(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
hide_routemap_holder = ET.SubElement(config, "hide-routemap-holder", xmlns="urn:brocade.com:mgmt:brocade-ip-policy")
route_map = ET.SubElement(hide_routemap_hold... | [
"def",
"hide_routemap_holder_route_map_action_rm",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"hide_routemap_holder",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"hide-routemap-holder\"",
... | 48.4 | 17.933333 |
def fraction_illuminated(ephemeris, body, t):
"""Compute the illuminated fraction of a body viewed from Earth.
The ``body`` should be an integer or string that can be looked up in
the given ``ephemeris``, which will also be asked to provide
positions for the Earth and Sun. The return value will be a
... | [
"def",
"fraction_illuminated",
"(",
"ephemeris",
",",
"body",
",",
"t",
")",
":",
"a",
"=",
"phase_angle",
"(",
"ephemeris",
",",
"body",
",",
"t",
")",
".",
"radians",
"return",
"0.5",
"*",
"(",
"1.0",
"+",
"cos",
"(",
"a",
")",
")"
] | 43.5 | 18.75 |
def job(self):
"""REST binding for the job associated with the submitted build.
Returns:
Job: REST binding for running job or ``None`` if connection information was not available or no job was submitted.
"""
if self._submitter and hasattr(self._submitter, '_job_access'):
... | [
"def",
"job",
"(",
"self",
")",
":",
"if",
"self",
".",
"_submitter",
"and",
"hasattr",
"(",
"self",
".",
"_submitter",
",",
"'_job_access'",
")",
":",
"return",
"self",
".",
"_submitter",
".",
"_job_access",
"(",
")",
"return",
"None"
] | 41.888889 | 26.222222 |
def _get_dict_from_list(dict_key, list_of_dicts):
"""Retrieve a specific dict from a list of dicts.
Parameters
----------
dict_key : str
The (single) key of the dict to be retrieved from the list.
list_of_dicts : list
The list of dicts to search for the specific dict.
Returns
... | [
"def",
"_get_dict_from_list",
"(",
"dict_key",
",",
"list_of_dicts",
")",
":",
"the_dict",
"=",
"[",
"cur_dict",
"for",
"cur_dict",
"in",
"list_of_dicts",
"if",
"cur_dict",
".",
"get",
"(",
"dict_key",
")",
"]",
"if",
"not",
"the_dict",
":",
"raise",
"ValueE... | 30.809524 | 21 |
def _UpdateProcessingStatus(self, pid, process_status, used_memory):
"""Updates the processing status.
Args:
pid (int): process identifier (PID) of the worker process.
process_status (dict[str, object]): status values received from
the worker process.
used_memory (int): size of used... | [
"def",
"_UpdateProcessingStatus",
"(",
"self",
",",
"pid",
",",
"process_status",
",",
"used_memory",
")",
":",
"self",
".",
"_RaiseIfNotRegistered",
"(",
"pid",
")",
"if",
"not",
"process_status",
":",
"return",
"process",
"=",
"self",
".",
"_processes_per_pid"... | 37.549296 | 20.253521 |
def set(self, id, translation, domain='messages'):
"""
Sets a message translation.
"""
assert isinstance(id, (str, unicode))
assert isinstance(translation, (str, unicode))
assert isinstance(domain, (str, unicode))
self.add({id: translation}, domain) | [
"def",
"set",
"(",
"self",
",",
"id",
",",
"translation",
",",
"domain",
"=",
"'messages'",
")",
":",
"assert",
"isinstance",
"(",
"id",
",",
"(",
"str",
",",
"unicode",
")",
")",
"assert",
"isinstance",
"(",
"translation",
",",
"(",
"str",
",",
"uni... | 33.111111 | 9.555556 |
def get_methods(self, node):
"""return visible methods"""
methods = [
m
for m in node.values()
if isinstance(m, astroid.FunctionDef)
and not decorated_with_property(m)
and self.show_attr(m.name)
]
return sorted(methods, key=lamb... | [
"def",
"get_methods",
"(",
"self",
",",
"node",
")",
":",
"methods",
"=",
"[",
"m",
"for",
"m",
"in",
"node",
".",
"values",
"(",
")",
"if",
"isinstance",
"(",
"m",
",",
"astroid",
".",
"FunctionDef",
")",
"and",
"not",
"decorated_with_property",
"(",
... | 32.4 | 12.6 |
def get_human_key(self, key):
"""Return the human key (aka Python identifier) of a key (aka database value)."""
for human_key, k in self._identifier_map.items():
if k == key:
return human_key
raise KeyError(key) | [
"def",
"get_human_key",
"(",
"self",
",",
"key",
")",
":",
"for",
"human_key",
",",
"k",
"in",
"self",
".",
"_identifier_map",
".",
"items",
"(",
")",
":",
"if",
"k",
"==",
"key",
":",
"return",
"human_key",
"raise",
"KeyError",
"(",
"key",
")"
] | 43 | 10.833333 |
def expand_composites (properties):
""" Expand all composite properties in the set so that all components
are explicitly expressed.
"""
if __debug__:
from .property import Property
assert is_iterable_typed(properties, Property)
explicit_features = set(p.feature for p in propertie... | [
"def",
"expand_composites",
"(",
"properties",
")",
":",
"if",
"__debug__",
":",
"from",
".",
"property",
"import",
"Property",
"assert",
"is_iterable_typed",
"(",
"properties",
",",
"Property",
")",
"explicit_features",
"=",
"set",
"(",
"p",
".",
"feature",
"... | 42.473684 | 23.105263 |
def load_byte(buf, pos):
"""Load single byte"""
end = pos + 1
if end > len(buf):
raise BadRarFile('cannot load byte')
return S_BYTE.unpack_from(buf, pos)[0], end | [
"def",
"load_byte",
"(",
"buf",
",",
"pos",
")",
":",
"end",
"=",
"pos",
"+",
"1",
"if",
"end",
">",
"len",
"(",
"buf",
")",
":",
"raise",
"BadRarFile",
"(",
"'cannot load byte'",
")",
"return",
"S_BYTE",
".",
"unpack_from",
"(",
"buf",
",",
"pos",
... | 30 | 11.333333 |
def reverse_timezone(self, query, timeout=DEFAULT_SENTINEL):
"""
Find the timezone for a point in `query`.
GeoNames always returns a timezone: if the point being queried
doesn't have an assigned Olson timezone id, a ``pytz.FixedOffset``
timezone is used to produce the :class:`ge... | [
"def",
"reverse_timezone",
"(",
"self",
",",
"query",
",",
"timeout",
"=",
"DEFAULT_SENTINEL",
")",
":",
"ensure_pytz_is_installed",
"(",
")",
"try",
":",
"lat",
",",
"lng",
"=",
"self",
".",
"_coerce_point_to_string",
"(",
"query",
")",
".",
"split",
"(",
... | 37.375 | 25.625 |
def list_topics(self, name):
'''
Retrieves the topics in the service namespace.
name:
Name of the service bus namespace.
'''
response = self._perform_get(
self._get_list_topics_path(name),
None)
return _MinidomXmlToObject.convert_resp... | [
"def",
"list_topics",
"(",
"self",
",",
"name",
")",
":",
"response",
"=",
"self",
".",
"_perform_get",
"(",
"self",
".",
"_get_list_topics_path",
"(",
"name",
")",
",",
"None",
")",
"return",
"_MinidomXmlToObject",
".",
"convert_response_to_feeds",
"(",
"resp... | 27.388889 | 20.722222 |
def retry_ex(callback, times=3, cap=120000):
"""
Retry a callback function if any exception is raised.
:param function callback: The function to call
:keyword int times: Number of times to retry on initial failure
:keyword int cap: Maximum wait time in milliseconds
:returns: The return value of... | [
"def",
"retry_ex",
"(",
"callback",
",",
"times",
"=",
"3",
",",
"cap",
"=",
"120000",
")",
":",
"for",
"attempt",
"in",
"range",
"(",
"times",
"+",
"1",
")",
":",
"if",
"attempt",
">",
"0",
":",
"time",
".",
"sleep",
"(",
"retry_wait_time",
"(",
... | 34.473684 | 15.210526 |
def load_yaml_by_relpath(cls, directories, rel_path, log_debug=False):
"""Load a yaml file with path that is relative to one of given directories.
Args:
directories: list of directories to search
name: relative path of the yaml file to load
log_debug: log all message... | [
"def",
"load_yaml_by_relpath",
"(",
"cls",
",",
"directories",
",",
"rel_path",
",",
"log_debug",
"=",
"False",
")",
":",
"for",
"d",
"in",
"directories",
":",
"if",
"d",
".",
"startswith",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~'",
")",
")... | 43.9 | 20.7 |
def participants(self):
"""agents + computers (i.e. all non-observers)"""
ret = []
for p in self.players:
try:
if p.isComputer: ret.append(p)
if not p.isObserver: ret.append(p) # could cause an exception if player isn't a PlayerPreGame
... | [
"def",
"participants",
"(",
"self",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"p",
"in",
"self",
".",
"players",
":",
"try",
":",
"if",
"p",
".",
"isComputer",
":",
"ret",
".",
"append",
"(",
"p",
")",
"if",
"not",
"p",
".",
"isObserver",
":",
"re... | 39.777778 | 19.666667 |
def _ParseIdentifierMappingRecord(
self, parser_mediator, table_name, esedb_record):
"""Extracts an identifier mapping from a SruDbIdMapTable record.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
table_... | [
"def",
"_ParseIdentifierMappingRecord",
"(",
"self",
",",
"parser_mediator",
",",
"table_name",
",",
"esedb_record",
")",
":",
"record_values",
"=",
"self",
".",
"_GetRecordValues",
"(",
"parser_mediator",
",",
"table_name",
",",
"esedb_record",
")",
"identifier",
"... | 37.6 | 20.818182 |
def pauli_kraus_map(probabilities):
r"""
Generate the Kraus operators corresponding to a pauli channel.
:params list|floats probabilities: The 4^num_qubits list of probabilities specifying the desired pauli channel.
There should be either 4 or 16 probabilities specified in the order I, X, Y, Z for 1 qu... | [
"def",
"pauli_kraus_map",
"(",
"probabilities",
")",
":",
"if",
"len",
"(",
"probabilities",
")",
"not",
"in",
"[",
"4",
",",
"16",
"]",
":",
"raise",
"ValueError",
"(",
"\"Currently we only support one or two qubits, \"",
"\"so the provided list of probabilities must h... | 42.84375 | 28.5 |
def generateKey(password, bits=32):
"""
Generates a new encryption key based on the inputted password.
:param password | <str>
bits | <int> | 16 or 32 bits
:return <str>
"""
if bits == 32:
hasher = hashlib.sha256
elif bits == 16:
... | [
"def",
"generateKey",
"(",
"password",
",",
"bits",
"=",
"32",
")",
":",
"if",
"bits",
"==",
"32",
":",
"hasher",
"=",
"hashlib",
".",
"sha256",
"elif",
"bits",
"==",
"16",
":",
"hasher",
"=",
"hashlib",
".",
"md5",
"else",
":",
"raise",
"StandardErr... | 24.764706 | 16.764706 |
def seconds_to_hms(input_seconds):
"""Convert seconds to human-readable time."""
minutes, seconds = divmod(input_seconds, 60)
hours, minutes = divmod(minutes, 60)
hours = int(hours)
minutes = int(minutes)
seconds = str(int(seconds)).zfill(2)
return hours, minutes, seconds | [
"def",
"seconds_to_hms",
"(",
"input_seconds",
")",
":",
"minutes",
",",
"seconds",
"=",
"divmod",
"(",
"input_seconds",
",",
"60",
")",
"hours",
",",
"minutes",
"=",
"divmod",
"(",
"minutes",
",",
"60",
")",
"hours",
"=",
"int",
"(",
"hours",
")",
"mi... | 29.3 | 13.2 |
def setUnacknowledgedPreKeyMessage(self, preKeyId, signedPreKeyId, baseKey):
"""
:type preKeyId: int
:type signedPreKeyId: int
:type baseKey: ECPublicKey
"""
self.sessionStructure.pendingPreKey.signedPreKeyId = signedPreKeyId
self.sessionStructure.pendingPreKey.ba... | [
"def",
"setUnacknowledgedPreKeyMessage",
"(",
"self",
",",
"preKeyId",
",",
"signedPreKeyId",
",",
"baseKey",
")",
":",
"self",
".",
"sessionStructure",
".",
"pendingPreKey",
".",
"signedPreKeyId",
"=",
"signedPreKeyId",
"self",
".",
"sessionStructure",
".",
"pendin... | 39.909091 | 18.636364 |
def frames_iter(socket, tty):
"""
Return a generator of frames read from socket. A frame is a tuple where
the first item is the stream number and the second item is a chunk of data.
If the tty setting is enabled, the streams are multiplexed into the stdout
stream.
"""
if tty:
return... | [
"def",
"frames_iter",
"(",
"socket",
",",
"tty",
")",
":",
"if",
"tty",
":",
"return",
"(",
"(",
"STDOUT",
",",
"frame",
")",
"for",
"frame",
"in",
"frames_iter_tty",
"(",
"socket",
")",
")",
"else",
":",
"return",
"frames_iter_no_tty",
"(",
"socket",
... | 34.666667 | 23.5 |
def process_item(self, item, spider):
"""
Store item data in DB.
First determine if a version of the article already exists,
if so then 'migrate' the older version to the archive table.
Second store the new article in the current version table
"""
# Set default... | [
"def",
"process_item",
"(",
"self",
",",
"item",
",",
"spider",
")",
":",
"# Set defaults",
"version",
"=",
"1",
"ancestor",
"=",
"0",
"# Search the CurrentVersion table for an old version of the article",
"try",
":",
"self",
".",
"cursor",
".",
"execute",
"(",
"s... | 45.11236 | 22.685393 |
def save(self, *args, **kwargs):
'''Make sure that the term is valid.
If changed, create a QualifiedDublinCoreElementHistory object and save it.
'''
if not self.term in self.DCELEMENT_CODE_MAP:
raise ValueError('Extended Dublin Core Terms such as '+self.DCTERM_CODE_MAP[self.t... | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"term",
"in",
"self",
".",
"DCELEMENT_CODE_MAP",
":",
"raise",
"ValueError",
"(",
"'Extended Dublin Core Terms such as '",
"+",
"self",
".",
"DCTERM_... | 48.433333 | 16.966667 |
def _get_interleague_fl(cls, home_team_lg, away_team_lg):
"""
get inter league flg
:param home_team_lg: home team league
:param away_team_lg: away team league
:return: inter league flg(T or F or U)
"""
if (home_team_lg == MlbamConst.UNKNOWN_SHORT) or (away_team_lg... | [
"def",
"_get_interleague_fl",
"(",
"cls",
",",
"home_team_lg",
",",
"away_team_lg",
")",
":",
"if",
"(",
"home_team_lg",
"==",
"MlbamConst",
".",
"UNKNOWN_SHORT",
")",
"or",
"(",
"away_team_lg",
"==",
"MlbamConst",
".",
"UNKNOWN_SHORT",
")",
":",
"return",
"Ml... | 41.75 | 9.75 |
def explained_variance_visualizer(X, y=None, ax=None, scale=True,
center=True, colormap=palettes.DEFAULT_SEQUENCE,
**kwargs):
"""Produce a plot of the explained variance produced by a dimensionality
reduction algorithm using n=1 to n=... | [
"def",
"explained_variance_visualizer",
"(",
"X",
",",
"y",
"=",
"None",
",",
"ax",
"=",
"None",
",",
"scale",
"=",
"True",
",",
"center",
"=",
"True",
",",
"colormap",
"=",
"palettes",
".",
"DEFAULT_SEQUENCE",
",",
"*",
"*",
"kwargs",
")",
":",
"# Ins... | 38.204082 | 21.102041 |
def lows(self, assets, dt):
"""
The low field's aggregation returns the smallest low seen between
the market open and the current dt.
If there has been no data on or before the `dt` the low is `nan`.
Returns
-------
np.array with dtype=float64, in order of assets... | [
"def",
"lows",
"(",
"self",
",",
"assets",
",",
"dt",
")",
":",
"market_open",
",",
"prev_dt",
",",
"dt_value",
",",
"entries",
"=",
"self",
".",
"_prelude",
"(",
"dt",
",",
"'low'",
")",
"lows",
"=",
"[",
"]",
"session_label",
"=",
"self",
".",
"_... | 38.873016 | 15.793651 |
def set_trace(*args, **kwargs):
"""Call pdb.set_trace, making sure it receives the unwrapped stdout.
This is so we don't keep drawing progress bars over debugger output.
"""
# There's no stream attr if capture plugin is enabled:
out = sys.stdout.stream if hasattr(sys.stdout, 'stream') else None
... | [
"def",
"set_trace",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# There's no stream attr if capture plugin is enabled:",
"out",
"=",
"sys",
".",
"stdout",
".",
"stream",
"if",
"hasattr",
"(",
"sys",
".",
"stdout",
",",
"'stream'",
")",
"else",
"Non... | 35.368421 | 22.894737 |
def _build_parser(self):
"""Build command line argument parser.
Returns:
:class:`argparse.ArgumentParser`: the command line argument parser.
You probably won't need to use it directly. To parse command line
arguments and update the :class:`ConfigurationManager` insta... | [
"def",
"_build_parser",
"(",
"self",
")",
":",
"main_parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"self",
".",
"common",
".",
"help",
",",
"prefix_chars",
"=",
"'-+'",
")",
"self",
".",
"_add_options_to_parser",
"(",
"self",
".",... | 45.84 | 24.44 |
def generate_event_set(ucerf, background_sids, src_filter, ses_idx, seed):
"""
Generates the event set corresponding to a particular branch
"""
serial = seed + ses_idx * TWO16
# get rates from file
with h5py.File(ucerf.source_file, 'r') as hdf5:
occurrences = ucerf.tom.sample_number_of_o... | [
"def",
"generate_event_set",
"(",
"ucerf",
",",
"background_sids",
",",
"src_filter",
",",
"ses_idx",
",",
"seed",
")",
":",
"serial",
"=",
"seed",
"+",
"ses_idx",
"*",
"TWO16",
"# get rates from file",
"with",
"h5py",
".",
"File",
"(",
"ucerf",
".",
"source... | 41.083333 | 17.75 |
def set_widgets(self):
"""Set widgets on the extra keywords tab."""
self.clear()
self.description_label.setText(
'In this step you can set some extra keywords for the layer. This '
'keywords can be used for creating richer reporting or map.')
subcategory = self.pa... | [
"def",
"set_widgets",
"(",
"self",
")",
":",
"self",
".",
"clear",
"(",
")",
"self",
".",
"description_label",
".",
"setText",
"(",
"'In this step you can set some extra keywords for the layer. This '",
"'keywords can be used for creating richer reporting or map.'",
")",
"sub... | 41.541667 | 21.041667 |
def undeploy(self, id_networkv4):
"""Remove deployment of network in equipments and set column 'active = 0' in tables redeipv4 ]
:param id_networkv4: ID for NetworkIPv4
:return: Equipments configuration output
"""
uri = 'api/networkv4/%s/equipments/' % id_networkv4
re... | [
"def",
"undeploy",
"(",
"self",
",",
"id_networkv4",
")",
":",
"uri",
"=",
"'api/networkv4/%s/equipments/'",
"%",
"id_networkv4",
"return",
"super",
"(",
"ApiNetworkIPv4",
",",
"self",
")",
".",
"delete",
"(",
"uri",
")"
] | 32.181818 | 19.545455 |
def _handle_raw_packet(self, raw_packet):
"""Parse incoming packet."""
if raw_packet[1:2] == b'\x1f':
self._reset_timeout()
year = raw_packet[2]
month = raw_packet[3]
day = raw_packet[4]
hour = raw_packet[5]
minute = raw_packet[6]
... | [
"def",
"_handle_raw_packet",
"(",
"self",
",",
"raw_packet",
")",
":",
"if",
"raw_packet",
"[",
"1",
":",
"2",
"]",
"==",
"b'\\x1f'",
":",
"self",
".",
"_reset_timeout",
"(",
")",
"year",
"=",
"raw_packet",
"[",
"2",
"]",
"month",
"=",
"raw_packet",
"[... | 45.921569 | 12.705882 |
def _run_query(self, query):
"""
Run one query against BigQuery and return the result.
:param query: the query to run
:type query: str
:return: list of per-row response dicts (key => value)
:rtype: ``list``
"""
query_request = self.service.jobs()
... | [
"def",
"_run_query",
"(",
"self",
",",
"query",
")",
":",
"query_request",
"=",
"self",
".",
"service",
".",
"jobs",
"(",
")",
"logger",
".",
"debug",
"(",
"'Running query: %s'",
",",
"query",
")",
"start",
"=",
"datetime",
".",
"now",
"(",
")",
"resp"... | 38.46875 | 14.96875 |
def new(n, prefix=None):
"""lib2to3's AST requires unique objects as children."""
if isinstance(n, Leaf):
return Leaf(n.type, n.value, prefix=n.prefix if prefix is None else prefix)
# this is hacky, we assume complex nodes are just being reused once from the
# original AST.
n.parent = None... | [
"def",
"new",
"(",
"n",
",",
"prefix",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"n",
",",
"Leaf",
")",
":",
"return",
"Leaf",
"(",
"n",
".",
"type",
",",
"n",
".",
"value",
",",
"prefix",
"=",
"n",
".",
"prefix",
"if",
"prefix",
"is",
... | 31.25 | 24.25 |
def write_compounds(self, stream, compounds, properties=None):
"""Write iterable of compounds as YAML object to stream.
Args:
stream: File-like object.
compounds: Iterable of compound entries.
properties: Set of compound properties to output (or None to output
... | [
"def",
"write_compounds",
"(",
"self",
",",
"stream",
",",
"compounds",
",",
"properties",
"=",
"None",
")",
":",
"self",
".",
"_write_entries",
"(",
"stream",
",",
"compounds",
",",
"self",
".",
"convert_compound_entry",
",",
"properties",
")"
] | 39.818182 | 18.636364 |
def check_recommended_attributes(self, dataset):
'''
Feature type specific check of global recommended attributes.
:param netCDF4.Dataset dataset: An open netCDF dataset
'''
results = []
recommended_ctx = TestCtx(BaseCheck.MEDIUM, 'Recommended global attributes')
... | [
"def",
"check_recommended_attributes",
"(",
"self",
",",
"dataset",
")",
":",
"results",
"=",
"[",
"]",
"recommended_ctx",
"=",
"TestCtx",
"(",
"BaseCheck",
".",
"MEDIUM",
",",
"'Recommended global attributes'",
")",
"# Check time_coverage_duration and resolution",
"for... | 48.111111 | 27.111111 |
def stop(self):
"""Stops the adb logcat service."""
if not self._adb_logcat_process:
return
try:
utils.stop_standing_subprocess(self._adb_logcat_process)
except:
self._ad.log.exception('Failed to stop adb logcat.')
self._adb_logcat_process = No... | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_adb_logcat_process",
":",
"return",
"try",
":",
"utils",
".",
"stop_standing_subprocess",
"(",
"self",
".",
"_adb_logcat_process",
")",
"except",
":",
"self",
".",
"_ad",
".",
"log",
".",
... | 34.888889 | 17 |
def predict(self, x):
"""
Predict values for a single data point or an RDD of points
using the model trained.
"""
if isinstance(x, RDD):
return x.map(lambda v: self.predict(v))
x = _convert_to_vector(x)
if self.numClasses == 2:
margin = se... | [
"def",
"predict",
"(",
"self",
",",
"x",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"RDD",
")",
":",
"return",
"x",
".",
"map",
"(",
"lambda",
"v",
":",
"self",
".",
"predict",
"(",
"v",
")",
")",
"x",
"=",
"_convert_to_vector",
"(",
"x",
")"... | 37.351351 | 12.594595 |
def _check_endings(self):
"""Check begin/end of slug, raises Error if malformed."""
if self.slug.startswith("/") and self.slug.endswith("/"):
raise InvalidSlugError(
_("Invalid slug. Did you mean {}, without the leading and trailing slashes?".format(self.slug.strip("/"))))
... | [
"def",
"_check_endings",
"(",
"self",
")",
":",
"if",
"self",
".",
"slug",
".",
"startswith",
"(",
"\"/\"",
")",
"and",
"self",
".",
"slug",
".",
"endswith",
"(",
"\"/\"",
")",
":",
"raise",
"InvalidSlugError",
"(",
"_",
"(",
"\"Invalid slug. Did you mean ... | 61.454545 | 25.363636 |
def solve(self, verbose=False, allow_brute_force=True):
"""Solve the Sudoku.
:param verbose: If the steps used for solving the Sudoku
should be printed. Default is `False`
:type verbose: bool
:param allow_brute_force: If Dancing Links Brute Force method
... | [
"def",
"solve",
"(",
"self",
",",
"verbose",
"=",
"False",
",",
"allow_brute_force",
"=",
"True",
")",
":",
"while",
"not",
"self",
".",
"is_solved",
":",
"# Update possibles arrays.",
"self",
".",
"_update",
"(",
")",
"# See if any position can be singled out.",
... | 49.734694 | 24.163265 |
def Extract_Checkpoints(self):
'''
Extract the checkpoints and store in self.tracking_data
'''
# Make sure page is available
if self.page is None:
raise Exception("The HTML data was not fetched due to some reasons")
soup = BeautifulSoup(self.page,'html.parser')
invalid_tracking_no = soup.find('span... | [
"def",
"Extract_Checkpoints",
"(",
"self",
")",
":",
"# Make sure page is available",
"if",
"self",
".",
"page",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"The HTML data was not fetched due to some reasons\"",
")",
"soup",
"=",
"BeautifulSoup",
"(",
"self",
".",... | 33.319149 | 25.148936 |
def makedirs(name):
"""helper function for python 2 and 3 to call os.makedirs()
avoiding an error if the directory to be created already exists"""
import os, errno
try:
os.makedirs(name)
except OSError as ex:
if ex.errno == errno.EEXIST and os.path.isdir(name):
# ign... | [
"def",
"makedirs",
"(",
"name",
")",
":",
"import",
"os",
",",
"errno",
"try",
":",
"os",
".",
"makedirs",
"(",
"name",
")",
"except",
"OSError",
"as",
"ex",
":",
"if",
"ex",
".",
"errno",
"==",
"errno",
".",
"EEXIST",
"and",
"os",
".",
"path",
"... | 27.866667 | 18.533333 |
async def build_pool_config_request(submitter_did: str,
writes: bool,
force: bool) -> str:
"""
Builds a POOL_CONFIG request. Request to change Pool's configuration.
:param submitter_did: DID of the submitter stored in secured Wallet.
... | [
"async",
"def",
"build_pool_config_request",
"(",
"submitter_did",
":",
"str",
",",
"writes",
":",
"bool",
",",
"force",
":",
"bool",
")",
"->",
"str",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"logger",
".",
"debug",
"(",
"\... | 42.756757 | 23.189189 |
def delete_currency_by_id(cls, currency_id, **kwargs):
"""Delete Currency
Delete an instance of Currency by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_currency_by_id(curren... | [
"def",
"delete_currency_by_id",
"(",
"cls",
",",
"currency_id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_delete_currency_by_i... | 41.52381 | 20.142857 |
def on_status(self, status):
"""Print out some tweets"""
self.out.write(json.dumps(status))
self.out.write(os.linesep)
self.received += 1
return not self.terminate | [
"def",
"on_status",
"(",
"self",
",",
"status",
")",
":",
"self",
".",
"out",
".",
"write",
"(",
"json",
".",
"dumps",
"(",
"status",
")",
")",
"self",
".",
"out",
".",
"write",
"(",
"os",
".",
"linesep",
")",
"self",
".",
"received",
"+=",
"1",
... | 28.285714 | 11.571429 |
def Cube(center=(0., 0., 0.), x_length=1.0, y_length=1.0, z_length=1.0, bounds=None):
"""Create a cube by either specifying the center and side lengths or just
the bounds of the cube. If ``bounds`` are given, all other arguments are
ignored.
Parameters
----------
center : np.ndarray or list
... | [
"def",
"Cube",
"(",
"center",
"=",
"(",
"0.",
",",
"0.",
",",
"0.",
")",
",",
"x_length",
"=",
"1.0",
",",
"y_length",
"=",
"1.0",
",",
"z_length",
"=",
"1.0",
",",
"bounds",
"=",
"None",
")",
":",
"src",
"=",
"vtk",
".",
"vtkCubeSource",
"(",
... | 31.971429 | 20.485714 |
def verify_roster_push(self, fix = False):
"""Check if `self` is valid roster push item.
Valid item must have proper `subscription` value other and valid value
for 'ask'.
:Parameters:
- `fix`: if `True` than replace invalid 'subscription' and 'ask'
values with... | [
"def",
"verify_roster_push",
"(",
"self",
",",
"fix",
"=",
"False",
")",
":",
"self",
".",
"_verify",
"(",
"(",
"None",
",",
"u\"from\"",
",",
"u\"to\"",
",",
"u\"both\"",
",",
"u\"remove\"",
")",
",",
"fix",
")"
] | 33.266667 | 21.266667 |
def get_apis(self):
"""Returns set of api names referenced in this Registry
:return: set of api name strings
"""
out = set(x.api for x in self.types.values() if x.api)
for ft in self.features.values():
out.update(ft.get_apis())
for ext in self.extensions.valu... | [
"def",
"get_apis",
"(",
"self",
")",
":",
"out",
"=",
"set",
"(",
"x",
".",
"api",
"for",
"x",
"in",
"self",
".",
"types",
".",
"values",
"(",
")",
"if",
"x",
".",
"api",
")",
"for",
"ft",
"in",
"self",
".",
"features",
".",
"values",
"(",
")... | 33.909091 | 10.454545 |
def zip_a_folder(src, dst):
"""Add a folder and everything inside to zip archive.
Example::
|---paper
|--- algorithm.pdf
|--- images
|--- 1.jpg
zip_a_folder("paper", "paper.zip")
paper.zip
|---paper
|--- algorithm.pd... | [
"def",
"zip_a_folder",
"(",
"src",
",",
"dst",
")",
":",
"src",
",",
"dst",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"src",
")",
",",
"os",
".",
"path",
".",
"abspath",
"(",
"dst",
")",
"cwd",
"=",
"os",
".",
"getcwd",
"(",
")",
"todo",
"... | 22 | 19.789474 |
def get_ontology(self, id=None, uri=None, match=None):
"""
get the saved-ontology with given ID or via other methods...
"""
if not id and not uri and not match:
return None
if type(id) == type("string"):
uri = id
id = None
if not ... | [
"def",
"get_ontology",
"(",
"self",
",",
"id",
"=",
"None",
",",
"uri",
"=",
"None",
",",
"match",
"=",
"None",
")",
":",
"if",
"not",
"id",
"and",
"not",
"uri",
"and",
"not",
"match",
":",
"return",
"None",
"if",
"type",
"(",
"id",
")",
"==",
... | 29.344828 | 14.103448 |
def unlike(self, photo_id):
"""
Remove a user’s like of a photo.
Note: This action is idempotent; sending the DELETE request
to a single photo multiple times has no additional effect.
:param photo_id [string]: The photo’s ID. Required.
:return: [Photo]: The Unsplash Pho... | [
"def",
"unlike",
"(",
"self",
",",
"photo_id",
")",
":",
"url",
"=",
"\"/photos/%s/like\"",
"%",
"photo_id",
"result",
"=",
"self",
".",
"_delete",
"(",
"url",
")",
"return",
"PhotoModel",
".",
"parse",
"(",
"result",
")"
] | 33.923077 | 13.769231 |
def access_token_handler(self, **args):
"""Get access token based on cookie sent with this request.
This handler deals with two cases:
1) Non-browser client (indicated by no messageId set in request)
where the response is a simple JSON response.
2) Browser client (indicate by ... | [
"def",
"access_token_handler",
"(",
"self",
",",
"*",
"*",
"args",
")",
":",
"message_id",
"=",
"request",
".",
"args",
".",
"get",
"(",
"'messageId'",
",",
"default",
"=",
"None",
")",
"origin",
"=",
"request",
".",
"args",
".",
"get",
"(",
"'origin'"... | 39.384615 | 20.25 |
def key_by(self, key_selector):
"""Applies a key_by operator to the stream.
Attributes:
key_attribute_index (int): The index of the key attributed
(assuming tuple records).
"""
op = Operator(
_generate_uuid(),
OpType.KeyBy,
"... | [
"def",
"key_by",
"(",
"self",
",",
"key_selector",
")",
":",
"op",
"=",
"Operator",
"(",
"_generate_uuid",
"(",
")",
",",
"OpType",
".",
"KeyBy",
",",
"\"KeyBy\"",
",",
"other",
"=",
"key_selector",
",",
"num_instances",
"=",
"self",
".",
"env",
".",
"... | 31.142857 | 14 |
def _get_agent_grounding(agent):
"""Convert an agent to the corresponding PyBEL DSL object (to be filled with variants later)."""
def _get_id(_agent, key):
_id = _agent.db_refs.get(key)
if isinstance(_id, list):
_id = _id[0]
return _id
hgnc_id = _get_id(agent, 'HGNC')
... | [
"def",
"_get_agent_grounding",
"(",
"agent",
")",
":",
"def",
"_get_id",
"(",
"_agent",
",",
"key",
")",
":",
"_id",
"=",
"_agent",
".",
"db_refs",
".",
"get",
"(",
"key",
")",
"if",
"isinstance",
"(",
"_id",
",",
"list",
")",
":",
"_id",
"=",
"_id... | 26.607143 | 17 |
def gen500(request, baseURI, project=None):
"""Return a 500 error"""
return HttpResponseServerError(
render_to_response('plugIt/500.html', {
'context': {
'ebuio_baseUrl': baseURI,
'ebuio_userMode': request.session.get('plugit-standalone-usermode', 'ano'),
... | [
"def",
"gen500",
"(",
"request",
",",
"baseURI",
",",
"project",
"=",
"None",
")",
":",
"return",
"HttpResponseServerError",
"(",
"render_to_response",
"(",
"'plugIt/500.html'",
",",
"{",
"'context'",
":",
"{",
"'ebuio_baseUrl'",
":",
"baseURI",
",",
"'ebuio_use... | 40.6 | 13.2 |
def _create_row_labels(self):
"""
Take the original labels for rows. Rename if alternative labels are
provided. Append label suffix if label_suffix is True.
Returns
----------
labels : dictionary
Dictionary, keys are original column name, values are final la... | [
"def",
"_create_row_labels",
"(",
"self",
")",
":",
"# start with the original column names",
"labels",
"=",
"{",
"}",
"for",
"c",
"in",
"self",
".",
"_columns",
":",
"labels",
"[",
"c",
"]",
"=",
"c",
"# replace column names with alternative names if provided",
"if... | 34.75 | 18.0625 |
def _build_command(self):
"""
Command to start the Dynamips hypervisor process.
(to be passed to subprocess.Popen())
"""
command = [self._path]
command.extend(["-N1"]) # use instance IDs for filenames
command.extend(["-l", "dynamips_i{}_log.txt".format(self._id)... | [
"def",
"_build_command",
"(",
"self",
")",
":",
"command",
"=",
"[",
"self",
".",
"_path",
"]",
"command",
".",
"extend",
"(",
"[",
"\"-N1\"",
"]",
")",
"# use instance IDs for filenames",
"command",
".",
"extend",
"(",
"[",
"\"-l\"",
",",
"\"dynamips_i{}_lo... | 43.411765 | 20.352941 |
def get_query_param(self, key, default=None):
"""Get query parameter uniformly for GET and POST requests."""
value = self.request.query_params.get(key, None)
if value is None:
value = self.request.data.get(key, None)
if value is None:
value = default
retur... | [
"def",
"get_query_param",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"value",
"=",
"self",
".",
"request",
".",
"query_params",
".",
"get",
"(",
"key",
",",
"None",
")",
"if",
"value",
"is",
"None",
":",
"value",
"=",
"self",
"... | 40 | 12 |
def _validate(value, optdict, name=""):
"""return a validated value for an option according to its type
optional argument name is only used for error message formatting
"""
try:
_type = optdict["type"]
except KeyError:
# FIXME
return value
return _call_validator(_type, o... | [
"def",
"_validate",
"(",
"value",
",",
"optdict",
",",
"name",
"=",
"\"\"",
")",
":",
"try",
":",
"_type",
"=",
"optdict",
"[",
"\"type\"",
"]",
"except",
"KeyError",
":",
"# FIXME",
"return",
"value",
"return",
"_call_validator",
"(",
"_type",
",",
"opt... | 30 | 17.272727 |
def delete_all(self, filter=None, timeout=-1):
"""
Delete an SNMPv3 User based on User name specified in filter. The user will be deleted only if it has no associated destinations.
Args:
username: ID or URI of SNMPv3 user.
filter: A general filter/query string to narrow ... | [
"def",
"delete_all",
"(",
"self",
",",
"filter",
"=",
"None",
",",
"timeout",
"=",
"-",
"1",
")",
":",
"return",
"self",
".",
"_client",
".",
"delete_all",
"(",
"filter",
"=",
"filter",
",",
"timeout",
"=",
"timeout",
")"
] | 44.692308 | 29.307692 |
def parse_args(args, kwargs):
"""Returns a kwargs dictionary by turning args into kwargs"""
if 'style' in kwargs:
args += (kwargs['style'],)
del kwargs['style']
for arg in args:
if not isinstance(arg, (bytes, unicode)):
raise ValueError("args must be strings:" + repr(args... | [
"def",
"parse_args",
"(",
"args",
",",
"kwargs",
")",
":",
"if",
"'style'",
"in",
"kwargs",
":",
"args",
"+=",
"(",
"kwargs",
"[",
"'style'",
"]",
",",
")",
"del",
"kwargs",
"[",
"'style'",
"]",
"for",
"arg",
"in",
"args",
":",
"if",
"not",
"isinst... | 43.875 | 15.34375 |
def extract_bits(self, val):
"""Extras the 4 bits, XORS the message data, and does table lookups."""
# Step one, extract the Most significant 4 bits of the CRC register
thisval = self.high >> 4
# XOR in the Message Data into the extracted bits
thisval = thisval ^ val
... | [
"def",
"extract_bits",
"(",
"self",
",",
"val",
")",
":",
"# Step one, extract the Most significant 4 bits of the CRC register\r",
"thisval",
"=",
"self",
".",
"high",
">>",
"4",
"# XOR in the Message Data into the extracted bits\r",
"thisval",
"=",
"thisval",
"^",
"val",
... | 54.4375 | 16.0625 |
def _initial_broks(self, broker_name):
"""Get initial_broks from the scheduler
This is used by the brokers to prepare the initial status broks
This do not send broks, it only makes scheduler internal processing. Then the broker
must use the *_broks* API to get all the stuff
:p... | [
"def",
"_initial_broks",
"(",
"self",
",",
"broker_name",
")",
":",
"with",
"self",
".",
"app",
".",
"conf_lock",
":",
"logger",
".",
"info",
"(",
"\"A new broker just connected : %s\"",
",",
"broker_name",
")",
"return",
"self",
".",
"app",
".",
"sched",
".... | 39.6 | 22.266667 |
def calc_ethsw_port(self, port_num, port_def):
"""
Split and create the port entry for an Ethernet Switch
:param port_num: port number
:type port_num: str or int
:param str port_def: port definition
"""
# Port String - access 1 SW2 1
# 0: type 1: vlan 2: ... | [
"def",
"calc_ethsw_port",
"(",
"self",
",",
"port_num",
",",
"port_def",
")",
":",
"# Port String - access 1 SW2 1",
"# 0: type 1: vlan 2: destination device 3: destination port",
"port_def",
"=",
"port_def",
".",
"split",
"(",
"' '",
")",
"if",
"len",
"(",
"port_def",
... | 36.925926 | 9.666667 |
def handle_api_exceptions(self, method, *url_parts, **kwargs):
"""Call REST API and handle exceptions
Params:
method: 'HEAD', 'GET', 'POST', 'PATCH' or 'DELETE'
url_parts: like in rest_api_url() method
api_ver: like in rest_api_url() method
kwargs: othe... | [
"def",
"handle_api_exceptions",
"(",
"self",
",",
"method",
",",
"*",
"url_parts",
",",
"*",
"*",
"kwargs",
")",
":",
"# The outer part - about error handler",
"assert",
"method",
"in",
"(",
"'HEAD'",
",",
"'GET'",
",",
"'POST'",
",",
"'PATCH'",
",",
"'DELETE'... | 49.153846 | 22.807692 |
def find_all(self, cls):
"""Required functionality."""
final_results = []
table = self.get_class_table(cls)
for db_result in table.scan():
obj = cls.from_data(db_result['value'])
final_results.append(obj)
return final_results | [
"def",
"find_all",
"(",
"self",
",",
"cls",
")",
":",
"final_results",
"=",
"[",
"]",
"table",
"=",
"self",
".",
"get_class_table",
"(",
"cls",
")",
"for",
"db_result",
"in",
"table",
".",
"scan",
"(",
")",
":",
"obj",
"=",
"cls",
".",
"from_data",
... | 31.333333 | 11 |
def cluster_application_statistics(self, state_list=None,
application_type_list=None):
"""
With the Application Statistics API, you can obtain a collection of
triples, each of which contains the application type, the application
state and the number... | [
"def",
"cluster_application_statistics",
"(",
"self",
",",
"state_list",
"=",
"None",
",",
"application_type_list",
"=",
"None",
")",
":",
"path",
"=",
"'/ws/v1/cluster/appstatistics'",
"# TODO: validate state argument",
"states",
"=",
"','",
".",
"join",
"(",
"state_... | 46.052632 | 22 |
def get(self, name, default="", parent_search=False, multikeys_search=False, __settings_temp=None, __rank_recursion=0):
"""
Récupération d'une configuration
le paramètre ```name``` peut être soit un nom ou
un chemin vers la valeur (séparateur /)
```parent_search``` est le boolean qui indique si on doi... | [
"def",
"get",
"(",
"self",
",",
"name",
",",
"default",
"=",
"\"\"",
",",
"parent_search",
"=",
"False",
",",
"multikeys_search",
"=",
"False",
",",
"__settings_temp",
"=",
"None",
",",
"__rank_recursion",
"=",
"0",
")",
":",
"# configuration des settings temp... | 32.62987 | 23.844156 |
def mappings_frequency(df, filepath=None):
"""
Plots the frequency of logical conjunction mappings
Parameters
----------
df: `pandas.DataFrame`_
DataFrame with columns `frequency` and `mapping`
filepath: str
Absolute path to a folder where to write the plot
Returns
--... | [
"def",
"mappings_frequency",
"(",
"df",
",",
"filepath",
"=",
"None",
")",
":",
"df",
"=",
"df",
".",
"sort_values",
"(",
"'frequency'",
")",
"df",
"[",
"'conf'",
"]",
"=",
"df",
".",
"frequency",
".",
"map",
"(",
"lambda",
"f",
":",
"0",
"if",
"f"... | 24.131579 | 26.026316 |
def make_lando_router(config, obj, queue_name):
"""
Makes MessageRouter which can listen to queue_name sending messages to the VM version of lando.
:param config: WorkerConfig/ServerConfig: settings for connecting to the queue
:param obj: object: implements lando specific methods
... | [
"def",
"make_lando_router",
"(",
"config",
",",
"obj",
",",
"queue_name",
")",
":",
"return",
"MessageRouter",
"(",
"config",
",",
"obj",
",",
"queue_name",
",",
"VM_LANDO_INCOMING_MESSAGES",
",",
"processor_constructor",
"=",
"WorkQueueProcessor",
")"
] | 56.7 | 24.7 |
def get_statepostal(self, obj):
"""State postal abbreviation if county or state else ``None``."""
if obj.division.level.name == DivisionLevel.STATE:
return us.states.lookup(obj.division.code).abbr
elif obj.division.level.name == DivisionLevel.COUNTY:
return us.states.look... | [
"def",
"get_statepostal",
"(",
"self",
",",
"obj",
")",
":",
"if",
"obj",
".",
"division",
".",
"level",
".",
"name",
"==",
"DivisionLevel",
".",
"STATE",
":",
"return",
"us",
".",
"states",
".",
"lookup",
"(",
"obj",
".",
"division",
".",
"code",
")... | 52.428571 | 16.285714 |
def request(self, request, proxies, timeout, verify, **_):
"""Responsible for dispatching the request and returning the result.
Network level exceptions should be raised and only
``requests.Response`` should be returned.
:param request: A ``requests.PreparedRequest`` object containing ... | [
"def",
"request",
"(",
"self",
",",
"request",
",",
"proxies",
",",
"timeout",
",",
"verify",
",",
"*",
"*",
"_",
")",
":",
"settings",
"=",
"self",
".",
"http",
".",
"merge_environment_settings",
"(",
"request",
".",
"url",
",",
"proxies",
",",
"False... | 43.826087 | 23.521739 |
def set_tenant(self, tenant, include_public=True):
"""
Main API method to current database schema,
but it does not actually modify the db connection.
"""
self.set_schema(tenant.schema_name, include_public)
self.tenant = tenant | [
"def",
"set_tenant",
"(",
"self",
",",
"tenant",
",",
"include_public",
"=",
"True",
")",
":",
"self",
".",
"set_schema",
"(",
"tenant",
".",
"schema_name",
",",
"include_public",
")",
"self",
".",
"tenant",
"=",
"tenant"
] | 38.285714 | 10 |
def project(self, points):
"""Project 3D points to image coordinates.
This projects 3D points expressed in the camera coordinate system to image points.
Parameters
--------------------
points : (3, N) ndarray
3D points
Returns
--------------------
... | [
"def",
"project",
"(",
"self",
",",
"points",
")",
":",
"rvec",
"=",
"tvec",
"=",
"np",
".",
"zeros",
"(",
"3",
")",
"image_points",
",",
"jac",
"=",
"cv2",
".",
"projectPoints",
"(",
"points",
".",
"T",
".",
"reshape",
"(",
"-",
"1",
",",
"1",
... | 33.777778 | 21.833333 |
def upgradeProcessor1to2(oldProcessor):
"""
Batch processors stopped polling at version 2, so they no longer needed the
idleInterval attribute. They also gained a scheduled attribute which
tracks their interaction with the scheduler. Since they stopped polling,
we also set them up as a timed event... | [
"def",
"upgradeProcessor1to2",
"(",
"oldProcessor",
")",
":",
"newProcessor",
"=",
"oldProcessor",
".",
"upgradeVersion",
"(",
"oldProcessor",
".",
"typeName",
",",
"1",
",",
"2",
",",
"busyInterval",
"=",
"oldProcessor",
".",
"busyInterval",
")",
"newProcessor",
... | 39.636364 | 18.606061 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.