text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def compare_seqs(seqs):
"""
compare pairs of sequences
"""
A, B, ignore_gaps = seqs
a, b = A[1], B[1] # actual sequences
if len(a) != len(b):
print('# reads are not the same length', file=sys.stderr)
exit()
if ignore_gaps is True:
pident = calc_pident_ignore_gaps(a, b... | [
"def",
"compare_seqs",
"(",
"seqs",
")",
":",
"A",
",",
"B",
",",
"ignore_gaps",
"=",
"seqs",
"a",
",",
"b",
"=",
"A",
"[",
"1",
"]",
",",
"B",
"[",
"1",
"]",
"# actual sequences",
"if",
"len",
"(",
"a",
")",
"!=",
"len",
"(",
"b",
")",
":",
... | 27.357143 | 12.357143 |
def all_schema_names(self, cache=False, cache_timeout=None, force=False):
"""Parameters need to be passed as keyword arguments.
For unused parameters, they are referenced in
cache_util.memoized_func decorator.
:param cache: whether cache is enabled for the function
:type cache:... | [
"def",
"all_schema_names",
"(",
"self",
",",
"cache",
"=",
"False",
",",
"cache_timeout",
"=",
"None",
",",
"force",
"=",
"False",
")",
":",
"return",
"self",
".",
"db_engine_spec",
".",
"get_schema_names",
"(",
"self",
".",
"inspector",
")"
] | 38.6875 | 17.9375 |
def validate(self):
"""Base validation + entities = rows."""
super().validate()
nb_entities = len(self.entities)
if nb_entities != self.rows:
raise self.error(
'Number of entities: %s != number of rows: %s' % (
nb_entities, self.rows)) | [
"def",
"validate",
"(",
"self",
")",
":",
"super",
"(",
")",
".",
"validate",
"(",
")",
"nb_entities",
"=",
"len",
"(",
"self",
".",
"entities",
")",
"if",
"nb_entities",
"!=",
"self",
".",
"rows",
":",
"raise",
"self",
".",
"error",
"(",
"'Number of... | 38.5 | 10 |
def _nodeSetValuesFromDict(self, dct):
""" Sets values from a dictionary in the current node.
Non-recursive auxiliary function for setValuesFromDict
"""
if 'data' in dct:
qFont = QtGui.QFont()
success = qFont.fromString(dct['data'])
if not success:... | [
"def",
"_nodeSetValuesFromDict",
"(",
"self",
",",
"dct",
")",
":",
"if",
"'data'",
"in",
"dct",
":",
"qFont",
"=",
"QtGui",
".",
"QFont",
"(",
")",
"success",
"=",
"qFont",
".",
"fromString",
"(",
"dct",
"[",
"'data'",
"]",
")",
"if",
"not",
"succes... | 40.538462 | 11.384615 |
def array_map(ol,map_func,*args):
'''
obseleted,just for compatible
from elist.elist import *
ol = [1,2,3,4]
def map_func(ele,mul,plus):
return(ele*mul+plus)
array_map(ol,map_func,2,100)
'''
rslt = list(map(lambda ele:map_func(ele,*args),ol))
return(r... | [
"def",
"array_map",
"(",
"ol",
",",
"map_func",
",",
"*",
"args",
")",
":",
"rslt",
"=",
"list",
"(",
"map",
"(",
"lambda",
"ele",
":",
"map_func",
"(",
"ele",
",",
"*",
"args",
")",
",",
"ol",
")",
")",
"return",
"(",
"rslt",
")"
] | 26.083333 | 16.416667 |
def open(self, session=None):
"""
:param requests.Session session:
Optional requests session
:return:
file-like object over the decoded bytes
"""
self.__kwargs.update(stream=True)
session = session or requests
resp = session.request(self.__me... | [
"def",
"open",
"(",
"self",
",",
"session",
"=",
"None",
")",
":",
"self",
".",
"__kwargs",
".",
"update",
"(",
"stream",
"=",
"True",
")",
"session",
"=",
"session",
"or",
"requests",
"resp",
"=",
"session",
".",
"request",
"(",
"self",
".",
"__meth... | 26.0625 | 15.8125 |
def query(self, coords, order=1):
"""
Returns the P&G (2010) correction to the SFD'98 E(B-V) at the specified
location(s) on the sky. If component is 'err', then return the
uncertainty in the correction.
Args:
coords (:obj:`astropy.coordinates.SkyCoord`): The coordin... | [
"def",
"query",
"(",
"self",
",",
"coords",
",",
"order",
"=",
"1",
")",
":",
"return",
"super",
"(",
"PG2010Query",
",",
"self",
")",
".",
"query",
"(",
"coords",
",",
"order",
"=",
"order",
")"
] | 44.444444 | 23.666667 |
def authenticated(self, user_token, **validation_context):
"""Checks if user is authenticated using token passed in argument
:param user_token: string representing token
:param validation_context: Token.validate optional keyword arguments
"""
token = self.token_storage.get(user... | [
"def",
"authenticated",
"(",
"self",
",",
"user_token",
",",
"*",
"*",
"validation_context",
")",
":",
"token",
"=",
"self",
".",
"token_storage",
".",
"get",
"(",
"user_token",
")",
"if",
"token",
"and",
"token",
".",
"validate",
"(",
"user_token",
",",
... | 36.083333 | 21.916667 |
def set_stop_chars(self, stop_chars):
"""
Set stop characters used when determining end of URL.
.. deprecated:: 0.7
Use :func:`set_stop_chars_left` or :func:`set_stop_chars_right`
instead.
:param list stop_chars: list of characters
"""
warnings.... | [
"def",
"set_stop_chars",
"(",
"self",
",",
"stop_chars",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Method set_stop_chars is deprecated, \"",
"\"use `set_stop_chars_left` or \"",
"\"`set_stop_chars_right` instead\"",
",",
"DeprecationWarning",
")",
"self",
".",
"_stop_chars",... | 36.470588 | 18.235294 |
def wet_records_from_file_obj(f, take_ownership=False):
"""Iterate through records in WET file object."""
while True:
record = WETRecord.read(f)
if record is None:
break
if not record.url:
continue
yield record
if take_ownership:
f.close() | [
"def",
"wet_records_from_file_obj",
"(",
"f",
",",
"take_ownership",
"=",
"False",
")",
":",
"while",
"True",
":",
"record",
"=",
"WETRecord",
".",
"read",
"(",
"f",
")",
"if",
"record",
"is",
"None",
":",
"break",
"if",
"not",
"record",
".",
"url",
":... | 17.8 | 24.933333 |
def unsticky(self):
"""Unsticky this post.
:returns: The json response from the server
"""
url = self.reddit_session.config['sticky_submission']
data = {'id': self.fullname, 'state': False}
return self.reddit_session.request_json(url, data=data) | [
"def",
"unsticky",
"(",
"self",
")",
":",
"url",
"=",
"self",
".",
"reddit_session",
".",
"config",
"[",
"'sticky_submission'",
"]",
"data",
"=",
"{",
"'id'",
":",
"self",
".",
"fullname",
",",
"'state'",
":",
"False",
"}",
"return",
"self",
".",
"redd... | 31.888889 | 18.666667 |
def distance_stats(x, y, **kwargs):
"""
distance_stats(x, y, *, exponent=1)
Computes the usual (biased) estimators for the distance covariance
and distance correlation between two random vectors, and the
individual distance variances.
Parameters
----------
x: array_like
First r... | [
"def",
"distance_stats",
"(",
"x",
",",
"y",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"Stats",
"(",
"*",
"[",
"_sqrt",
"(",
"s",
")",
"for",
"s",
"in",
"distance_stats_sqr",
"(",
"x",
",",
"y",
",",
"*",
"*",
"kwargs",
")",
"]",
")"
] | 36.833333 | 23.287879 |
def add_edurange(self, edurange):
"""
Parameters
----------
edurange : etree.Element
etree representation of a <edurange> element
(annotation that groups a number of EDUs)
<edu-range> seems to glue together a number of `<edu> elements,
whic... | [
"def",
"add_edurange",
"(",
"self",
",",
"edurange",
")",
":",
"edurange_id",
"=",
"self",
".",
"get_element_id",
"(",
"edurange",
")",
"edurange_attribs",
"=",
"self",
".",
"element_attribs_to_dict",
"(",
"edurange",
")",
"# contains 'span' or nothing",
"self",
"... | 46.525 | 24.975 |
def _set_priority_mapping_table(self, v, load=False):
"""
Setter method for priority_mapping_table, mapped from YANG variable /policy_map/class/priority_mapping_table (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_priority_mapping_table is considered as a pr... | [
"def",
"_set_priority_mapping_table",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
... | 85.136364 | 40 |
def _convert_hex_str_to_int(val):
"""Convert hexadecimal formatted ids to signed int64"""
if val is None:
return None
hex_num = int(val, 16)
# ensure it fits into 64-bit
if hex_num > 0x7FFFFFFFFFFFFFFF:
hex_num -= 0x10000000000000000
assert -9223372036854775808 <= hex_num <= 9... | [
"def",
"_convert_hex_str_to_int",
"(",
"val",
")",
":",
"if",
"val",
"is",
"None",
":",
"return",
"None",
"hex_num",
"=",
"int",
"(",
"val",
",",
"16",
")",
"# ensure it fits into 64-bit",
"if",
"hex_num",
">",
"0x7FFFFFFFFFFFFFFF",
":",
"hex_num",
"-=",
"0... | 28.833333 | 16.916667 |
def add_loaded_callback(self, callback):
"""Add a callback to be run when the ALDB load is complete."""
if callback not in self._cb_aldb_loaded:
self._cb_aldb_loaded.append(callback) | [
"def",
"add_loaded_callback",
"(",
"self",
",",
"callback",
")",
":",
"if",
"callback",
"not",
"in",
"self",
".",
"_cb_aldb_loaded",
":",
"self",
".",
"_cb_aldb_loaded",
".",
"append",
"(",
"callback",
")"
] | 51.75 | 4.25 |
def _calculate_remaining_battery_percentage(self, voltage):
"""Calculate percentage."""
min_voltage = 2500
max_voltage = 3000
percent = (voltage - min_voltage) / (max_voltage - min_voltage) * 200
return min(200, percent) | [
"def",
"_calculate_remaining_battery_percentage",
"(",
"self",
",",
"voltage",
")",
":",
"min_voltage",
"=",
"2500",
"max_voltage",
"=",
"3000",
"percent",
"=",
"(",
"voltage",
"-",
"min_voltage",
")",
"/",
"(",
"max_voltage",
"-",
"min_voltage",
")",
"*",
"20... | 42.5 | 15.333333 |
def _get_user_dir_path(self):
"""Returns Path object representing the user config resource"""
xdg_config_home = os.environ.get('XDG_CONFIG_HOME', '~/.config')
user_dir = Path(xdg_config_home, 'thefuck').expanduser()
legacy_user_dir = Path('~', '.thefuck').expanduser()
# For back... | [
"def",
"_get_user_dir_path",
"(",
"self",
")",
":",
"xdg_config_home",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'XDG_CONFIG_HOME'",
",",
"'~/.config'",
")",
"user_dir",
"=",
"Path",
"(",
"xdg_config_home",
",",
"'thefuck'",
")",
".",
"expanduser",
"(",
"... | 46 | 19.153846 |
def compute_to_fields(self, to_fields):
"""
compute the to_fields parameterse to make it uniformly a dict of CompositePart
:param set[unicode]|dict[unicode, unicode] to_fields: the list/dict of fields to match
:return: the well formated to_field containing only subclasses of CompositePar... | [
"def",
"compute_to_fields",
"(",
"self",
",",
"to_fields",
")",
":",
"# for problem in trim_join, we must try to give the fields in a consistent order with others models...",
"# see #26515 at https://code.djangoproject.com/ticket/26515",
"return",
"OrderedDict",
"(",
"(",
"k",
",",
... | 54.5 | 30.785714 |
def _get_content(self, response):
"""Checks for errors in the response. Returns response content, in bytes.
:param response: response object
:raise:
:UnexpectedResponse: if the server responded with an unexpected response
:return:
- ServiceNow response content
... | [
"def",
"_get_content",
"(",
"self",
",",
"response",
")",
":",
"method",
"=",
"response",
".",
"request",
".",
"method",
"self",
".",
"last_response",
"=",
"response",
"server_error",
"=",
"{",
"'summary'",
":",
"None",
",",
"'details'",
":",
"None",
"}",
... | 39.192982 | 18.631579 |
def to_rfc3339(timestamp):
"""Converts ``timestamp`` to an RFC 3339 date string format.
``timestamp`` can be either a ``datetime.datetime`` or a
``datetime.timedelta``. Instances of the later are assumed to be a delta
with the beginining of the unix epoch, 1st of January, 1970
The returned string... | [
"def",
"to_rfc3339",
"(",
"timestamp",
")",
":",
"if",
"isinstance",
"(",
"timestamp",
",",
"datetime",
".",
"datetime",
")",
":",
"timestamp",
"=",
"timestamp",
"-",
"_EPOCH_START",
"if",
"not",
"isinstance",
"(",
"timestamp",
",",
"datetime",
".",
"timedel... | 37.962963 | 24.814815 |
def encode_request(name, expected, updated):
""" Encode request into client_message"""
client_message = ClientMessage(payload_size=calculate_size(name, expected, updated))
client_message.set_message_type(REQUEST_TYPE)
client_message.set_retryable(RETRYABLE)
client_message.append_str(name)
client... | [
"def",
"encode_request",
"(",
"name",
",",
"expected",
",",
"updated",
")",
":",
"client_message",
"=",
"ClientMessage",
"(",
"payload_size",
"=",
"calculate_size",
"(",
"name",
",",
"expected",
",",
"updated",
")",
")",
"client_message",
".",
"set_message_type"... | 44.8 | 8.5 |
def register_signals(self, app):
"""Register the signals."""
before_record_index.connect(inject_provisional_community)
if app.config['COMMUNITIES_OAI_ENABLED']:
listen(Community, 'after_insert', create_oaipmh_set)
listen(Community, 'after_delete', destroy_oaipmh_set)
... | [
"def",
"register_signals",
"(",
"self",
",",
"app",
")",
":",
"before_record_index",
".",
"connect",
"(",
"inject_provisional_community",
")",
"if",
"app",
".",
"config",
"[",
"'COMMUNITIES_OAI_ENABLED'",
"]",
":",
"listen",
"(",
"Community",
",",
"'after_insert'"... | 52 | 15 |
def choose_encoding(cls, parent, path, encoding):
"""
Show the encodings dialog and returns the user choice.
:param parent: parent widget.
:param path: file path
:param encoding: current file encoding
:return: selected encoding
"""
dlg = cls(parent, path,... | [
"def",
"choose_encoding",
"(",
"cls",
",",
"parent",
",",
"path",
",",
"encoding",
")",
":",
"dlg",
"=",
"cls",
"(",
"parent",
",",
"path",
",",
"encoding",
")",
"dlg",
".",
"exec_",
"(",
")",
"return",
"dlg",
".",
"ui",
".",
"comboBoxEncodings",
"."... | 33 | 11.166667 |
def no_next_candidate(self):
"""
Stops Taskmaster processing by not returning a next candidate.
Note that we have to clean-up the Taskmaster candidate list
because the cycle detection depends on the fact all nodes have
been processed somehow.
"""
while self.candi... | [
"def",
"no_next_candidate",
"(",
"self",
")",
":",
"while",
"self",
".",
"candidates",
":",
"candidates",
"=",
"self",
".",
"candidates",
"self",
".",
"candidates",
"=",
"[",
"]",
"self",
".",
"will_not_build",
"(",
"candidates",
")",
"return",
"None"
] | 34.769231 | 14.615385 |
def get_compression_extension(self):
"""
Find the filename extension for the 'docker save' output, which
may or may not be compressed.
Raises OsbsValidationException if the extension cannot be
determined due to a configuration error.
:returns: str including leading dot,... | [
"def",
"get_compression_extension",
"(",
"self",
")",
":",
"build_request",
"=",
"BuildRequest",
"(",
"build_json_store",
"=",
"self",
".",
"os_conf",
".",
"get_build_json_store",
"(",
")",
")",
"inner",
"=",
"build_request",
".",
"inner_template",
"postbuild_plugin... | 39.423077 | 17.807692 |
def _get_projection(el):
"""
Get coordinate reference system from non-auxiliary elements.
Return value is a tuple of a precedence integer and the projection,
to allow non-auxiliary components to take precedence.
"""
result = None
if hasattr(el, 'crs'):
result = (int(el._auxiliary_com... | [
"def",
"_get_projection",
"(",
"el",
")",
":",
"result",
"=",
"None",
"if",
"hasattr",
"(",
"el",
",",
"'crs'",
")",
":",
"result",
"=",
"(",
"int",
"(",
"el",
".",
"_auxiliary_component",
")",
",",
"el",
".",
"crs",
")",
"return",
"result"
] | 34.5 | 16.3 |
def submit(cluster_config_file, docker, screen, tmux, stop, start,
cluster_name, port_forward, script, script_args):
"""Uploads and runs a script on the specified cluster.
The script is automatically synced to the following location:
os.path.join("~", os.path.basename(script))
"""
a... | [
"def",
"submit",
"(",
"cluster_config_file",
",",
"docker",
",",
"screen",
",",
"tmux",
",",
"stop",
",",
"start",
",",
"cluster_name",
",",
"port_forward",
",",
"script",
",",
"script_args",
")",
":",
"assert",
"not",
"(",
"screen",
"and",
"tmux",
")",
... | 41.85 | 25.3 |
def _safe_match_list(inner_type, argument_value):
"""Represent the list of "inner_type" objects in MATCH form."""
stripped_type = strip_non_null_from_type(inner_type)
if isinstance(stripped_type, GraphQLList):
raise GraphQLInvalidArgumentError(u'MATCH does not currently support nested lists, '
... | [
"def",
"_safe_match_list",
"(",
"inner_type",
",",
"argument_value",
")",
":",
"stripped_type",
"=",
"strip_non_null_from_type",
"(",
"inner_type",
")",
"if",
"isinstance",
"(",
"stripped_type",
",",
"GraphQLList",
")",
":",
"raise",
"GraphQLInvalidArgumentError",
"("... | 47.823529 | 23.411765 |
def get_user_profile(self, auth_secret):
"""Get the profile (i.e., username, password, etc.) of a user.
Parameters
----------
auth_secret: str
The authentication secret of the logged-in user.
Returns
-------
bool
True if the logout is suc... | [
"def",
"get_user_profile",
"(",
"self",
",",
"auth_secret",
")",
":",
"result",
"=",
"{",
"pytwis_constants",
".",
"ERROR_KEY",
":",
"None",
"}",
"# Check if the user is logged in.",
"loggedin",
",",
"userid",
"=",
"self",
".",
"_is_loggedin",
"(",
"auth_secret",
... | 29.439024 | 21.658537 |
def get_preferences_from_user(self):
"""Launches preferences dialog and returns dict with preferences"""
dlg = PreferencesDialog(self.main_window)
change_choice = dlg.ShowModal()
preferences = {}
if change_choice == wx.ID_OK:
for (parameter, _), ctrl in zip(dlg.pa... | [
"def",
"get_preferences_from_user",
"(",
"self",
")",
":",
"dlg",
"=",
"PreferencesDialog",
"(",
"self",
".",
"main_window",
")",
"change_choice",
"=",
"dlg",
".",
"ShowModal",
"(",
")",
"preferences",
"=",
"{",
"}",
"if",
"change_choice",
"==",
"wx",
".",
... | 31.095238 | 20.571429 |
def decode_list(self, data_type, obj):
"""
The data_type argument must be a List.
See json_compat_obj_decode() for argument descriptions.
"""
if not isinstance(obj, list):
raise bv.ValidationError(
'expected list, got %s' % bv.generic_type_name(obj))
... | [
"def",
"decode_list",
"(",
"self",
",",
"data_type",
",",
"obj",
")",
":",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"list",
")",
":",
"raise",
"bv",
".",
"ValidationError",
"(",
"'expected list, got %s'",
"%",
"bv",
".",
"generic_type_name",
"(",
"obj",... | 39.363636 | 12.636364 |
def unblock_username(username, pipe=None):
""" unblock the given Username """
do_commit = False
if not pipe:
pipe = REDIS_SERVER.pipeline()
do_commit = True
if username:
pipe.delete(get_username_attempt_cache_key(username))
pipe.delete(get_username_blocked_cache_key(usern... | [
"def",
"unblock_username",
"(",
"username",
",",
"pipe",
"=",
"None",
")",
":",
"do_commit",
"=",
"False",
"if",
"not",
"pipe",
":",
"pipe",
"=",
"REDIS_SERVER",
".",
"pipeline",
"(",
")",
"do_commit",
"=",
"True",
"if",
"username",
":",
"pipe",
".",
"... | 33.090909 | 14.727273 |
def to_string(self):
"""
stringifies version
:return: string of version
"""
if self.major == -1:
major_str = 'x'
else:
major_str = self.major
if self.minor == -1:
minor_str = 'x'
else:
minor_str = self.minor
... | [
"def",
"to_string",
"(",
"self",
")",
":",
"if",
"self",
".",
"major",
"==",
"-",
"1",
":",
"major_str",
"=",
"'x'",
"else",
":",
"major_str",
"=",
"self",
".",
"major",
"if",
"self",
".",
"minor",
"==",
"-",
"1",
":",
"minor_str",
"=",
"'x'",
"e... | 26.5 | 13.388889 |
def chats_search(self, q=None, **kwargs):
"https://developer.zendesk.com/rest_api/docs/chat/chats#search-chats"
api_path = "/api/v2/chats/search"
api_query = {}
if "query" in kwargs.keys():
api_query.update(kwargs["query"])
del kwargs["query"]
if q:
... | [
"def",
"chats_search",
"(",
"self",
",",
"q",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/chats/search\"",
"api_query",
"=",
"{",
"}",
"if",
"\"query\"",
"in",
"kwargs",
".",
"keys",
"(",
")",
":",
"api_query",
".",
"upd... | 36.166667 | 14.666667 |
def get_networks(project_id, include_data='N', **kwargs):
"""
Get all networks in a project
Returns an array of network objects.
"""
log.info("Getting networks for project %s", project_id)
user_id = kwargs.get('user_id')
project = _get_project(project_id)
project.check_read_permi... | [
"def",
"get_networks",
"(",
"project_id",
",",
"include_data",
"=",
"'N'",
",",
"*",
"*",
"kwargs",
")",
":",
"log",
".",
"info",
"(",
"\"Getting networks for project %s\"",
",",
"project_id",
")",
"user_id",
"=",
"kwargs",
".",
"get",
"(",
"'user_id'",
")",... | 36.875 | 19.458333 |
def _nested_changes(changes):
'''
Print the changes data using the nested outputter
'''
ret = '\n'
ret += salt.output.out_format(
changes,
'nested',
__opts__,
nested_indent=14)
return ret | [
"def",
"_nested_changes",
"(",
"changes",
")",
":",
"ret",
"=",
"'\\n'",
"ret",
"+=",
"salt",
".",
"output",
".",
"out_format",
"(",
"changes",
",",
"'nested'",
",",
"__opts__",
",",
"nested_indent",
"=",
"14",
")",
"return",
"ret"
] | 22.636364 | 19.727273 |
def _sia_cache_key(subsystem):
"""The cache key of the subsystem.
This includes the native hash of the subsystem and all configuration values
which change the results of ``sia``.
"""
return (
hash(subsystem),
config.ASSUME_CUTS_CANNOT_CREATE_NEW_CONCEPTS,
config.CUT_ONE_APPR... | [
"def",
"_sia_cache_key",
"(",
"subsystem",
")",
":",
"return",
"(",
"hash",
"(",
"subsystem",
")",
",",
"config",
".",
"ASSUME_CUTS_CANNOT_CREATE_NEW_CONCEPTS",
",",
"config",
".",
"CUT_ONE_APPROXIMATION",
",",
"config",
".",
"MEASURE",
",",
"config",
".",
"PREC... | 31.4375 | 15.375 |
def round_data(filter_data):
""" round the data"""
for index, _ in enumerate(filter_data):
filter_data[index][0] = round(filter_data[index][0] / 100.0) * 100.0
return filter_data | [
"def",
"round_data",
"(",
"filter_data",
")",
":",
"for",
"index",
",",
"_",
"in",
"enumerate",
"(",
"filter_data",
")",
":",
"filter_data",
"[",
"index",
"]",
"[",
"0",
"]",
"=",
"round",
"(",
"filter_data",
"[",
"index",
"]",
"[",
"0",
"]",
"/",
... | 39.6 | 14 |
def system(self):
"""The system of units used to measure an instance"""
if self._base == 2:
return "NIST"
elif self._base == 10:
return "SI"
else:
# I don't expect to ever encounter this logic branch, but
# hey, it's better to have extra te... | [
"def",
"system",
"(",
"self",
")",
":",
"if",
"self",
".",
"_base",
"==",
"2",
":",
"return",
"\"NIST\"",
"elif",
"self",
".",
"_base",
"==",
"10",
":",
"return",
"\"SI\"",
"else",
":",
"# I don't expect to ever encounter this logic branch, but",
"# hey, it's be... | 41 | 17.916667 |
def translate(self):
"""Compile the template to a Python function."""
expressions, varnames, funcnames = self.expr.translate()
argnames = []
for varname in varnames:
argnames.append(VARIABLE_PREFIX + varname)
for funcname in funcnames:
argnames.append(FUN... | [
"def",
"translate",
"(",
"self",
")",
":",
"expressions",
",",
"varnames",
",",
"funcnames",
"=",
"self",
".",
"expr",
".",
"translate",
"(",
")",
"argnames",
"=",
"[",
"]",
"for",
"varname",
"in",
"varnames",
":",
"argnames",
".",
"append",
"(",
"VARI... | 33.08 | 18.6 |
def walk_and_clean(data):
"""
Recursively walks list of dicts (which may themselves embed lists and dicts),
transforming namedtuples to OrderedDicts and
using ``clean_key_name(k)`` to make keys into SQL-safe column names
>>> data = [{'a': 1}, [{'B': 2}, {'B': 3}], {'F': {'G': 4}}]
>>> pprint(wa... | [
"def",
"walk_and_clean",
"(",
"data",
")",
":",
"# transform namedtuples to OrderedDicts",
"if",
"hasattr",
"(",
"data",
",",
"'_fields'",
")",
":",
"data",
"=",
"OrderedDict",
"(",
"(",
"k",
",",
"v",
")",
"for",
"(",
"k",
",",
"v",
")",
"in",
"zip",
... | 42.59375 | 14.90625 |
def get_curricula_by_department(
department, future_terms=0, view_unpublished=False):
"""
Returns a list of restclients.Curriculum models, for the passed
Department model.
"""
if not isinstance(future_terms, int):
raise ValueError(future_terms)
if future_terms < 0 or future_term... | [
"def",
"get_curricula_by_department",
"(",
"department",
",",
"future_terms",
"=",
"0",
",",
"view_unpublished",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"future_terms",
",",
"int",
")",
":",
"raise",
"ValueError",
"(",
"future_terms",
")",
"if"... | 35.25 | 15.45 |
def listdir(store, path=None):
"""Obtain a directory listing for the given path. If `store` provides a `listdir`
method, this will be called, otherwise will fall back to implementation via the
`MutableMapping` interface."""
path = normalize_storage_path(path)
if hasattr(store, 'listdir'):
# ... | [
"def",
"listdir",
"(",
"store",
",",
"path",
"=",
"None",
")",
":",
"path",
"=",
"normalize_storage_path",
"(",
"path",
")",
"if",
"hasattr",
"(",
"store",
",",
"'listdir'",
")",
":",
"# pass through",
"return",
"store",
".",
"listdir",
"(",
"path",
")",... | 42.090909 | 11.818182 |
def _import_classes(self, class_names):
"""
Import a list of classes.
"""
classes = []
for name in class_names:
classes.extend(self._import_class_or_module(name))
return classes | [
"def",
"_import_classes",
"(",
"self",
",",
"class_names",
")",
":",
"classes",
"=",
"[",
"]",
"for",
"name",
"in",
"class_names",
":",
"classes",
".",
"extend",
"(",
"self",
".",
"_import_class_or_module",
"(",
"name",
")",
")",
"return",
"classes"
] | 28.75 | 9.5 |
def deploy_templates():
"""
Deploy any templates from your shortest TEMPLATE_DIRS setting
"""
deployed = None
if not hasattr(env, 'project_template_dir'):
#the normal pattern would mean the shortest path is the main one.
#its probably the last listed
length = 1000
... | [
"def",
"deploy_templates",
"(",
")",
":",
"deployed",
"=",
"None",
"if",
"not",
"hasattr",
"(",
"env",
",",
"'project_template_dir'",
")",
":",
"#the normal pattern would mean the shortest path is the main one.",
"#its probably the last listed",
"length",
"=",
"1000",
"fo... | 35.956522 | 16.478261 |
def get_queryset(self):
"""
Check that the queryset is defined and call it.
"""
if self.queryset is None:
raise ImproperlyConfigured(
"'%s' must define 'queryset'" % self.__class__.__name__)
return self.queryset() | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"if",
"self",
".",
"queryset",
"is",
"None",
":",
"raise",
"ImproperlyConfigured",
"(",
"\"'%s' must define 'queryset'\"",
"%",
"self",
".",
"__class__",
".",
"__name__",
")",
"return",
"self",
".",
"queryset",
"("... | 34.25 | 10.25 |
def proj(vec, vec_onto):
""" Vector projection.
Calculated as:
.. math::
\\mathsf{vec\\_onto} * \\frac{\\mathsf{vec}\\cdot\\mathsf{vec\\_onto}}
{\\mathsf{vec\\_onto}\\cdot\\mathsf{vec\\_onto}}
Parameters
----------
vec
length-R |npfloat_| --
Vector to projec... | [
"def",
"proj",
"(",
"vec",
",",
"vec_onto",
")",
":",
"# Imports",
"import",
"numpy",
"as",
"np",
"# Ensure vectors",
"if",
"not",
"len",
"(",
"vec",
".",
"shape",
")",
"==",
"1",
":",
"raise",
"ValueError",
"(",
"\"'vec' is not a vector\"",
")",
"## end i... | 23.586957 | 23.26087 |
def _check_virtualenv():
"""Makes sure that the virtualenv specified in the global settings file
actually exists.
"""
from os import waitpid
from subprocess import Popen, PIPE
penvs = Popen("source /usr/local/bin/virtualenvwrapper.sh; workon",
shell=True, executable="/bin/bash",... | [
"def",
"_check_virtualenv",
"(",
")",
":",
"from",
"os",
"import",
"waitpid",
"from",
"subprocess",
"import",
"Popen",
",",
"PIPE",
"penvs",
"=",
"Popen",
"(",
"\"source /usr/local/bin/virtualenvwrapper.sh; workon\"",
",",
"shell",
"=",
"True",
",",
"executable",
... | 38.181818 | 20.181818 |
def _parse_prefix_as_idd(idd_pattern, number):
"""Strips the IDD from the start of the number if present.
Helper function used by _maybe_strip_i18n_prefix_and_normalize().
Returns a 2-tuple:
- Boolean indicating if IDD was stripped
- Number with IDD stripped
"""
match = idd_pattern.mat... | [
"def",
"_parse_prefix_as_idd",
"(",
"idd_pattern",
",",
"number",
")",
":",
"match",
"=",
"idd_pattern",
".",
"match",
"(",
"number",
")",
"if",
"match",
":",
"match_end",
"=",
"match",
".",
"end",
"(",
")",
"# Only strip this if the first digit after the match is... | 38.666667 | 16.142857 |
def tee(*popenargs, **kwargs):
"""
Run a command as if it were piped though tee.
Output generated by the command is displayed in real time to the terminal.
It is also captured in strings and returned once the process terminated.
This function is very useful for logging output from cluster runs.... | [
"def",
"tee",
"(",
"*",
"popenargs",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"subprocess",
",",
"select",
",",
"sys",
"process",
"=",
"subprocess",
".",
"Popen",
"(",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",... | 36.536585 | 22.341463 |
def guess_filename(obj):
"""Tries to guess the filename of the given object."""
name = getattr(obj, 'name', None)
if name and name[0] != '<' and name[-1] != '>':
return os.path.basename(name) | [
"def",
"guess_filename",
"(",
"obj",
")",
":",
"name",
"=",
"getattr",
"(",
"obj",
",",
"'name'",
",",
"None",
")",
"if",
"name",
"and",
"name",
"[",
"0",
"]",
"!=",
"'<'",
"and",
"name",
"[",
"-",
"1",
"]",
"!=",
"'>'",
":",
"return",
"os",
".... | 41.4 | 6.6 |
def symbol_top(body_output, targets, model_hparams, vocab_size):
"""Generate logits.
Args:
body_output: A Tensor with shape
[batch, p0, p1, model_hparams.hidden_size].
targets: Unused.
model_hparams: HParams, model hyperparmeters.
vocab_size: int, vocabulary size.
Returns:
logits: A Te... | [
"def",
"symbol_top",
"(",
"body_output",
",",
"targets",
",",
"model_hparams",
",",
"vocab_size",
")",
":",
"del",
"targets",
"# unused arg",
"if",
"model_hparams",
".",
"shared_embedding_and_softmax_weights",
":",
"scope_name",
"=",
"\"shared\"",
"reuse",
"=",
"tf"... | 36.545455 | 18.181818 |
def esrchc(value, array):
"""
Search for a given value within a character string array.
Return the index of the first equivalent array entry, or -1
if no equivalent element is found.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/esrchc_c.html
:param value: Key value to be found in ar... | [
"def",
"esrchc",
"(",
"value",
",",
"array",
")",
":",
"value",
"=",
"stypes",
".",
"stringToCharP",
"(",
"value",
")",
"ndim",
"=",
"ctypes",
".",
"c_int",
"(",
"len",
"(",
"array",
")",
")",
"lenvals",
"=",
"ctypes",
".",
"c_int",
"(",
"len",
"("... | 36.590909 | 17.045455 |
def _str_to_fn(self, fn_as_str):
"""
If the argument is not a string, return whatever was passed in.
Parses a string such as package.module.function, imports the module
and returns the function.
:param fn_as_str: The string to parse. If not a string, return it.
"""
... | [
"def",
"_str_to_fn",
"(",
"self",
",",
"fn_as_str",
")",
":",
"if",
"not",
"isinstance",
"(",
"fn_as_str",
",",
"str",
")",
":",
"return",
"fn_as_str",
"path",
",",
"_",
",",
"function",
"=",
"fn_as_str",
".",
"rpartition",
"(",
"'.'",
")",
"module",
"... | 36.857143 | 16.285714 |
def set_pkg_license_comment(self, doc, text):
"""Sets the package's license comment.
Raises OrderError if no package previously defined.
Raises CardinalityError if already set.
Raises SPDXValueError if text is not free form text.
"""
self.assert_package_exists()
i... | [
"def",
"set_pkg_license_comment",
"(",
"self",
",",
"doc",
",",
"text",
")",
":",
"self",
".",
"assert_package_exists",
"(",
")",
"if",
"not",
"self",
".",
"package_license_comment_set",
":",
"self",
".",
"package_license_comment_set",
"=",
"True",
"if",
"valida... | 44.25 | 14.0625 |
def _AssAttr(self, t):
""" Handle assigning an attribute of an object
"""
self._dispatch(t.expr)
self._write('.'+t.attrname) | [
"def",
"_AssAttr",
"(",
"self",
",",
"t",
")",
":",
"self",
".",
"_dispatch",
"(",
"t",
".",
"expr",
")",
"self",
".",
"_write",
"(",
"'.'",
"+",
"t",
".",
"attrname",
")"
] | 30.4 | 6.6 |
def upload_job_delete(self, upload_job_id, **kwargs): # noqa: E501
"""Delete an upload job # noqa: E501
Delete an upload job # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = ... | [
"def",
"upload_job_delete",
"(",
"self",
",",
"upload_job_id",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'asynchronous'",
")",
":",
"return",
"self",
".",... | 44.47619 | 20.857143 |
def resample(self, resampledWaveTab):
"""Resample the spectrum for the given wavelength set.
Given wavelength array must be monotonically increasing or decreasing.
Throughput interpolation is done using :func:`numpy.interp`.
Parameters
----------
resampledWaveTab : arra... | [
"def",
"resample",
"(",
"self",
",",
"resampledWaveTab",
")",
":",
"# Check whether the input wavetab is in descending order",
"if",
"resampledWaveTab",
"[",
"0",
"]",
"<",
"resampledWaveTab",
"[",
"-",
"1",
"]",
":",
"newwave",
"=",
"resampledWaveTab",
"newasc",
"=... | 35.411765 | 18.921569 |
def parse_lines(self, lines: Iterable[str]) -> List[ParseResults]:
"""Parse multiple lines in succession."""
return [
self.parseString(line, line_number)
for line_number, line in enumerate(lines)
] | [
"def",
"parse_lines",
"(",
"self",
",",
"lines",
":",
"Iterable",
"[",
"str",
"]",
")",
"->",
"List",
"[",
"ParseResults",
"]",
":",
"return",
"[",
"self",
".",
"parseString",
"(",
"line",
",",
"line_number",
")",
"for",
"line_number",
",",
"line",
"in... | 40 | 16.833333 |
def _build_table_options(self, row):
""" Setup the mostly-non-schema table options, like caching settings """
options = dict((o, row.get(o)) for o in self.recognized_table_options if o in row)
# the option name when creating tables is "dclocal_read_repair_chance",
# but the column name ... | [
"def",
"_build_table_options",
"(",
"self",
",",
"row",
")",
":",
"options",
"=",
"dict",
"(",
"(",
"o",
",",
"row",
".",
"get",
"(",
"o",
")",
")",
"for",
"o",
"in",
"self",
".",
"recognized_table_options",
"if",
"o",
"in",
"row",
")",
"# the option... | 52.785714 | 24.5 |
def samples(self, anystring, limit=None, offset=None, sortby=None):
'''Return an object representing the samples identified by the input domain, IP, or URL'''
uri = self._uris['samples'].format(anystring)
params = {'limit': limit, 'offset': offset, 'sortby': sortby}
return self.get_par... | [
"def",
"samples",
"(",
"self",
",",
"anystring",
",",
"limit",
"=",
"None",
",",
"offset",
"=",
"None",
",",
"sortby",
"=",
"None",
")",
":",
"uri",
"=",
"self",
".",
"_uris",
"[",
"'samples'",
"]",
".",
"format",
"(",
"anystring",
")",
"params",
"... | 47 | 29.857143 |
def get_last_or_frame_exception():
"""Intended to be used going into post mortem routines. If
sys.last_traceback is set, we will return that and assume that
this is what post-mortem will want. If sys.last_traceback has not
been set, then perhaps we *about* to raise an error and are
fielding an exce... | [
"def",
"get_last_or_frame_exception",
"(",
")",
":",
"try",
":",
"if",
"inspect",
".",
"istraceback",
"(",
"sys",
".",
"last_traceback",
")",
":",
"# We do have a traceback so prefer that.",
"return",
"sys",
".",
"last_type",
",",
"sys",
".",
"last_value",
",",
... | 41.866667 | 18.866667 |
def setup(self, builder):
"""Performs this component's simulation setup and return sub-components.
Parameters
----------
builder : `engine.Builder`
Interface to several simulation tools including access to common random
number generation, in particular.
... | [
"def",
"setup",
"(",
"self",
",",
"builder",
")",
":",
"builder",
".",
"components",
".",
"add_components",
"(",
"self",
".",
"transitions",
")",
"self",
".",
"random",
"=",
"builder",
".",
"randomness",
".",
"get_stream",
"(",
"self",
".",
"key",
")"
] | 32.75 | 19.4375 |
def ephemeral(*,
port: int = 6060,
timeout_connection: int = 30,
verbose: bool = False
) -> Iterator[Client]:
"""
Launches an ephemeral server instance that will be immediately
close when no longer in context.
Parameters:
port: the port th... | [
"def",
"ephemeral",
"(",
"*",
",",
"port",
":",
"int",
"=",
"6060",
",",
"timeout_connection",
":",
"int",
"=",
"30",
",",
"verbose",
":",
"bool",
"=",
"False",
")",
"->",
"Iterator",
"[",
"Client",
"]",
":",
"url",
"=",
"\"http://127.0.0.1:{}\"",
".",... | 36.034483 | 15.068966 |
def get_field_groups(layer_purpose, layer_subcategory=None):
"""Obtain list of field groups from layer purpose and subcategory.
:param layer_purpose: The layer purpose.
:type layer_purpose: str
:param layer_subcategory: Exposure or hazard value.
:type layer_subcategory: str
:returns: List of ... | [
"def",
"get_field_groups",
"(",
"layer_purpose",
",",
"layer_subcategory",
"=",
"None",
")",
":",
"layer_purpose_dict",
"=",
"definition",
"(",
"layer_purpose",
")",
"if",
"not",
"layer_purpose_dict",
":",
"return",
"[",
"]",
"field_groups",
"=",
"deepcopy",
"(",
... | 36.217391 | 17.652174 |
def oauth_request(self):
""" Makes a oauth connection """
# get tokens from server and make a dict of them.
self._server_tokens = self.request_token()
self.store["oauth-request-token"] = self._server_tokens["token"]
self.store["oauth-request-secret"] = self._server_tokens["token... | [
"def",
"oauth_request",
"(",
"self",
")",
":",
"# get tokens from server and make a dict of them.",
"self",
".",
"_server_tokens",
"=",
"self",
".",
"request_token",
"(",
")",
"self",
".",
"store",
"[",
"\"oauth-request-token\"",
"]",
"=",
"self",
".",
"_server_toke... | 44 | 22.833333 |
def _screaming_snake_case(cls, text):
"""
Transform text to SCREAMING_SNAKE_CASE
:param text:
:return:
"""
if text.isupper():
return text
result = ''
for pos, symbol in enumerate(text):
if symbol.isupper() and pos > 0:
... | [
"def",
"_screaming_snake_case",
"(",
"cls",
",",
"text",
")",
":",
"if",
"text",
".",
"isupper",
"(",
")",
":",
"return",
"text",
"result",
"=",
"''",
"for",
"pos",
",",
"symbol",
"in",
"enumerate",
"(",
"text",
")",
":",
"if",
"symbol",
".",
"isuppe... | 25.75 | 12.25 |
def _collect_dirty_tabs(self, exept=None):
"""
Collects the list of dirty tabs
"""
widgets = []
filenames = []
for i in range(self.count()):
widget = self.widget(i)
try:
if widget.dirty and widget != exept:
widge... | [
"def",
"_collect_dirty_tabs",
"(",
"self",
",",
"exept",
"=",
"None",
")",
":",
"widgets",
"=",
"[",
"]",
"filenames",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"count",
"(",
")",
")",
":",
"widget",
"=",
"self",
".",
"widget",
... | 31.2 | 8.933333 |
def calc_mass_from_fit_and_conv_factor(A, Damping, ConvFactor):
"""
Calculates mass from the A parameter from fitting, the damping from
fitting in angular units and the Conversion factor calculated from
comparing the ratio of the z signal and first harmonic of z.
Parameters
----------
A :... | [
"def",
"calc_mass_from_fit_and_conv_factor",
"(",
"A",
",",
"Damping",
",",
"ConvFactor",
")",
":",
"T0",
"=",
"300",
"mFromA",
"=",
"2",
"*",
"Boltzmann",
"*",
"T0",
"/",
"(",
"pi",
"*",
"A",
")",
"*",
"ConvFactor",
"**",
"2",
"*",
"Damping",
"return"... | 28.521739 | 22 |
def forwards(self, orm):
"Write your forwards methods here."
orm.Project.objects.update(label=F('name'))
orm.Cohort.objects.update(label=F('name'))
orm.Sample.objects.update(name=F('label')) | [
"def",
"forwards",
"(",
"self",
",",
"orm",
")",
":",
"orm",
".",
"Project",
".",
"objects",
".",
"update",
"(",
"label",
"=",
"F",
"(",
"'name'",
")",
")",
"orm",
".",
"Cohort",
".",
"objects",
".",
"update",
"(",
"label",
"=",
"F",
"(",
"'name'... | 43.6 | 10 |
def save_lastnode_id():
"""Save the id of the last node created."""
init_counter()
with FileLock(_COUNTER_FILE):
with AtomicFile(_COUNTER_FILE, mode="w") as fh:
fh.write("%d\n" % _COUNTER) | [
"def",
"save_lastnode_id",
"(",
")",
":",
"init_counter",
"(",
")",
"with",
"FileLock",
"(",
"_COUNTER_FILE",
")",
":",
"with",
"AtomicFile",
"(",
"_COUNTER_FILE",
",",
"mode",
"=",
"\"w\"",
")",
"as",
"fh",
":",
"fh",
".",
"write",
"(",
"\"%d\\n\"",
"%"... | 30.714286 | 14.571429 |
def show_banner(ctx, param, value):
"""Shows dynaconf awesome banner"""
if not value or ctx.resilient_parsing:
return
set_settings()
click.echo(settings.dynaconf_banner)
click.echo("Learn more at: http://github.com/rochacbruno/dynaconf")
ctx.exit() | [
"def",
"show_banner",
"(",
"ctx",
",",
"param",
",",
"value",
")",
":",
"if",
"not",
"value",
"or",
"ctx",
".",
"resilient_parsing",
":",
"return",
"set_settings",
"(",
")",
"click",
".",
"echo",
"(",
"settings",
".",
"dynaconf_banner",
")",
"click",
"."... | 34.125 | 14 |
def get_offdiag_vals(dcorr):
"""
for lin dcorr i guess
"""
del_indexes=[]
for spc1 in np.unique(dcorr.index.get_level_values(0)):
for spc2 in np.unique(dcorr.index.get_level_values(0)):
if (not (spc1,spc2) in del_indexes) and (not (spc2,spc1) in del_indexes):
del_... | [
"def",
"get_offdiag_vals",
"(",
"dcorr",
")",
":",
"del_indexes",
"=",
"[",
"]",
"for",
"spc1",
"in",
"np",
".",
"unique",
"(",
"dcorr",
".",
"index",
".",
"get_level_values",
"(",
"0",
")",
")",
":",
"for",
"spc2",
"in",
"np",
".",
"unique",
"(",
... | 36.9375 | 16.8125 |
def _periodicfeatures_worker(task):
'''
This is a parallel worker for the drivers below.
'''
pfpickle, lcbasedir, outdir, starfeatures, kwargs = task
try:
return get_periodicfeatures(pfpickle,
lcbasedir,
outdir,
... | [
"def",
"_periodicfeatures_worker",
"(",
"task",
")",
":",
"pfpickle",
",",
"lcbasedir",
",",
"outdir",
",",
"starfeatures",
",",
"kwargs",
"=",
"task",
"try",
":",
"return",
"get_periodicfeatures",
"(",
"pfpickle",
",",
"lcbasedir",
",",
"outdir",
",",
"starfe... | 26.736842 | 24.315789 |
def underlying_order_book_id(self):
"""
[str] 合约标的代码,目前除股指期货(IH, IF, IC)之外的期货合约,这一字段全部为’null’(期货专用)
"""
try:
return self.__dict__["underlying_order_book_id"]
except (KeyError, ValueError):
raise AttributeError(
"Instrument(order_book_id={})... | [
"def",
"underlying_order_book_id",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"__dict__",
"[",
"\"underlying_order_book_id\"",
"]",
"except",
"(",
"KeyError",
",",
"ValueError",
")",
":",
"raise",
"AttributeError",
"(",
"\"Instrument(order_book_id={})... | 39.8 | 19.4 |
def write_deps(deps_dict):
"""Write dependencies in a log file
into directory `/var/log/slpkg/dep/`
"""
for name, dependencies in deps_dict.iteritems():
if find_package(name + _meta_.sp, _meta_.pkg_path):
dep_path = _meta_.log_path + "dep/"
if not os.path.exists(dep_path)... | [
"def",
"write_deps",
"(",
"deps_dict",
")",
":",
"for",
"name",
",",
"dependencies",
"in",
"deps_dict",
".",
"iteritems",
"(",
")",
":",
"if",
"find_package",
"(",
"name",
"+",
"_meta_",
".",
"sp",
",",
"_meta_",
".",
"pkg_path",
")",
":",
"dep_path",
... | 40.25 | 6.5 |
def _populate(cls, as_of=None, delete=False):
"""Populate the table with billing cycles starting from `as_of`
Args:
as_of (date): The date at which to begin the populating
delete (bool): Should future billing cycles be deleted?
"""
billing_cycle_helper = get_bi... | [
"def",
"_populate",
"(",
"cls",
",",
"as_of",
"=",
"None",
",",
"delete",
"=",
"False",
")",
":",
"billing_cycle_helper",
"=",
"get_billing_cycle",
"(",
")",
"billing_cycles_exist",
"=",
"BillingCycle",
".",
"objects",
".",
"exists",
"(",
")",
"try",
":",
... | 40.054545 | 24.709091 |
def createDocument(self, namespaceURI, localName, doctype=None):
'''If specified must be a SOAP envelope, else may contruct an empty document.
'''
prefix = self._soap_env_prefix
if namespaceURI == self.reserved_ns[prefix]:
qualifiedName = '%s:%s' %(prefix,localName)
... | [
"def",
"createDocument",
"(",
"self",
",",
"namespaceURI",
",",
"localName",
",",
"doctype",
"=",
"None",
")",
":",
"prefix",
"=",
"self",
".",
"_soap_env_prefix",
"if",
"namespaceURI",
"==",
"self",
".",
"reserved_ns",
"[",
"prefix",
"]",
":",
"qualifiedNam... | 44.952381 | 25.142857 |
def add_subplot(self, x, y, n, margin=0.05):
"""Creates a div child subplot in a matplotlib.figure.add_subplot style.
Parameters
----------
x : int
The number of rows in the grid.
y : int
The number of columns in the grid.
n : int
The ... | [
"def",
"add_subplot",
"(",
"self",
",",
"x",
",",
"y",
",",
"n",
",",
"margin",
"=",
"0.05",
")",
":",
"width",
"=",
"1.",
"/",
"y",
"height",
"=",
"1.",
"/",
"x",
"left",
"=",
"(",
"(",
"n",
"-",
"1",
")",
"%",
"y",
")",
"*",
"width",
"t... | 29.828571 | 15.514286 |
def get_kvm_archs():
"""
Gets a list of architectures for which KVM is available on this server.
:returns: List of architectures for which KVM is available on this server.
"""
kvm = []
if not os.path.exists("/dev/kvm"):
return kvm
arch = platform.ma... | [
"def",
"get_kvm_archs",
"(",
")",
":",
"kvm",
"=",
"[",
"]",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"\"/dev/kvm\"",
")",
":",
"return",
"kvm",
"arch",
"=",
"platform",
".",
"machine",
"(",
")",
"if",
"arch",
"==",
"\"x86_64\"",
":",
"k... | 26.85 | 18.75 |
def ValidateKey(cls, key_path):
"""Validates this key against supported key names.
Args:
key_path (str): path of a Windows Registry key.
Raises:
FormatError: when key is not supported.
"""
for prefix in cls.VALID_PREFIXES:
if key_path.startswith(prefix):
return
# TOD... | [
"def",
"ValidateKey",
"(",
"cls",
",",
"key_path",
")",
":",
"for",
"prefix",
"in",
"cls",
".",
"VALID_PREFIXES",
":",
"if",
"key_path",
".",
"startswith",
"(",
"prefix",
")",
":",
"return",
"# TODO: move check to validator.",
"if",
"key_path",
".",
"startswit... | 29 | 17.047619 |
def put(self, key, value, overwrite=True):
"""Marshall the python object given as 'value' into a string, using the
to_string marshalling method passed in the constructor, and store it in
the DynamoDB table under key 'key'.
"""
self._get_table()
s = self.to_string(value)
... | [
"def",
"put",
"(",
"self",
",",
"key",
",",
"value",
",",
"overwrite",
"=",
"True",
")",
":",
"self",
".",
"_get_table",
"(",
")",
"s",
"=",
"self",
".",
"to_string",
"(",
"value",
")",
"log",
".",
"debug",
"(",
"\"Storing in key '%s' the object: '%s'\""... | 35.6 | 14.666667 |
def sqr(x, context=None):
"""
Return the square of ``x``.
"""
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_sqr,
(BigFloat._implicit_convert(x),),
context,
) | [
"def",
"sqr",
"(",
"x",
",",
"context",
"=",
"None",
")",
":",
"return",
"_apply_function_in_current_context",
"(",
"BigFloat",
",",
"mpfr",
".",
"mpfr_sqr",
",",
"(",
"BigFloat",
".",
"_implicit_convert",
"(",
"x",
")",
",",
")",
",",
"context",
",",
")... | 19.727273 | 15.545455 |
def pdhg_stepsize(L, tau=None, sigma=None):
r"""Default step sizes for `pdhg`.
Parameters
----------
L : `Operator` or float
Operator or norm of the operator that are used in the `pdhg` method.
If it is an `Operator`, the norm is computed with
``Operator.norm(estimate=True)``.
... | [
"def",
"pdhg_stepsize",
"(",
"L",
",",
"tau",
"=",
"None",
",",
"sigma",
"=",
"None",
")",
":",
"if",
"tau",
"is",
"not",
"None",
"and",
"sigma",
"is",
"not",
"None",
":",
"return",
"float",
"(",
"tau",
")",
",",
"float",
"(",
"sigma",
")",
"L_no... | 29.75 | 21.828125 |
def plot_stoch_vol(data, trace=None, ax=None):
"""
Generate plot for stochastic volatility model.
Parameters
----------
data : pandas.Series
Returns to model.
trace : pymc3.sampling.BaseTrace object, optional
trace as returned by model_stoch_vol
If not passed, sample fro... | [
"def",
"plot_stoch_vol",
"(",
"data",
",",
"trace",
"=",
"None",
",",
"ax",
"=",
"None",
")",
":",
"if",
"trace",
"is",
"None",
":",
"trace",
"=",
"model_stoch_vol",
"(",
"data",
")",
"if",
"ax",
"is",
"None",
":",
"fig",
",",
"ax",
"=",
"plt",
"... | 25.527778 | 20.694444 |
def agent_heartbeat(self, agent_id, metrics, run_states):
"""Notify server about agent state, receive commands.
Args:
agent_id (str): agent_id
metrics (dict): system metrics
run_states (dict): run_id: state mapping
Returns:
List of commands to exe... | [
"def",
"agent_heartbeat",
"(",
"self",
",",
"agent_id",
",",
"metrics",
",",
"run_states",
")",
":",
"mutation",
"=",
"gql",
"(",
"'''\n mutation Heartbeat(\n $id: ID!,\n $metrics: JSONString,\n $runState: JSONString\n ) {\n a... | 32.025 | 16.875 |
def save(self, with_data=False):
"""
Edits this Source
"""
r = self._client.request('PUT', self.url, json=self._serialize(with_data=with_data))
return self._deserialize(r.json(), self._manager) | [
"def",
"save",
"(",
"self",
",",
"with_data",
"=",
"False",
")",
":",
"r",
"=",
"self",
".",
"_client",
".",
"request",
"(",
"'PUT'",
",",
"self",
".",
"url",
",",
"json",
"=",
"self",
".",
"_serialize",
"(",
"with_data",
"=",
"with_data",
")",
")"... | 38 | 15.333333 |
def create_vip(self, vip_request_ids):
"""
Method to create vip request
param vip_request_ids: vip_request ids
"""
uri = 'api/v3/vip-request/deploy/%s/' % vip_request_ids
return super(ApiVipRequest, self).post(uri) | [
"def",
"create_vip",
"(",
"self",
",",
"vip_request_ids",
")",
":",
"uri",
"=",
"'api/v3/vip-request/deploy/%s/'",
"%",
"vip_request_ids",
"return",
"super",
"(",
"ApiVipRequest",
",",
"self",
")",
".",
"post",
"(",
"uri",
")"
] | 28.444444 | 14 |
def delete_return_line_item_by_id(cls, return_line_item_id, **kwargs):
"""Delete ReturnLineItem
Delete an instance of ReturnLineItem by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.... | [
"def",
"delete_return_line_item_by_id",
"(",
"cls",
",",
"return_line_item_id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_dele... | 45.809524 | 24.142857 |
def _mean_prediction(self, mu, Y, h, t_z):
""" Creates a h-step ahead mean prediction
This function is used for predict(). We have to iterate over the number
of timepoints (h) that the user wants to predict, using as inputs the ARIMA
parameters, past datapoints, and past predicted datap... | [
"def",
"_mean_prediction",
"(",
"self",
",",
"mu",
",",
"Y",
",",
"h",
",",
"t_z",
")",
":",
"# Create arrays to iteratre over",
"Y_exp",
"=",
"Y",
".",
"copy",
"(",
")",
"mu_exp",
"=",
"mu",
".",
"copy",
"(",
")",
"# Loop over h time periods ",
"... | 29.666667 | 21.784314 |
def store(self, prof_name, prof_type):
"""
Store a profile with the given name and type.
:param str prof_name:
Profile name.
:param str prof_type:
Profile type.
"""
prof_dir = self.__profile_dir(prof_name)
prof_stub = self.__profile_stub(prof_name, prof_type, prof_dir)
if not os.path.e... | [
"def",
"store",
"(",
"self",
",",
"prof_name",
",",
"prof_type",
")",
":",
"prof_dir",
"=",
"self",
".",
"__profile_dir",
"(",
"prof_name",
")",
"prof_stub",
"=",
"self",
".",
"__profile_stub",
"(",
"prof_name",
",",
"prof_type",
",",
"prof_dir",
")",
"if"... | 27.457143 | 14.428571 |
def iter_stack_frames(frames=None, start_frame=None, skip=0, skip_top_modules=()):
"""
Given an optional list of frames (defaults to current stack),
iterates over all frames that do not contain the ``__traceback_hide__``
local variable.
Frames can be skipped by either providing a number, or a tuple... | [
"def",
"iter_stack_frames",
"(",
"frames",
"=",
"None",
",",
"start_frame",
"=",
"None",
",",
"skip",
"=",
"0",
",",
"skip_top_modules",
"=",
"(",
")",
")",
":",
"if",
"not",
"frames",
":",
"frame",
"=",
"start_frame",
"if",
"start_frame",
"is",
"not",
... | 40.823529 | 22 |
def events_list(self, *args):
"""Display a list of all registered events"""
def merge(a, b, path=None):
"merges b into a"
if path is None: path = []
for key in b:
if key in a:
if isinstance(a[key], dict) and isinstance(b[key], dict... | [
"def",
"events_list",
"(",
"self",
",",
"*",
"args",
")",
":",
"def",
"merge",
"(",
"a",
",",
"b",
",",
"path",
"=",
"None",
")",
":",
"\"merges b into a\"",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"[",
"]",
"for",
"key",
"in",
"b",
":",
... | 35.037037 | 17.518519 |
def batchzip(size, iterable=None, rest=False):
"""
todo : add example
:param size:
:param iterable:
:param rest:
:return:
"""
fn = ibatch(size, rest=rest) >> zipflow
return fn if iterable is None else fn(iterable) | [
"def",
"batchzip",
"(",
"size",
",",
"iterable",
"=",
"None",
",",
"rest",
"=",
"False",
")",
":",
"fn",
"=",
"ibatch",
"(",
"size",
",",
"rest",
"=",
"rest",
")",
">>",
"zipflow",
"return",
"fn",
"if",
"iterable",
"is",
"None",
"else",
"fn",
"(",
... | 21.818182 | 15.818182 |
def create(type_dict, *type_parameters):
"""
type_parameters should be:
(name, (alternative1, alternative2, ...))
where name is a string, and the alternatives are all valid serialized
types.
"""
assert len(type_parameters) == 2
name = type_parameters[0]
alternatives = type_paramete... | [
"def",
"create",
"(",
"type_dict",
",",
"*",
"type_parameters",
")",
":",
"assert",
"len",
"(",
"type_parameters",
")",
"==",
"2",
"name",
"=",
"type_parameters",
"[",
"0",
"]",
"alternatives",
"=",
"type_parameters",
"[",
"1",
"]",
"assert",
"isinstance",
... | 37.625 | 13.125 |
def bounds(self) -> typing.Tuple[typing.Tuple[float, float], typing.Tuple[float, float]]:
"""Return the bounds property in relative coordinates.
Bounds is a tuple ((top, left), (height, width))"""
... | [
"def",
"bounds",
"(",
"self",
")",
"->",
"typing",
".",
"Tuple",
"[",
"typing",
".",
"Tuple",
"[",
"float",
",",
"float",
"]",
",",
"typing",
".",
"Tuple",
"[",
"float",
",",
"float",
"]",
"]",
":",
"..."
] | 44.2 | 23.6 |
def get_or_create_user(self, username, ldap_user):
"""
This must return a (User, created) 2-tuple for the given LDAP user.
username is the Django-friendly username of the user. ldap_user.dn is
the user's DN and ldap_user.attrs contains all of their LDAP attributes.
"""
mo... | [
"def",
"get_or_create_user",
"(",
"self",
",",
"username",
",",
"ldap_user",
")",
":",
"model",
"=",
"self",
".",
"get_user_model",
"(",
")",
"username_field",
"=",
"getattr",
"(",
"model",
",",
"'USERNAME_FIELD'",
",",
"'username'",
")",
"kwargs",
"=",
"{",... | 39.8 | 21.8 |
def wait_script(name,
source=None,
template=None,
onlyif=None,
unless=None,
cwd=None,
runas=None,
shell=None,
env=None,
stateful=False,
umask=None,
... | [
"def",
"wait_script",
"(",
"name",
",",
"source",
"=",
"None",
",",
"template",
"=",
"None",
",",
"onlyif",
"=",
"None",
",",
"unless",
"=",
"None",
",",
"cwd",
"=",
"None",
",",
"runas",
"=",
"None",
",",
"shell",
"=",
"None",
",",
"env",
"=",
"... | 32.866667 | 25.626667 |
def get_urls(self):
"""Get the admin urls
"""
info = '%s_%s' % (self.model._meta.app_label, self.model._meta.model_name)
def pat(regex, fn):
return url(regex, self.admin_site.admin_view(fn), name='%s_%s' % (info, fn.__name__))
url_patterns = [
pat(r'^([0... | [
"def",
"get_urls",
"(",
"self",
")",
":",
"info",
"=",
"'%s_%s'",
"%",
"(",
"self",
".",
"model",
".",
"_meta",
".",
"app_label",
",",
"self",
".",
"model",
".",
"_meta",
".",
"model_name",
")",
"def",
"pat",
"(",
"regex",
",",
"fn",
")",
":",
"r... | 39.764706 | 27.294118 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.