text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def get_mfd(self, slip, area, shear_modulus=30.0):
'''
Calculates activity rate on the fault
:param float slip:
Slip rate in mm/yr
:param fault_width:
Width of the fault (km)
:param float disp_length_ratio:
Displacement to length ratio (dime... | [
"def",
"get_mfd",
"(",
"self",
",",
"slip",
",",
"area",
",",
"shear_modulus",
"=",
"30.0",
")",
":",
"# Working in Nm so convert: shear_modulus - GPa -> Nm",
"# area - km ** 2. -> m ** 2.",
"# slip - mm/yr -> m/yr",
"moment_rate",
"=",
"(",
"shear_modulus",
"*",
"1.E9",... | 40.608696 | 19.173913 |
def _select_concept(self, line):
"""try to match a class and load it"""
g = self.current['graph']
if not line:
out = g.all_skos_concepts
using_pattern = False
else:
using_pattern = True
if line.isdigit():
line = int(line)
... | [
"def",
"_select_concept",
"(",
"self",
",",
"line",
")",
":",
"g",
"=",
"self",
".",
"current",
"[",
"'graph'",
"]",
"if",
"not",
"line",
":",
"out",
"=",
"g",
".",
"all_skos_concepts",
"using_pattern",
"=",
"False",
"else",
":",
"using_pattern",
"=",
... | 37.538462 | 17.923077 |
def process_commenters(self):
"""Group comments by author."""
for index, submission in enumerate(self.submissions.values()):
if submission.num_comments == 0:
continue
real_submission = self.reddit.submission(id=submission.id)
real_submission.comment_so... | [
"def",
"process_commenters",
"(",
"self",
")",
":",
"for",
"index",
",",
"submission",
"in",
"enumerate",
"(",
"self",
".",
"submissions",
".",
"values",
"(",
")",
")",
":",
"if",
"submission",
".",
"num_comments",
"==",
"0",
":",
"continue",
"real_submiss... | 40.171429 | 19.685714 |
def get_associations(self, env):
"""
Get all the associations for this env.
Root cannot have associations, so return None for root.
returns a map of hostnames to environments.
"""
if env.is_root:
return None
associations = self.associations.get_all... | [
"def",
"get_associations",
"(",
"self",
",",
"env",
")",
":",
"if",
"env",
".",
"is_root",
":",
"return",
"None",
"associations",
"=",
"self",
".",
"associations",
".",
"get_all",
"(",
")",
"return",
"[",
"assoc",
"for",
"assoc",
"in",
"associations",
"i... | 28.266667 | 19.066667 |
def b64_hmac_md5(key, data):
"""
return base64-encoded HMAC-MD5 for key and data, with trailing '='
stripped.
"""
bdigest = base64.b64encode(hmac.new(key, data, _md5).digest()).strip().decode("utf-8")
return re.sub('=+$', '', bdigest) | [
"def",
"b64_hmac_md5",
"(",
"key",
",",
"data",
")",
":",
"bdigest",
"=",
"base64",
".",
"b64encode",
"(",
"hmac",
".",
"new",
"(",
"key",
",",
"data",
",",
"_md5",
")",
".",
"digest",
"(",
")",
")",
".",
"strip",
"(",
")",
".",
"decode",
"(",
... | 36 | 17.428571 |
def _depaginate_all(self, url):
"""GETs the url provided and traverses the 'next' url that's
returned while storing the data in a list. Returns a single list of all
items.
"""
items = []
for x in self._depagination_generator(url):
items += x
return ite... | [
"def",
"_depaginate_all",
"(",
"self",
",",
"url",
")",
":",
"items",
"=",
"[",
"]",
"for",
"x",
"in",
"self",
".",
"_depagination_generator",
"(",
"url",
")",
":",
"items",
"+=",
"x",
"return",
"items"
] | 34.888889 | 16.111111 |
def get_build_metadata(key):
'''get_build_metadata will return metadata about an instance from within it.
:param key: the key to look up
'''
headers = {"Metadata-Flavor":"Google"}
url = "http://metadata.google.internal/computeMetadata/v1/instance/attributes/%s" %(key)
response = requests... | [
"def",
"get_build_metadata",
"(",
"key",
")",
":",
"headers",
"=",
"{",
"\"Metadata-Flavor\"",
":",
"\"Google\"",
"}",
"url",
"=",
"\"http://metadata.google.internal/computeMetadata/v1/instance/attributes/%s\"",
"%",
"(",
"key",
")",
"response",
"=",
"requests",
".",
... | 42.1 | 20.7 |
def list_assignment_submissions_courses(self, course_id, assignment_id, grouped=None, include=None):
"""
List assignment submissions.
Get all existing submissions for an assignment.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course... | [
"def",
"list_assignment_submissions_courses",
"(",
"self",
",",
"course_id",
",",
"assignment_id",
",",
"grouped",
"=",
"None",
",",
"include",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH... | 44.870968 | 26.903226 |
def path_has(self, **kwargs):
"""
Checks if the current path has a node spec'd by kwargs
"""
str_node = "/" # This node will always be "False"
for key, val in kwargs.items():
if key == 'node': str_node = val
if str_node in self... | [
"def",
"path_has",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"str_node",
"=",
"\"/\"",
"# This node will always be \"False\"",
"for",
"key",
",",
"val",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"key",
"==",
"'node'",
":",
"str_node",
"=",... | 42.461538 | 11.846154 |
def label_correcting_get_cycle(self, j, pred):
'''
API:
label_correcting_get_cycle(self, labelled, pred)
Description:
In label correcting check cycle it is decided pred has a cycle and
nodes in the cycle are labelled. We will create a list of nodes
... | [
"def",
"label_correcting_get_cycle",
"(",
"self",
",",
"j",
",",
"pred",
")",
":",
"cycle",
"=",
"[",
"]",
"cycle",
".",
"append",
"(",
"j",
")",
"current",
"=",
"pred",
"[",
"j",
"]",
"while",
"current",
"!=",
"j",
":",
"cycle",
".",
"append",
"("... | 38.481481 | 22.259259 |
def validate(self, reason=True):
# type: (bool) -> list
"""Return the validation results and include an (optional) reason.
If reason keyword is true, the validation is returned for each validation
the [(<result: bool>, <reason:str>), ...]. If reason is False, only a single list of valid... | [
"def",
"validate",
"(",
"self",
",",
"reason",
"=",
"True",
")",
":",
"# type: (bool) -> list",
"self",
".",
"_validation_results",
"=",
"[",
"validator",
".",
"is_valid",
"(",
"self",
".",
"_value",
")",
"for",
"validator",
"in",
"getattr",
"(",
"self",
"... | 52.227273 | 30.272727 |
def uuid_to_slug(uuid):
"""
Return IOTile Cloud compatible Device Slug
:param uuid: UUID
:return: string in the form of d--0000-0000-0000-0001
"""
if not isinstance(uuid, int):
raise ArgumentError("Invalid id that is not an integer", id=uuid)
if uuid < 0 or uuid > 0x7fffffff:
... | [
"def",
"uuid_to_slug",
"(",
"uuid",
")",
":",
"if",
"not",
"isinstance",
"(",
"uuid",
",",
"int",
")",
":",
"raise",
"ArgumentError",
"(",
"\"Invalid id that is not an integer\"",
",",
"id",
"=",
"uuid",
")",
"if",
"uuid",
"<",
"0",
"or",
"uuid",
">",
"0... | 36.4 | 22.933333 |
def edge_history(self, source, target, attribute):
"""
Returns a dictionary of attribute vales for each Graph in the
:class:`.GraphCollection` for a single edge.
Parameters
----------
source : str
Identifier for source node.
target : str
I... | [
"def",
"edge_history",
"(",
"self",
",",
"source",
",",
"target",
",",
"attribute",
")",
":",
"return",
"{",
"attr",
"[",
"'graph'",
"]",
":",
"attr",
"[",
"attribute",
"]",
"for",
"i",
",",
"attr",
"in",
"self",
".",
"master_graph",
".",
"edge",
"["... | 29.238095 | 19.714286 |
def _symlink_check(name, target, force, user, group, win_owner):
'''
Check the symlink function
'''
changes = {}
if not os.path.exists(name) and not __salt__['file.is_link'](name):
changes['new'] = name
return None, 'Symlink {0} to {1} is set for creation'.format(
name, t... | [
"def",
"_symlink_check",
"(",
"name",
",",
"target",
",",
"force",
",",
"user",
",",
"group",
",",
"win_owner",
")",
":",
"changes",
"=",
"{",
"}",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"name",
")",
"and",
"not",
"__salt__",
"[",
"'fi... | 44.411765 | 22.588235 |
def is_readable(path):
'''
Check if a given path is readable by the current user.
:param path: The path to check
:returns: True or False
'''
if os.access(path, os.F_OK) and os.access(path, os.R_OK):
# The path exists and is readable
return True
# The path does not exist
... | [
"def",
"is_readable",
"(",
"path",
")",
":",
"if",
"os",
".",
"access",
"(",
"path",
",",
"os",
".",
"F_OK",
")",
"and",
"os",
".",
"access",
"(",
"path",
",",
"os",
".",
"R_OK",
")",
":",
"# The path exists and is readable",
"return",
"True",
"# The p... | 22.928571 | 22.785714 |
def rpc(_cloud_rpc_name, **params):
"""
调用 LeanEngine 上的远程代码
与 cloud.run 类似,但是允许传入 leancloud.Object 作为参数,也允许传入 leancloud.Object 作为结果
:param name: 需要调用的远程 Cloud Code 的名称
:type name: basestring
:param params: 调用参数
:return: 调用结果
"""
encoded_params = {}
for key, value in params.items... | [
"def",
"rpc",
"(",
"_cloud_rpc_name",
",",
"*",
"*",
"params",
")",
":",
"encoded_params",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"params",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"params",
",",
"leancloud",
".",
"Object",
")"... | 36.666667 | 15.222222 |
def publish(self, topic, schema=None, name=None):
"""
Publish this stream on a topic for other Streams applications to subscribe to.
A Streams application may publish a stream to allow other
Streams applications to subscribe to it. A subscriber
matches a publisher if the topic an... | [
"def",
"publish",
"(",
"self",
",",
"topic",
",",
"schema",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"sl",
"=",
"_SourceLocation",
"(",
"_source_info",
"(",
")",
",",
"'publish'",
")",
"schema",
"=",
"streamsx",
".",
"topology",
".",
"schema",
... | 43.597015 | 23.955224 |
def authenticate(self):
"""
Authenticates with the PA Oauth system
"""
if self._auth_token is None or self._token_expiry < time.time():
self._perform_auth()
yield self._auth_token | [
"def",
"authenticate",
"(",
"self",
")",
":",
"if",
"self",
".",
"_auth_token",
"is",
"None",
"or",
"self",
".",
"_token_expiry",
"<",
"time",
".",
"time",
"(",
")",
":",
"self",
".",
"_perform_auth",
"(",
")",
"yield",
"self",
".",
"_auth_token"
] | 28.125 | 14.125 |
def parse_pseudo_lang(self, sel, m, has_selector):
"""Parse pseudo language."""
values = m.group('values')
patterns = []
for token in RE_VALUES.finditer(values):
if token.group('split'):
continue
value = token.group('value')
if value.s... | [
"def",
"parse_pseudo_lang",
"(",
"self",
",",
"sel",
",",
"m",
",",
"has_selector",
")",
":",
"values",
"=",
"m",
".",
"group",
"(",
"'values'",
")",
"patterns",
"=",
"[",
"]",
"for",
"token",
"in",
"RE_VALUES",
".",
"finditer",
"(",
"values",
")",
"... | 36.892857 | 17.25 |
def createTable(self, tableName, path=None, source=None, schema=None, **options):
"""Creates a table based on the dataset in a data source.
It returns the DataFrame associated with the table.
The data source is specified by the ``source`` and a set of ``options``.
If ``source`` is not ... | [
"def",
"createTable",
"(",
"self",
",",
"tableName",
",",
"path",
"=",
"None",
",",
"source",
"=",
"None",
",",
"schema",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"if",
"path",
"is",
"not",
"None",
":",
"options",
"[",
"\"path\"",
"]",
"=",... | 48.962963 | 28.074074 |
def add_full_state_methods(class_with_globalize_methods):
"""
class decorator to create "_full_state" methods/properties on the class (so they
are valid for all instances created from this class).
Parameters
----------
class_with_globalize_methods
"""
assert hasattr(class_with_globaliz... | [
"def",
"add_full_state_methods",
"(",
"class_with_globalize_methods",
")",
":",
"assert",
"hasattr",
"(",
"class_with_globalize_methods",
",",
"'active_set'",
")",
"assert",
"hasattr",
"(",
"class_with_globalize_methods",
",",
"'nstates_full'",
")",
"for",
"name",
",",
... | 42.133333 | 25.6 |
def register(self, schema):
"""Register input schema class.
When registering a schema, all inner schemas are registered as well.
:param Schema schema: schema to register.
:return: old registered schema.
:rtype: type
"""
result = None
uuid = schema.uuid
... | [
"def",
"register",
"(",
"self",
",",
"schema",
")",
":",
"result",
"=",
"None",
"uuid",
"=",
"schema",
".",
"uuid",
"if",
"uuid",
"in",
"self",
".",
"_schbyuuid",
":",
"result",
"=",
"self",
".",
"_schbyuuid",
"[",
"uuid",
"]",
"if",
"result",
"!=",
... | 24.09375 | 22.65625 |
def acosh(x):
"""
Inverse hyperbolic cosine
"""
if isinstance(x, UncertainFunction):
mcpts = np.arccosh(x._mcpts)
return UncertainFunction(mcpts)
else:
return np.arccosh(x) | [
"def",
"acosh",
"(",
"x",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"UncertainFunction",
")",
":",
"mcpts",
"=",
"np",
".",
"arccosh",
"(",
"x",
".",
"_mcpts",
")",
"return",
"UncertainFunction",
"(",
"mcpts",
")",
"else",
":",
"return",
"np",
"."... | 23.111111 | 9.555556 |
def consecutive_groups(iterable, ordering=lambda x: x):
"""Yield groups of consecutive items using :func:`itertools.groupby`.
The *ordering* function determines whether two items are adjacent by
returning their position.
By default, the ordering function is the identity function. This is
suitable f... | [
"def",
"consecutive_groups",
"(",
"iterable",
",",
"ordering",
"=",
"lambda",
"x",
":",
"x",
")",
":",
"for",
"k",
",",
"g",
"in",
"groupby",
"(",
"enumerate",
"(",
"iterable",
")",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"0",
"]",
"-",
"o... | 32.171429 | 19.771429 |
def upload_index_file(self, test_address, timestamp):
""" Create an index.html file with links to all the log files
that were just uploaded. """
global already_uploaded_files
already_uploaded_files = list(set(already_uploaded_files))
already_uploaded_files.sort()
file... | [
"def",
"upload_index_file",
"(",
"self",
",",
"test_address",
",",
"timestamp",
")",
":",
"global",
"already_uploaded_files",
"already_uploaded_files",
"=",
"list",
"(",
"set",
"(",
"already_uploaded_files",
")",
")",
"already_uploaded_files",
".",
"sort",
"(",
")",... | 48.529412 | 12 |
def toURLEncoded(self):
"""Generate an x-www-urlencoded string"""
args = self.toPostArgs().items()
args.sort()
return urllib.urlencode(args) | [
"def",
"toURLEncoded",
"(",
"self",
")",
":",
"args",
"=",
"self",
".",
"toPostArgs",
"(",
")",
".",
"items",
"(",
")",
"args",
".",
"sort",
"(",
")",
"return",
"urllib",
".",
"urlencode",
"(",
"args",
")"
] | 33.6 | 8.2 |
def _publish_grade(self, score, only_if_higher=None):
"""
Publish a grade to the runtime.
"""
grade_dict = {
'value': score.raw_earned,
'max_value': score.raw_possible,
'only_if_higher': only_if_higher,
}
self.runtime.publish(self, 'gra... | [
"def",
"_publish_grade",
"(",
"self",
",",
"score",
",",
"only_if_higher",
"=",
"None",
")",
":",
"grade_dict",
"=",
"{",
"'value'",
":",
"score",
".",
"raw_earned",
",",
"'max_value'",
":",
"score",
".",
"raw_possible",
",",
"'only_if_higher'",
":",
"only_i... | 32.7 | 8.9 |
def get_sdc_by_id(self, id):
"""
Get ScaleIO SDC object by its id
:param name: id of SDC
:return: ScaleIO SDC object
:raise KeyError: No SDC with specified id found
:rtype: SDC object
"""
for sdc in self.sdc:
if sdc.id == id:
re... | [
"def",
"get_sdc_by_id",
"(",
"self",
",",
"id",
")",
":",
"for",
"sdc",
"in",
"self",
".",
"sdc",
":",
"if",
"sdc",
".",
"id",
"==",
"id",
":",
"return",
"sdc",
"raise",
"KeyError",
"(",
"\"SDC with that ID not found\"",
")"
] | 30.833333 | 8.833333 |
def validation_curve(train_scores, test_scores, param_range, param_name=None,
semilogx=False, ax=None):
"""Plot a validation curve
Plot a metric vs hyperpameter values for the training and test set
Parameters
----------
train_scores : array-like
Scores for the training... | [
"def",
"validation_curve",
"(",
"train_scores",
",",
"test_scores",
",",
"param_range",
",",
"param_name",
"=",
"None",
",",
"semilogx",
"=",
"False",
",",
"ax",
"=",
"None",
")",
":",
"if",
"ax",
"is",
"None",
":",
"ax",
"=",
"plt",
".",
"gca",
"(",
... | 28.129032 | 23.33871 |
def _set_addr(self, addr):
"""private helper method"""
if self._addr != addr:
ioctl(self._fd, SMBUS.I2C_SLAVE, addr)
self._addr = addr | [
"def",
"_set_addr",
"(",
"self",
",",
"addr",
")",
":",
"if",
"self",
".",
"_addr",
"!=",
"addr",
":",
"ioctl",
"(",
"self",
".",
"_fd",
",",
"SMBUS",
".",
"I2C_SLAVE",
",",
"addr",
")",
"self",
".",
"_addr",
"=",
"addr"
] | 34 | 9 |
def add_roles(self, databaseName, roleNames, collectionName=None):
"""Add multiple roles
Args:
databaseName (str): Database Name
roleNames (list of RoleSpecs): roles
Keyword Args:
collectionName (str): Collection
Raises:
... | [
"def",
"add_roles",
"(",
"self",
",",
"databaseName",
",",
"roleNames",
",",
"collectionName",
"=",
"None",
")",
":",
"for",
"roleName",
"in",
"roleNames",
":",
"self",
".",
"add_role",
"(",
"databaseName",
",",
"roleName",
",",
"collectionName",
")"
] | 34.133333 | 19.333333 |
def generate_entropy(strength, internal_entropy, external_entropy):
'''
strength - length of produced seed. One of 128, 192, 256
random - binary stream of random data from external HRNG
'''
if strength not in (128, 192, 256):
raise ValueError("Invalid strength")
if not internal_entropy:... | [
"def",
"generate_entropy",
"(",
"strength",
",",
"internal_entropy",
",",
"external_entropy",
")",
":",
"if",
"strength",
"not",
"in",
"(",
"128",
",",
"192",
",",
"256",
")",
":",
"raise",
"ValueError",
"(",
"\"Invalid strength\"",
")",
"if",
"not",
"intern... | 32.555556 | 21.888889 |
def deconstruct(self):
"""Deconstruction for migrations.
Return a simpler object (_SerializedWorkflow), since our Workflows
are rather hard to serialize: Django doesn't like deconstructing
metaclass-built classes.
"""
name, path, args, kwargs = super(StateField, self).de... | [
"def",
"deconstruct",
"(",
"self",
")",
":",
"name",
",",
"path",
",",
"args",
",",
"kwargs",
"=",
"super",
"(",
"StateField",
",",
"self",
")",
".",
"deconstruct",
"(",
")",
"# We want to display the proper class name, which isn't available",
"# at the same point f... | 40.541667 | 20.875 |
def _getModules(self):
"""
Import and load application modules.
:return: <dict>
"""
modules = {}
modulesPath = os.path.join("application", "module")
moduleList = os.listdir(modulesPath)
for moduleName in moduleList:
modulePath = os.path.join(... | [
"def",
"_getModules",
"(",
"self",
")",
":",
"modules",
"=",
"{",
"}",
"modulesPath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"\"application\"",
",",
"\"module\"",
")",
"moduleList",
"=",
"os",
".",
"listdir",
"(",
"modulesPath",
")",
"for",
"moduleNam... | 30 | 18 |
def verify_password(self, password, password_hash):
"""Verify plaintext ``password`` against ``hashed password``.
Args:
password(str): Plaintext password that the user types in.
password_hash(str): Password hash generated by a previous call to ``hash_password()``.
Return... | [
"def",
"verify_password",
"(",
"self",
",",
"password",
",",
"password_hash",
")",
":",
"# Print deprecation warning if called with (password, user) instead of (password, user.password)",
"if",
"isinstance",
"(",
"password_hash",
",",
"self",
".",
"user_manager",
".",
"db_man... | 46.344828 | 29.586207 |
def line_content_counts_as_uncovered_manual(content: str) -> bool:
"""
Args:
content: A line with indentation and tail comments/space removed.
Returns:
Whether the line could be included in the coverage report.
"""
# Omit empty lines.
if not content:
return False
# ... | [
"def",
"line_content_counts_as_uncovered_manual",
"(",
"content",
":",
"str",
")",
"->",
"bool",
":",
"# Omit empty lines.",
"if",
"not",
"content",
":",
"return",
"False",
"# Omit declarations.",
"for",
"keyword",
"in",
"[",
"'def'",
",",
"'class'",
"]",
":",
"... | 27.684211 | 22.526316 |
def _viewEntryNumber(self, ientry, select=True):
"""views entry #ientry. Also selects entry in listview if select=True"""
# pass entry to viewer dialog
self._viewing_ientry = ientry
entry = self.purrer.entries[ientry]
busy = BusyIndicator()
self.view_entry_dialog.viewEntr... | [
"def",
"_viewEntryNumber",
"(",
"self",
",",
"ientry",
",",
"select",
"=",
"True",
")",
":",
"# pass entry to viewer dialog",
"self",
".",
"_viewing_ientry",
"=",
"ientry",
"entry",
"=",
"self",
".",
"purrer",
".",
"entries",
"[",
"ientry",
"]",
"busy",
"=",... | 52.428571 | 16.714286 |
def main(**options):
"""Spline loc tool."""
application = Application(**options)
# fails application when your defined threshold is higher than your ratio of com/loc.
if not application.run():
sys.exit(1)
return application | [
"def",
"main",
"(",
"*",
"*",
"options",
")",
":",
"application",
"=",
"Application",
"(",
"*",
"*",
"options",
")",
"# fails application when your defined threshold is higher than your ratio of com/loc.",
"if",
"not",
"application",
".",
"run",
"(",
")",
":",
"sys"... | 35 | 17 |
def baseline_or_audit(self, allow_deletion=False, audit_only=False):
"""Baseline synchonization or audit.
Both functions implemented in this routine because audit is a prerequisite
for a baseline sync. In the case of baseline sync the last timestamp seen
is recorded as client state.
... | [
"def",
"baseline_or_audit",
"(",
"self",
",",
"allow_deletion",
"=",
"False",
",",
"audit_only",
"=",
"False",
")",
":",
"action",
"=",
"(",
"'audit'",
"if",
"(",
"audit_only",
")",
"else",
"'baseline sync'",
")",
"self",
".",
"logger",
".",
"debug",
"(",
... | 50.313953 | 18.534884 |
def _utc_to_local(self, data, local_zone="America/Los_Angeles"):
""" Adjust index of dataframe according to timezone that is requested by user.
Parameters
----------
data : pd.DataFrame()
Pandas dataframe of json timeseries response from server.
local_zone :... | [
"def",
"_utc_to_local",
"(",
"self",
",",
"data",
",",
"local_zone",
"=",
"\"America/Los_Angeles\"",
")",
":",
"# Accounts for localtime shift",
"data",
".",
"index",
"=",
"data",
".",
"index",
".",
"tz_localize",
"(",
"pytz",
".",
"utc",
")",
".",
"tz_convert... | 33.416667 | 24.875 |
def ParseMany(text):
"""Parses many YAML documents into a list of Python objects.
Args:
text: A YAML source with multiple documents embedded.
Returns:
A list of Python data structures corresponding to the YAML documents.
"""
precondition.AssertType(text, Text)
if compatibility.PY2:
text = tex... | [
"def",
"ParseMany",
"(",
"text",
")",
":",
"precondition",
".",
"AssertType",
"(",
"text",
",",
"Text",
")",
"if",
"compatibility",
".",
"PY2",
":",
"text",
"=",
"text",
".",
"encode",
"(",
"\"utf-8\"",
")",
"return",
"list",
"(",
"yaml",
".",
"safe_lo... | 24.266667 | 21.533333 |
def _getParameters(self):
"""Returns the result of this decorator."""
param = self.query._getParameters()
key = self.__PATTERN_KEY % (str(self._getIndex()))
val = self.__PATTERN_VALUE % (self.__column, self.__value)
#self.__column.getColumnAlias()
param.update({key:val})
... | [
"def",
"_getParameters",
"(",
"self",
")",
":",
"param",
"=",
"self",
".",
"query",
".",
"_getParameters",
"(",
")",
"key",
"=",
"self",
".",
"__PATTERN_KEY",
"%",
"(",
"str",
"(",
"self",
".",
"_getIndex",
"(",
")",
")",
")",
"val",
"=",
"self",
"... | 41.625 | 11.5 |
def fetch_csv_dataframe(
download_url,
filename=None,
subdir=None,
**pandas_kwargs):
"""
Download a remote file from `download_url` and save it locally as `filename`.
Load that local file as a CSV into Pandas using extra keyword arguments such as sep='\t'.
"""
path = ... | [
"def",
"fetch_csv_dataframe",
"(",
"download_url",
",",
"filename",
"=",
"None",
",",
"subdir",
"=",
"None",
",",
"*",
"*",
"pandas_kwargs",
")",
":",
"path",
"=",
"fetch_file",
"(",
"download_url",
"=",
"download_url",
",",
"filename",
"=",
"filename",
",",... | 31.533333 | 17.266667 |
def get_composition_query_session_for_repository(self, repository_id, proxy):
"""Gets a composition query session for the given repository.
arg: repository_id (osid.id.Id): the Id of the repository
arg proxy (osid.proxy.Proxy): a proxy
return: (osid.repository.CompositionQuerySes... | [
"def",
"get_composition_query_session_for_repository",
"(",
"self",
",",
"repository_id",
",",
"proxy",
")",
":",
"if",
"repository_id",
"is",
"None",
":",
"raise",
"NullArgument",
"(",
")",
"if",
"not",
"self",
".",
"supports_composition_query",
"(",
")",
":",
... | 42.903226 | 16.451613 |
def get(self, request, **kwargs):
"""
Return the customer's valid subscriptions.
Returns with status code 200.
"""
customer, _created = Customer.get_or_create(
subscriber=subscriber_request_callback(self.request)
)
serializer = SubscriptionSerializer(customer.subscription)
return Response(serialize... | [
"def",
"get",
"(",
"self",
",",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"customer",
",",
"_created",
"=",
"Customer",
".",
"get_or_create",
"(",
"subscriber",
"=",
"subscriber_request_callback",
"(",
"self",
".",
"request",
")",
")",
"serializer",
"=... | 26.333333 | 15.333333 |
def relpath(self):
"""
Determine the relative path to this repository
Returns:
str: relative path to this repository
"""
here = os.path.abspath(os.path.curdir)
relpath = os.path.relpath(self.fpath, here)
return relpath | [
"def",
"relpath",
"(",
"self",
")",
":",
"here",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"curdir",
")",
"relpath",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"self",
".",
"fpath",
",",
"here",
")",
"return",
"relpat... | 27.8 | 14.4 |
def update_widget_attrs(self, bound_field, attrs):
"""
Update the dictionary of attributes used while rendering the input widget
"""
bound_field.form.update_widget_attrs(bound_field, attrs)
widget_classes = self.widget.attrs.get('class', None)
if widget_classes:
... | [
"def",
"update_widget_attrs",
"(",
"self",
",",
"bound_field",
",",
"attrs",
")",
":",
"bound_field",
".",
"form",
".",
"update_widget_attrs",
"(",
"bound_field",
",",
"attrs",
")",
"widget_classes",
"=",
"self",
".",
"widget",
".",
"attrs",
".",
"get",
"(",... | 40.25 | 15.916667 |
def read_interactions(path, comments="#", directed=False, delimiter=None,
nodetype=None, timestamptype=None, encoding='utf-8', keys=False):
"""Read a DyNetx graph from interaction list format.
Parameters
----------
path : basestring
The desired output filenam... | [
"def",
"read_interactions",
"(",
"path",
",",
"comments",
"=",
"\"#\"",
",",
"directed",
"=",
"False",
",",
"delimiter",
"=",
"None",
",",
"nodetype",
"=",
"None",
",",
"timestamptype",
"=",
"None",
",",
"encoding",
"=",
"'utf-8'",
",",
"keys",
"=",
"Fal... | 34.190476 | 27.095238 |
def over(self, window):
"""
Define a windowing column.
:param window: a :class:`WindowSpec`
:return: a Column
>>> from pyspark.sql import Window
>>> window = Window.partitionBy("name").orderBy("age").rowsBetween(-1, 1)
>>> from pyspark.sql.functions import rank,... | [
"def",
"over",
"(",
"self",
",",
"window",
")",
":",
"from",
"pyspark",
".",
"sql",
".",
"window",
"import",
"WindowSpec",
"if",
"not",
"isinstance",
"(",
"window",
",",
"WindowSpec",
")",
":",
"raise",
"TypeError",
"(",
"\"window should be WindowSpec\"",
")... | 36.117647 | 15.176471 |
def next_flightmode_colour(self):
'''allocate a colour to be used for a flight mode'''
if self.flightmode_colour_index > len(flightmode_colours):
print("Out of colours; reusing")
self.flightmode_colour_index = 0
ret = flightmode_colours[self.flightmode_colour_index]
... | [
"def",
"next_flightmode_colour",
"(",
"self",
")",
":",
"if",
"self",
".",
"flightmode_colour_index",
">",
"len",
"(",
"flightmode_colours",
")",
":",
"print",
"(",
"\"Out of colours; reusing\"",
")",
"self",
".",
"flightmode_colour_index",
"=",
"0",
"ret",
"=",
... | 46 | 13.25 |
def qteMakeWidgetActive(self, widgetObj: QtGui.QWidget):
"""
Give keyboard focus to ``widgetObj``.
If ``widgetObj`` is **None** then the internal focus state
is reset, but the focus manger will automatically
activate the first available widget again.
|Args|
* `... | [
"def",
"qteMakeWidgetActive",
"(",
"self",
",",
"widgetObj",
":",
"QtGui",
".",
"QWidget",
")",
":",
"# Void the active widget information.",
"if",
"widgetObj",
"is",
"None",
":",
"self",
".",
"_qteActiveWidget",
"=",
"None",
"return",
"# Ensure that this applet is an... | 33.775862 | 21.017241 |
def get_or_create_iobject(identifier_uid,
identifier_namespace_uri,
iobject_type_name,
iobject_type_namespace_uri,
iobject_type_revision_name,
iobject_family_name,
... | [
"def",
"get_or_create_iobject",
"(",
"identifier_uid",
",",
"identifier_namespace_uri",
",",
"iobject_type_name",
",",
"iobject_type_namespace_uri",
",",
"iobject_type_revision_name",
",",
"iobject_family_name",
",",
"iobject_family_revision_name",
"=",
"\"\"",
",",
"identifier... | 48.246914 | 31.45679 |
def text(self, text, stylename=None):
"""Add text within the current container."""
assert self._containers
container = self._containers[-1]
if stylename is not None:
stylename = self._get_style_name(stylename)
container.addElement(Span(stylename=stylename, text=te... | [
"def",
"text",
"(",
"self",
",",
"text",
",",
"stylename",
"=",
"None",
")",
":",
"assert",
"self",
".",
"_containers",
"container",
"=",
"self",
".",
"_containers",
"[",
"-",
"1",
"]",
"if",
"stylename",
"is",
"not",
"None",
":",
"stylename",
"=",
"... | 42.222222 | 11.111111 |
def action(self, observations):
""" Calculate value for given state """
observations = self.input_block(observations)
policy_hidden = self.policy_backbone(observations)
action = self.action_head(policy_hidden)
return action | [
"def",
"action",
"(",
"self",
",",
"observations",
")",
":",
"observations",
"=",
"self",
".",
"input_block",
"(",
"observations",
")",
"policy_hidden",
"=",
"self",
".",
"policy_backbone",
"(",
"observations",
")",
"action",
"=",
"self",
".",
"action_head",
... | 43 | 11.166667 |
def guess_mime_type(url):
"""Use the mimetypes module to lookup the type for an extension.
This function also adds some extensions required for HTML5
"""
(mimetype, _mimeencoding) = mimetypes.guess_type(url)
if not mimetype:
ext = os.path.splitext(url)[1]
mimetype = _MIME_TYPES.get(... | [
"def",
"guess_mime_type",
"(",
"url",
")",
":",
"(",
"mimetype",
",",
"_mimeencoding",
")",
"=",
"mimetypes",
".",
"guess_type",
"(",
"url",
")",
"if",
"not",
"mimetype",
":",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"url",
")",
"[",
"1",... | 35.615385 | 14.307692 |
def expose_ideal_query_execution_start_points(compound_match_query, location_types,
coerced_locations):
"""Ensure that OrientDB only considers desirable query start points in query planning."""
new_queries = []
for match_query in compound_match_query.match_quer... | [
"def",
"expose_ideal_query_execution_start_points",
"(",
"compound_match_query",
",",
"location_types",
",",
"coerced_locations",
")",
":",
"new_queries",
"=",
"[",
"]",
"for",
"match_query",
"in",
"compound_match_query",
".",
"match_queries",
":",
"location_classification"... | 59.09375 | 31.625 |
def __build_url(self, api_call, **kwargs):
"""Builds the api query"""
kwargs['key'] = self.api_key
if 'language' not in kwargs:
kwargs['language'] = self.language
if 'format' not in kwargs:
kwargs['format'] = self.__format
api_query = urlencode(kwargs)
... | [
"def",
"__build_url",
"(",
"self",
",",
"api_call",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'key'",
"]",
"=",
"self",
".",
"api_key",
"if",
"'language'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'language'",
"]",
"=",
"self",
".",
"lang... | 37.25 | 7.25 |
def plot(self, figure_list):
'''
When each subscript is called, uses its standard plotting
Args:
figure_list: list of figures passed from the guit
'''
#TODO: be smarter about how we plot ScriptIterator
if self._current_subscript_stage is not None:
... | [
"def",
"plot",
"(",
"self",
",",
"figure_list",
")",
":",
"#TODO: be smarter about how we plot ScriptIterator",
"if",
"self",
".",
"_current_subscript_stage",
"is",
"not",
"None",
":",
"if",
"self",
".",
"_current_subscript_stage",
"[",
"'current_subscript'",
"]",
"is... | 44.606061 | 34.242424 |
def dmi(arg, n, high_col='high', low_col='low', close_col='close'):
""" Return the dmi+, dmi-, Average directional index
( http://en.wikipedia.org/wiki/Average_Directional_Index )
TODO - break up calcuat
"""
converted = arg[[close_col, high_col, low_col]]
converted.columns = ['close', 'high'... | [
"def",
"dmi",
"(",
"arg",
",",
"n",
",",
"high_col",
"=",
"'high'",
",",
"low_col",
"=",
"'low'",
",",
"close_col",
"=",
"'close'",
")",
":",
"converted",
"=",
"arg",
"[",
"[",
"close_col",
",",
"high_col",
",",
"low_col",
"]",
"]",
"converted",
".",... | 31.5 | 16.678571 |
def lines(self, encoding=None, errors='strict', retain=True):
r""" Open this file, read all lines, return them in a list.
Optional arguments:
`encoding` - The Unicode encoding (or character set) of
the file. The default is ``None``, meaning the content
of th... | [
"def",
"lines",
"(",
"self",
",",
"encoding",
"=",
"None",
",",
"errors",
"=",
"'strict'",
",",
"retain",
"=",
"True",
")",
":",
"return",
"self",
".",
"text",
"(",
"encoding",
",",
"errors",
")",
".",
"splitlines",
"(",
"retain",
")"
] | 51.833333 | 23.055556 |
def must_stop(self):
"""
Return True if the worker must stop when the current loop is over.
"""
return bool(self.terminate_gracefuly and self.end_signal_caught
or self.num_loops >= self.max_loops or self.end_forced
or self.wanted_end_date and datetime.ut... | [
"def",
"must_stop",
"(",
"self",
")",
":",
"return",
"bool",
"(",
"self",
".",
"terminate_gracefuly",
"and",
"self",
".",
"end_signal_caught",
"or",
"self",
".",
"num_loops",
">=",
"self",
".",
"max_loops",
"or",
"self",
".",
"end_forced",
"or",
"self",
".... | 49.285714 | 23.285714 |
def tail(f, window=20):
"""
Returns the last `window` lines of file `f` as a list.
@param window: the number of lines.
"""
if window == 0:
return []
BUFSIZ = 1024
f.seek(0, 2)
bytes = f.tell()
size = window + 1
block = -1
data = []
while size > 0 and bytes > 0:
... | [
"def",
"tail",
"(",
"f",
",",
"window",
"=",
"20",
")",
":",
"if",
"window",
"==",
"0",
":",
"return",
"[",
"]",
"BUFSIZ",
"=",
"1024",
"f",
".",
"seek",
"(",
"0",
",",
"2",
")",
"bytes",
"=",
"f",
".",
"tell",
"(",
")",
"size",
"=",
"windo... | 28.833333 | 15.9 |
def getDevicesById(self): # , query):
"""
rows = self.camera_collection.get(query)
devices_by_id = {}
for row in rows:
row.pop("classname")
device = DataModel.RTSPCameraDevice(**row)
devices_by_id[device._id] = device
return devices_by_id
... | [
"def",
"getDevicesById",
"(",
"self",
")",
":",
"# , query):",
"rows",
"=",
"self",
".",
"camera_collection",
".",
"get",
"(",
")",
"devices_by_id",
"=",
"{",
"}",
"for",
"row",
"in",
"rows",
":",
"classname",
"=",
"row",
".",
"pop",
"(",
"\"classname\""... | 35.130435 | 10.26087 |
def declare(full_table_name, definition, context):
"""
Parse declaration and create new SQL table accordingly.
:param full_table_name: full name of the table
:param definition: DataJoint table definition
:param context: dictionary of objects that might be referred to in the table.
"""
tabl... | [
"def",
"declare",
"(",
"full_table_name",
",",
"definition",
",",
"context",
")",
":",
"table_name",
"=",
"full_table_name",
".",
"strip",
"(",
"'`'",
")",
".",
"split",
"(",
"'.'",
")",
"[",
"1",
"]",
"if",
"len",
"(",
"table_name",
")",
">",
"MAX_TAB... | 42.5 | 20.092593 |
def intersects_first(self,
ray_origins,
ray_directions):
"""
Find the index of the first triangle a ray hits.
Parameters
----------
ray_origins: (n,3) float, origins of rays
ray_directions: (n,3) float, direction (vec... | [
"def",
"intersects_first",
"(",
"self",
",",
"ray_origins",
",",
"ray_directions",
")",
":",
"ray_origins",
"=",
"np",
".",
"asanyarray",
"(",
"deepcopy",
"(",
"ray_origins",
")",
")",
"ray_directions",
"=",
"np",
".",
"asanyarray",
"(",
"ray_directions",
")",... | 30.130435 | 20.391304 |
def send_event(self, event_type, category=None, dimensions=None,
properties=None, timestamp=None):
"""Send an event to SignalFx.
Args:
event_type (string): the event type (name of the event time
series).
category (string): the category of the e... | [
"def",
"send_event",
"(",
"self",
",",
"event_type",
",",
"category",
"=",
"None",
",",
"dimensions",
"=",
"None",
",",
"properties",
"=",
"None",
",",
"timestamp",
"=",
"None",
")",
":",
"if",
"category",
"and",
"category",
"not",
"in",
"SUPPORTED_EVENT_C... | 43.033333 | 19.766667 |
def _assemble_and_send_request(self):
"""
Fires off the Fedex request.
@warning: NEVER CALL THIS METHOD DIRECTLY. CALL send_request(),
WHICH RESIDES ON FedexBaseService AND IS INHERITED.
"""
# Fire off the query.
return self.client.service.getPickupAvailabil... | [
"def",
"_assemble_and_send_request",
"(",
"self",
")",
":",
"# Fire off the query.",
"return",
"self",
".",
"client",
".",
"service",
".",
"getPickupAvailability",
"(",
"WebAuthenticationDetail",
"=",
"self",
".",
"WebAuthenticationDetail",
",",
"ClientDetail",
"=",
"... | 40.153846 | 13.153846 |
def exit_config_mode(self, exit_config="exit all", pattern="#"):
"""Exit from configuration mode."""
return super(RadETXBase, self).exit_config_mode(
exit_config=exit_config, pattern=pattern
) | [
"def",
"exit_config_mode",
"(",
"self",
",",
"exit_config",
"=",
"\"exit all\"",
",",
"pattern",
"=",
"\"#\"",
")",
":",
"return",
"super",
"(",
"RadETXBase",
",",
"self",
")",
".",
"exit_config_mode",
"(",
"exit_config",
"=",
"exit_config",
",",
"pattern",
... | 44.8 | 16.6 |
def remove(path, follow_symlink=False):
"""
Implements an remove function that will delete files, folder trees and symlink trees
1.) Remove a file
2.) Remove a symlink and follow into with a recursive rm if follow_symlink
3.) Remove directory with rmtree
Args:
path (str): path to remov... | [
"def",
"remove",
"(",
"path",
",",
"follow_symlink",
"=",
"False",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"os",
".",
"remove",
"(",
"path",
")",
"elif",
"os",
".",
"path",
".",
"islink",
"(",
"path",
")",
":",
... | 29.95 | 19.05 |
def handle(self):
"""
Executes the command.
"""
creator = MigrationCreator()
name = self.argument("name")
table = self.option("table")
create = bool(self.option("create"))
if not table and create is not False:
table = create
path = s... | [
"def",
"handle",
"(",
"self",
")",
":",
"creator",
"=",
"MigrationCreator",
"(",
")",
"name",
"=",
"self",
".",
"argument",
"(",
"\"name\"",
")",
"table",
"=",
"self",
".",
"option",
"(",
"\"table\"",
")",
"create",
"=",
"bool",
"(",
"self",
".",
"op... | 27.7 | 18.8 |
def _raw_hex_id(obj):
"""Return the padded hexadecimal id of ``obj``."""
# interpret as a pointer since that's what really what id returns
packed = struct.pack('@P', id(obj))
return ''.join(map(_replacer, packed)) | [
"def",
"_raw_hex_id",
"(",
"obj",
")",
":",
"# interpret as a pointer since that's what really what id returns",
"packed",
"=",
"struct",
".",
"pack",
"(",
"'@P'",
",",
"id",
"(",
"obj",
")",
")",
"return",
"''",
".",
"join",
"(",
"map",
"(",
"_replacer",
",",... | 45 | 10.2 |
def get_values(self, *args, **kwargs):
"""
Convenience method that for simple single tag queries will
return just the values to be iterated on.
"""
if isinstance(args[0], list):
raise ValueError("Can only get_values() for a single tag.")
response = self.get_d... | [
"def",
"get_values",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"args",
"[",
"0",
"]",
",",
"list",
")",
":",
"raise",
"ValueError",
"(",
"\"Can only get_values() for a single tag.\"",
")",
"response",
"=",
... | 40.615385 | 15.692308 |
def tag_and_push_image(self, image, target_image, insecure=False, force=False,
dockercfg=None):
"""
tag provided image and push it to registry
:param image: str or ImageName, image id or name
:param target_image: ImageName, img
:param insecure: bool, a... | [
"def",
"tag_and_push_image",
"(",
"self",
",",
"image",
",",
"target_image",
",",
"insecure",
"=",
"False",
",",
"force",
"=",
"False",
",",
"dockercfg",
"=",
"None",
")",
":",
"logger",
".",
"info",
"(",
"\"tagging and pushing image '%s' as '%s'\"",
",",
"ima... | 49.111111 | 18.888889 |
def _trigger_event(self, event, *args, **kwargs):
"""Invoke an event handler."""
run_async = kwargs.pop('run_async', False)
if event in self.handlers:
if run_async:
return self.start_background_task(self.handlers[event], *args)
else:
try:
... | [
"def",
"_trigger_event",
"(",
"self",
",",
"event",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"run_async",
"=",
"kwargs",
".",
"pop",
"(",
"'run_async'",
",",
"False",
")",
"if",
"event",
"in",
"self",
".",
"handlers",
":",
"if",
"run_asyn... | 41.363636 | 16.272727 |
def mark(self, channel, ts):
""" https://api.slack.com/methods/im.mark
"""
self.params.update({
'channel': channel,
'ts': ts,
})
return FromUrl('https://slack.com/api/im.mark', self._requests)(data=self.params).post() | [
"def",
"mark",
"(",
"self",
",",
"channel",
",",
"ts",
")",
":",
"self",
".",
"params",
".",
"update",
"(",
"{",
"'channel'",
":",
"channel",
",",
"'ts'",
":",
"ts",
",",
"}",
")",
"return",
"FromUrl",
"(",
"'https://slack.com/api/im.mark'",
",",
"self... | 35.375 | 16.125 |
def _seconds_as_string(seconds):
"""
Returns seconds as a human-friendly string, e.g. '1d 4h 47m 41s'
"""
TIME_UNITS = [('s', 60), ('m', 60), ('h', 24), ('d', None)]
unit_strings = []
cur = max(int(seconds), 1)
for suffix, size in TIME_UNITS:
if size is not None:
cur, res... | [
"def",
"_seconds_as_string",
"(",
"seconds",
")",
":",
"TIME_UNITS",
"=",
"[",
"(",
"'s'",
",",
"60",
")",
",",
"(",
"'m'",
",",
"60",
")",
",",
"(",
"'h'",
",",
"24",
")",
",",
"(",
"'d'",
",",
"None",
")",
"]",
"unit_strings",
"=",
"[",
"]",
... | 31.933333 | 13.133333 |
def channels(self):
"""channel count or 0 for unknown"""
# from ProgramConfigElement()
if hasattr(self, "pce_channels"):
return self.pce_channels
conf = getattr(
self, "extensionChannelConfiguration", self.channelConfiguration)
if conf == 1:
... | [
"def",
"channels",
"(",
"self",
")",
":",
"# from ProgramConfigElement()",
"if",
"hasattr",
"(",
"self",
",",
"\"pce_channels\"",
")",
":",
"return",
"self",
".",
"pce_channels",
"conf",
"=",
"getattr",
"(",
"self",
",",
"\"extensionChannelConfiguration\"",
",",
... | 25.608696 | 17.956522 |
def download_data(cdbs_root, verbose=True, dry_run=False):
"""Download CDBS data files to given root directory.
Download is skipped if a data file already exists.
Parameters
----------
cdbs_root : str
Root directory for CDBS data files.
verbose : bool
Print extra information to... | [
"def",
"download_data",
"(",
"cdbs_root",
",",
"verbose",
"=",
"True",
",",
"dry_run",
"=",
"False",
")",
":",
"from",
".",
"config",
"import",
"conf",
"# Avoid potential circular import",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"cdbs_root",
")",... | 28.829268 | 19.231707 |
def DFS_Tree(G):
"""
Return an oriented tree constructed from dfs.
"""
if not G.vertices:
raise GraphInsertError("This graph have no vertices.")
pred = {}
T = digraph.DiGraph()
vertex_data = DFS(G)
for vertex in vertex_data:
pred[vertex] = vertex_data[vertex][0]... | [
"def",
"DFS_Tree",
"(",
"G",
")",
":",
"if",
"not",
"G",
".",
"vertices",
":",
"raise",
"GraphInsertError",
"(",
"\"This graph have no vertices.\"",
")",
"pred",
"=",
"{",
"}",
"T",
"=",
"digraph",
".",
"DiGraph",
"(",
")",
"vertex_data",
"=",
"DFS",
"("... | 29.045455 | 12.136364 |
def run_command_orig(cmd):
""" No idea how th f to get this to work """
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
if process.returncode == 0:
os.killpg(os.getpgid(pro.pid), signal.SIGTERM)
else:
... | [
"def",
"run_command_orig",
"(",
"cmd",
")",
":",
"process",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd",
",",
"shell",
"=",
"True",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
")",
"stdout",
",",
"stder... | 47 | 23.222222 |
def new(cls, user, provider, federated_id):
"""
Create a new login
:param user: AuthUser
:param provider: str - ie: facebook, twitter, ...
:param federated_id: str - an id associated to provider
:return:
"""
if cls.get_user(provider, federated_id):
... | [
"def",
"new",
"(",
"cls",
",",
"user",
",",
"provider",
",",
"federated_id",
")",
":",
"if",
"cls",
".",
"get_user",
"(",
"provider",
",",
"federated_id",
")",
":",
"raise",
"exceptions",
".",
"AuthError",
"(",
"\"Federation already\"",
")",
"return",
"cls... | 35.857143 | 12.714286 |
def _parse_recipients(self, to):
"""Make sure we have a "," separated list of recipients
:param to: Recipient(s)
:type to: (str,
list,
:class:`pyfilemail.Contact`,
:class:`pyfilemail.Group`
)
:rtype: ``str``
... | [
"def",
"_parse_recipients",
"(",
"self",
",",
"to",
")",
":",
"if",
"to",
"is",
"None",
":",
"return",
"None",
"if",
"isinstance",
"(",
"to",
",",
"list",
")",
":",
"recipients",
"=",
"[",
"]",
"for",
"recipient",
"in",
"to",
":",
"if",
"isinstance",... | 26.702703 | 18.972973 |
def goassoc_fieldmap(relationship_type=ACTS_UPSTREAM_OF_OR_WITHIN):
"""
Returns a mapping of canonical monarch fields to amigo-golr.
See: https://github.com/geneontology/amigo/blob/master/metadata/ann-config.yaml
"""
return {
M.SUBJECT: 'bioentity',
M.SUBJECT_CLOSURE: 'bioentity',
... | [
"def",
"goassoc_fieldmap",
"(",
"relationship_type",
"=",
"ACTS_UPSTREAM_OF_OR_WITHIN",
")",
":",
"return",
"{",
"M",
".",
"SUBJECT",
":",
"'bioentity'",
",",
"M",
".",
"SUBJECT_CLOSURE",
":",
"'bioentity'",
",",
"## In the GO AmiGO instance, the type field is not correct... | 42.413793 | 17.862069 |
def bindata(df, delta=1.0, method="average"):
"""
Bin average the index (usually pressure) to a given interval (default
delta = 1).
"""
start = np.floor(df.index[0])
stop = np.ceil(df.index[-1])
new_index = np.arange(start, stop, delta)
binned = pd.cut(df.index, bins=new_index)
if m... | [
"def",
"bindata",
"(",
"df",
",",
"delta",
"=",
"1.0",
",",
"method",
"=",
"\"average\"",
")",
":",
"start",
"=",
"np",
".",
"floor",
"(",
"df",
".",
"index",
"[",
"0",
"]",
")",
"stop",
"=",
"np",
".",
"ceil",
"(",
"df",
".",
"index",
"[",
"... | 31.545455 | 16.363636 |
def recall(ntp, nfn):
'''
This calculates recall.
https://en.wikipedia.org/wiki/Precision_and_recall
Parameters
----------
ntp : int
The number of true positives.
nfn : int
The number of false negatives.
Returns
-------
float
The precision calculated... | [
"def",
"recall",
"(",
"ntp",
",",
"nfn",
")",
":",
"if",
"(",
"ntp",
"+",
"nfn",
")",
">",
"0",
":",
"return",
"ntp",
"/",
"(",
"ntp",
"+",
"nfn",
")",
"else",
":",
"return",
"np",
".",
"nan"
] | 15.259259 | 27.037037 |
def add(self, resource):
"""Add a resource to the context"""
if isinstance(resource, Resource):
if isinstance(resource, Secret) and \
resource.mount != 'cubbyhole':
ensure_backend(resource,
SecretBackend,
... | [
"def",
"add",
"(",
"self",
",",
"resource",
")",
":",
"if",
"isinstance",
"(",
"resource",
",",
"Resource",
")",
":",
"if",
"isinstance",
"(",
"resource",
",",
"Secret",
")",
"and",
"resource",
".",
"mount",
"!=",
"'cubbyhole'",
":",
"ensure_backend",
"(... | 44.545455 | 12.227273 |
def fix_e305(self, result):
"""Add missing 2 blank lines after end of function or class."""
cr = '\n'
# check comment line
offset = result['line'] - 2
while True:
if offset < 0:
break
line = self.source[offset].lstrip()
if len(l... | [
"def",
"fix_e305",
"(",
"self",
",",
"result",
")",
":",
"cr",
"=",
"'\\n'",
"# check comment line",
"offset",
"=",
"result",
"[",
"'line'",
"]",
"-",
"2",
"while",
"True",
":",
"if",
"offset",
"<",
"0",
":",
"break",
"line",
"=",
"self",
".",
"sourc... | 30.5625 | 14 |
def query_recent(num=8, **kwargs):
'''
query recent posts.
'''
order_by_create = kwargs.get('order_by_create', False)
kind = kwargs.get('kind', None)
if order_by_create:
if kind:
recent_recs = TabPost.select().where(
(TabPos... | [
"def",
"query_recent",
"(",
"num",
"=",
"8",
",",
"*",
"*",
"kwargs",
")",
":",
"order_by_create",
"=",
"kwargs",
".",
"get",
"(",
"'order_by_create'",
",",
"False",
")",
"kind",
"=",
"kwargs",
".",
"get",
"(",
"'kind'",
",",
"None",
")",
"if",
"orde... | 34.727273 | 14.242424 |
def upsert_and_fetch(coll, doc, **kwargs):
"""
Fetch exactly one matching document or upsert
the document if not found, returning the matching
or upserted document.
See https://jira.mongodb.org/browse/SERVER-28434
describing the condition where MongoDB is uninterested in
providing an upsert... | [
"def",
"upsert_and_fetch",
"(",
"coll",
",",
"doc",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"coll",
".",
"find_one_and_update",
"(",
"doc",
",",
"{",
"\"$setOnInsert\"",
":",
"doc",
"}",
",",
"upsert",
"=",
"True",
",",
"return_document",
"=",
"pymo... | 30.653846 | 16.269231 |
def setCompleteRedYellowGreenDefinition(self, tlsID, tls):
"""setCompleteRedYellowGreenDefinition(string, ) -> None
.
"""
length = 1 + 4 + 1 + 4 + \
len(tls._subID) + 1 + 4 + 1 + 4 + 1 + 4 + 1 + 4 # tls parameter
itemNo = 1 + 1 + 1 + 1 + 1
for p in tls._phas... | [
"def",
"setCompleteRedYellowGreenDefinition",
"(",
"self",
",",
"tlsID",
",",
"tls",
")",
":",
"length",
"=",
"1",
"+",
"4",
"+",
"1",
"+",
"4",
"+",
"len",
"(",
"tls",
".",
"_subID",
")",
"+",
"1",
"+",
"4",
"+",
"1",
"+",
"4",
"+",
"1",
"+",
... | 47.9375 | 23.28125 |
def query_flag(ifo, name, start_time, end_time,
source='any', server="segments.ligo.org",
veto_definer=None, cache=False):
"""Return the times where the flag is active
Parameters
----------
ifo: string
The interferometer to query (H1, L1).
name: string
... | [
"def",
"query_flag",
"(",
"ifo",
",",
"name",
",",
"start_time",
",",
"end_time",
",",
"source",
"=",
"'any'",
",",
"server",
"=",
"\"segments.ligo.org\"",
",",
"veto_definer",
"=",
"None",
",",
"cache",
"=",
"False",
")",
":",
"info",
"=",
"name",
".",
... | 38.055118 | 20.582677 |
def update_records(self, headers, zoneID, updateRecords):
"""Update DNS records."""
IP = requests.get(self.GET_EXT_IP_URL).text
message = True
errorsRecords = []
sucessRecords = []
for record in updateRecords:
updateEndpoint = '/' + zoneID + '/dns_records/' + ... | [
"def",
"update_records",
"(",
"self",
",",
"headers",
",",
"zoneID",
",",
"updateRecords",
")",
":",
"IP",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"GET_EXT_IP_URL",
")",
".",
"text",
"message",
"=",
"True",
"errorsRecords",
"=",
"[",
"]",
"sucessR... | 41.366667 | 13.266667 |
def get_pull_request_thread(self, repository_id, pull_request_id, thread_id, project=None, iteration=None, base_iteration=None):
"""GetPullRequestThread.
[Preview API] Retrieve a thread in a pull request.
:param str repository_id: The repository ID of the pull request's target branch.
:p... | [
"def",
"get_pull_request_thread",
"(",
"self",
",",
"repository_id",
",",
"pull_request_id",
",",
"thread_id",
",",
"project",
"=",
"None",
",",
"iteration",
"=",
"None",
",",
"base_iteration",
"=",
"None",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"pro... | 67 | 31.741935 |
def _check_superbox_for_top_levels(self, boxes):
"""Several boxes can only occur at the top level."""
# We are only looking at the boxes contained in a superbox, so if any
# of the blacklisted boxes show up here, it's an error.
TOP_LEVEL_ONLY_BOXES = set(['dtbl'])
box_ids = set([... | [
"def",
"_check_superbox_for_top_levels",
"(",
"self",
",",
"boxes",
")",
":",
"# We are only looking at the boxes contained in a superbox, so if any",
"# of the blacklisted boxes show up here, it's an error.",
"TOP_LEVEL_ONLY_BOXES",
"=",
"set",
"(",
"[",
"'dtbl'",
"]",
")",
"box... | 49.066667 | 16.666667 |
def accel_increase_transparency(self, *args):
"""Callback to increase transparency.
"""
transparency = self.settings.styleBackground.get_int('transparency')
if int(transparency) - 2 > 0:
self.settings.styleBackground.set_int('transparency', int(transparency) - 2)
retu... | [
"def",
"accel_increase_transparency",
"(",
"self",
",",
"*",
"args",
")",
":",
"transparency",
"=",
"self",
".",
"settings",
".",
"styleBackground",
".",
"get_int",
"(",
"'transparency'",
")",
"if",
"int",
"(",
"transparency",
")",
"-",
"2",
">",
"0",
":",... | 45.857143 | 16.142857 |
def start_at(self, start_at):
"""
Sets the start_at of this Shift.
RFC 3339; shifted to location timezone + offset. Precision up to the minute is respected; seconds are truncated.
:param start_at: The start_at of this Shift.
:type: str
"""
if start_at is None:
... | [
"def",
"start_at",
"(",
"self",
",",
"start_at",
")",
":",
"if",
"start_at",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Invalid value for `start_at`, must not be `None`\"",
")",
"if",
"len",
"(",
"start_at",
")",
"<",
"1",
":",
"raise",
"ValueError",
"(... | 37.066667 | 25.333333 |
def process_phosphorylation_statements(self):
"""Looks for Phosphorylation events in the graph and extracts them into
INDRA statements.
In particular, looks for a Positive_regulation event node with a child
Phosphorylation event node.
If Positive_regulation has an outgoing Caus... | [
"def",
"process_phosphorylation_statements",
"(",
"self",
")",
":",
"G",
"=",
"self",
".",
"G",
"statements",
"=",
"[",
"]",
"pwcs",
"=",
"self",
".",
"find_event_parent_with_event_child",
"(",
"'Positive_regulation'",
",",
"'Phosphorylation'",
")",
"for",
"pair",... | 43.066667 | 23.511111 |
def from_sec(class_, sec):
"""
Create a key from an sec bytestream (which is an encoding of a public pair).
"""
public_pair = sec_to_public_pair(sec, class_._generator)
return class_(public_pair=public_pair, is_compressed=is_sec_compressed(sec)) | [
"def",
"from_sec",
"(",
"class_",
",",
"sec",
")",
":",
"public_pair",
"=",
"sec_to_public_pair",
"(",
"sec",
",",
"class_",
".",
"_generator",
")",
"return",
"class_",
"(",
"public_pair",
"=",
"public_pair",
",",
"is_compressed",
"=",
"is_sec_compressed",
"("... | 46.666667 | 21 |
def num_neighbors(self, pores, mode='or', flatten=False):
r"""
Returns the number of neigbhoring pores for each given input pore
Parameters
----------
pores : array_like
Pores whose neighbors are to be counted
flatten : boolean (optional)
If ``Fa... | [
"def",
"num_neighbors",
"(",
"self",
",",
"pores",
",",
"mode",
"=",
"'or'",
",",
"flatten",
"=",
"False",
")",
":",
"pores",
"=",
"self",
".",
"_parse_indices",
"(",
"pores",
")",
"# Count number of neighbors",
"num",
"=",
"self",
".",
"find_neighbor_pores"... | 37.826667 | 25.893333 |
def wateryear(self):
"""The actual hydrological year according to the selected
reference month.
The reference mont reference |Date.refmonth| defaults to November:
>>> october = Date('1996.10.01')
>>> november = Date('1996.11.01')
>>> october.wateryear
1996
... | [
"def",
"wateryear",
"(",
"self",
")",
":",
"if",
"self",
".",
"month",
"<",
"self",
".",
"_firstmonth_wateryear",
":",
"return",
"self",
".",
"year",
"return",
"self",
".",
"year",
"+",
"1"
] | 26.724138 | 18.448276 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.