text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def _process_data_var(string):
"""Transform datastring to key, values pair.
All values are transformed to floating point values.
Parameters
----------
string : str
Returns
-------
Tuple[Str, Str]
key, values pair
"""
key, var = string.split("<-")
if "structure" in ... | [
"def",
"_process_data_var",
"(",
"string",
")",
":",
"key",
",",
"var",
"=",
"string",
".",
"split",
"(",
"\"<-\"",
")",
"if",
"\"structure\"",
"in",
"var",
":",
"var",
",",
"dim",
"=",
"var",
".",
"replace",
"(",
"\"structure(\"",
",",
"\"\"",
")",
... | 34.393939 | 23.272727 |
def apply_all_link_refs(
bytecode: bytes, link_refs: List[Dict[str, Any]], attr_dict: Dict[str, str]
) -> bytes:
"""
Applies all link references corresponding to a valid attr_dict to the bytecode.
"""
if link_refs is None:
return bytecode
link_fns = (
apply_link_ref(offset, ref["... | [
"def",
"apply_all_link_refs",
"(",
"bytecode",
":",
"bytes",
",",
"link_refs",
":",
"List",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
",",
"attr_dict",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
")",
"->",
"bytes",
":",
"if",
"link_refs",
"is",
... | 32.4 | 18.933333 |
def get_l(self):
"""Returns the left border of the cell"""
cell_left = CellBorders(self.cell_attributes,
*self.cell.get_left_key_rect())
return cell_left.get_r() | [
"def",
"get_l",
"(",
"self",
")",
":",
"cell_left",
"=",
"CellBorders",
"(",
"self",
".",
"cell_attributes",
",",
"*",
"self",
".",
"cell",
".",
"get_left_key_rect",
"(",
")",
")",
"return",
"cell_left",
".",
"get_r",
"(",
")"
] | 35.5 | 18 |
def template2regex(template, ranges=None):
"""Convert a URL template to a regular expression.
Converts a template, such as /{name}/ to a regular expression, e.g.
/(?P<name>[^/]+)/ and a list of the named parameters found in the template
(e.g. ['name']). Ranges are given after a colon in a template name... | [
"def",
"template2regex",
"(",
"template",
",",
"ranges",
"=",
"None",
")",
":",
"if",
"len",
"(",
"template",
")",
"and",
"-",
"1",
"<",
"template",
".",
"find",
"(",
"'|'",
")",
"<",
"len",
"(",
"template",
")",
"-",
"1",
":",
"raise",
"InvalidTem... | 35.049383 | 20.098765 |
def SetCoreGRRKnowledgeBaseValues(kb, client_obj):
"""Set core values from GRR into the knowledgebase."""
client_schema = client_obj.Schema
kb.fqdn = utils.SmartUnicode(client_obj.Get(client_schema.FQDN, ""))
if not kb.fqdn:
kb.fqdn = utils.SmartUnicode(client_obj.Get(client_schema.HOSTNAME, ""))
versions... | [
"def",
"SetCoreGRRKnowledgeBaseValues",
"(",
"kb",
",",
"client_obj",
")",
":",
"client_schema",
"=",
"client_obj",
".",
"Schema",
"kb",
".",
"fqdn",
"=",
"utils",
".",
"SmartUnicode",
"(",
"client_obj",
".",
"Get",
"(",
"client_schema",
".",
"FQDN",
",",
"\... | 41.529412 | 16.705882 |
def snake_to_camel(snake_str):
'''
Convert `snake_str` from snake_case to camelCase
'''
components = snake_str.split('_')
if len(components) > 1:
camel = (components[0].lower() +
''.join(x.title() for x in components[1:]))
return camel
# Not snake_case
return... | [
"def",
"snake_to_camel",
"(",
"snake_str",
")",
":",
"components",
"=",
"snake_str",
".",
"split",
"(",
"'_'",
")",
"if",
"len",
"(",
"components",
")",
">",
"1",
":",
"camel",
"=",
"(",
"components",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"+",
"''... | 29.090909 | 16.727273 |
def getDisplayIdentifier(self):
"""Return the display_identifier if set, else return the claimed_id.
"""
if self.display_identifier is not None:
return self.display_identifier
if self.claimed_id is None:
return None
else:
return urlparse.urldef... | [
"def",
"getDisplayIdentifier",
"(",
"self",
")",
":",
"if",
"self",
".",
"display_identifier",
"is",
"not",
"None",
":",
"return",
"self",
".",
"display_identifier",
"if",
"self",
".",
"claimed_id",
"is",
"None",
":",
"return",
"None",
"else",
":",
"return",... | 37.222222 | 9.333333 |
def synchronize_files(inputpaths, outpath, database=None, tqdm_bar=None, report_file=None, ptee=None, verbose=False):
''' Main function to synchronize files contents by majority vote
The main job of this function is to walk through the input folders and align the files, so that we can compare every files across... | [
"def",
"synchronize_files",
"(",
"inputpaths",
",",
"outpath",
",",
"database",
"=",
"None",
",",
"tqdm_bar",
"=",
"None",
",",
"report_file",
"=",
"None",
",",
"ptee",
"=",
"None",
",",
"verbose",
"=",
"False",
")",
":",
"# (Generator) Files Synchronization A... | 55.202454 | 33.214724 |
def move_to_end(self, key=NOT_SET, index=NOT_SET, last=True):
"""Move an existing element to the end (or beginning if last==False).
Runs in O(N).
"""
if index is NOT_SET and key is not NOT_SET:
index, value = self._dict[key]
elif index is not NOT_SET and key is NOT_SET:
key, value = self._list[index]
... | [
"def",
"move_to_end",
"(",
"self",
",",
"key",
"=",
"NOT_SET",
",",
"index",
"=",
"NOT_SET",
",",
"last",
"=",
"True",
")",
":",
"if",
"index",
"is",
"NOT_SET",
"and",
"key",
"is",
"not",
"NOT_SET",
":",
"index",
",",
"value",
"=",
"self",
".",
"_d... | 27.37037 | 18.037037 |
def _load_csv_file(csv_file):
""" load csv file and check file content format
@param
csv_file: csv file path
e.g. csv file content:
username,password
test1,111111
test2,222222
test3,333333
@return
... | [
"def",
"_load_csv_file",
"(",
"csv_file",
")",
":",
"csv_content_list",
"=",
"[",
"]",
"with",
"io",
".",
"open",
"(",
"csv_file",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"csvfile",
":",
"reader",
"=",
"csv",
".",
"DictReader",
"(",
"csvfile",
")",
... | 32.961538 | 15.576923 |
def add(self, child):
"""
Adds a typed child object to the structure object.
@param child: Child object to be added.
"""
if isinstance(child, With):
self.add_with(child)
elif isinstance(child, EventConnection):
self.add_event_connection(child)
... | [
"def",
"add",
"(",
"self",
",",
"child",
")",
":",
"if",
"isinstance",
"(",
"child",
",",
"With",
")",
":",
"self",
".",
"add_with",
"(",
"child",
")",
"elif",
"isinstance",
"(",
"child",
",",
"EventConnection",
")",
":",
"self",
".",
"add_event_connec... | 33.421053 | 11.526316 |
def record_get_field_instances(rec, tag="", ind1=" ", ind2=" "):
"""
Return the list of field instances for the specified tag and indications.
Return empty list if not found.
If tag is empty string, returns all fields
Parameters (tag, ind1, ind2) can contain wildcard %.
:param rec: a record s... | [
"def",
"record_get_field_instances",
"(",
"rec",
",",
"tag",
"=",
"\"\"",
",",
"ind1",
"=",
"\" \"",
",",
"ind2",
"=",
"\" \"",
")",
":",
"if",
"not",
"rec",
":",
"return",
"[",
"]",
"if",
"not",
"tag",
":",
"return",
"rec",
".",
"items",
"(",
")",... | 39.375 | 20.075 |
def _get_broadcast_shape(shape1, shape2):
"""Given two shapes that are not identical, find the shape
that both input shapes can broadcast to."""
if shape1 == shape2:
return shape1
length1 = len(shape1)
length2 = len(shape2)
if length1 > length2:
shape = list(shape1)
else:
... | [
"def",
"_get_broadcast_shape",
"(",
"shape1",
",",
"shape2",
")",
":",
"if",
"shape1",
"==",
"shape2",
":",
"return",
"shape1",
"length1",
"=",
"len",
"(",
"shape1",
")",
"length2",
"=",
"len",
"(",
"shape2",
")",
"if",
"length1",
">",
"length2",
":",
... | 32.368421 | 15.789474 |
def proj_to_cartopy(proj):
"""
Converts a pyproj.Proj to a cartopy.crs.Projection
(Code copied from https://github.com/fmaussion/salem)
Parameters
----------
proj: pyproj.Proj
the projection to convert
Returns
-------
a cartopy.crs.Projection object
"""
import cart... | [
"def",
"proj_to_cartopy",
"(",
"proj",
")",
":",
"import",
"cartopy",
".",
"crs",
"as",
"ccrs",
"try",
":",
"from",
"osgeo",
"import",
"osr",
"has_gdal",
"=",
"True",
"except",
"ImportError",
":",
"has_gdal",
"=",
"False",
"proj",
"=",
"check_crs",
"(",
... | 24.852273 | 16.920455 |
def crossover(self, gene2):
""" Creates a new gene randomly inheriting attributes from its parents."""
assert self.key == gene2.key
# Note: we use "a if random() > 0.5 else b" instead of choice((a, b))
# here because `choice` is substantially slower.
new_gene = self.__class__(se... | [
"def",
"crossover",
"(",
"self",
",",
"gene2",
")",
":",
"assert",
"self",
".",
"key",
"==",
"gene2",
".",
"key",
"# Note: we use \"a if random() > 0.5 else b\" instead of choice((a, b))",
"# here because `choice` is substantially slower.",
"new_gene",
"=",
"self",
".",
"... | 39.928571 | 18.071429 |
def check_closed_streams(options):
"""Work around Python issue with multiprocessing forking on closed streams
https://bugs.python.org/issue28326
Attempting to a fork/exec a new Python process when any of std{in,out,err}
are closed or not flushable for some reason may raise an exception.
Fix this b... | [
"def",
"check_closed_streams",
"(",
"options",
")",
":",
"if",
"sys",
".",
"version_info",
"[",
"0",
":",
"3",
"]",
">=",
"(",
"3",
",",
"6",
",",
"4",
")",
":",
"return",
"True",
"# Issued fixed in Python 3.6.4+",
"if",
"sys",
".",
"stderr",
"is",
"No... | 35.22 | 21.54 |
def start_capture(self, adapter_number, output_file):
"""
Starts a packet capture.
:param adapter_number: adapter number
:param output_file: PCAP destination file for the capture
"""
try:
adapter = self._ethernet_adapters[adapter_number]
except KeyEr... | [
"def",
"start_capture",
"(",
"self",
",",
"adapter_number",
",",
"output_file",
")",
":",
"try",
":",
"adapter",
"=",
"self",
".",
"_ethernet_adapters",
"[",
"adapter_number",
"]",
"except",
"KeyError",
":",
"raise",
"VirtualBoxError",
"(",
"\"Adapter {adapter_num... | 51.419355 | 41.16129 |
def remove_module_docstring(app, what, name, obj, options, lines):
"""
Ignore the docstring of the ``clusterpolate`` module.
"""
if what == "module" and name == "clusterpolate":
del lines[:] | [
"def",
"remove_module_docstring",
"(",
"app",
",",
"what",
",",
"name",
",",
"obj",
",",
"options",
",",
"lines",
")",
":",
"if",
"what",
"==",
"\"module\"",
"and",
"name",
"==",
"\"clusterpolate\"",
":",
"del",
"lines",
"[",
":",
"]"
] | 34.833333 | 12.5 |
def del_calculation(job_id, confirmed=False):
"""
Delete a calculation and all associated outputs.
"""
if logs.dbcmd('get_job', job_id) is None:
print('There is no job %d' % job_id)
return
if confirmed or confirm(
'Are you sure you want to (abort and) delete this calcula... | [
"def",
"del_calculation",
"(",
"job_id",
",",
"confirmed",
"=",
"False",
")",
":",
"if",
"logs",
".",
"dbcmd",
"(",
"'get_job'",
",",
"job_id",
")",
"is",
"None",
":",
"print",
"(",
"'There is no job %d'",
"%",
"job_id",
")",
"return",
"if",
"confirmed",
... | 33.714286 | 16 |
def GetHiResImage(ID):
'''
Queries the Palomar Observatory Sky Survey II catalog to
obtain a higher resolution optical image of the star with EPIC number
:py:obj:`ID`.
'''
# Get the TPF info
client = kplr.API()
star = client.k2_star(ID)
k2ra = star.k2_ra
k2dec = star.k2_dec
... | [
"def",
"GetHiResImage",
"(",
"ID",
")",
":",
"# Get the TPF info",
"client",
"=",
"kplr",
".",
"API",
"(",
")",
"star",
"=",
"client",
".",
"k2_star",
"(",
"ID",
")",
"k2ra",
"=",
"star",
".",
"k2_ra",
"k2dec",
"=",
"star",
".",
"k2_dec",
"tpf",
"=",... | 30.535211 | 19.549296 |
def disable_performance_data(self):
"""Disable performance data processing (globally)
Format of the line that triggers function call::
DISABLE_PERFORMANCE_DATA
:return: None
"""
# todo: #783 create a dedicated brok for global parameters
if self.my_conf.process_p... | [
"def",
"disable_performance_data",
"(",
"self",
")",
":",
"# todo: #783 create a dedicated brok for global parameters",
"if",
"self",
".",
"my_conf",
".",
"process_performance_data",
":",
"self",
".",
"my_conf",
".",
"modified_attributes",
"|=",
"DICT_MODATTR",
"[",
"\"MO... | 39.733333 | 15.466667 |
def ndstype(self):
"""NDS type integer for this channel.
This property is mapped to the `Channel.type` string.
"""
if self.type is not None:
return io_nds2.Nds2ChannelType.find(self.type).value | [
"def",
"ndstype",
"(",
"self",
")",
":",
"if",
"self",
".",
"type",
"is",
"not",
"None",
":",
"return",
"io_nds2",
".",
"Nds2ChannelType",
".",
"find",
"(",
"self",
".",
"type",
")",
".",
"value"
] | 33.142857 | 16.285714 |
def update_git_repository(self, folder, git_repository):
"""Updates git remote for the managed theme folder if has changed.
:param git_repository: git url of the theme folder
:param folder: path of the git managed theme folder
"""
# load repo object from path
repo = git... | [
"def",
"update_git_repository",
"(",
"self",
",",
"folder",
",",
"git_repository",
")",
":",
"# load repo object from path",
"repo",
"=",
"git",
".",
"Repo",
"(",
"folder",
")",
"# keep local_head_name for to reset folder remote head later",
"local_head_name",
"=",
"repo"... | 36.033333 | 18.8 |
def get_uncompleted_tasks(self):
"""Return a list of all uncompleted tasks in this project.
.. warning:: Requires Todoist premium.
:return: A list of all uncompleted tasks in this project.
:rtype: list of :class:`pytodoist.todoist.Task`
>>> from pytodoist import todoist
... | [
"def",
"get_uncompleted_tasks",
"(",
"self",
")",
":",
"all_tasks",
"=",
"self",
".",
"get_tasks",
"(",
")",
"completed_tasks",
"=",
"self",
".",
"get_completed_tasks",
"(",
")",
"return",
"[",
"t",
"for",
"t",
"in",
"all_tasks",
"if",
"t",
"not",
"in",
... | 40.526316 | 15.631579 |
def wait_for_capture(self, timeout=None):
"""See base class documentation
"""
if self._process is None:
raise sniffer.InvalidOperationError(
"Trying to wait on a non-started process")
try:
utils.wait_for_standing_subprocess(self._... | [
"def",
"wait_for_capture",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"self",
".",
"_process",
"is",
"None",
":",
"raise",
"sniffer",
".",
"InvalidOperationError",
"(",
"\"Trying to wait on a non-started process\"",
")",
"try",
":",
"utils",
".",
... | 39.454545 | 11.636364 |
def gauge_laplacian(npts, spacing=1.0, beta=0.1):
"""Construct a Gauge Laplacian from Quantum Chromodynamics for regular 2D grids.
Note that this function is not written efficiently, but should be
fine for N x N grids where N is in the low hundreds.
Parameters
----------
npts : int
num... | [
"def",
"gauge_laplacian",
"(",
"npts",
",",
"spacing",
"=",
"1.0",
",",
"beta",
"=",
"0.1",
")",
":",
"# The gauge Laplacian has the same sparsity structure as a normal",
"# Laplacian, so we start out with a Poisson Operator",
"N",
"=",
"npts",
"A",
"=",
"poisson",
"(",
... | 29.156522 | 20.53913 |
def check(schema, data, trace=False):
"""Verify some json.
Args:
schema - the description of a general-case 'valid' json object.
data - the json data to verify.
Returns:
bool: True if data matches the schema, False otherwise.
Raises:
TypeError:
... | [
"def",
"check",
"(",
"schema",
",",
"data",
",",
"trace",
"=",
"False",
")",
":",
"if",
"trace",
"==",
"True",
":",
"trace",
"=",
"1",
"else",
":",
"trace",
"=",
"None",
"return",
"_check",
"(",
"schema",
",",
"data",
",",
"trace",
"=",
"trace",
... | 27.73913 | 22.217391 |
def get_schema(self, table_name, database=None):
"""
Return a Schema object for the indicated table and database
Parameters
----------
table_name : string
May be fully qualified
database : string, default None
Returns
-------
schema : i... | [
"def",
"get_schema",
"(",
"self",
",",
"table_name",
",",
"database",
"=",
"None",
")",
":",
"qualified_name",
"=",
"self",
".",
"_fully_qualified_name",
"(",
"table_name",
",",
"database",
")",
"query",
"=",
"'DESC {0}'",
".",
"format",
"(",
"qualified_name",... | 29.590909 | 18.681818 |
def write_versions(dirs, items):
"""Write data versioning for genomes present in the configuration.
"""
genomes = {}
for d in items:
genomes[d["genome_build"]] = d.get("reference", {}).get("versions")
out_file = _get_out_file(dirs)
found_versions = False
if genomes and out_file:
... | [
"def",
"write_versions",
"(",
"dirs",
",",
"items",
")",
":",
"genomes",
"=",
"{",
"}",
"for",
"d",
"in",
"items",
":",
"genomes",
"[",
"d",
"[",
"\"genome_build\"",
"]",
"]",
"=",
"d",
".",
"get",
"(",
"\"reference\"",
",",
"{",
"}",
")",
".",
"... | 46.185185 | 15.925926 |
def get_repository_admin_session(self):
"""Gets the repository administrative session for creating, updating and deleteing repositories.
return: (osid.repository.RepositoryAdminSession) - a
``RepositoryAdminSession``
raise: OperationFailed - unable to complete request
r... | [
"def",
"get_repository_admin_session",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"supports_repository_admin",
"(",
")",
":",
"raise",
"errors",
".",
"Unimplemented",
"(",
")",
"# pylint: disable=no-member",
"return",
"sessions",
".",
"RepositoryAdminSession",
... | 44.9375 | 15.375 |
def get_bandstructure(self):
"""
returns a LobsterBandStructureSymmLine object which can be plotted with a normal BSPlotter
"""
return LobsterBandStructureSymmLine(kpoints=self.kpoints_array, eigenvals=self.eigenvals, lattice=self.lattice,
efe... | [
"def",
"get_bandstructure",
"(",
"self",
")",
":",
"return",
"LobsterBandStructureSymmLine",
"(",
"kpoints",
"=",
"self",
".",
"kpoints_array",
",",
"eigenvals",
"=",
"self",
".",
"eigenvals",
",",
"lattice",
"=",
"self",
".",
"lattice",
",",
"efermi",
"=",
... | 55.666667 | 33.666667 |
def remove_this_tlink(self,tlink_id):
"""
Removes the tlink for the given tlink identifier
@type tlink_id: string
@param tlink_id: the tlink identifier to be removed
"""
for tlink in self.get_tlinks():
if tlink.get_id() == tlink_id:
self.node.r... | [
"def",
"remove_this_tlink",
"(",
"self",
",",
"tlink_id",
")",
":",
"for",
"tlink",
"in",
"self",
".",
"get_tlinks",
"(",
")",
":",
"if",
"tlink",
".",
"get_id",
"(",
")",
"==",
"tlink_id",
":",
"self",
".",
"node",
".",
"remove",
"(",
"tlink",
".",
... | 35.6 | 8 |
def ms_to_times(ms):
"""
Convert milliseconds to normalized tuple (h, m, s, ms).
Arguments:
ms: Number of milliseconds (may be int, float or other numeric class).
Should be non-negative.
Returns:
Named tuple (h, m, s, ms) of ints.
Invariants: ``ms in range(1... | [
"def",
"ms_to_times",
"(",
"ms",
")",
":",
"ms",
"=",
"int",
"(",
"round",
"(",
"ms",
")",
")",
"h",
",",
"ms",
"=",
"divmod",
"(",
"ms",
",",
"3600000",
")",
"m",
",",
"ms",
"=",
"divmod",
"(",
"ms",
",",
"60000",
")",
"s",
",",
"ms",
"=",... | 28.055556 | 19.166667 |
def print_tree(graph, tails, node_id_map):
"""Print out a tree of blocks starting from the common ancestor."""
# Example:
# |
# | 5
# * a {0, 1, 2, 3, 4}
# |
# | 6
# |\
# * | b {0, 1, 2, 3}
# | * n {4}
# | |
# | | 7
# * | c {0, 1, 2, 3}
# | * o {4}
# | |
... | [
"def",
"print_tree",
"(",
"graph",
",",
"tails",
",",
"node_id_map",
")",
":",
"# Example:",
"# |",
"# | 5",
"# * a {0, 1, 2, 3, 4}",
"# |",
"# | 6",
"# |\\",
"# * | b {0, 1, 2, 3}",
"# | * n {4}",
"# | |",
"# | | 7",
"# * | c {0, 1, 2, 3}",
"# | * o {4}",
"# | |",... | 21.270588 | 23.729412 |
def execute_sparql_query(query, prefix=None, endpoint='https://query.wikidata.org/sparql',
user_agent=config['USER_AGENT_DEFAULT'], as_dataframe=False):
"""
Static method which can be used to execute any SPARQL query
:param prefix: The URI prefixes required for an en... | [
"def",
"execute_sparql_query",
"(",
"query",
",",
"prefix",
"=",
"None",
",",
"endpoint",
"=",
"'https://query.wikidata.org/sparql'",
",",
"user_agent",
"=",
"config",
"[",
"'USER_AGENT_DEFAULT'",
"]",
",",
"as_dataframe",
"=",
"False",
")",
":",
"if",
"not",
"e... | 40.333333 | 26.333333 |
def betweenness(self, kind='vertex', directed=None, weighted=None):
'''Computes the betweenness centrality of a graph.
kind : string, either 'vertex' (default) or 'edge'
directed : bool, defaults to self.is_directed()
weighted : bool, defaults to self.is_weighted()
'''
assert kind in ('vertex', ... | [
"def",
"betweenness",
"(",
"self",
",",
"kind",
"=",
"'vertex'",
",",
"directed",
"=",
"None",
",",
"weighted",
"=",
"None",
")",
":",
"assert",
"kind",
"in",
"(",
"'vertex'",
",",
"'edge'",
")",
",",
"'Invalid kind argument: '",
"+",
"kind",
"weighted",
... | 42.866667 | 19.8 |
def probabilistic_collocation(order, dist, subset=.1):
"""
Probabilistic collocation method.
Args:
order (int, numpy.ndarray) : Quadrature order along each axis.
dist (Dist) : Distribution to generate samples from.
subset (float) : Rate of which to removed samples.
"""
absci... | [
"def",
"probabilistic_collocation",
"(",
"order",
",",
"dist",
",",
"subset",
"=",
".1",
")",
":",
"abscissas",
",",
"weights",
"=",
"chaospy",
".",
"quad",
".",
"collection",
".",
"golub_welsch",
"(",
"order",
",",
"dist",
")",
"likelihood",
"=",
"dist",
... | 32.052632 | 19.210526 |
def append(self, data):
"""Add a data set to the next block index"""
index = self.n_blocks # note off by one so use as index
self[index] = data
self.refs.append(data) | [
"def",
"append",
"(",
"self",
",",
"data",
")",
":",
"index",
"=",
"self",
".",
"n_blocks",
"# note off by one so use as index",
"self",
"[",
"index",
"]",
"=",
"data",
"self",
".",
"refs",
".",
"append",
"(",
"data",
")"
] | 38.8 | 12.8 |
def build_request(self, input_data=None, api_data=None, aux_data=None, *args, **kwargs):
"""
Builds request
:param input_data:
:param api_data:
:param aux_data:
:param args:
:param kwargs:
:return:
"""
if input_data is not None:
... | [
"def",
"build_request",
"(",
"self",
",",
"input_data",
"=",
"None",
",",
"api_data",
"=",
"None",
",",
"aux_data",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"input_data",
"is",
"not",
"None",
":",
"self",
".",
"client_d... | 34.583333 | 18.666667 |
def abs_area(max):
"""
Point area palette (continuous), with area proportional to value.
Parameters
----------
max : float
A number representing the maximum size
Returns
-------
out : function
Palette function that takes a sequence of values
in the range ``[0, 1... | [
"def",
"abs_area",
"(",
"max",
")",
":",
"def",
"abs_area_palette",
"(",
"x",
")",
":",
"return",
"rescale",
"(",
"np",
".",
"sqrt",
"(",
"np",
".",
"abs",
"(",
"x",
")",
")",
",",
"to",
"=",
"(",
"0",
",",
"max",
")",
",",
"_from",
"=",
"(",... | 27.935484 | 22.645161 |
def _cork_one(self, s, obj):
"""
Construct a socketpair, saving one side of it, and passing the other to
`obj` to be written to by one of its threads.
"""
rsock, wsock = mitogen.parent.create_socketpair(size=4096)
mitogen.core.set_cloexec(rsock.fileno())
mitogen.c... | [
"def",
"_cork_one",
"(",
"self",
",",
"s",
",",
"obj",
")",
":",
"rsock",
",",
"wsock",
"=",
"mitogen",
".",
"parent",
".",
"create_socketpair",
"(",
"size",
"=",
"4096",
")",
"mitogen",
".",
"core",
".",
"set_cloexec",
"(",
"rsock",
".",
"fileno",
"... | 42.454545 | 11 |
def _compose_dict_for_nginx(port_specs):
"""Return a dictionary containing the Compose spec required to run
Dusty's nginx container used for host forwarding."""
spec = {'image': constants.NGINX_IMAGE,
'volumes': ['{}:{}'.format(constants.NGINX_CONFIG_DIR_IN_VM, constants.NGINX_CONFIG_DIR_IN_CONT... | [
"def",
"_compose_dict_for_nginx",
"(",
"port_specs",
")",
":",
"spec",
"=",
"{",
"'image'",
":",
"constants",
".",
"NGINX_IMAGE",
",",
"'volumes'",
":",
"[",
"'{}:{}'",
".",
"format",
"(",
"constants",
".",
"NGINX_CONFIG_DIR_IN_VM",
",",
"constants",
".",
"NGI... | 58.307692 | 20.461538 |
def invalid_code(self, code, card_id=None):
"""
设置卡券失效
"""
card_data = {
'code': code
}
if card_id:
card_data['card_id'] = card_id
return self._post(
'card/code/unavailable',
data=card_data
) | [
"def",
"invalid_code",
"(",
"self",
",",
"code",
",",
"card_id",
"=",
"None",
")",
":",
"card_data",
"=",
"{",
"'code'",
":",
"code",
"}",
"if",
"card_id",
":",
"card_data",
"[",
"'card_id'",
"]",
"=",
"card_id",
"return",
"self",
".",
"_post",
"(",
... | 22.384615 | 13.923077 |
def is_equal_to(self, other, **kwargs):
"""Asserts that val is equal to other."""
if self._check_dict_like(self.val, check_values=False, return_as_bool=True) and \
self._check_dict_like(other, check_values=False, return_as_bool=True):
if self._dict_not_equal(self.val, other, ... | [
"def",
"is_equal_to",
"(",
"self",
",",
"other",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_check_dict_like",
"(",
"self",
".",
"val",
",",
"check_values",
"=",
"False",
",",
"return_as_bool",
"=",
"True",
")",
"and",
"self",
".",
"_check_... | 64.4 | 34.7 |
def GetTagDescription(tag_name):
"""
Gets the current description of a point configured in a real-time eDNA
service.
:param tag_name: fully-qualified (site.service.tag) eDNA tag
:return: tag description
"""
# Check if the point even exists
if not DoesIDExist(tag_name):
... | [
"def",
"GetTagDescription",
"(",
"tag_name",
")",
":",
"# Check if the point even exists\r",
"if",
"not",
"DoesIDExist",
"(",
"tag_name",
")",
":",
"warnings",
".",
"warn",
"(",
"\"WARNING- \"",
"+",
"tag_name",
"+",
"\" does not exist or \"",
"+",
"\"connection was d... | 38.529412 | 20.588235 |
def convert_coord(coord_from,matrix_file,base_to_aligned=True):
'''Takes an XYZ array (in DICOM coordinates) and uses the matrix file produced by 3dAllineate to transform it. By default, the 3dAllineate
matrix transforms from base to aligned space; to get the inverse transform set ``base_to_aligned`` to ``False... | [
"def",
"convert_coord",
"(",
"coord_from",
",",
"matrix_file",
",",
"base_to_aligned",
"=",
"True",
")",
":",
"with",
"open",
"(",
"matrix_file",
")",
"as",
"f",
":",
"try",
":",
"values",
"=",
"[",
"float",
"(",
"y",
")",
"for",
"y",
"in",
"' '",
".... | 60.9375 | 37.0625 |
def before_content(self):
"""Called before parsing content. Push the class name onto the class name
stack. Used to construct the full name for members.
"""
ChapelObject.before_content(self)
if self.names:
self.env.temp_data['chpl:class'] = self.names[0][0]
... | [
"def",
"before_content",
"(",
"self",
")",
":",
"ChapelObject",
".",
"before_content",
"(",
"self",
")",
"if",
"self",
".",
"names",
":",
"self",
".",
"env",
".",
"temp_data",
"[",
"'chpl:class'",
"]",
"=",
"self",
".",
"names",
"[",
"0",
"]",
"[",
"... | 42.125 | 10.125 |
def get(self, type: Type[T], query: Mapping[str, Any]) -> T:
"""Gets a query from the data pipeline.
1) Extracts the query the sequence of data sources.
2) Inserts the result into the data sinks (if appropriate).
3) Transforms the result into the requested type if it wasn't already.
... | [
"def",
"get",
"(",
"self",
",",
"type",
":",
"Type",
"[",
"T",
"]",
",",
"query",
":",
"Mapping",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"T",
":",
"LOGGER",
".",
"info",
"(",
"\"Getting SourceHandlers for \\\"{type}\\\"\"",
".",
"format",
"(",
"type",... | 37.925 | 23.075 |
def copy(self):
"""
Returns a copy of the datamat.
"""
return self.filter(np.ones(self._num_fix).astype(bool)) | [
"def",
"copy",
"(",
"self",
")",
":",
"return",
"self",
".",
"filter",
"(",
"np",
".",
"ones",
"(",
"self",
".",
"_num_fix",
")",
".",
"astype",
"(",
"bool",
")",
")"
] | 27.6 | 10 |
def match(self, dom, act):
"""
Check if the given `domain` and `act` are allowed
by this capability
"""
return self.match_domain(dom) and self.match_action(act) | [
"def",
"match",
"(",
"self",
",",
"dom",
",",
"act",
")",
":",
"return",
"self",
".",
"match_domain",
"(",
"dom",
")",
"and",
"self",
".",
"match_action",
"(",
"act",
")"
] | 32.5 | 11.5 |
def get_owned_by(cls, username, api=None):
"""Query ( List ) datasets by owner
:param api: Api instance
:param username: Owner username
:return: Collection object
"""
api = api if api else cls._API
return super(Dataset, cls)._query(
url=cls._URL['owne... | [
"def",
"get_owned_by",
"(",
"cls",
",",
"username",
",",
"api",
"=",
"None",
")",
":",
"api",
"=",
"api",
"if",
"api",
"else",
"cls",
".",
"_API",
"return",
"super",
"(",
"Dataset",
",",
"cls",
")",
".",
"_query",
"(",
"url",
"=",
"cls",
".",
"_U... | 30.615385 | 11.538462 |
def connection_exists(self, from_obj, to_obj):
"""
Returns ``True`` if a connection between the given objects exists,
else ``False``.
"""
self._validate_ctypes(from_obj, to_obj)
return self.connections.filter(from_pk=from_obj.pk, to_pk=to_obj.pk).exists() | [
"def",
"connection_exists",
"(",
"self",
",",
"from_obj",
",",
"to_obj",
")",
":",
"self",
".",
"_validate_ctypes",
"(",
"from_obj",
",",
"to_obj",
")",
"return",
"self",
".",
"connections",
".",
"filter",
"(",
"from_pk",
"=",
"from_obj",
".",
"pk",
",",
... | 42.428571 | 15.571429 |
def add(self, name, attr=None, value=None):
"Set values in constant"
if isinstance(name, tuple) or isinstance(name, list):
name, attr, value = self.__set_iter_value(name)
if attr is None:
attr = name
if value is None:
value = attr
self.__da... | [
"def",
"add",
"(",
"self",
",",
"name",
",",
"attr",
"=",
"None",
",",
"value",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"name",
",",
"tuple",
")",
"or",
"isinstance",
"(",
"name",
",",
"list",
")",
":",
"name",
",",
"attr",
",",
"value",
... | 29.933333 | 21.666667 |
def params(self):
"""Parameters used in the url of the API call and for authentication.
:return: parameters used in the url.
:rtype: dict
"""
params = {}
params["access_token"] = self.access_token
params["account_id"] = self.account_id
return params | [
"def",
"params",
"(",
"self",
")",
":",
"params",
"=",
"{",
"}",
"params",
"[",
"\"access_token\"",
"]",
"=",
"self",
".",
"access_token",
"params",
"[",
"\"account_id\"",
"]",
"=",
"self",
".",
"account_id",
"return",
"params"
] | 30.5 | 14.3 |
def _get_day_of_month(other, day_option):
"""Find the day in `other`'s month that satisfies a BaseCFTimeOffset's
onOffset policy, as described by the `day_option` argument.
Parameters
----------
other : cftime.datetime
day_option : 'start', 'end'
'start': returns 1
'end': return... | [
"def",
"_get_day_of_month",
"(",
"other",
",",
"day_option",
")",
":",
"if",
"day_option",
"==",
"'start'",
":",
"return",
"1",
"elif",
"day_option",
"==",
"'end'",
":",
"days_in_month",
"=",
"_days_in_month",
"(",
"other",
")",
"return",
"days_in_month",
"eli... | 26.285714 | 17.892857 |
def set_referencepixel(self, pix):
"""Set the reference pixel of the given axis in this coordinate."""
assert len(pix) == len(self._coord["crpix"])
self._coord["crpix"] = pix[::-1] | [
"def",
"set_referencepixel",
"(",
"self",
",",
"pix",
")",
":",
"assert",
"len",
"(",
"pix",
")",
"==",
"len",
"(",
"self",
".",
"_coord",
"[",
"\"crpix\"",
"]",
")",
"self",
".",
"_coord",
"[",
"\"crpix\"",
"]",
"=",
"pix",
"[",
":",
":",
"-",
"... | 50.25 | 4.5 |
def identify_groups(ref_labels, pred_labels, return_overlaps=False):
"""Which predicted label explains which reference label?
A predicted label explains the reference label which maximizes the minimum
of ``relative_overlaps_pred`` and ``relative_overlaps_ref``.
Compare this with ``compute_association_... | [
"def",
"identify_groups",
"(",
"ref_labels",
",",
"pred_labels",
",",
"return_overlaps",
"=",
"False",
")",
":",
"ref_unique",
",",
"ref_counts",
"=",
"np",
".",
"unique",
"(",
"ref_labels",
",",
"return_counts",
"=",
"True",
")",
"ref_dict",
"=",
"dict",
"(... | 55 | 29.970588 |
def daily_from_hourly(df):
"""Aggregates data (hourly to daily values) according to the characteristics
of each variable (e.g., average for temperature, sum for precipitation)
Args:
df: dataframe including time series with one hour time steps
Returns:
dataframe (daily)
"""
df_... | [
"def",
"daily_from_hourly",
"(",
"df",
")",
":",
"df_daily",
"=",
"pd",
".",
"DataFrame",
"(",
")",
"if",
"'temp'",
"in",
"df",
":",
"df_daily",
"[",
"'temp'",
"]",
"=",
"df",
".",
"temp",
".",
"resample",
"(",
"'D'",
")",
".",
"mean",
"(",
")",
... | 28.414634 | 25.902439 |
def may_be_null_is_nullable():
"""If may_be_null returns nullable or if NULL can be passed in.
This can still be wrong if the specific typelib is older than the linked
libgirepository.
https://bugzilla.gnome.org/show_bug.cgi?id=660879#c47
"""
repo = GIRepository()
repo.require("GLib", "2.... | [
"def",
"may_be_null_is_nullable",
"(",
")",
":",
"repo",
"=",
"GIRepository",
"(",
")",
"repo",
".",
"require",
"(",
"\"GLib\"",
",",
"\"2.0\"",
",",
"0",
")",
"info",
"=",
"repo",
".",
"find_by_name",
"(",
"\"GLib\"",
",",
"\"spawn_sync\"",
")",
"# this a... | 33.642857 | 18.5 |
def ecg_wave_detector(ecg, rpeaks):
"""
Returns the localization of the P, Q, T waves. This function needs massive help!
Parameters
----------
ecg : list or ndarray
ECG signal (preferably filtered).
rpeaks : list or ndarray
R peaks localization.
Returns
----------
e... | [
"def",
"ecg_wave_detector",
"(",
"ecg",
",",
"rpeaks",
")",
":",
"q_waves",
"=",
"[",
"]",
"p_waves",
"=",
"[",
"]",
"q_waves_starts",
"=",
"[",
"]",
"s_waves",
"=",
"[",
"]",
"t_waves",
"=",
"[",
"]",
"t_waves_starts",
"=",
"[",
"]",
"t_waves_ends",
... | 36.695946 | 27.763514 |
def init_pkg(pkg, repo_dest):
"""
Initializes a custom named package module.
This works by replacing all instances of 'project' with a custom module
name.
"""
vars = {'pkg': pkg}
with dir_path(repo_dest):
patch("""\
diff --git a/manage.py b/manage.py
index 40ebb0a..c... | [
"def",
"init_pkg",
"(",
"pkg",
",",
"repo_dest",
")",
":",
"vars",
"=",
"{",
"'pkg'",
":",
"pkg",
"}",
"with",
"dir_path",
"(",
"repo_dest",
")",
":",
"patch",
"(",
"\"\"\"\\\n diff --git a/manage.py b/manage.py\n index 40ebb0a..cdfe363 100755\n ---... | 35.358491 | 18.886792 |
def remember(self, request, username, **kw):
""" Returns 'WWW-Authenticate' header with a value that should be used
in 'Authorization' header.
"""
if self.credentials_callback:
token = self.credentials_callback(username, request)
api_key = 'ApiKey {}:{}'.format(us... | [
"def",
"remember",
"(",
"self",
",",
"request",
",",
"username",
",",
"*",
"*",
"kw",
")",
":",
"if",
"self",
".",
"credentials_callback",
":",
"token",
"=",
"self",
".",
"credentials_callback",
"(",
"username",
",",
"request",
")",
"api_key",
"=",
"'Api... | 47.25 | 8.375 |
def execute(cmd):
""" execute command, return rc and output string.
The cmd argument can be a string or a list composed of
the command name and each of its argument.
eg, ['/usr/bin/cp', '-r', 'src', 'dst'] """
# Parse cmd string to a list
if not isinstance(cmd, list):
cmd = shlex.split(... | [
"def",
"execute",
"(",
"cmd",
")",
":",
"# Parse cmd string to a list",
"if",
"not",
"isinstance",
"(",
"cmd",
",",
"list",
")",
":",
"cmd",
"=",
"shlex",
".",
"split",
"(",
"cmd",
")",
"# Execute command",
"rc",
"=",
"0",
"output",
"=",
"\"\"",
"try",
... | 33.666667 | 17.5 |
def memoize(fnc):
"""memoization function.
>>> import random
>>> imax = 100
>>> def fnc1(arg=True):
... return arg and random.choice((True, False))
>>> fnc2 = memoize(fnc1)
>>> (ret1, ret2) = (fnc1(), fnc2())
>>> assert any(fnc1() != ret1 for i in range(imax))
>>> assert all(fnc... | [
"def",
"memoize",
"(",
"fnc",
")",
":",
"cache",
"=",
"dict",
"(",
")",
"@",
"functools",
".",
"wraps",
"(",
"fnc",
")",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Decorated one\"\"\"",
"key",
"=",
"repr",
"(",
"a... | 25.333333 | 16.416667 |
def as_iframe(self, html_data):
"""Build the HTML representation for the mapviz."""
srcdoc = html_data.replace('"', "'")
return ('<iframe id="{div_id}", srcdoc="{srcdoc}" style="width: {width}; '
'height: {height};"></iframe>'.format(
div_id=self.div_id,
... | [
"def",
"as_iframe",
"(",
"self",
",",
"html_data",
")",
":",
"srcdoc",
"=",
"html_data",
".",
"replace",
"(",
"'\"'",
",",
"\"'\"",
")",
"return",
"(",
"'<iframe id=\"{div_id}\", srcdoc=\"{srcdoc}\" style=\"width: {width}; '",
"'height: {height};\"></iframe>'",
".",
"fo... | 42 | 11.9 |
def _command_list(self):
""" build the command list """
## base args
cmd = [self.params.binary,
"-i", OPJ(self.workdir, self.name+".treemix.in.gz"),
"-o", OPJ(self.workdir, self.name),
]
## addon params
args = []
for key,... | [
"def",
"_command_list",
"(",
"self",
")",
":",
"## base args",
"cmd",
"=",
"[",
"self",
".",
"params",
".",
"binary",
",",
"\"-i\"",
",",
"OPJ",
"(",
"self",
".",
"workdir",
",",
"self",
".",
"name",
"+",
"\".treemix.in.gz\"",
")",
",",
"\"-o\"",
",",
... | 31.777778 | 15.925926 |
def unhandled_keys(self, size, key):
"""
Override this method to intercept keystrokes in subclasses.
Default behavior: Toggle flagged on space, ignore other keys.
"""
if key == " ":
if not self.flagged:
self.display.new_files.append(self.get_node().get... | [
"def",
"unhandled_keys",
"(",
"self",
",",
"size",
",",
"key",
")",
":",
"if",
"key",
"==",
"\" \"",
":",
"if",
"not",
"self",
".",
"flagged",
":",
"self",
".",
"display",
".",
"new_files",
".",
"append",
"(",
"self",
".",
"get_node",
"(",
")",
"."... | 37.2 | 15.866667 |
def from_string(cls, s):
"""
Init a new object from a string.
Args:
s (string): raw email
Returns:
Instance of MailParser
"""
log.debug("Parsing email from string")
message = email.message_from_string(s)
return cls(message) | [
"def",
"from_string",
"(",
"cls",
",",
"s",
")",
":",
"log",
".",
"debug",
"(",
"\"Parsing email from string\"",
")",
"message",
"=",
"email",
".",
"message_from_string",
"(",
"s",
")",
"return",
"cls",
"(",
"message",
")"
] | 21.5 | 16.071429 |
def build_sector_fundamentals(sector):
'''
In this method, for the given sector, we'll get the data we need for each stock
in the sector from IEX. Once we have the data, we'll check that the earnings
reports meet our criteria with `eps_good()`. We'll put stocks that meet those
requirements into a da... | [
"def",
"build_sector_fundamentals",
"(",
"sector",
")",
":",
"stocks",
"=",
"get_sector",
"(",
"sector",
")",
"if",
"len",
"(",
"stocks",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"Invalid sector name: {}\"",
".",
"format",
"(",
"sector",
")",
")",
... | 38.140351 | 20.77193 |
def modExp(a, d, n):
"""returns a ** d (mod n)"""
assert d >= 0
assert n >= 0
base2D = int2baseTwo(d)
base2DLength = len(base2D)
modArray = []
result = 1
for i in range(1, base2DLength + 1):
if i == 1:
modArray.append(a % n)
else:
modArray.append((... | [
"def",
"modExp",
"(",
"a",
",",
"d",
",",
"n",
")",
":",
"assert",
"d",
">=",
"0",
"assert",
"n",
">=",
"0",
"base2D",
"=",
"int2baseTwo",
"(",
"d",
")",
"base2DLength",
"=",
"len",
"(",
"base2D",
")",
"modArray",
"=",
"[",
"]",
"result",
"=",
... | 27.176471 | 14.705882 |
def handle_close(self, header, payload):
"""
Called when a close frame has been decoded from the stream.
:param header: The decoded `Header`.
:param payload: The bytestring payload associated with the close frame.
"""
if not payload:
self.close(1000, None)
... | [
"def",
"handle_close",
"(",
"self",
",",
"header",
",",
"payload",
")",
":",
"if",
"not",
"payload",
":",
"self",
".",
"close",
"(",
"1000",
",",
"None",
")",
"return",
"if",
"len",
"(",
"payload",
")",
"<",
"2",
":",
"raise",
"WebSocketError",
"(",
... | 36.307692 | 15.538462 |
def send_video_note(self, *args, **kwargs):
"""See :func:`send_video`"""
return send_video_note(*args, **self._merge_overrides(**kwargs)).run() | [
"def",
"send_video_note",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"send_video_note",
"(",
"*",
"args",
",",
"*",
"*",
"self",
".",
"_merge_overrides",
"(",
"*",
"*",
"kwargs",
")",
")",
".",
"run",
"(",
")"
] | 52.333333 | 13.666667 |
def _get_socketpair(self):
"""
Return an unused socketpair, creating one if none exist.
"""
try:
return self._cls_idle_socketpairs.pop() # pop() must be atomic
except IndexError:
rsock, wsock = socket.socketpair()
set_cloexec(rsock.fileno())
... | [
"def",
"_get_socketpair",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_cls_idle_socketpairs",
".",
"pop",
"(",
")",
"# pop() must be atomic",
"except",
"IndexError",
":",
"rsock",
",",
"wsock",
"=",
"socket",
".",
"socketpair",
"(",
")",
"set_... | 36.333333 | 12.333333 |
def _basic_cancel(self, frame_in):
"""Handle a Basic Cancel frame.
:param specification.Basic.Cancel frame_in: Amqp frame.
:return:
"""
LOGGER.warning(
'Received Basic.Cancel on consumer_tag: %s',
try_utf8_decode(frame_in.consumer_tag)
)
... | [
"def",
"_basic_cancel",
"(",
"self",
",",
"frame_in",
")",
":",
"LOGGER",
".",
"warning",
"(",
"'Received Basic.Cancel on consumer_tag: %s'",
",",
"try_utf8_decode",
"(",
"frame_in",
".",
"consumer_tag",
")",
")",
"self",
".",
"remove_consumer_tag",
"(",
"frame_in",... | 29.666667 | 18.5 |
def from_records(cls, records, name=None, **kwargs):
"""Creates a new instance of self from the given (list of) record(s).
A "record" is a tuple in which each element is the value of one field
in the resulting record array. This is done by calling
`numpy.rec.fromrecords` on the given re... | [
"def",
"from_records",
"(",
"cls",
",",
"records",
",",
"name",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"obj",
"=",
"numpy",
".",
"rec",
".",
"fromrecords",
"(",
"records",
",",
"*",
"*",
"kwargs",
")",
".",
"view",
"(",
"type",
"=",
"cls... | 36.6 | 21.4 |
def cauldron_extras(self):
""" Yield extra tuples containing a field name and a callable that takes
a row
"""
for extra in super(Dimension, self).cauldron_extras:
yield extra
if self.formatters:
prop = self.id + '_raw'
else:
prop = sel... | [
"def",
"cauldron_extras",
"(",
"self",
")",
":",
"for",
"extra",
"in",
"super",
"(",
"Dimension",
",",
"self",
")",
".",
"cauldron_extras",
":",
"yield",
"extra",
"if",
"self",
".",
"formatters",
":",
"prop",
"=",
"self",
".",
"id",
"+",
"'_raw'",
"els... | 29.230769 | 17.923077 |
def fit(self, X, y=None):
"""
Fits the RFECV with the wrapped model to the specified data and draws
the rfecv curve with the optimal number of features found.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Training vector, where n_samples... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
")",
":",
"X",
",",
"y",
"=",
"check_X_y",
"(",
"X",
",",
"y",
",",
"\"csr\"",
")",
"n_features",
"=",
"X",
".",
"shape",
"[",
"1",
"]",
"# This check is kind of unnecessary since RFE will do ... | 34.471429 | 21.357143 |
def _get_reference(self):
""":return: Reference Object we point to
:raise TypeError: If this symbolic reference is detached, hence it doesn't point
to a reference, but to a commit"""
sha, target_ref_path = self._get_ref_info(self.repo, self.path)
if target_ref_path is None:
... | [
"def",
"_get_reference",
"(",
"self",
")",
":",
"sha",
",",
"target_ref_path",
"=",
"self",
".",
"_get_ref_info",
"(",
"self",
".",
"repo",
",",
"self",
".",
"path",
")",
"if",
"target_ref_path",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"\"%s is a det... | 58.625 | 21.875 |
def parse_package(self, inputstring, addhash=True):
"""Parse package code."""
if addhash:
use_hash = self.genhash(True, inputstring)
else:
use_hash = None
return self.parse(inputstring, self.file_parser, {"nl_at_eof_check": True}, {"header": "package", "use_hash":... | [
"def",
"parse_package",
"(",
"self",
",",
"inputstring",
",",
"addhash",
"=",
"True",
")",
":",
"if",
"addhash",
":",
"use_hash",
"=",
"self",
".",
"genhash",
"(",
"True",
",",
"inputstring",
")",
"else",
":",
"use_hash",
"=",
"None",
"return",
"self",
... | 46.428571 | 24.857143 |
def calc_containment(self):
"""Calculate PSF containment."""
hists = self.hists
hists_out = self._hists_eff
quantiles = [0.34, 0.68, 0.90, 0.95]
cth_axis_idx = dict(evclass=2, evtype=3)
for k in ['evclass']: # ,'evtype']:
print(k)
non = hists['... | [
"def",
"calc_containment",
"(",
"self",
")",
":",
"hists",
"=",
"self",
".",
"hists",
"hists_out",
"=",
"self",
".",
"_hists_eff",
"quantiles",
"=",
"[",
"0.34",
",",
"0.68",
",",
"0.90",
",",
"0.95",
"]",
"cth_axis_idx",
"=",
"dict",
"(",
"evclass",
"... | 39.242424 | 18.939394 |
def array(self) -> numpy.ndarray:
"""The series data of all logged |IOSequence| objects contained in
one single |numpy.ndarray| object.
The documentation on |NetCDFVariableAgg.shape| explains how
|NetCDFVariableAgg.array| is structured. The first example
confirms that, under de... | [
"def",
"array",
"(",
"self",
")",
"->",
"numpy",
".",
"ndarray",
":",
"array",
"=",
"numpy",
".",
"full",
"(",
"self",
".",
"shape",
",",
"fillvalue",
",",
"dtype",
"=",
"float",
")",
"idx0",
"=",
"0",
"idxs",
":",
"List",
"[",
"Any",
"]",
"=",
... | 44 | 18.15 |
def commatize(leafs):
"""
Accepts/turns: (Name, Name, ..., Name, Name)
Returns/into: (Name, Comma, Name, Comma, ..., Name, Comma, Name)
"""
new_leafs = []
for leaf in leafs:
new_leafs.append(leaf)
new_leafs.append(Comma())
del new_leafs[-1]
return new_leafs | [
"def",
"commatize",
"(",
"leafs",
")",
":",
"new_leafs",
"=",
"[",
"]",
"for",
"leaf",
"in",
"leafs",
":",
"new_leafs",
".",
"append",
"(",
"leaf",
")",
"new_leafs",
".",
"append",
"(",
"Comma",
"(",
")",
")",
"del",
"new_leafs",
"[",
"-",
"1",
"]"... | 26.818182 | 13.727273 |
def execute(self, command, term='xterm'):
""" Execute a command on the remote server
This method will forward traffic from the websocket to the SSH server
and the other way around.
You must connect to a SSH server using ssh_connect()
prior to starting the session.
"""
... | [
"def",
"execute",
"(",
"self",
",",
"command",
",",
"term",
"=",
"'xterm'",
")",
":",
"transport",
"=",
"self",
".",
"_ssh",
".",
"get_transport",
"(",
")",
"channel",
"=",
"transport",
".",
"open_session",
"(",
")",
"channel",
".",
"get_pty",
"(",
"te... | 34.333333 | 13.066667 |
def warnExtractFromRegexpGroups(self, line, match):
"""
Extract file name, line number, and warning text as groups (1,2,3)
of warningPattern match."""
file = match.group(1)
lineNo = match.group(2)
if lineNo is not None:
lineNo = int(lineNo)
text = matc... | [
"def",
"warnExtractFromRegexpGroups",
"(",
"self",
",",
"line",
",",
"match",
")",
":",
"file",
"=",
"match",
".",
"group",
"(",
"1",
")",
"lineNo",
"=",
"match",
".",
"group",
"(",
"2",
")",
"if",
"lineNo",
"is",
"not",
"None",
":",
"lineNo",
"=",
... | 35.7 | 9.9 |
def serial_udb_extra_f5_send(self, sue_YAWKP_AILERON, sue_YAWKD_AILERON, sue_ROLLKP, sue_ROLLKD, sue_YAW_STABILIZATION_AILERON, sue_AILERON_BOOST, force_mavlink1=False):
'''
Backwards compatible version of SERIAL_UDB_EXTRA F5: format
sue_YAWKP_AILERON : Serial UD... | [
"def",
"serial_udb_extra_f5_send",
"(",
"self",
",",
"sue_YAWKP_AILERON",
",",
"sue_YAWKD_AILERON",
",",
"sue_ROLLKP",
",",
"sue_ROLLKD",
",",
"sue_YAW_STABILIZATION_AILERON",
",",
"sue_AILERON_BOOST",
",",
"force_mavlink1",
"=",
"False",
")",
":",
"return",
"self",
"... | 91.538462 | 70.307692 |
def clone(self, data=None, shared_data=True, new_type=None, link=True,
*args, **overrides):
"""Clones the object, overriding data and parameters.
Args:
data: New data replacing the existing data
shared_data (bool, optional): Whether to use existing data
... | [
"def",
"clone",
"(",
"self",
",",
"data",
"=",
"None",
",",
"shared_data",
"=",
"True",
",",
"new_type",
"=",
"None",
",",
"link",
"=",
"True",
",",
"*",
"args",
",",
"*",
"*",
"overrides",
")",
":",
"if",
"'link_inputs'",
"in",
"overrides",
"and",
... | 45.657895 | 18.236842 |
def getAceTypeText(self, t):
'''
returns the textual representation of a acetype bit
'''
try:
return self.validAceTypes[t]['TEXT']
except KeyError:
raise CommandExecutionError((
'No ACE type "{0}". It should be one of the following: {1}'
... | [
"def",
"getAceTypeText",
"(",
"self",
",",
"t",
")",
":",
"try",
":",
"return",
"self",
".",
"validAceTypes",
"[",
"t",
"]",
"[",
"'TEXT'",
"]",
"except",
"KeyError",
":",
"raise",
"CommandExecutionError",
"(",
"(",
"'No ACE type \"{0}\". It should be one of th... | 37 | 19.8 |
def match_filtered_identities(self, fa, fb):
"""Determine if two filtered identities are the same.
The method compares the email addresses or the names of each
filtered identity to check if they are the same. When the given
filtered identities are the same object or share the same UUID,... | [
"def",
"match_filtered_identities",
"(",
"self",
",",
"fa",
",",
"fb",
")",
":",
"if",
"not",
"isinstance",
"(",
"fa",
",",
"EmailNameIdentity",
")",
":",
"raise",
"ValueError",
"(",
"\"<fa> is not an instance of UniqueIdentity\"",
")",
"if",
"not",
"isinstance",
... | 36.775 | 21.675 |
def proximal(self):
"""Return the ``proximal factory`` of the functional.
See Also
--------
odl.solvers.nonsmooth.proximal_operators.proximal_l1 :
`proximal factory` for the L1-norm.
"""
if self.pointwise_norm.exponent == 1:
return proximal_l1(spa... | [
"def",
"proximal",
"(",
"self",
")",
":",
"if",
"self",
".",
"pointwise_norm",
".",
"exponent",
"==",
"1",
":",
"return",
"proximal_l1",
"(",
"space",
"=",
"self",
".",
"domain",
")",
"elif",
"self",
".",
"pointwise_norm",
".",
"exponent",
"==",
"2",
"... | 37.4 | 16.066667 |
def default(self):
"""Default the NTP source entry from the node.
Returns:
True if the operation succeeds, otherwise False.
"""
cmd = self.command_builder('ntp source', default=True)
return self.configure(cmd) | [
"def",
"default",
"(",
"self",
")",
":",
"cmd",
"=",
"self",
".",
"command_builder",
"(",
"'ntp source'",
",",
"default",
"=",
"True",
")",
"return",
"self",
".",
"configure",
"(",
"cmd",
")"
] | 31.875 | 16.75 |
def failed_login_limit_reached(self):
""" A boolean method to check for failed login limit being reached"""
login_limit = 10
if self.failed_logins and self.failed_logins >= login_limit:
return True
else:
return False | [
"def",
"failed_login_limit_reached",
"(",
"self",
")",
":",
"login_limit",
"=",
"10",
"if",
"self",
".",
"failed_logins",
"and",
"self",
".",
"failed_logins",
">=",
"login_limit",
":",
"return",
"True",
"else",
":",
"return",
"False"
] | 38 | 15.285714 |
def switch_to_datetime_instants(df, start_year, eplus_frequency):
"""
works inplace
"""
# timestep -> monthly
if eplus_frequency in (TIMESTEP, DAILY, HOURLY, MONTHLY):
# prepare year switch
if eplus_frequency in (TIMESTEP, HOURLY, DAILY):
# print((df[["month", "day"]] - d... | [
"def",
"switch_to_datetime_instants",
"(",
"df",
",",
"start_year",
",",
"eplus_frequency",
")",
":",
"# timestep -> monthly",
"if",
"eplus_frequency",
"in",
"(",
"TIMESTEP",
",",
"DAILY",
",",
"HOURLY",
",",
"MONTHLY",
")",
":",
"# prepare year switch",
"if",
"ep... | 35.780488 | 22.780488 |
def to_source(node, indent_with=' ' * 4, add_line_information=False,
pretty_string=pretty_string, pretty_source=pretty_source):
"""This function can convert a node tree back into python sourcecode.
This is useful for debugging purposes, especially if you're dealing with
custom asts not generat... | [
"def",
"to_source",
"(",
"node",
",",
"indent_with",
"=",
"' '",
"*",
"4",
",",
"add_line_information",
"=",
"False",
",",
"pretty_string",
"=",
"pretty_string",
",",
"pretty_source",
"=",
"pretty_source",
")",
":",
"generator",
"=",
"SourceGenerator",
"(",
"i... | 47 | 22.925926 |
def get_annotation_data_between_times(self, id_tier, start, end):
"""Gives the annotations within the times.
When the tier contains reference annotations this will be returned,
check :func:`get_ref_annotation_data_between_times` for the format.
:param str id_tier: Name of the tier.
... | [
"def",
"get_annotation_data_between_times",
"(",
"self",
",",
"id_tier",
",",
"start",
",",
"end",
")",
":",
"if",
"self",
".",
"tiers",
"[",
"id_tier",
"]",
"[",
"1",
"]",
":",
"return",
"self",
".",
"get_ref_annotation_data_between_times",
"(",
"id_tier",
... | 50.705882 | 17.705882 |
def write(filename, mesh, write_binary=False):
"""Writes mdpa files, cf.
<https://github.com/KratosMultiphysics/Kratos/wiki/Input-data>.
"""
assert not write_binary
if mesh.points.shape[1] == 2:
logging.warning(
"mdpa requires 3D points, but 2D points given. "
"Append... | [
"def",
"write",
"(",
"filename",
",",
"mesh",
",",
"write_binary",
"=",
"False",
")",
":",
"assert",
"not",
"write_binary",
"if",
"mesh",
".",
"points",
".",
"shape",
"[",
"1",
"]",
"==",
"2",
":",
"logging",
".",
"warning",
"(",
"\"mdpa requires 3D poin... | 32.244898 | 20.326531 |
def get(self, request, *args, **kwargs):
"""Handle get request"""
try:
kwargs = self.load_object(kwargs)
except Exception as e:
return self.render_te_response({
'title': str(e),
})
if not self.has_permission(request):
retur... | [
"def",
"get",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"kwargs",
"=",
"self",
".",
"load_object",
"(",
"kwargs",
")",
"except",
"Exception",
"as",
"e",
":",
"return",
"self",
".",
"render_te_respon... | 33.142857 | 13.857143 |
def _build_indices(X, flann_args):
"Builds FLANN indices for each bag."
# TODO: should probably multithread this
logger.info("Building indices...")
indices = [None] * len(X)
for i, bag in enumerate(plog(X, name="index building")):
indices[i] = idx = FLANNIndex(**flann_args)
idx.build... | [
"def",
"_build_indices",
"(",
"X",
",",
"flann_args",
")",
":",
"# TODO: should probably multithread this",
"logger",
".",
"info",
"(",
"\"Building indices...\"",
")",
"indices",
"=",
"[",
"None",
"]",
"*",
"len",
"(",
"X",
")",
"for",
"i",
",",
"bag",
"in",... | 38 | 9.777778 |
def make_id(name):
"""
Create a random id combined with the creditor name.
@return string consisting of name (truncated at 22 chars), -,
12 char rand hex string.
"""
name = re.sub(r'[^a-zA-Z0-9]', '', name)
r = get_rand_string(12)
if len(name) > 22:
name = name[:22]
return na... | [
"def",
"make_id",
"(",
"name",
")",
":",
"name",
"=",
"re",
".",
"sub",
"(",
"r'[^a-zA-Z0-9]'",
",",
"''",
",",
"name",
")",
"r",
"=",
"get_rand_string",
"(",
"12",
")",
"if",
"len",
"(",
"name",
")",
">",
"22",
":",
"name",
"=",
"name",
"[",
"... | 29.272727 | 12.727273 |
def python2_round(number, ndigits=0):
"""Python 2 round function,
see: http://python3porting.com/differences.html#rounding-behavior
The behavior of round has changed in Python 3. In Python 2, rounding of
halfway cases was away from zero, and round() would always return a float.
Round a number to a ... | [
"def",
"python2_round",
"(",
"number",
",",
"ndigits",
"=",
"0",
")",
":",
"p",
"=",
"10",
"**",
"ndigits",
"return",
"float",
"(",
"math",
".",
"floor",
"(",
"(",
"number",
"*",
"p",
")",
"+",
"math",
".",
"copysign",
"(",
"0.5",
",",
"number",
... | 36.7 | 22.9 |
def resolve_secrets(self):
"""Retrieve handles for all basic:secret: fields on input.
The process must have the ``secrets`` resource requirement
specified in order to access any secrets. Otherwise this method
will raise a ``PermissionDenied`` exception.
:return: A dictionary of... | [
"def",
"resolve_secrets",
"(",
"self",
")",
":",
"secrets",
"=",
"{",
"}",
"for",
"field_schema",
",",
"fields",
"in",
"iterate_fields",
"(",
"self",
".",
"input",
",",
"self",
".",
"process",
".",
"input_schema",
")",
":",
"# pylint: disable=no-member",
"if... | 39.829268 | 23.804878 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.