text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def make_copy(klass, inst, func=None, argv=None, extra_argv=None, copy_sig=True):
"""Makes a new instance of the partial application wrapper based on
an existing instance, optionally overriding the original's wrapped
function and/or saved arguments.
:param inst: The partial instance we'... | [
"def",
"make_copy",
"(",
"klass",
",",
"inst",
",",
"func",
"=",
"None",
",",
"argv",
"=",
"None",
",",
"extra_argv",
"=",
"None",
",",
"copy_sig",
"=",
"True",
")",
":",
"dest",
"=",
"klass",
"(",
"func",
"or",
"inst",
".",
"func",
")",
"dest",
... | 39.545455 | 21.181818 |
def get_line_relative_to_node(self, target_node: ast.AST, offset: int) -> str:
"""
Raises:
IndexError: when ``offset`` takes the request out of bounds of this
Function's lines.
"""
return self.lines[target_node.lineno - self.node.lineno + offset] | [
"def",
"get_line_relative_to_node",
"(",
"self",
",",
"target_node",
":",
"ast",
".",
"AST",
",",
"offset",
":",
"int",
")",
"->",
"str",
":",
"return",
"self",
".",
"lines",
"[",
"target_node",
".",
"lineno",
"-",
"self",
".",
"node",
".",
"lineno",
"... | 42.857143 | 20.285714 |
def sendFuture(self, future):
"""Send a Future to be executed remotely."""
future = copy.copy(future)
future.greenlet = None
future.children = {}
try:
if shared.getConst(hash(future.callable), timeout=0):
# Enforce name reference passing if already sh... | [
"def",
"sendFuture",
"(",
"self",
",",
"future",
")",
":",
"future",
"=",
"copy",
".",
"copy",
"(",
"future",
")",
"future",
".",
"greenlet",
"=",
"None",
"future",
".",
"children",
"=",
"{",
"}",
"try",
":",
"if",
"shared",
".",
"getConst",
"(",
"... | 42.92 | 18.2 |
def LayerTree_loadSnapshot(self, tiles):
"""
Function path: LayerTree.loadSnapshot
Domain: LayerTree
Method name: loadSnapshot
Parameters:
Required arguments:
'tiles' (type: array) -> An array of tiles composing the snapshot.
Returns:
'snapshotId' (type: SnapshotId) -> The id of the snap... | [
"def",
"LayerTree_loadSnapshot",
"(",
"self",
",",
"tiles",
")",
":",
"assert",
"isinstance",
"(",
"tiles",
",",
"(",
"list",
",",
"tuple",
")",
")",
",",
"\"Argument 'tiles' must be of type '['list', 'tuple']'. Received type: '%s'\"",
"%",
"type",
"(",
"tiles",
")"... | 31.05 | 20.65 |
def RANSAC(model_func, eval_func, data, num_points, num_iter, threshold, recalculate=False):
"""Apply RANSAC.
This RANSAC implementation will choose the best model based on the number of points in the consensus set. At evaluation time the model is created using num_points points. Then it will be recalculated u... | [
"def",
"RANSAC",
"(",
"model_func",
",",
"eval_func",
",",
"data",
",",
"num_points",
",",
"num_iter",
",",
"threshold",
",",
"recalculate",
"=",
"False",
")",
":",
"M",
"=",
"None",
"max_consensus",
"=",
"0",
"all_idx",
"=",
"list",
"(",
"range",
"(",
... | 43.081081 | 27.810811 |
def as_dict(self):
"""
turns attribute filter object into python dictionary
"""
output_dictionary = dict()
for attribute_name, type_instance in inspect.getmembers(self):
if attribute_name.startswith('__') or inspect.ismethod(type_instance):
continue... | [
"def",
"as_dict",
"(",
"self",
")",
":",
"output_dictionary",
"=",
"dict",
"(",
")",
"for",
"attribute_name",
",",
"type_instance",
"in",
"inspect",
".",
"getmembers",
"(",
"self",
")",
":",
"if",
"attribute_name",
".",
"startswith",
"(",
"'__'",
")",
"or"... | 32.666667 | 23.888889 |
def parse_directives(lexer: Lexer, is_const: bool) -> List[DirectiveNode]:
"""Directives[Const]: Directive[?Const]+"""
directives: List[DirectiveNode] = []
append = directives.append
while peek(lexer, TokenKind.AT):
append(parse_directive(lexer, is_const))
return directives | [
"def",
"parse_directives",
"(",
"lexer",
":",
"Lexer",
",",
"is_const",
":",
"bool",
")",
"->",
"List",
"[",
"DirectiveNode",
"]",
":",
"directives",
":",
"List",
"[",
"DirectiveNode",
"]",
"=",
"[",
"]",
"append",
"=",
"directives",
".",
"append",
"whil... | 42.285714 | 10.714286 |
def read_df_or_series_from_csv(desired_type: Type[pd.DataFrame], file_path: str, encoding: str,
logger: Logger, **kwargs) -> pd.DataFrame:
"""
Helper method to read a dataframe from a csv file. By default this is well suited for a dataframe with
headers in the first row, for e... | [
"def",
"read_df_or_series_from_csv",
"(",
"desired_type",
":",
"Type",
"[",
"pd",
".",
"DataFrame",
"]",
",",
"file_path",
":",
"str",
",",
"encoding",
":",
"str",
",",
"logger",
":",
"Logger",
",",
"*",
"*",
"kwargs",
")",
"->",
"pd",
".",
"DataFrame",
... | 52.060606 | 34.848485 |
def project_new_folder(object_id, input_params={}, always_retry=True, **kwargs):
"""
Invokes the /project-xxxx/newFolder API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Folders-and-Deletion#API-method%3A-%2Fclass-xxxx%2FnewFolder
"""
return DXHTTPRequest('/%s/newF... | [
"def",
"project_new_folder",
"(",
"object_id",
",",
"input_params",
"=",
"{",
"}",
",",
"always_retry",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"DXHTTPRequest",
"(",
"'/%s/newFolder'",
"%",
"object_id",
",",
"input_params",
",",
"always_retry... | 54.857143 | 35.714286 |
def _find_install_targets(name=None,
version=None,
pkgs=None,
sources=None,
skip_suggestions=False,
pkg_verify=False,
normalize=True,
igno... | [
"def",
"_find_install_targets",
"(",
"name",
"=",
"None",
",",
"version",
"=",
"None",
",",
"pkgs",
"=",
"None",
",",
"sources",
"=",
"None",
",",
"skip_suggestions",
"=",
"False",
",",
"pkg_verify",
"=",
"False",
",",
"normalize",
"=",
"True",
",",
"ign... | 41.385965 | 18.836257 |
def main():
'''main is the entrypoint to the sregistry client. The flow works to first
to determine the subparser in use based on the command. The command then
imports the correct main (files imported in this folder) associated with
the action of choice. When the client is imported, it is actually impor... | [
"def",
"main",
"(",
")",
":",
"from",
"sregistry",
".",
"main",
"import",
"Client",
"as",
"cli",
"parser",
"=",
"get_parser",
"(",
")",
"subparsers",
"=",
"get_subparsers",
"(",
"parser",
")",
"def",
"help",
"(",
"return_code",
"=",
"0",
")",
":",
"'''... | 37.012987 | 21.584416 |
def dump(self, filename):
"""
Dumps statistics.
@param filename: filename where stats will be dumped, filename is
created and must not exist prior to this call.
@type filename: string
"""
flags = os.O_WRONLY|os.O_CREAT|os.O_NOFOLLOW|os.O_EXCL
... | [
"def",
"dump",
"(",
"self",
",",
"filename",
")",
":",
"flags",
"=",
"os",
".",
"O_WRONLY",
"|",
"os",
".",
"O_CREAT",
"|",
"os",
".",
"O_NOFOLLOW",
"|",
"os",
".",
"O_EXCL",
"fd",
"=",
"os",
".",
"open",
"(",
"filename",
",",
"flags",
",",
"0600... | 33.5 | 16.5 |
def get_link_density(node, node_text=None):
"""
Computes the ratio for text in given node and text in links
contained in the node. It is computed from number of
characters in the texts.
:parameter Element node:
HTML element in which links density is computed.
:parameter string node_text... | [
"def",
"get_link_density",
"(",
"node",
",",
"node_text",
"=",
"None",
")",
":",
"if",
"node_text",
"is",
"None",
":",
"node_text",
"=",
"node",
".",
"text_content",
"(",
")",
"node_text",
"=",
"normalize_whitespace",
"(",
"node_text",
".",
"strip",
"(",
"... | 36.724138 | 18.172414 |
def get_links(html, outformat):
"""Return a list of reference links from the html.
Parameters
----------
html : str
outformat : int
the output format of the citations
Returns
-------
List[str]
the links to the references
"""
if outformat == FORMAT_BIBTEX:
... | [
"def",
"get_links",
"(",
"html",
",",
"outformat",
")",
":",
"if",
"outformat",
"==",
"FORMAT_BIBTEX",
":",
"refre",
"=",
"re",
".",
"compile",
"(",
"r'<a href=\"https://scholar.googleusercontent.com(/scholar\\.bib\\?[^\"]*)'",
")",
"elif",
"outformat",
"==",
"FORMAT_... | 36.857143 | 24.25 |
def minimac(args):
"""
%prog batchminimac input.txt
Use MINIMAC3 to impute vcf on all chromosomes.
"""
p = OptionParser(minimac.__doc__)
p.set_home("shapeit")
p.set_home("minimac")
p.set_outfile()
p.set_chr()
p.set_ref()
p.set_cpus()
opts, args = p.parse_args(args)
... | [
"def",
"minimac",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"minimac",
".",
"__doc__",
")",
"p",
".",
"set_home",
"(",
"\"shapeit\"",
")",
"p",
".",
"set_home",
"(",
"\"minimac\"",
")",
"p",
".",
"set_outfile",
"(",
")",
"p",
".",
"set_ch... | 33.430556 | 19.125 |
def hook_key(key, callback, suppress=False):
"""
Hooks key up and key down events for a single key. Returns the event handler
created. To remove a hooked key use `unhook_key(key)` or
`unhook_key(handler)`.
Note: this function shares state with hotkeys, so `clear_all_hotkeys`
affects it aswell.
... | [
"def",
"hook_key",
"(",
"key",
",",
"callback",
",",
"suppress",
"=",
"False",
")",
":",
"_listener",
".",
"start_if_necessary",
"(",
")",
"store",
"=",
"_listener",
".",
"blocking_keys",
"if",
"suppress",
"else",
"_listener",
".",
"nonblocking_keys",
"scan_co... | 34.826087 | 16.565217 |
def WriteEventBody(self, event):
"""Writes the body of an event to the output.
Args:
event (EventObject): event.
"""
output_string = NativePythonFormatterHelper.GetFormattedEventObject(event)
self._output_writer.Write(output_string) | [
"def",
"WriteEventBody",
"(",
"self",
",",
"event",
")",
":",
"output_string",
"=",
"NativePythonFormatterHelper",
".",
"GetFormattedEventObject",
"(",
"event",
")",
"self",
".",
"_output_writer",
".",
"Write",
"(",
"output_string",
")"
] | 31.5 | 16 |
def _cleanly_slice_encoded_string(encoded_string, length_limit):
"""
Takes a byte string (a UTF-8 encoded string) and splits it into two pieces such that the first slice is no
longer than argument `length_limit`, then returns a tuple containing the first slice and remainder of the
byte s... | [
"def",
"_cleanly_slice_encoded_string",
"(",
"encoded_string",
",",
"length_limit",
")",
":",
"sliced",
",",
"remaining",
"=",
"encoded_string",
"[",
":",
"length_limit",
"]",
",",
"encoded_string",
"[",
"length_limit",
":",
"]",
"try",
":",
"sliced",
".",
"deco... | 55.666667 | 37.25 |
def validate_ldap(self):
logging.debug('Validating LDAPLoginForm against LDAP')
'Validate the username/password data against ldap directory'
ldap_mgr = current_app.ldap3_login_manager
username = self.username.data
password = self.password.data
result = ldap_mgr.authentic... | [
"def",
"validate_ldap",
"(",
"self",
")",
":",
"logging",
".",
"debug",
"(",
"'Validating LDAPLoginForm against LDAP'",
")",
"ldap_mgr",
"=",
"current_app",
".",
"ldap3_login_manager",
"username",
"=",
"self",
".",
"username",
".",
"data",
"password",
"=",
"self",... | 35.347826 | 19 |
def initialize_concept_scheme(rdf, cs, label, language, set_modified):
"""Initialize a concept scheme: Optionally add a label if the concept
scheme doesn't have a label, and optionally add a dct:modified
timestamp."""
# check whether the concept scheme is unlabeled, and label it if possible
labels ... | [
"def",
"initialize_concept_scheme",
"(",
"rdf",
",",
"cs",
",",
"label",
",",
"language",
",",
"set_modified",
")",
":",
"# check whether the concept scheme is unlabeled, and label it if possible",
"labels",
"=",
"list",
"(",
"rdf",
".",
"objects",
"(",
"cs",
",",
"... | 44.478261 | 22.043478 |
def get_last_modified_unix_sec():
"""Get last modified unix time for a given file"""
path = request.args.get("path")
if path and os.path.isfile(path):
try:
last_modified = os.path.getmtime(path)
return jsonify({"path": path, "last_modified_unix_sec": last_modified})
... | [
"def",
"get_last_modified_unix_sec",
"(",
")",
":",
"path",
"=",
"request",
".",
"args",
".",
"get",
"(",
"\"path\"",
")",
"if",
"path",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"try",
":",
"last_modified",
"=",
"os",
".",
"pat... | 38 | 22.153846 |
def _from_p12_keyfile_contents(cls, service_account_email,
private_key_pkcs12,
private_key_password=None, scopes='',
token_uri=oauth2client.GOOGLE_TOKEN_URI,
revoke_uri=oauth2clien... | [
"def",
"_from_p12_keyfile_contents",
"(",
"cls",
",",
"service_account_email",
",",
"private_key_pkcs12",
",",
"private_key_password",
"=",
"None",
",",
"scopes",
"=",
"''",
",",
"token_uri",
"=",
"oauth2client",
".",
"GOOGLE_TOKEN_URI",
",",
"revoke_uri",
"=",
"oau... | 50.731707 | 23.463415 |
def name(self):
"""Array name following h5py convention."""
if self.path:
# follow h5py convention: add leading slash
name = self.path
if name[0] != '/':
name = '/' + name
return name
return None | [
"def",
"name",
"(",
"self",
")",
":",
"if",
"self",
".",
"path",
":",
"# follow h5py convention: add leading slash",
"name",
"=",
"self",
".",
"path",
"if",
"name",
"[",
"0",
"]",
"!=",
"'/'",
":",
"name",
"=",
"'/'",
"+",
"name",
"return",
"name",
"re... | 30.555556 | 14 |
def _set_ldp_params(self, v, load=False):
"""
Setter method for ldp_params, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/mpls_interface/ldp_params (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_ldp_params is considered as a private
... | [
"def",
"_set_ldp_params",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"bas... | 87.909091 | 42 |
def upd_doc(self, doc, index_update=True, label_guesser_update=True):
"""
Update a document in the index
"""
if not self.index_writer and index_update:
self.index_writer = self.index.writer()
if not self.label_guesser_updater and label_guesser_update:
self... | [
"def",
"upd_doc",
"(",
"self",
",",
"doc",
",",
"index_update",
"=",
"True",
",",
"label_guesser_update",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"index_writer",
"and",
"index_update",
":",
"self",
".",
"index_writer",
"=",
"self",
".",
"index",
... | 45.538462 | 14 |
def set(self, level=None):
"""
Set the default log level
If the level is not specified environment variable DEBUG is used
with the following meaning::
DEBUG=0 ... LOG_WARN (default)
DEBUG=1 ... LOG_INFO
DEBUG=2 ... LOG_DEBUG
DEBUG=3 ... L... | [
"def",
"set",
"(",
"self",
",",
"level",
"=",
"None",
")",
":",
"# If level specified, use given",
"if",
"level",
"is",
"not",
"None",
":",
"Logging",
".",
"_level",
"=",
"level",
"# Otherwise attempt to detect from the environment",
"else",
":",
"try",
":",
"Lo... | 33.25 | 13.083333 |
def visual_search(
self, accept_language=None, content_type=None, user_agent=None, client_id=None, client_ip=None, location=None, market=None, safe_search=None, set_lang=None, knowledge_request=None, image=None, custom_headers=None, raw=False, **operation_config):
"""Visual Search API lets you disco... | [
"def",
"visual_search",
"(",
"self",
",",
"accept_language",
"=",
"None",
",",
"content_type",
"=",
"None",
",",
"user_agent",
"=",
"None",
",",
"client_id",
"=",
"None",
",",
"client_ip",
"=",
"None",
",",
"location",
"=",
"None",
",",
"market",
"=",
"N... | 65.407407 | 33.011111 |
def create(self, pools):
"""
Method to create pool's
:param pools: List containing pool's desired to be created on database
:return: None
"""
data = {'server_pools': pools}
return super(ApiPool, self).post('api/v3/pool/', data) | [
"def",
"create",
"(",
"self",
",",
"pools",
")",
":",
"data",
"=",
"{",
"'server_pools'",
":",
"pools",
"}",
"return",
"super",
"(",
"ApiPool",
",",
"self",
")",
".",
"post",
"(",
"'api/v3/pool/'",
",",
"data",
")"
] | 27.6 | 18.6 |
def _log(message):
"""
Logs a message.
:param str message: The log message.
:rtype: None
"""
# @todo Replace with log package.
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + ' ' + str(message), flush=True) | [
"def",
"_log",
"(",
"message",
")",
":",
"# @todo Replace with log package.",
"print",
"(",
"time",
".",
"strftime",
"(",
"'%Y-%m-%d %H:%M:%S'",
",",
"time",
".",
"localtime",
"(",
")",
")",
"+",
"' '",
"+",
"str",
"(",
"message",
")",
",",
"flush",
"=",
... | 26.9 | 20.5 |
def allow_unregister(self, plugin_override=True):
""" Returns True if students can unregister from course """
vals = self._hook_manager.call_hook('course_allow_unregister', course=self, default=self._allow_unregister)
return vals[0] if len(vals) and plugin_override else self._allow_unregister | [
"def",
"allow_unregister",
"(",
"self",
",",
"plugin_override",
"=",
"True",
")",
":",
"vals",
"=",
"self",
".",
"_hook_manager",
".",
"call_hook",
"(",
"'course_allow_unregister'",
",",
"course",
"=",
"self",
",",
"default",
"=",
"self",
".",
"_allow_unregist... | 78.5 | 31.75 |
def from_str(cls, s):
"""Construct an import object from a string."""
ast_obj = ast.parse(s).body[0]
if not isinstance(ast_obj, cls._expected_ast_type):
raise AssertionError(
'Expected ast of type {!r} but got {!r}'.format(
cls._expected_ast_type,
... | [
"def",
"from_str",
"(",
"cls",
",",
"s",
")",
":",
"ast_obj",
"=",
"ast",
".",
"parse",
"(",
"s",
")",
".",
"body",
"[",
"0",
"]",
"if",
"not",
"isinstance",
"(",
"ast_obj",
",",
"cls",
".",
"_expected_ast_type",
")",
":",
"raise",
"AssertionError",
... | 36.090909 | 13.636364 |
def repo(
state, host, source, target,
branch='master', pull=True, rebase=False,
user=None, group=None, use_ssh_user=False, ssh_keyscan=False,
):
'''
Clone/pull git repositories.
+ source: the git source URL
+ target: target directory to clone to
+ branch: branch to pull/checkout
+ ... | [
"def",
"repo",
"(",
"state",
",",
"host",
",",
"source",
",",
"target",
",",
"branch",
"=",
"'master'",
",",
"pull",
"=",
"True",
",",
"rebase",
"=",
"False",
",",
"user",
"=",
"None",
",",
"group",
"=",
"None",
",",
"use_ssh_user",
"=",
"False",
"... | 31.575472 | 22.330189 |
def luhn_checksum(number, chars=DIGITS):
'''
Calculates the Luhn checksum for `number`
:param number: string or int
:param chars: string
>>> luhn_checksum(1234)
4
'''
length = len(chars)
number = [chars.index(n) for n in reversed(str(number))]
return (
sum(number[::2])... | [
"def",
"luhn_checksum",
"(",
"number",
",",
"chars",
"=",
"DIGITS",
")",
":",
"length",
"=",
"len",
"(",
"chars",
")",
"number",
"=",
"[",
"chars",
".",
"index",
"(",
"n",
")",
"for",
"n",
"in",
"reversed",
"(",
"str",
"(",
"number",
")",
")",
"]... | 22.529412 | 22.882353 |
def attribute_iterator(self, mapped_class=None, key=None):
"""
Returns an iterator over all mapped attributes for the given mapped
class and attribute key. See :method:`get_attribute_map` for details.
"""
for attr in self._attribute_iterator(mapped_class, key):
yield ... | [
"def",
"attribute_iterator",
"(",
"self",
",",
"mapped_class",
"=",
"None",
",",
"key",
"=",
"None",
")",
":",
"for",
"attr",
"in",
"self",
".",
"_attribute_iterator",
"(",
"mapped_class",
",",
"key",
")",
":",
"yield",
"attr"
] | 45.428571 | 18.857143 |
def get_input_grads(self, merge_multi_context=True):
"""Get the gradients with respect to the inputs of the module.
Parameters
----------
merge_multi_context : bool
Defaults to ``True``. In the case when data-parallelism is used, the outputs
will be collected fro... | [
"def",
"get_input_grads",
"(",
"self",
",",
"merge_multi_context",
"=",
"True",
")",
":",
"assert",
"self",
".",
"inputs_need_grad",
"if",
"merge_multi_context",
":",
"return",
"_merge_multi_context",
"(",
"self",
".",
"input_grad_arrays",
",",
"self",
".",
"data_... | 43.047619 | 24.333333 |
def delete_documents(self):
"""Deletes all the documents using the pk associated to them.
"""
pk = str(self._primary_key)
for doc in self._whoosh.searcher().documents():
if pk in doc:
doc_pk = str(doc[pk])
self._whoosh.delete_by_term(pk, doc_pk) | [
"def",
"delete_documents",
"(",
"self",
")",
":",
"pk",
"=",
"str",
"(",
"self",
".",
"_primary_key",
")",
"for",
"doc",
"in",
"self",
".",
"_whoosh",
".",
"searcher",
"(",
")",
".",
"documents",
"(",
")",
":",
"if",
"pk",
"in",
"doc",
":",
"doc_pk... | 34.75 | 9 |
def _insert(self, name, value, timestamp, intervals, **kwargs):
'''
Insert the value.
'''
if 'pipeline' in kwargs:
pipe = kwargs.get('pipeline')
else:
pipe = self._client.pipeline(transaction=False)
for interval,config in self._intervals.iteritems():
timestamps = self._normali... | [
"def",
"_insert",
"(",
"self",
",",
"name",
",",
"value",
",",
"timestamp",
",",
"intervals",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'pipeline'",
"in",
"kwargs",
":",
"pipe",
"=",
"kwargs",
".",
"get",
"(",
"'pipeline'",
")",
"else",
":",
"pipe",
... | 32.352941 | 21.764706 |
def _get_to_one_relationship_value(self, obj, column):
"""
Compute datas produced for a many to one relationship
:param obj obj: The instance we manage
:param dict column: The column description dictionnary
:returns: The associated value
"""
related_key = column.... | [
"def",
"_get_to_one_relationship_value",
"(",
"self",
",",
"obj",
",",
"column",
")",
":",
"related_key",
"=",
"column",
".",
"get",
"(",
"'related_key'",
",",
"None",
")",
"related",
"=",
"getattr",
"(",
"obj",
",",
"column",
"[",
"'__col__'",
"]",
".",
... | 34.75 | 15.15 |
def add_rec_new(self, k, val):
"""Recursively add a new value and its children to me, and assign a
variable to it.
Args:
k (str): The name of the variable to assign.
val (LispVal): The value to be added and assigned.
Returns:
LispVal: The added value... | [
"def",
"add_rec_new",
"(",
"self",
",",
"k",
",",
"val",
")",
":",
"self",
".",
"rec_new",
"(",
"val",
")",
"self",
"[",
"k",
"]",
"=",
"val",
"return",
"val"
] | 27.642857 | 18.214286 |
def _update_param(self):
r"""Update parameters
This method updates the values of the algorthm parameters with the
methods provided
"""
# Update the gamma parameter.
if not isinstance(self._beta_update, type(None)):
self._beta = self._beta_update(self._beta)... | [
"def",
"_update_param",
"(",
"self",
")",
":",
"# Update the gamma parameter.",
"if",
"not",
"isinstance",
"(",
"self",
".",
"_beta_update",
",",
"type",
"(",
"None",
")",
")",
":",
"self",
".",
"_beta",
"=",
"self",
".",
"_beta_update",
"(",
"self",
".",
... | 30.866667 | 20.333333 |
def __last_commit(self):
"""
Retrieve the most recent commit message (with ``svn info``)
Returns:
tuple: (datestr, (revno, user, None, desc))
$ svn info
Path: .
URL: http://python-dlp.googlecode.com/svn/trunk/layercake-python
Repository Root: http://... | [
"def",
"__last_commit",
"(",
"self",
")",
":",
"cmd",
"=",
"[",
"'svn'",
",",
"'info'",
"]",
"op",
"=",
"self",
".",
"sh",
"(",
"cmd",
",",
"shell",
"=",
"False",
")",
"if",
"not",
"op",
":",
"return",
"None",
"author",
",",
"rev",
",",
"datestr"... | 35.321429 | 17.392857 |
def current_url_name(context):
"""
Returns the name of the current URL, namespaced, or False.
Example usage:
{% current_url_name as url_name %}
<a href="#"{% if url_name == 'myapp:home' %} class="active"{% endif %}">Home</a>
"""
url_name = False
if context.request.resolver_ma... | [
"def",
"current_url_name",
"(",
"context",
")",
":",
"url_name",
"=",
"False",
"if",
"context",
".",
"request",
".",
"resolver_match",
":",
"url_name",
"=",
"\"{}:{}\"",
".",
"format",
"(",
"context",
".",
"request",
".",
"resolver_match",
".",
"namespace",
... | 29.888889 | 21.555556 |
def get_video_end_time(video_file):
"""Get video end time in seconds"""
if not os.path.isfile(video_file):
print("Error, video file {} does not exist".format(video_file))
return None
try:
time_string = FFProbe(video_file).video[0].creation_time
try:
creation_time ... | [
"def",
"get_video_end_time",
"(",
"video_file",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"video_file",
")",
":",
"print",
"(",
"\"Error, video file {} does not exist\"",
".",
"format",
"(",
"video_file",
")",
")",
"return",
"None",
"try",
... | 34.3125 | 16.75 |
def set_copyright(self, copyright_):
"""Sets the copyright.
arg: copyright (string): the new copyright
raise: InvalidArgument - ``copyright`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
raise: NullArgument - ``copyright`` is ``null``
*complia... | [
"def",
"set_copyright",
"(",
"self",
",",
"copyright_",
")",
":",
"# Implemented from template for osid.repository.AssetForm.set_title_template",
"self",
".",
"_my_map",
"[",
"'copyright'",
"]",
"=",
"self",
".",
"_get_display_text",
"(",
"copyright_",
",",
"self",
".",... | 46.666667 | 23.916667 |
def getschemas(cls):
"""Get inner schemas by name.
:return: ordered dict by name.
:rtype: OrderedDict
"""
members = getmembers(cls, lambda member: isinstance(member, Schema))
result = OrderedDict()
for name, member in members:
result[name] = member
... | [
"def",
"getschemas",
"(",
"cls",
")",
":",
"members",
"=",
"getmembers",
"(",
"cls",
",",
"lambda",
"member",
":",
"isinstance",
"(",
"member",
",",
"Schema",
")",
")",
"result",
"=",
"OrderedDict",
"(",
")",
"for",
"name",
",",
"member",
"in",
"member... | 23.5 | 19.357143 |
def update_cache(self, data=None):
"""call with new data or set data to self.cache_data and call this
"""
if data:
self.cache_data = data
self.cache_updated = timezone.now()
self.save() | [
"def",
"update_cache",
"(",
"self",
",",
"data",
"=",
"None",
")",
":",
"if",
"data",
":",
"self",
".",
"cache_data",
"=",
"data",
"self",
".",
"cache_updated",
"=",
"timezone",
".",
"now",
"(",
")",
"self",
".",
"save",
"(",
")"
] | 33 | 8.571429 |
def assign(name, value):
'''
Assign a single sysctl parameter for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.assign net.ipv4.ip_forward 1
'''
value = six.text_type(value)
if six.PY3:
tran_tab = name.translate(''.maketrans('./', '/.'))
else:
... | [
"def",
"assign",
"(",
"name",
",",
"value",
")",
":",
"value",
"=",
"six",
".",
"text_type",
"(",
"value",
")",
"if",
"six",
".",
"PY3",
":",
"tran_tab",
"=",
"name",
".",
"translate",
"(",
"''",
".",
"maketrans",
"(",
"'./'",
",",
"'/.'",
")",
"... | 31.933333 | 23.844444 |
def get_all_handlers(self) -> T.Dict[str, T.List[T.Callable]]:
"""Returns a dict with event names as keys and lists of
registered handlers as values."""
events = {}
for event, handlers in self._events.items():
events[event] = list(handlers)
return events | [
"def",
"get_all_handlers",
"(",
"self",
")",
"->",
"T",
".",
"Dict",
"[",
"str",
",",
"T",
".",
"List",
"[",
"T",
".",
"Callable",
"]",
"]",
":",
"events",
"=",
"{",
"}",
"for",
"event",
",",
"handlers",
"in",
"self",
".",
"_events",
".",
"items"... | 37.5 | 14.5 |
def map_axes(dim_vars, reverse_map=False):
"""
axis name -> [dimension names]
dimension name -> [axis_name], length 0 if reverse_map
"""
ret_val = defaultdict(list)
axes = ['X', 'Y', 'Z', 'T']
for k, v in dim_vars.items():
axis = getattr(v, 'axis', '')
if not axis:
... | [
"def",
"map_axes",
"(",
"dim_vars",
",",
"reverse_map",
"=",
"False",
")",
":",
"ret_val",
"=",
"defaultdict",
"(",
"list",
")",
"axes",
"=",
"[",
"'X'",
",",
"'Y'",
",",
"'Z'",
",",
"'T'",
"]",
"for",
"k",
",",
"v",
"in",
"dim_vars",
".",
"items",... | 24.952381 | 13.904762 |
def get_parent_book_ids(self, book_id):
"""Gets the parent ``Ids`` of the given book.
arg: book_id (osid.id.Id): a book ``Id``
return: (osid.id.IdList) - the parent ``Ids`` of the book
raise: NotFound - ``book_id`` is not found
raise: NullArgument - ``book_id`` is ``null``
... | [
"def",
"get_parent_book_ids",
"(",
"self",
",",
"book_id",
")",
":",
"# Implemented from template for",
"# osid.resource.BinHierarchySession.get_parent_bin_ids",
"if",
"self",
".",
"_catalog_session",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_catalog_session",
".... | 47 | 17.588235 |
def ssn(self, min_age=16, max_age=90):
"""
Returns 11 character Estonian personal identity code (isikukood, IK).
Age of person is between 16 and 90 years, based on local computer date.
This function assigns random sex to person.
An Estonian Personal identification code consists ... | [
"def",
"ssn",
"(",
"self",
",",
"min_age",
"=",
"16",
",",
"max_age",
"=",
"90",
")",
":",
"age",
"=",
"datetime",
".",
"timedelta",
"(",
"days",
"=",
"self",
".",
"generator",
".",
"random",
".",
"randrange",
"(",
"min_age",
"*",
"365",
",",
"max_... | 47.033333 | 20.366667 |
def __start(self): # pragma: no cover
"""Starts the real-time engine that captures tasks."""
assert not self.dispatcher_thread
self.dispatcher_thread = threading.Thread(target=self.__run_dispatcher,
name='clearly-dispatcher')
self.disp... | [
"def",
"__start",
"(",
"self",
")",
":",
"# pragma: no cover",
"assert",
"not",
"self",
".",
"dispatcher_thread",
"self",
".",
"dispatcher_thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"self",
".",
"__run_dispatcher",
",",
"name",
"=",
"'clearl... | 42.6 | 17.2 |
def register(**kwargs):
"""Registers a notification_cls.
"""
def _wrapper(notification_cls):
if not issubclass(notification_cls, (Notification,)):
raise RegisterNotificationError(
f"Wrapped class must be a 'Notification' class. "
f"Got '{notification_cls... | [
"def",
"register",
"(",
"*",
"*",
"kwargs",
")",
":",
"def",
"_wrapper",
"(",
"notification_cls",
")",
":",
"if",
"not",
"issubclass",
"(",
"notification_cls",
",",
"(",
"Notification",
",",
")",
")",
":",
"raise",
"RegisterNotificationError",
"(",
"f\"Wrapp... | 30.4 | 19.4 |
def _load_features_from_images(self, images, names=None):
""" Load feature image data from image files.
Args:
images: A list of image filenames.
names: An optional list of strings to use as the feature names. Must
be in the same order as the images.
"""
i... | [
"def",
"_load_features_from_images",
"(",
"self",
",",
"images",
",",
"names",
"=",
"None",
")",
":",
"if",
"names",
"is",
"not",
"None",
"and",
"len",
"(",
"names",
")",
"!=",
"len",
"(",
"images",
")",
":",
"raise",
"Exception",
"(",
"\"Lists of featur... | 46.461538 | 19.846154 |
def get_xy_steps(bbox, h_dim):
r"""Return meshgrid spacing based on bounding box.
bbox: dictionary
Dictionary containing coordinates for corners of study area.
h_dim: integer
Horizontal resolution in meters.
Returns
-------
x_steps, (X, ) ndarray
Number of grids in x di... | [
"def",
"get_xy_steps",
"(",
"bbox",
",",
"h_dim",
")",
":",
"x_range",
",",
"y_range",
"=",
"get_xy_range",
"(",
"bbox",
")",
"x_steps",
"=",
"np",
".",
"ceil",
"(",
"x_range",
"/",
"h_dim",
")",
"y_steps",
"=",
"np",
".",
"ceil",
"(",
"y_range",
"/"... | 24.681818 | 17.090909 |
def install_wic(self, wic_slot_id, wic):
"""
Installs a WIC on this adapter.
:param wic_slot_id: WIC slot ID (integer)
:param wic: WIC instance
"""
self._wics[wic_slot_id] = wic
# Dynamips WICs ports start on a multiple of 16 + port number
# WIC1 port 1... | [
"def",
"install_wic",
"(",
"self",
",",
"wic_slot_id",
",",
"wic",
")",
":",
"self",
".",
"_wics",
"[",
"wic_slot_id",
"]",
"=",
"wic",
"# Dynamips WICs ports start on a multiple of 16 + port number",
"# WIC1 port 1 = 16, WIC1 port 2 = 17",
"# WIC2 port 1 = 32, WIC2 port 2 = ... | 32.777778 | 11 |
def _is_expired(self, key):
"""Check if a key is expired. If so, delete the key."""
if not hasattr(self, '_index'):
return False # haven't initalized yet, so don't bother
try:
timeout = self._index[key]
except KeyError:
if self.timeout:
... | [
"def",
"_is_expired",
"(",
"self",
",",
"key",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_index'",
")",
":",
"return",
"False",
"# haven't initalized yet, so don't bother",
"try",
":",
"timeout",
"=",
"self",
".",
"_index",
"[",
"key",
"]",
"ex... | 37.1875 | 14.375 |
def long2rfc1924(l):
"""Convert a network byte order 128-bit integer to an rfc1924 IPv6
address.
>>> long2rfc1924(ip2long('1080::8:800:200C:417A'))
'4)+k&C#VzJ4br>0wv%Yp'
>>> long2rfc1924(ip2long('::'))
'00000000000000000000'
>>> long2rfc1924(MAX_IP)
'=r54lj&NUUO~Hi%c2ym0'
:param... | [
"def",
"long2rfc1924",
"(",
"l",
")",
":",
"if",
"MAX_IP",
"<",
"l",
"or",
"l",
"<",
"MIN_IP",
":",
"raise",
"TypeError",
"(",
"\"expected int between %d and %d inclusive\"",
"%",
"(",
"MIN_IP",
",",
"MAX_IP",
")",
")",
"o",
"=",
"[",
"]",
"r",
"=",
"l... | 26.035714 | 18.214286 |
def requires_columns(required_cols):
"""Decorator that raises a `MalformedResultsError` if any of
`required_cols` is not present as a column in the matches of the
`Results` object bearing the decorated method.
:param required_cols: names of required columns
:type required_cols: `list` of `str`
... | [
"def",
"requires_columns",
"(",
"required_cols",
")",
":",
"def",
"dec",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"decorated_function",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"actual_cols",
"=",
"list",
"(",
"args",
"[",
... | 38.291667 | 14.583333 |
def parse(file_contents, file_name):
'''
Takes a list of files which are assumed to be jinja2 templates and tries to
parse the contents of the files
Args:
file_contents (str): File contents of a jinja file
Raises:
Exception: An exception is raised if the contents of the file cannot... | [
"def",
"parse",
"(",
"file_contents",
",",
"file_name",
")",
":",
"env",
"=",
"Environment",
"(",
")",
"result",
"=",
"\"\"",
"try",
":",
"env",
".",
"parse",
"(",
"file_contents",
")",
"except",
"Exception",
":",
"_",
",",
"exc_value",
",",
"_",
"=",
... | 26.652174 | 24.304348 |
def _asciify_dict(data):
""" Ascii-fies dict keys and values """
ret = {}
for key, value in data.iteritems():
if isinstance(key, unicode):
key = _remove_accents(key)
key = key.encode('utf-8')
# # note new if
if isinstance(value, unicode):
value... | [
"def",
"_asciify_dict",
"(",
"data",
")",
":",
"ret",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"data",
".",
"iteritems",
"(",
")",
":",
"if",
"isinstance",
"(",
"key",
",",
"unicode",
")",
":",
"key",
"=",
"_remove_accents",
"(",
"key",
")"... | 33.470588 | 7.058824 |
def update_geometry(self):
"""
Updates the Widget geometry.
:return: Method success.
:rtype: bool
"""
self.setGeometry(self.__editor.contentsRect().left(),
self.__editor.contentsRect().top(),
self.get_width(),
... | [
"def",
"update_geometry",
"(",
"self",
")",
":",
"self",
".",
"setGeometry",
"(",
"self",
".",
"__editor",
".",
"contentsRect",
"(",
")",
".",
"left",
"(",
")",
",",
"self",
".",
"__editor",
".",
"contentsRect",
"(",
")",
".",
"top",
"(",
")",
",",
... | 29.307692 | 16.384615 |
def _install_gatk_jar(name, fname, manifest, system_config, toolplus_dir):
"""Install a jar for GATK or associated tools like MuTect.
"""
if not fname.endswith(".jar"):
raise ValueError("--toolplus argument for %s expects a jar file: %s" % (name, fname))
version = get_gatk_jar_version(name, fnam... | [
"def",
"_install_gatk_jar",
"(",
"name",
",",
"fname",
",",
"manifest",
",",
"system_config",
",",
"toolplus_dir",
")",
":",
"if",
"not",
"fname",
".",
"endswith",
"(",
"\".jar\"",
")",
":",
"raise",
"ValueError",
"(",
"\"--toolplus argument for %s expects a jar f... | 57.9 | 20.2 |
def printoptions():
'''print paver options.
Prettified by json.
`long_description` is removed
'''
x = json.dumps(environment.options,
indent=4,
sort_keys=True,
skipkeys=True,
cls=MyEncoder)
print(x) | [
"def",
"printoptions",
"(",
")",
":",
"x",
"=",
"json",
".",
"dumps",
"(",
"environment",
".",
"options",
",",
"indent",
"=",
"4",
",",
"sort_keys",
"=",
"True",
",",
"skipkeys",
"=",
"True",
",",
"cls",
"=",
"MyEncoder",
")",
"print",
"(",
"x",
")... | 24 | 16 |
def _prevent_default_initializer_splitting(self, item, indent_amt):
"""Prevent splitting between a default initializer.
When there is a default initializer, it's best to keep it all on
the same line. It's nicer and more readable, even if it goes
over the maximum allowable line length. T... | [
"def",
"_prevent_default_initializer_splitting",
"(",
"self",
",",
"item",
",",
"indent_amt",
")",
":",
"if",
"unicode",
"(",
"item",
")",
"==",
"'='",
":",
"# This is the assignment in the initializer. Just remove spaces for",
"# now.",
"self",
".",
"_delete_whitespace",... | 39.578947 | 23.210526 |
def get_digest_keys(self):
"""Returns a list of the type choices"""
digest_keys = []
for col in xrange(self.GetNumberCols()):
digest_key = self.GetCellValue(self.has_header, col)
if digest_key == "":
digest_key = self.digest_types.keys()[0]
di... | [
"def",
"get_digest_keys",
"(",
"self",
")",
":",
"digest_keys",
"=",
"[",
"]",
"for",
"col",
"in",
"xrange",
"(",
"self",
".",
"GetNumberCols",
"(",
")",
")",
":",
"digest_key",
"=",
"self",
".",
"GetCellValue",
"(",
"self",
".",
"has_header",
",",
"co... | 33.272727 | 16.545455 |
def page(self, course, error="", post=False):
""" Get all data and display the page """
users = sorted(list(self.user_manager.get_users_info(self.user_manager.get_course_registered_users(course, False)).items()),
key=lambda k: k[1][0] if k[1] is not None else "")
users = ... | [
"def",
"page",
"(",
"self",
",",
"course",
",",
"error",
"=",
"\"\"",
",",
"post",
"=",
"False",
")",
":",
"users",
"=",
"sorted",
"(",
"list",
"(",
"self",
".",
"user_manager",
".",
"get_users_info",
"(",
"self",
".",
"user_manager",
".",
"get_course_... | 61.095238 | 40.666667 |
def get_stp_mst_detail_output_msti_msti_bridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti ... | [
"def",
"get_stp_mst_detail_output_msti_msti_bridge_id",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_stp_mst_detail",
"=",
"ET",
".",
"Element",
"(",
"\"get_stp_mst_detail\"",
")",
"config",
"=... | 44.533333 | 14.733333 |
def expand_template(template, namespace):
""" Expand the given (preparsed) template.
Currently, only Tempita templates are supported.
@param template: The template, in preparsed form, or as a string (which then will be preparsed).
@param namespace: Custom namespace that is added to the pred... | [
"def",
"expand_template",
"(",
"template",
",",
"namespace",
")",
":",
"# Create helper namespace",
"formatters",
"=",
"dict",
"(",
"(",
"name",
"[",
"4",
":",
"]",
",",
"method",
")",
"for",
"name",
",",
"method",
"in",
"globals",
"(",
")",
".",
"items"... | 37.704545 | 20.090909 |
def draw(self):
"""Draws the dragger at the current mouse location.
Should be called in every frame.
"""
if not self.visible:
return
if self.isEnabled:
# Draw the dragger's current appearance to the window.
if self.dragg... | [
"def",
"draw",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"visible",
":",
"return",
"if",
"self",
".",
"isEnabled",
":",
"# Draw the dragger's current appearance to the window.\r",
"if",
"self",
".",
"dragging",
":",
"self",
".",
"window",
".",
"blit",
... | 31.904762 | 19.238095 |
def delete_process_work_item_type_rule(self, process_id, wit_ref_name, rule_id):
"""DeleteProcessWorkItemTypeRule.
[Preview API] Removes a rule from the work item type in the process.
:param str process_id: The ID of the process
:param str wit_ref_name: The reference name of the work ite... | [
"def",
"delete_process_work_item_type_rule",
"(",
"self",
",",
"process_id",
",",
"wit_ref_name",
",",
"rule_id",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"process_id",
"is",
"not",
"None",
":",
"route_values",
"[",
"'processId'",
"]",
"=",
"self",
".",
... | 54.166667 | 19.5 |
def blend(self, other, percent=0.5):
"""blend this color with the other one.
Args:
:other:
the grapefruit.Color to blend with this one.
Returns:
A grapefruit.Color instance which is the result of blending
this color on the other one.
>>> c1 = Color.from_rgb(1, 0.5, 0, 0.2)
... | [
"def",
"blend",
"(",
"self",
",",
"other",
",",
"percent",
"=",
"0.5",
")",
":",
"dest",
"=",
"1.0",
"-",
"percent",
"rgb",
"=",
"tuple",
"(",
"(",
"(",
"u",
"*",
"percent",
")",
"+",
"(",
"v",
"*",
"dest",
")",
"for",
"u",
",",
"v",
"in",
... | 28.318182 | 19.409091 |
def get_variant_genotypes(self, variant):
"""Get the genotypes from a well formed variant instance.
Args:
marker (Variant): A Variant instance.
Returns:
A list of Genotypes instance containing a pointer to the variant as
well as a vector of encoded genotypes... | [
"def",
"get_variant_genotypes",
"(",
"self",
",",
"variant",
")",
":",
"if",
"not",
"self",
".",
"has_index",
":",
"raise",
"NotImplementedError",
"(",
"\"Not implemented when IMPUTE2 file is \"",
"\"not indexed (see genipe)\"",
")",
"# Find the variant in the index",
"try"... | 32.837838 | 22.297297 |
def _server_enable():
"""Checks whether the server should be enabled/disabled and makes the
change accordingly.
"""
prev = None if "enabled" not in db else db["enabled"]
if args["disable"]:
db["enabled"] = False
okay("Disabled the CI server. No pull requests will be processed.")
... | [
"def",
"_server_enable",
"(",
")",
":",
"prev",
"=",
"None",
"if",
"\"enabled\"",
"not",
"in",
"db",
"else",
"db",
"[",
"\"enabled\"",
"]",
"if",
"args",
"[",
"\"disable\"",
"]",
":",
"db",
"[",
"\"enabled\"",
"]",
"=",
"False",
"okay",
"(",
"\"Disable... | 33.25 | 19.125 |
def retrieveVals(self):
"""Retrieve values for graphs."""
lighttpdInfo = LighttpdInfo(self._host, self._port,
self._user, self._password,
self._statuspath, self._ssl)
stats = lighttpdInfo.getServerStats()
if self.hasGraph('... | [
"def",
"retrieveVals",
"(",
"self",
")",
":",
"lighttpdInfo",
"=",
"LighttpdInfo",
"(",
"self",
".",
"_host",
",",
"self",
".",
"_port",
",",
"self",
".",
"_user",
",",
"self",
".",
"_password",
",",
"self",
".",
"_statuspath",
",",
"self",
".",
"_ssl"... | 56.4 | 18.6 |
def _addPort(n: LNode, lp: LPort, intf: Interface,
reverseDirection=False):
"""
add port to LPort for interface
"""
origin = originObjOfPort(intf)
d = intf._direction
d = PortTypeFromDir(d)
if reverseDirection:
d = PortType.opposite(d)
new_lp = LPort(lp, d, lp.side... | [
"def",
"_addPort",
"(",
"n",
":",
"LNode",
",",
"lp",
":",
"LPort",
",",
"intf",
":",
"Interface",
",",
"reverseDirection",
"=",
"False",
")",
":",
"origin",
"=",
"originObjOfPort",
"(",
"intf",
")",
"d",
"=",
"intf",
".",
"_direction",
"d",
"=",
"Po... | 26.4 | 14.32 |
def detect_global_table_updates(record):
"""This will detect DDB Global Table updates that are not relevant to application data updates. These need to be
skipped over as they are pure noise.
:param record:
:return:
"""
# This only affects MODIFY events.
if record['eventName'] == 'MODIFY'... | [
"def",
"detect_global_table_updates",
"(",
"record",
")",
":",
"# This only affects MODIFY events.",
"if",
"record",
"[",
"'eventName'",
"]",
"==",
"'MODIFY'",
":",
"# Need to compare the old and new images to check for GT specific changes only (just pop off the GT fields)",
"old_ima... | 43.117647 | 25.764706 |
def rectangle(cls, vertices, **kwargs):
"""Shortcut for creating a rectangle aligned with the screen axes from only two corners.
Parameters
----------
vertices : array-like
An array containing the ``[x, y]`` positions of two corners.
kwargs
Other keyword ... | [
"def",
"rectangle",
"(",
"cls",
",",
"vertices",
",",
"*",
"*",
"kwargs",
")",
":",
"bottom_left",
",",
"top_right",
"=",
"vertices",
"top_left",
"=",
"[",
"bottom_left",
"[",
"0",
"]",
",",
"top_right",
"[",
"1",
"]",
"]",
"bottom_right",
"=",
"[",
... | 39.466667 | 19.266667 |
def list():
"""
List available format.
"""
choice_len = max(map(len, _input_choices.keys()))
tmpl = " {:<%d}: {}\n" % choice_len
text = ''.join(map(
lambda k_v: tmpl.format(k_v[0], k_v[1][0]), six.iteritems(_input_choices)))
click.echo(text) | [
"def",
"list",
"(",
")",
":",
"choice_len",
"=",
"max",
"(",
"map",
"(",
"len",
",",
"_input_choices",
".",
"keys",
"(",
")",
")",
")",
"tmpl",
"=",
"\" {:<%d}: {}\\n\"",
"%",
"choice_len",
"text",
"=",
"''",
".",
"join",
"(",
"map",
"(",
"lambda",
... | 30 | 15.111111 |
def write(proto_dataset_uri, input):
"""Use YAML from a file or stdin to populate the readme.
To stream content from stdin use "-", e.g.
echo "desc: my data" | dtool readme write <DS_URI> -
"""
proto_dataset = dtoolcore.ProtoDataSet.from_uri(
uri=proto_dataset_uri
)
_validate_and_p... | [
"def",
"write",
"(",
"proto_dataset_uri",
",",
"input",
")",
":",
"proto_dataset",
"=",
"dtoolcore",
".",
"ProtoDataSet",
".",
"from_uri",
"(",
"uri",
"=",
"proto_dataset_uri",
")",
"_validate_and_put_readme",
"(",
"proto_dataset",
",",
"input",
".",
"read",
"("... | 31.636364 | 16.454545 |
def add_edge(self, node1_name, node2_name, edge_length=DEFAULT_EDGE_LENGTH):
""" Adds a new edge to the current tree with specified characteristics
Forbids addition of an edge, if a parent node is not present
Forbids addition of an edge, if a child node already exists
:param node1_name... | [
"def",
"add_edge",
"(",
"self",
",",
"node1_name",
",",
"node2_name",
",",
"edge_length",
"=",
"DEFAULT_EDGE_LENGTH",
")",
":",
"if",
"not",
"self",
".",
"__has_node",
"(",
"name",
"=",
"node1_name",
")",
":",
"raise",
"ValueError",
"(",
"\"Can not add an edge... | 60.888889 | 29.277778 |
def add_angles(self, indexes, deg=False, cossin=False, periodic=True):
"""
Adds the list of angles to the feature list
Parameters
----------
indexes : np.ndarray, shape=(num_pairs, 3), dtype=int
an array with triplets of atom indices
deg : bool, optional, def... | [
"def",
"add_angles",
"(",
"self",
",",
"indexes",
",",
"deg",
"=",
"False",
",",
"cossin",
"=",
"False",
",",
"periodic",
"=",
"True",
")",
":",
"from",
".",
"angles",
"import",
"AngleFeature",
"indexes",
"=",
"self",
".",
"_check_indices",
"(",
"indexes... | 45.076923 | 18.769231 |
def get_oauth_url(self):
""" Returns the URL with OAuth params """
params = OrderedDict()
if "?" in self.url:
url = self.url[:self.url.find("?")]
for key, value in parse_qsl(urlparse(self.url).query):
params[key] = value
else:
url = se... | [
"def",
"get_oauth_url",
"(",
"self",
")",
":",
"params",
"=",
"OrderedDict",
"(",
")",
"if",
"\"?\"",
"in",
"self",
".",
"url",
":",
"url",
"=",
"self",
".",
"url",
"[",
":",
"self",
".",
"url",
".",
"find",
"(",
"\"?\"",
")",
"]",
"for",
"key",
... | 34.7 | 18.75 |
def handle_backend_response(self, orig_request, backend_request,
response_status, response_headers,
response_body, method_config, start_response):
"""Handle backend response, transforming output as needed.
This calls start_response and returns the res... | [
"def",
"handle_backend_response",
"(",
"self",
",",
"orig_request",
",",
"backend_request",
",",
"response_status",
",",
"response_headers",
",",
"response_body",
",",
"method_config",
",",
"start_response",
")",
":",
"# Verify that the response is json. If it isn't treat, t... | 45.906977 | 23.465116 |
def uniformly_refine_triangulation(self, faces=False, trisect=False):
"""
return points defining a refined triangulation obtained by bisection of all edges
in the triangulation
"""
if faces:
x_v1, y_v1 = self._add_face_centroids()
else:
if not tr... | [
"def",
"uniformly_refine_triangulation",
"(",
"self",
",",
"faces",
"=",
"False",
",",
"trisect",
"=",
"False",
")",
":",
"if",
"faces",
":",
"x_v1",
",",
"y_v1",
"=",
"self",
".",
"_add_face_centroids",
"(",
")",
"else",
":",
"if",
"not",
"trisect",
":"... | 29.5 | 22.25 |
def QPSK_BEP(tx_data,rx_data,Ncorr = 1024,Ntransient = 0):
"""
Count bit errors between a transmitted and received QPSK signal.
Time delay between streams is detected as well as ambiquity resolution
due to carrier phase lock offsets of :math:`k*\\frac{\\pi}{4}`, k=0,1,2,3.
The ndarray sdata is Tx +/... | [
"def",
"QPSK_BEP",
"(",
"tx_data",
",",
"rx_data",
",",
"Ncorr",
"=",
"1024",
",",
"Ntransient",
"=",
"0",
")",
":",
"#Remove Ntransient symbols",
"tx_data",
"=",
"tx_data",
"[",
"Ntransient",
":",
"]",
"rx_data",
"=",
"rx_data",
"[",
"Ntransient",
":",
"]... | 40.897059 | 15.161765 |
def start(path=None, host=None, port=None, color=None, cors=None, detach=False, nolog=False):
"""start web server"""
if detach:
sys.argv.append('--no-log')
idx = sys.argv.index('-d')
del sys.argv[idx]
cmd = sys.executable + ' ' + ' '.join([sys.argv[0], 'start'] + sys.argv[1... | [
"def",
"start",
"(",
"path",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"color",
"=",
"None",
",",
"cors",
"=",
"None",
",",
"detach",
"=",
"False",
",",
"nolog",
"=",
"False",
")",
":",
"if",
"detach",
":",
"sys",
".... | 43.148148 | 18.592593 |
def load(self):
"""
Extract tabular data as |TableData| instances from a MediaWiki text
object.
|load_source_desc_text|
:return:
Loaded table data iterator.
|load_table_name_desc|
=================== =========================================... | [
"def",
"load",
"(",
"self",
")",
":",
"self",
".",
"_validate",
"(",
")",
"self",
".",
"_logger",
".",
"logging_load",
"(",
")",
"formatter",
"=",
"MediaWikiTableFormatter",
"(",
"self",
".",
"source",
")",
"formatter",
".",
"accept",
"(",
"self",
")",
... | 38.657143 | 18.942857 |
def buffered_read(fh, lock, offsets, bytecounts, buffersize=None):
"""Return iterator over segments read from file."""
if buffersize is None:
buffersize = 2**26
length = len(offsets)
i = 0
while i < length:
data = []
with lock:
size = 0
while size < bu... | [
"def",
"buffered_read",
"(",
"fh",
",",
"lock",
",",
"offsets",
",",
"bytecounts",
",",
"buffersize",
"=",
"None",
")",
":",
"if",
"buffersize",
"is",
"None",
":",
"buffersize",
"=",
"2",
"**",
"26",
"length",
"=",
"len",
"(",
"offsets",
")",
"i",
"=... | 33.047619 | 12.809524 |
def extract(self, content, output):
"""Try to extract tables from an invoice"""
for table in self['tables']:
# First apply default options.
plugin_settings = DEFAULT_OPTIONS.copy()
plugin_settings.update(table)
table = plugin_settings
# Validate settings
assert... | [
"def",
"extract",
"(",
"self",
",",
"content",
",",
"output",
")",
":",
"for",
"table",
"in",
"self",
"[",
"'tables'",
"]",
":",
"# First apply default options.",
"plugin_settings",
"=",
"DEFAULT_OPTIONS",
".",
"copy",
"(",
")",
"plugin_settings",
".",
"update... | 39.26087 | 20.326087 |
def mercado(self):
""" Obtém o status do mercado na rodada atual.
Returns:
Uma instância de cartolafc.Mercado representando o status do mercado na rodada atual.
"""
url = '{api_url}/mercado/status'.format(api_url=self._api_url)
data = self._request(url)
retu... | [
"def",
"mercado",
"(",
"self",
")",
":",
"url",
"=",
"'{api_url}/mercado/status'",
".",
"format",
"(",
"api_url",
"=",
"self",
".",
"_api_url",
")",
"data",
"=",
"self",
".",
"_request",
"(",
"url",
")",
"return",
"Mercado",
".",
"from_dict",
"(",
"data"... | 33.7 | 22.2 |
def make_call_types(f, globals_d):
# type: (Callable, Dict) -> Tuple[Dict[str, Anno], Anno]
"""Make a call_types dictionary that describes what arguments to pass to f
Args:
f: The function to inspect for argument names (without self)
globals_d: A dictionary of globals to lookup annotation d... | [
"def",
"make_call_types",
"(",
"f",
",",
"globals_d",
")",
":",
"# type: (Callable, Dict) -> Tuple[Dict[str, Anno], Anno]",
"arg_spec",
"=",
"getargspec",
"(",
"f",
")",
"args",
"=",
"[",
"k",
"for",
"k",
"in",
"arg_spec",
".",
"args",
"if",
"k",
"!=",
"\"self... | 39.351351 | 20.675676 |
def cmd_startstop(options):
"""Start or Stop the specified instance.
Finds instances that match args and instance-state expected by the
command. Then, the target instance is determined, the action is
performed on the instance, and the eturn information is displayed.
Args:
options (object)... | [
"def",
"cmd_startstop",
"(",
"options",
")",
":",
"statelu",
"=",
"{",
"\"start\"",
":",
"\"stopped\"",
",",
"\"stop\"",
":",
"\"running\"",
"}",
"options",
".",
"inst_state",
"=",
"statelu",
"[",
"options",
".",
"command",
"]",
"debg",
".",
"dprint",
"(",... | 44.076923 | 20.192308 |
def visitObjectExpr(self, ctx: jsgParser.ObjectExprContext):
""" objectExpr: OBRACE membersDef? CBRACE
OBRACE (LEXER_ID_REF | ANY)? MAPSTO valueType ebnfSuffix? CBRACE
"""
if not self._name:
self._name = self._context.anon_id()
if ctx.membersDef():
... | [
"def",
"visitObjectExpr",
"(",
"self",
",",
"ctx",
":",
"jsgParser",
".",
"ObjectExprContext",
")",
":",
"if",
"not",
"self",
".",
"_name",
":",
"self",
".",
"_name",
"=",
"self",
".",
"_context",
".",
"anon_id",
"(",
")",
"if",
"ctx",
".",
"membersDef... | 45.866667 | 15 |
def watchdog_handler(self):
"""Take care of threads if wachdog expires."""
_LOGGING.debug('%s Watchdog expired. Resetting connection.', self.name)
self.watchdog.stop()
self.reset_thrd.set() | [
"def",
"watchdog_handler",
"(",
"self",
")",
":",
"_LOGGING",
".",
"debug",
"(",
"'%s Watchdog expired. Resetting connection.'",
",",
"self",
".",
"name",
")",
"self",
".",
"watchdog",
".",
"stop",
"(",
")",
"self",
".",
"reset_thrd",
".",
"set",
"(",
")"
] | 43.4 | 15 |
def _get_matching_dns_entry_ids(self, identifier=None, rtype=None,
name=None, content=None):
"""Return a list of DNS entries that match the given criteria."""
record_ids = []
if not identifier:
records = self._list_records(rtype, name, content)
... | [
"def",
"_get_matching_dns_entry_ids",
"(",
"self",
",",
"identifier",
"=",
"None",
",",
"rtype",
"=",
"None",
",",
"name",
"=",
"None",
",",
"content",
"=",
"None",
")",
":",
"record_ids",
"=",
"[",
"]",
"if",
"not",
"identifier",
":",
"records",
"=",
... | 45.1 | 16.4 |
def getStyleCount(self, verbose=None):
"""
Returns the number of Visual Styles available in the current session
:param verbose: print more
:returns: 200: successful operation
"""
response=api(url=self.___url+'styles/count', method="GET", verbose=verbose, parse_params=F... | [
"def",
"getStyleCount",
"(",
"self",
",",
"verbose",
"=",
"None",
")",
":",
"response",
"=",
"api",
"(",
"url",
"=",
"self",
".",
"___url",
"+",
"'styles/count'",
",",
"method",
"=",
"\"GET\"",
",",
"verbose",
"=",
"verbose",
",",
"parse_params",
"=",
... | 30.818182 | 22.454545 |
def disable_host_svc_notifications(self, host):
"""Disable services notifications for a host
Format of the line that triggers function call::
DISABLE_HOST_SVC_NOTIFICATIONS;<host_name>
:param host: host to edit
:type host: alignak.objects.host.Host
:return: None
... | [
"def",
"disable_host_svc_notifications",
"(",
"self",
",",
"host",
")",
":",
"for",
"service_id",
"in",
"host",
".",
"services",
":",
"if",
"service_id",
"in",
"self",
".",
"daemon",
".",
"services",
":",
"service",
"=",
"self",
".",
"daemon",
".",
"servic... | 39.2 | 14.466667 |
def b58check_unpack(b58_s):
""" Takes in a base 58 check string and returns: the version byte, the
original encoded binary string, and the checksum.
"""
num_leading_zeros = len(re.match(r'^1*', b58_s).group(0))
# convert from b58 to b16
hex_s = change_charset(b58_s, B58_KEYSPACE, HEX_KEYSPAC... | [
"def",
"b58check_unpack",
"(",
"b58_s",
")",
":",
"num_leading_zeros",
"=",
"len",
"(",
"re",
".",
"match",
"(",
"r'^1*'",
",",
"b58_s",
")",
".",
"group",
"(",
"0",
")",
")",
"# convert from b58 to b16",
"hex_s",
"=",
"change_charset",
"(",
"b58_s",
",",
... | 42.5 | 14.708333 |
def move(self, from_id, to_uuid):
"""Move an identity into a unique identity.
The method moves the identity identified by <from_id> to
the unique identity <to_uuid>.
In the case of<from_id> is equal to <to_uuid> and this unique identity
does not exist, a new unique identity wil... | [
"def",
"move",
"(",
"self",
",",
"from_id",
",",
"to_uuid",
")",
":",
"if",
"not",
"from_id",
"or",
"not",
"to_uuid",
":",
"return",
"CMD_SUCCESS",
"try",
":",
"api",
".",
"move_identity",
"(",
"self",
".",
"db",
",",
"from_id",
",",
"to_uuid",
")",
... | 38.1 | 22.166667 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.