text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def set_params(self, **params):
"""Set parameters on this object
Safe setter method - attributes should not be modified directly as some
changes are not valid.
Valid parameters:
- n_jobs
- verbose
Parameters
----------
params : key-value pairs of... | [
"def",
"set_params",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"if",
"'n_jobs'",
"in",
"params",
":",
"self",
".",
"n_jobs",
"=",
"params",
"[",
"'n_jobs'",
"]",
"if",
"'verbose'",
"in",
"params",
":",
"self",
".",
"verbose",
"=",
"params",
"["... | 26.666667 | 18.458333 |
def File(self, name, directory = None, create = 1):
"""Look up or create a File node with the specified name. If
the name is a relative path (begins with ./, ../, or a file name),
then it is looked up relative to the supplied directory node,
or to the top level directory of the FS (supp... | [
"def",
"File",
"(",
"self",
",",
"name",
",",
"directory",
"=",
"None",
",",
"create",
"=",
"1",
")",
":",
"return",
"self",
".",
"_lookup",
"(",
"name",
",",
"directory",
",",
"File",
",",
"create",
")"
] | 49.181818 | 19.545455 |
def format_repeated_pair_list(self, key, root_list, level):
"""
Process (possibly) repeated lists of pairs e.g. POINTs blocks
"""
lines = []
def depth(L):
return isinstance(L, (tuple, list)) and max(map(depth, L)) + 1
if depth(root_list) == 2:
#... | [
"def",
"format_repeated_pair_list",
"(",
"self",
",",
"key",
",",
"root_list",
",",
"level",
")",
":",
"lines",
"=",
"[",
"]",
"def",
"depth",
"(",
"L",
")",
":",
"return",
"isinstance",
"(",
"L",
",",
"(",
"tuple",
",",
"list",
")",
")",
"and",
"m... | 27.222222 | 21.444444 |
def delete_tasks(config, task_id):
"""Delete tasks from a project."""
if task_id is None:
msg = ("Are you sure you want to delete all the tasks and associated task runs?")
if click.confirm(msg):
res = _delete_tasks(config, task_id)
click.echo(res)
else:
... | [
"def",
"delete_tasks",
"(",
"config",
",",
"task_id",
")",
":",
"if",
"task_id",
"is",
"None",
":",
"msg",
"=",
"(",
"\"Are you sure you want to delete all the tasks and associated task runs?\"",
")",
"if",
"click",
".",
"confirm",
"(",
"msg",
")",
":",
"res",
"... | 31.769231 | 17.461538 |
def request_transaction_history(self):
""" Request full account history.
Submit a request for a full transaction history. A
successfully accepted submission results in a response
containing a URL in the Location header to a file that will
be available once the r... | [
"def",
"request_transaction_history",
"(",
"self",
")",
":",
"url",
"=",
"\"{0}/{1}/accounts/{2}/alltransactions\"",
".",
"format",
"(",
"self",
".",
"domain",
",",
"self",
".",
"API_VERSION",
",",
"self",
".",
"account_id",
")",
"try",
":",
"resp",
"=",
"self... | 40.230769 | 20.538462 |
def get_node_children(self, name):
r"""
Get the list of children structures of a node.
See :py:meth:`ptrie.Trie.get_node` for details about the structure
:param name: Parent node name
:type name: :ref:`NodeName`
:rtype: list
:raises:
* RuntimeError (... | [
"def",
"get_node_children",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"_validate_node_name",
"(",
"name",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Argument `name` is not valid\"",
")",
"self",
".",
"_node_in_tree",
"(",
"name",
")",
"return",
"[... | 30.45 | 19.8 |
def _add_entity_id(self, config, co_name):
"""
Use the CO name to construct the entity ID for the virtual IdP
for the CO.
The entity ID has the form
{base_entity_id}/{co_name}
:type config: satosa.satosa_config.SATOSAConfig
:type co_name: str
:rtype: sa... | [
"def",
"_add_entity_id",
"(",
"self",
",",
"config",
",",
"co_name",
")",
":",
"base_entity_id",
"=",
"config",
"[",
"'entityid'",
"]",
"co_entity_id",
"=",
"\"{}/{}\"",
".",
"format",
"(",
"base_entity_id",
",",
"quote_plus",
"(",
"co_name",
")",
")",
"conf... | 28.217391 | 18.130435 |
def add(self, key, metric, **dims):
"""Adds custom metric instances to the registry with dimensions
which are not created with their constructors default arguments
"""
return super(MetricsRegistry, self).add(
self.metadata.register(key, **dims), metric) | [
"def",
"add",
"(",
"self",
",",
"key",
",",
"metric",
",",
"*",
"*",
"dims",
")",
":",
"return",
"super",
"(",
"MetricsRegistry",
",",
"self",
")",
".",
"add",
"(",
"self",
".",
"metadata",
".",
"register",
"(",
"key",
",",
"*",
"*",
"dims",
")",... | 48.666667 | 10 |
def _get_mapping(self, line, parser=None, previous=None):
'''mapping will take the command from a Dockerfile and return a map
function to add it to the appropriate place. Any lines that don't
cleanly map are assumed to be comments.
Parameters
==========
li... | [
"def",
"_get_mapping",
"(",
"self",
",",
"line",
",",
"parser",
"=",
"None",
",",
"previous",
"=",
"None",
")",
":",
"# Split the command into cleanly the command and rest",
"if",
"not",
"isinstance",
"(",
"line",
",",
"list",
")",
":",
"line",
"=",
"self",
... | 33.222222 | 18 |
def round_dict(dic, places):
"""
Rounds all values in a dict containing only numeric types to `places` decimal places.
If places is None, round to INT.
"""
if places is None:
for key, value in dic.items():
dic[key] = round(value)
else:
for key, value in dic.items():
... | [
"def",
"round_dict",
"(",
"dic",
",",
"places",
")",
":",
"if",
"places",
"is",
"None",
":",
"for",
"key",
",",
"value",
"in",
"dic",
".",
"items",
"(",
")",
":",
"dic",
"[",
"key",
"]",
"=",
"round",
"(",
"value",
")",
"else",
":",
"for",
"key... | 32 | 11.454545 |
def apply_sql_script(conn, fname):
"""
Apply the given SQL script to the database
:param conn: a DB API 2 connection
:param fname: full path to the creation script
"""
sql = open(fname).read()
try:
# we cannot use conn.executescript which is non transactional
for query in sq... | [
"def",
"apply_sql_script",
"(",
"conn",
",",
"fname",
")",
":",
"sql",
"=",
"open",
"(",
"fname",
")",
".",
"read",
"(",
")",
"try",
":",
"# we cannot use conn.executescript which is non transactional",
"for",
"query",
"in",
"sql",
".",
"split",
"(",
"'\\n\\n'... | 29.466667 | 13.6 |
def format_key_from_backend(self, key):
"""Strip the configured prefix from a key retrieved from the backend
before passing it on to other pghoard code and presenting it to the
user."""
if not self.prefix:
return key
if not key.startswith(self.prefix):
rai... | [
"def",
"format_key_from_backend",
"(",
"self",
",",
"key",
")",
":",
"if",
"not",
"self",
".",
"prefix",
":",
"return",
"key",
"if",
"not",
"key",
".",
"startswith",
"(",
"self",
".",
"prefix",
")",
":",
"raise",
"StorageError",
"(",
"\"Key {!r} does not s... | 49.222222 | 15.666667 |
def mixedToUnder(s): # pragma: no cover
"""
Sample:
>>> mixedToUnder("FooBarBaz")
'foo_bar_baz'
Special case for ID:
>>> mixedToUnder("FooBarID")
'foo_bar_id'
"""
if s.endswith('ID'):
return mixedToUnder(s[:-2] + "_id")
trans = _mixedToUnderRE.sub(mixedT... | [
"def",
"mixedToUnder",
"(",
"s",
")",
":",
"# pragma: no cover",
"if",
"s",
".",
"endswith",
"(",
"'ID'",
")",
":",
"return",
"mixedToUnder",
"(",
"s",
"[",
":",
"-",
"2",
"]",
"+",
"\"_id\"",
")",
"trans",
"=",
"_mixedToUnderRE",
".",
"sub",
"(",
"m... | 24.4375 | 13.1875 |
def get_device_configs():
'''
Return a `pandas.DataFrame`, where each row corresponds to an available
device configuration, including the `device` (i.e., the name of the
device).
'''
frames = []
for i in range(2):
for device in get_video_sources():
df_device_i = get_conf... | [
"def",
"get_device_configs",
"(",
")",
":",
"frames",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"2",
")",
":",
"for",
"device",
"in",
"get_video_sources",
"(",
")",
":",
"df_device_i",
"=",
"get_configs",
"(",
"device",
")",
"df_device_i",
".",
"i... | 36.052632 | 22.263158 |
def get_object_from_path(path):
"""
Import's object from given Python path.
"""
try:
return sys.IMPORT_CACHE[path]
except KeyError:
_path = path.split('.')
module_path = '.'.join(_path[:-1])
class_name = _path[-1]
module = importlib.import_module(module_path)
... | [
"def",
"get_object_from_path",
"(",
"path",
")",
":",
"try",
":",
"return",
"sys",
".",
"IMPORT_CACHE",
"[",
"path",
"]",
"except",
"KeyError",
":",
"_path",
"=",
"path",
".",
"split",
"(",
"'.'",
")",
"module_path",
"=",
"'.'",
".",
"join",
"(",
"_pat... | 31.230769 | 9.538462 |
def bsrch(self, domain):
"""
This function uses the Bloomberg API to retrieve 'bsrch' (Bloomberg
SRCH Data) queries. Returns list of tickers.
Parameters
----------
domain: string
A character string with the name of the domain to execute.
It can be... | [
"def",
"bsrch",
"(",
"self",
",",
"domain",
")",
":",
"logger",
"=",
"_get_logger",
"(",
"self",
".",
"debug",
")",
"request",
"=",
"self",
".",
"exrService",
".",
"createRequest",
"(",
"'ExcelGetGridRequest'",
")",
"request",
".",
"set",
"(",
"'Domain'",
... | 41.068966 | 20.37931 |
def build_groups(self, tokens):
"""Build dict of groups from list of tokens"""
groups = {}
for token in tokens:
match_type = MatchType.start if token.group_end else MatchType.single
groups[token.group_start] = (token, match_type)
if token.group_end:
... | [
"def",
"build_groups",
"(",
"self",
",",
"tokens",
")",
":",
"groups",
"=",
"{",
"}",
"for",
"token",
"in",
"tokens",
":",
"match_type",
"=",
"MatchType",
".",
"start",
"if",
"token",
".",
"group_end",
"else",
"MatchType",
".",
"single",
"groups",
"[",
... | 43.111111 | 17.111111 |
def plot_gate_map(backend, figsize=None,
plot_directed=False,
label_qubits=True,
qubit_size=24,
line_width=4,
font_size=12,
qubit_color=None,
line_color=None,
font_color='w'):
... | [
"def",
"plot_gate_map",
"(",
"backend",
",",
"figsize",
"=",
"None",
",",
"plot_directed",
"=",
"False",
",",
"label_qubits",
"=",
"True",
",",
"qubit_size",
"=",
"24",
",",
"line_width",
"=",
"4",
",",
"font_size",
"=",
"12",
",",
"qubit_color",
"=",
"N... | 36.6375 | 18.45625 |
def get_attribute_value(
self, tag_name, attribute, format_value=False, **attribute_filter
):
"""
Return the attribute value in xml files which matches the tag name and the specific attribute
:param str tag_name: specify the tag name
:param str attribute: specify the attribu... | [
"def",
"get_attribute_value",
"(",
"self",
",",
"tag_name",
",",
"attribute",
",",
"format_value",
"=",
"False",
",",
"*",
"*",
"attribute_filter",
")",
":",
"for",
"value",
"in",
"self",
".",
"get_all_attribute_value",
"(",
"tag_name",
",",
"attribute",
",",
... | 40.066667 | 23.8 |
def GetEntries(self, parser_mediator, match=None, **unused_kwargs):
"""Extracts relevant BT entries.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
match (Optional[dict[str: object]]): keys extracted from PLIS... | [
"def",
"GetEntries",
"(",
"self",
",",
"parser_mediator",
",",
"match",
"=",
"None",
",",
"*",
"*",
"unused_kwargs",
")",
":",
"device_cache",
"=",
"match",
".",
"get",
"(",
"'DeviceCache'",
",",
"{",
"}",
")",
"for",
"device",
",",
"value",
"in",
"ite... | 41.538462 | 22.480769 |
def fix_germline_samplename(in_file, sample_name, data):
"""Replace germline sample names, originally from normal BAM file.
"""
out_file = "%s-fixnames%s" % utils.splitext_plus(in_file)
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
sample_f... | [
"def",
"fix_germline_samplename",
"(",
"in_file",
",",
"sample_name",
",",
"data",
")",
":",
"out_file",
"=",
"\"%s-fixnames%s\"",
"%",
"utils",
".",
"splitext_plus",
"(",
"in_file",
")",
"if",
"not",
"utils",
".",
"file_exists",
"(",
"out_file",
")",
":",
"... | 59.416667 | 19.833333 |
def _prepare_batch_request(self):
"""Prepares headers and body for a batch request.
:rtype: tuple (dict, str)
:returns: The pair of headers and body of the batch request to be sent.
:raises: :class:`ValueError` if no requests have been deferred.
"""
if len(self._requests... | [
"def",
"_prepare_batch_request",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"_requests",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"No deferred requests\"",
")",
"multi",
"=",
"MIMEMultipart",
"(",
")",
"for",
"method",
",",
"uri",
",",... | 35.321429 | 16.678571 |
def unregister_model(self, storagemodel:object, modeldefinition = None, delete_queue=False):
""" clear up an Queueservice for an StorageQueueModel in your Azure Storage Account
Will delete the hole Queue if delete_queue Flag is True!
required Parameter is:
- storag... | [
"def",
"unregister_model",
"(",
"self",
",",
"storagemodel",
":",
"object",
",",
"modeldefinition",
"=",
"None",
",",
"delete_queue",
"=",
"False",
")",
":",
"\"\"\" remove from modeldefinitions \"\"\"",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
... | 43.956522 | 24.565217 |
def remove_disk_encryption_password(self, id_p):
"""Removes a password used for hard disk encryption/decryption from
the running VM. As soon as the medium requiring this password
is accessed the VM is paused with an error and the password must be
provided again.
in id_p of type ... | [
"def",
"remove_disk_encryption_password",
"(",
"self",
",",
"id_p",
")",
":",
"if",
"not",
"isinstance",
"(",
"id_p",
",",
"basestring",
")",
":",
"raise",
"TypeError",
"(",
"\"id_p can only be an instance of type basestring\"",
")",
"self",
".",
"_call",
"(",
"\"... | 44.2 | 19.4 |
def __definitions_descriptor(self):
"""Describes the definitions section of the OpenAPI spec.
Returns:
Dictionary describing the definitions of the spec.
"""
# Filter out any keys that aren't 'properties' or 'type'
result = {}
for def_key, def_value in self.__parser.schemas().iteritems():... | [
"def",
"__definitions_descriptor",
"(",
"self",
")",
":",
"# Filter out any keys that aren't 'properties' or 'type'",
"result",
"=",
"{",
"}",
"for",
"def_key",
",",
"def_value",
"in",
"self",
".",
"__parser",
".",
"schemas",
"(",
")",
".",
"iteritems",
"(",
")",
... | 38.714286 | 14.257143 |
def _put_attributes_using_post(self, domain_or_name, item_name, attributes,
replace=True, expected_value=None):
"""
Monkey-patched version of SDBConnection.put_attributes that uses POST instead of GET
The GET version is subject to the URL length limit which kicks in before th... | [
"def",
"_put_attributes_using_post",
"(",
"self",
",",
"domain_or_name",
",",
"item_name",
",",
"attributes",
",",
"replace",
"=",
"True",
",",
"expected_value",
"=",
"None",
")",
":",
"domain",
",",
"domain_name",
"=",
"self",
".",
"get_domain_and_name",
"(",
... | 49.166667 | 24.166667 |
def bias(self):
"""
Frequency Bias.
Formula: (a+b)/(a+c)"""
return (self.table[0, 0] + self.table[0, 1]) / (self.table[0, 0] + self.table[1, 0]) | [
"def",
"bias",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"table",
"[",
"0",
",",
"0",
"]",
"+",
"self",
".",
"table",
"[",
"0",
",",
"1",
"]",
")",
"/",
"(",
"self",
".",
"table",
"[",
"0",
",",
"0",
"]",
"+",
"self",
".",
"table... | 34.6 | 18.8 |
def _run_main(main, argv):
"""Calls main, optionally with pdb or profiler."""
if FLAGS.run_with_pdb:
sys.exit(pdb.runcall(main, argv))
elif FLAGS.run_with_profiling or FLAGS.profile_file:
# Avoid import overhead since most apps (including performance-sensitive
# ones) won't be run with profiling.
... | [
"def",
"_run_main",
"(",
"main",
",",
"argv",
")",
":",
"if",
"FLAGS",
".",
"run_with_pdb",
":",
"sys",
".",
"exit",
"(",
"pdb",
".",
"runcall",
"(",
"main",
",",
"argv",
")",
")",
"elif",
"FLAGS",
".",
"run_with_profiling",
"or",
"FLAGS",
".",
"prof... | 32.904762 | 14.904762 |
def simulate(sim_type: str,
num_qubits: int,
num_gates: int,
num_prefix_qubits: int = 0,
use_processes: bool = False) -> None:
""""Runs the simulator."""
circuit = cirq.Circuit(device=test_device)
for _ in range(num_gates):
which = np.random.choic... | [
"def",
"simulate",
"(",
"sim_type",
":",
"str",
",",
"num_qubits",
":",
"int",
",",
"num_gates",
":",
"int",
",",
"num_prefix_qubits",
":",
"int",
"=",
"0",
",",
"use_processes",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"circuit",
"=",
"cirq"... | 40.205882 | 14.617647 |
def hjorth(X, D=None):
""" Compute Hjorth mobility and complexity of a time series from either two
cases below:
1. X, the time series of type list (default)
2. D, a first order differential sequence of X (if D is provided,
recommended to speed up)
In case 1, D is computed using N... | [
"def",
"hjorth",
"(",
"X",
",",
"D",
"=",
"None",
")",
":",
"if",
"D",
"is",
"None",
":",
"D",
"=",
"numpy",
".",
"diff",
"(",
"X",
")",
"D",
"=",
"D",
".",
"tolist",
"(",
")",
"D",
".",
"insert",
"(",
"0",
",",
"X",
"[",
"0",
"]",
")",... | 20.589286 | 25.553571 |
def update_dist_caches(dist_path, fix_zipimporter_caches):
"""
Fix any globally cached `dist_path` related data
`dist_path` should be a path of a newly installed egg distribution (zipped
or unzipped).
sys.path_importer_cache contains finder objects that have been cached when
importing data fro... | [
"def",
"update_dist_caches",
"(",
"dist_path",
",",
"fix_zipimporter_caches",
")",
":",
"# There are several other known sources of stale zipimport.zipimporter",
"# instances that we do not clear here, but might if ever given a reason to",
"# do so:",
"# * Global setuptools pkg_resources.worki... | 58.475 | 30.325 |
def subcache(self, path):
"""Clone this case, and extend the prefix"""
cache = self.clone()
cache.prefix = os.path.join(cache.prefix if cache.prefix else '', path)
return cache | [
"def",
"subcache",
"(",
"self",
",",
"path",
")",
":",
"cache",
"=",
"self",
".",
"clone",
"(",
")",
"cache",
".",
"prefix",
"=",
"os",
".",
"path",
".",
"join",
"(",
"cache",
".",
"prefix",
"if",
"cache",
".",
"prefix",
"else",
"''",
",",
"path"... | 29.142857 | 23.714286 |
def sprint(self, id):
"""Return the information about a sprint.
:param sprint_id: the sprint retrieving issues from
:type sprint_id: int
:rtype: :class:`~jira.resources.Sprint`
"""
sprint = Sprint(self._options, self._session)
sprint.find(id)
return spr... | [
"def",
"sprint",
"(",
"self",
",",
"id",
")",
":",
"sprint",
"=",
"Sprint",
"(",
"self",
".",
"_options",
",",
"self",
".",
"_session",
")",
"sprint",
".",
"find",
"(",
"id",
")",
"return",
"sprint"
] | 26 | 18.833333 |
def get_attachment_data(attachmentTable, sql,
nameField="ATT_NAME", blobField="DATA",
contentTypeField="CONTENT_TYPE",
rel_object_field="REL_OBJECTID"):
""" gets all the data to pass to a feature service """
if arcpyFound == False:
... | [
"def",
"get_attachment_data",
"(",
"attachmentTable",
",",
"sql",
",",
"nameField",
"=",
"\"ATT_NAME\"",
",",
"blobField",
"=",
"\"DATA\"",
",",
"contentTypeField",
"=",
"\"CONTENT_TYPE\"",
",",
"rel_object_field",
"=",
"\"REL_OBJECTID\"",
")",
":",
"if",
"arcpyFoun... | 38.413793 | 12.551724 |
def _collect_classical_memory_write_locations(program: Program) -> List[Optional[Tuple[int, int]]]:
"""Collect classical memory locations that are the destination of MEASURE instructions
These locations are important for munging output buffers returned from the QPU
server to the shape expected by the user.... | [
"def",
"_collect_classical_memory_write_locations",
"(",
"program",
":",
"Program",
")",
"->",
"List",
"[",
"Optional",
"[",
"Tuple",
"[",
"int",
",",
"int",
"]",
"]",
"]",
":",
"ro_size",
"=",
"None",
"for",
"instr",
"in",
"program",
":",
"if",
"isinstanc... | 47.8 | 23.955556 |
def set_all_vlan_states(self, nexus_host, vlanid_range):
"""Set the VLAN states to active."""
starttime = time.time()
if not vlanid_range:
LOG.warning("Exiting set_all_vlan_states: "
"No vlans to configure")
return
# Eliminate possible w... | [
"def",
"set_all_vlan_states",
"(",
"self",
",",
"nexus_host",
",",
"vlanid_range",
")",
":",
"starttime",
"=",
"time",
".",
"time",
"(",
")",
"if",
"not",
"vlanid_range",
":",
"LOG",
".",
"warning",
"(",
"\"Exiting set_all_vlan_states: \"",
"\"No vlans to configur... | 36.837838 | 17.216216 |
async def answer_callback_query(self, callback_query_id: base.String,
text: typing.Union[base.String, None] = None,
show_alert: typing.Union[base.Boolean, None] = None,
url: typing.Union[base.String, None] = None... | [
"async",
"def",
"answer_callback_query",
"(",
"self",
",",
"callback_query_id",
":",
"base",
".",
"String",
",",
"text",
":",
"typing",
".",
"Union",
"[",
"base",
".",
"String",
",",
"None",
"]",
"=",
"None",
",",
"show_alert",
":",
"typing",
".",
"Union... | 61.352941 | 33.882353 |
def _pkl_magseries_plot(stimes, smags, serrs,
plotdpi=100,
magsarefluxes=False):
'''This returns the magseries plot PNG as base64, plus arrays as dict.
Parameters
----------
stimes,smags,serrs : np.array
The mag/flux time-series arrays along with... | [
"def",
"_pkl_magseries_plot",
"(",
"stimes",
",",
"smags",
",",
"serrs",
",",
"plotdpi",
"=",
"100",
",",
"magsarefluxes",
"=",
"False",
")",
":",
"scaledplottime",
"=",
"stimes",
"-",
"npmin",
"(",
"stimes",
")",
"# open the figure instance",
"magseriesfig",
... | 27.942308 | 22.019231 |
def try_next(self):
"""
Like next(), but only returns the item that would be selected
right now, without locking and without changing the queue.
"""
with self.condition:
try:
return self.force[0]
except IndexError:
pass
... | [
"def",
"try_next",
"(",
"self",
")",
":",
"with",
"self",
".",
"condition",
":",
"try",
":",
"return",
"self",
".",
"force",
"[",
"0",
"]",
"except",
"IndexError",
":",
"pass",
"return",
"self",
".",
"_get_next",
"(",
"False",
")"
] | 28.833333 | 15.5 |
def _energy_evaluation(self, operator):
"""
Evaluate the energy of the current input circuit with respect to the given operator.
:param operator: Hamiltonian of the system
:return: Energy of the Hamiltonian
"""
if self._quantum_state is not None:
input_circu... | [
"def",
"_energy_evaluation",
"(",
"self",
",",
"operator",
")",
":",
"if",
"self",
".",
"_quantum_state",
"is",
"not",
"None",
":",
"input_circuit",
"=",
"self",
".",
"_quantum_state",
"else",
":",
"input_circuit",
"=",
"[",
"self",
".",
"opt_circuit",
"]",
... | 43.238095 | 22.190476 |
def get_subsites(self):
""" Returns a list of subsites defined for this site
:rtype: list[Site]
"""
url = self.build_url(
self._endpoints.get('get_subsites').format(id=self.object_id))
response = self.con.get(url)
if not response:
return []
... | [
"def",
"get_subsites",
"(",
"self",
")",
":",
"url",
"=",
"self",
".",
"build_url",
"(",
"self",
".",
"_endpoints",
".",
"get",
"(",
"'get_subsites'",
")",
".",
"format",
"(",
"id",
"=",
"self",
".",
"object_id",
")",
")",
"response",
"=",
"self",
".... | 31.647059 | 21.705882 |
def purge():
"""Removes all files generated by Blended"""
print("Purging the Blended files!")
# Remove the templates folder
templ_dir = os.path.join(cwd, "templates")
if os.path.exists(templ_dir):
shutil.rmtree(templ_dir)
# Remove the content folder
cont_dir = os.path.join(cwd, "co... | [
"def",
"purge",
"(",
")",
":",
"print",
"(",
"\"Purging the Blended files!\"",
")",
"# Remove the templates folder",
"templ_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"cwd",
",",
"\"templates\"",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"templ_... | 29.484848 | 14.212121 |
def link_contentkey_authorization_policy(access_token, ckap_id, options_id, \
ams_redirected_rest_endpoint):
'''Link Media Service Content Key Authorization Policy.
Args:
access_token (str): A valid Azure authentication token.
ckap_id (str): A Media Service Asset Content Key Authorization Polic... | [
"def",
"link_contentkey_authorization_policy",
"(",
"access_token",
",",
"ckap_id",
",",
"options_id",
",",
"ams_redirected_rest_endpoint",
")",
":",
"path",
"=",
"'/ContentKeyAuthorizationPolicies'",
"full_path",
"=",
"''",
".",
"join",
"(",
"[",
"path",
",",
"\"('\"... | 48.809524 | 28.428571 |
def on_item_toggled(self, index, state=None):
"""An item is requesting to be toggled"""
if not index.data(model.IsIdle):
return self.info("Cannot toggle")
if not index.data(model.IsOptional):
return self.info("This item is mandatory")
if state is None:
... | [
"def",
"on_item_toggled",
"(",
"self",
",",
"index",
",",
"state",
"=",
"None",
")",
":",
"if",
"not",
"index",
".",
"data",
"(",
"model",
".",
"IsIdle",
")",
":",
"return",
"self",
".",
"info",
"(",
"\"Cannot toggle\"",
")",
"if",
"not",
"index",
".... | 40.631579 | 16.657895 |
def restore_flattened_dict(i):
"""
Input: {
dict - flattened dict
}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
dict - restored dict
... | [
"def",
"restore_flattened_dict",
"(",
"i",
")",
":",
"# Check vars",
"a",
"=",
"{",
"}",
"# default",
"b",
"=",
"i",
"[",
"'dict'",
"]",
"first",
"=",
"True",
"for",
"x",
"in",
"b",
":",
"if",
"first",
":",
"first",
"=",
"False",
"y",
"=",
"x",
"... | 22.111111 | 19.222222 |
def get_lr_scheduler(learning_rate, lr_refactor_step, lr_refactor_ratio,
num_example, batch_size, begin_epoch):
"""
Compute learning rate and refactor scheduler
Parameters:
---------
learning_rate : float
original learning rate
lr_refactor_step : comma separated str... | [
"def",
"get_lr_scheduler",
"(",
"learning_rate",
",",
"lr_refactor_step",
",",
"lr_refactor_ratio",
",",
"num_example",
",",
"batch_size",
",",
"begin_epoch",
")",
":",
"assert",
"lr_refactor_ratio",
">",
"0",
"iter_refactor",
"=",
"[",
"int",
"(",
"r",
")",
"fo... | 35.268293 | 18.780488 |
def nx_topsort_rank(graph, nodes=None):
"""
graph = inputs.exi_graph.reverse()
nodes = flat_node_order_
"""
import utool as ut
if False:
# Determenistic version
# Ok, this doesn't work.
dag_ranks = nx_dag_node_rank(graph, nodes)
toprank = ut.argsort(dag_ranks, lis... | [
"def",
"nx_topsort_rank",
"(",
"graph",
",",
"nodes",
"=",
"None",
")",
":",
"import",
"utool",
"as",
"ut",
"if",
"False",
":",
"# Determenistic version",
"# Ok, this doesn't work.",
"dag_ranks",
"=",
"nx_dag_node_rank",
"(",
"graph",
",",
"nodes",
")",
"toprank... | 34 | 11.684211 |
def describe(self, **kwargs):
"""Describe this parameter instance for purpose of self-documentation.
Args:
kwargs (dict): dictionary of additional description items for
extending default description
Returns:
dict: dictionary of description items
... | [
"def",
"describe",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"description",
"=",
"{",
"'label'",
":",
"self",
".",
"label",
",",
"# note: details are expected to be large so it should",
"# be reformatted",
"'details'",
":",
"inspect",
".",
"cleandoc",
... | 32.138889 | 19.666667 |
def get_config(self, service, setting):
"""
Access the configuration for a given service and setting. If the
service is not found, return a default value.
"""
try:
return self.get_service(service)[setting]
except KeyError:
return getattr(self, sett... | [
"def",
"get_config",
"(",
"self",
",",
"service",
",",
"setting",
")",
":",
"try",
":",
"return",
"self",
".",
"get_service",
"(",
"service",
")",
"[",
"setting",
"]",
"except",
"KeyError",
":",
"return",
"getattr",
"(",
"self",
",",
"setting",
"+",
"'... | 36.555556 | 13 |
def _filter_paired(tumor, normal, out_file, reference, data):
"""filter paired vcf file with GATK
:param tumor: (str) sample name for tumor
:param normal: (str) sample name for normal
:param out_file: (str) final vcf file
:param reference: (str) genome in fasta format
:param data:... | [
"def",
"_filter_paired",
"(",
"tumor",
",",
"normal",
",",
"out_file",
",",
"reference",
",",
"data",
")",
":",
"in_file",
"=",
"utils",
".",
"splitext_plus",
"(",
"out_file",
")",
"[",
"0",
"]",
"+",
"\"-tmp.vcf\"",
"shutil",
".",
"move",
"(",
"out_file... | 49.222222 | 15.555556 |
def register_observer(self, observer, events=None):
"""Register a listener function.
:param observer: external listener function
:param events: tuple or list of relevant events (default=None)
"""
if events is not None and not isinstance(events, (tuple, list)):
events... | [
"def",
"register_observer",
"(",
"self",
",",
"observer",
",",
"events",
"=",
"None",
")",
":",
"if",
"events",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"events",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"events",
"=",
"(",
"events... | 41.230769 | 17.461538 |
def create_subkey(primary_bytes, subkey, signer_func, secret_bytes=b''):
"""Export new subkey to GPG primary key."""
subkey_packet = protocol.packet(tag=(7 if secret_bytes else 14),
blob=(subkey.data() + secret_bytes))
packets = list(decode.parse_packets(io.BytesIO(primar... | [
"def",
"create_subkey",
"(",
"primary_bytes",
",",
"subkey",
",",
"signer_func",
",",
"secret_bytes",
"=",
"b''",
")",
":",
"subkey_packet",
"=",
"protocol",
".",
"packet",
"(",
"tag",
"=",
"(",
"7",
"if",
"secret_bytes",
"else",
"14",
")",
",",
"blob",
... | 39.45283 | 18.490566 |
def start_daemon_thread(target, args=()):
"""starts a deamon thread for a given target function and arguments."""
th = Thread(target=target, args=args)
th.daemon = True
th.start()
return th | [
"def",
"start_daemon_thread",
"(",
"target",
",",
"args",
"=",
"(",
")",
")",
":",
"th",
"=",
"Thread",
"(",
"target",
"=",
"target",
",",
"args",
"=",
"args",
")",
"th",
".",
"daemon",
"=",
"True",
"th",
".",
"start",
"(",
")",
"return",
"th"
] | 34 | 12.5 |
def find_existing_configs(self, default):
'''
Find configuration files on the system.
:return:
'''
configs = []
for cfg in [default, self._config_filename_, 'minion', 'proxy', 'cloud', 'spm']:
if not cfg:
continue
config_path = self... | [
"def",
"find_existing_configs",
"(",
"self",
",",
"default",
")",
":",
"configs",
"=",
"[",
"]",
"for",
"cfg",
"in",
"[",
"default",
",",
"self",
".",
"_config_filename_",
",",
"'minion'",
",",
"'proxy'",
",",
"'cloud'",
",",
"'spm'",
"]",
":",
"if",
"... | 33 | 21 |
def autocorr_coeff(x, t, tau1, tau2):
"""Calculate the autocorrelation coefficient."""
return corr_coeff(x, x, t, tau1, tau2) | [
"def",
"autocorr_coeff",
"(",
"x",
",",
"t",
",",
"tau1",
",",
"tau2",
")",
":",
"return",
"corr_coeff",
"(",
"x",
",",
"x",
",",
"t",
",",
"tau1",
",",
"tau2",
")"
] | 44.333333 | 1.333333 |
def toString(val, join_char='\n'):
"""
Turn a string or array value into a string.
"""
if type(val) in (list, tuple):
return join_char.join(val)
return val | [
"def",
"toString",
"(",
"val",
",",
"join_char",
"=",
"'\\n'",
")",
":",
"if",
"type",
"(",
"val",
")",
"in",
"(",
"list",
",",
"tuple",
")",
":",
"return",
"join_char",
".",
"join",
"(",
"val",
")",
"return",
"val"
] | 28.714286 | 6.142857 |
def _maybe_remove_implicit_api(self, template):
"""
Implicit API resource are tentatively added to the template for uniform handling of both Implicit & Explicit
APIs. They need to removed from the template, if there are *no* API events attached to this resource.
This method removes the I... | [
"def",
"_maybe_remove_implicit_api",
"(",
"self",
",",
"template",
")",
":",
"# Remove Implicit API resource if no paths got added",
"implicit_api_resource",
"=",
"template",
".",
"get",
"(",
"self",
".",
"implicit_api_logical_id",
")",
"if",
"implicit_api_resource",
"and",... | 57.052632 | 35.789474 |
def cmd_add_label(docid, label_name, color=None):
"""
Arguments: <document_id> <label_name> [<label_color>]
Add a label on a document.
Color must be specified if the label doesn't exist yet.
Color will be ignored if the label already exists.
Color format must be given in hexadecimal format. Ex... | [
"def",
"cmd_add_label",
"(",
"docid",
",",
"label_name",
",",
"color",
"=",
"None",
")",
":",
"dsearch",
"=",
"get_docsearch",
"(",
")",
"doc",
"=",
"dsearch",
".",
"get",
"(",
"docid",
")",
"if",
"doc",
"is",
"None",
":",
"raise",
"Exception",
"(",
... | 26.529412 | 20.098039 |
def get_current_url(environ, root_only=False, strip_querystring=False, host_only=False):
"""A handy helper function that recreates the full URL for the current
request or parts of it. Here an example:
>>> from werkzeug import create_environ
>>> env = create_environ("/?param=foo", "http://localhost/scr... | [
"def",
"get_current_url",
"(",
"environ",
",",
"root_only",
"=",
"False",
",",
"strip_querystring",
"=",
"False",
",",
"host_only",
"=",
"False",
")",
":",
"tmp",
"=",
"[",
"environ",
"[",
"\"wsgi.url_scheme\"",
"]",
",",
"\"://\"",
",",
"get_host",
"(",
"... | 39.588235 | 18.029412 |
def scan(self, thing, thing_type=None, blocking=False):
"""
\nScan a single or list of URLs, or Domains\n
NOTE: URLs must include the scheme (http:// or https://)\n
NOTE: For a single domain or list of domains this method will automatically append an 'http://' to the \n
beginning... | [
"def",
"scan",
"(",
"self",
",",
"thing",
",",
"thing_type",
"=",
"None",
",",
"blocking",
"=",
"False",
")",
":",
"thing_id",
"=",
"self",
".",
"_whatis",
"(",
"thing",
")",
"if",
"thing_type",
"is",
"None",
":",
"thing_type",
"=",
"thing_id",
"query_... | 43.1 | 21.611111 |
def ssrStatusWS(symbols=None, on_data=None):
'''https://iextrading.com/developer/docs/#short-sale-price-test-status'''
symbols = _strToList(symbols)
sendinit = ({'symbols': symbols, 'channels': ['ssr']},)
return _stream(_wsURL('deep'), sendinit, on_data) | [
"def",
"ssrStatusWS",
"(",
"symbols",
"=",
"None",
",",
"on_data",
"=",
"None",
")",
":",
"symbols",
"=",
"_strToList",
"(",
"symbols",
")",
"sendinit",
"=",
"(",
"{",
"'symbols'",
":",
"symbols",
",",
"'channels'",
":",
"[",
"'ssr'",
"]",
"}",
",",
... | 53.2 | 16 |
def conferences(self):
"""
Access the conferences
:returns: twilio.rest.api.v2010.account.conference.ConferenceList
:rtype: twilio.rest.api.v2010.account.conference.ConferenceList
"""
if self._conferences is None:
self._conferences = ConferenceList(self._vers... | [
"def",
"conferences",
"(",
"self",
")",
":",
"if",
"self",
".",
"_conferences",
"is",
"None",
":",
"self",
".",
"_conferences",
"=",
"ConferenceList",
"(",
"self",
".",
"_version",
",",
"account_sid",
"=",
"self",
".",
"_solution",
"[",
"'sid'",
"]",
","... | 38.5 | 20.1 |
async def async_change_device(
self, device_id: int, group_number: int, unit_number: int,
enable_status: ESFlags, switches: SwitchFlags) -> None:
"""
Change settings for a device on the base unit.
:param device_id: unique identifier for the device to be changed
:... | [
"async",
"def",
"async_change_device",
"(",
"self",
",",
"device_id",
":",
"int",
",",
"group_number",
":",
"int",
",",
"unit_number",
":",
"int",
",",
"enable_status",
":",
"ESFlags",
",",
"switches",
":",
"SwitchFlags",
")",
"->",
"None",
":",
"# Lookup de... | 52.567568 | 24.72973 |
def p_chr_one(p):
""" string : CHR bexpr %prec UMINUS
"""
arg_list = make_arg_list(make_argument(p[2], p.lineno(1)))
arg_list[0].value = make_typecast(TYPE.ubyte, arg_list[0].value, p.lineno(1))
p[0] = make_builtin(p.lineno(1), 'CHR', arg_list, type_=TYPE.string) | [
"def",
"p_chr_one",
"(",
"p",
")",
":",
"arg_list",
"=",
"make_arg_list",
"(",
"make_argument",
"(",
"p",
"[",
"2",
"]",
",",
"p",
".",
"lineno",
"(",
"1",
")",
")",
")",
"arg_list",
"[",
"0",
"]",
".",
"value",
"=",
"make_typecast",
"(",
"TYPE",
... | 46.333333 | 19.666667 |
def eval_basis(self, x, regularize=True):
"""
basis_mat = C.eval_basis(x)
Evaluates self's basis functions on x and returns them stacked
in a matrix. basis_mat[i,j] gives basis function i evaluated at
x[j,:].
"""
if regularize:
x = regularize_array(x)... | [
"def",
"eval_basis",
"(",
"self",
",",
"x",
",",
"regularize",
"=",
"True",
")",
":",
"if",
"regularize",
":",
"x",
"=",
"regularize_array",
"(",
"x",
")",
"out",
"=",
"zeros",
"(",
"(",
"self",
".",
"n",
",",
"x",
".",
"shape",
"[",
"0",
"]",
... | 28.117647 | 20.117647 |
def getShocks(self):
'''
Draws a new Markov state and income shocks for the representative agent.
Parameters
----------
None
Returns
-------
None
'''
cutoffs = np.cumsum(self.MrkvArray[self.MrkvNow,:])
MrkvDraw = drawUniform(N=1,s... | [
"def",
"getShocks",
"(",
"self",
")",
":",
"cutoffs",
"=",
"np",
".",
"cumsum",
"(",
"self",
".",
"MrkvArray",
"[",
"self",
".",
"MrkvNow",
",",
":",
"]",
")",
"MrkvDraw",
"=",
"drawUniform",
"(",
"N",
"=",
"1",
",",
"seed",
"=",
"self",
".",
"RN... | 42.333333 | 30.037037 |
def captureException(self, exc_info=None, **kwargs):
"""
Creates an event from an exception.
>>> try:
>>> exc_info = sys.exc_info()
>>> client.captureException(exc_info)
>>> finally:
>>> del exc_info
If exc_info is not provided, or is set to ... | [
"def",
"captureException",
"(",
"self",
",",
"exc_info",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"exc_info",
"is",
"None",
"or",
"exc_info",
"is",
"True",
":",
"exc_info",
"=",
"sys",
".",
"exc_info",
"(",
")",
"return",
"self",
".",
"c... | 32.047619 | 19.095238 |
def set_pprint_format(indent=None, width=None, depth=None):
"""
This will set the constants for the pprint
:param indent: number of spaces to indent
:param width: max width of the line
:param depth: mas depth of the objects
:return: current settings
"""
if indent is not None:
PPR... | [
"def",
"set_pprint_format",
"(",
"indent",
"=",
"None",
",",
"width",
"=",
"None",
",",
"depth",
"=",
"None",
")",
":",
"if",
"indent",
"is",
"not",
"None",
":",
"PPRINT_FORMAT",
"[",
"'indent'",
"]",
"=",
"indent",
"if",
"width",
"is",
"not",
"None",
... | 32.666667 | 7.2 |
def main (args):
"""Usage: print_sedml input-filename
"""
if len(args) != 2:
print(main.__doc__)
sys.exit(1)
doc = libsedml.readSedML(args[1]);
if ( doc.getErrorLog().getNumFailsWithSeverity(libsedml.LIBSEDML_SEV_ERROR) > 0):
print doc.getErrorLog().toString();
sys.exit(2);
print 'The... | [
"def",
"main",
"(",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"!=",
"2",
":",
"print",
"(",
"main",
".",
"__doc__",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"doc",
"=",
"libsedml",
".",
"readSedML",
"(",
"args",
"[",
"1",
"]",
")",
"if"... | 43.293103 | 27.275862 |
def _cache_eta(self):
""" Prints the estimated time left."""
self._calc_eta()
self._cached_output += ' | ETA: ' + self._get_time(self.eta) | [
"def",
"_cache_eta",
"(",
"self",
")",
":",
"self",
".",
"_calc_eta",
"(",
")",
"self",
".",
"_cached_output",
"+=",
"' | ETA: '",
"+",
"self",
".",
"_get_time",
"(",
"self",
".",
"eta",
")"
] | 39.75 | 15.75 |
def source_debianize_name(name):
"make name acceptable as a Debian source package name"
name = name.replace('_','-')
name = name.replace('.','-')
name = name.lower()
return name | [
"def",
"source_debianize_name",
"(",
"name",
")",
":",
"name",
"=",
"name",
".",
"replace",
"(",
"'_'",
",",
"'-'",
")",
"name",
"=",
"name",
".",
"replace",
"(",
"'.'",
",",
"'-'",
")",
"name",
"=",
"name",
".",
"lower",
"(",
")",
"return",
"name"... | 32 | 14 |
def _get_default_grid():
"""In the grid specification, 0 corresponds to the best channel, 1
to the second best, and so on. A, B, C refer to the PC components."""
s = """
time,0A 1A,0A 0B,0A 1B,0A
0A,1A time,1A 0B,1A 1B,1A
0A,0B 1A,0B time,0B 1B,0B
0A,1B 1A,1B 0B,1B time,1B
... | [
"def",
"_get_default_grid",
"(",
")",
":",
"s",
"=",
"\"\"\"\n time,0A 1A,0A 0B,0A 1B,0A\n 0A,1A time,1A 0B,1A 1B,1A\n 0A,0B 1A,0B time,0B 1B,0B\n 0A,1B 1A,1B 0B,1B time,1B\n \"\"\"",
".",
"strip",
"(",
")",
"dims",
"=",
"[",
"[",
"_",
"for",
"_",... | 36.166667 | 6.75 |
def get_value(self, var, cast=None, default=NOTSET, parse_default=False):
"""Return value for given environment variable.
:param var: Name of variable.
:param cast: Type to cast return value as.
:param default: If var not present in environ, return this instead.
:param parse_def... | [
"def",
"get_value",
"(",
"self",
",",
"var",
",",
"cast",
"=",
"None",
",",
"default",
"=",
"NOTSET",
",",
"parse_default",
"=",
"False",
")",
":",
"logger",
".",
"debug",
"(",
"\"get '{0}' casted as '{1}' with default '{2}'\"",
".",
"format",
"(",
"var",
",... | 31.45614 | 20.052632 |
def get_friendly_name(cert, password):
'''
Get the friendly name of the given certificate
cert
The certificate to install
password
The password for the certificate being installed formatted in the way
described for openssl command in the PASS PHRASE ARGUMENTS section
N... | [
"def",
"get_friendly_name",
"(",
"cert",
",",
"password",
")",
":",
"cmd",
"=",
"'openssl pkcs12 -in {0} -passin pass:{1} -info -nodes -nokeys 2> /dev/null | '",
"'grep friendlyName:'",
".",
"format",
"(",
"_quote",
"(",
"cert",
")",
",",
"_quote",
"(",
"password",
")",... | 32.166667 | 28.916667 |
def send(self, template, email, _vars=None, options=None, schedule_time=None, limit=None):
"""
Remotely send an email template to a single email address.
http://docs.sailthru.com/api/send
@param template: template string
@param email: Email value
@param _vars: a key/value... | [
"def",
"send",
"(",
"self",
",",
"template",
",",
"email",
",",
"_vars",
"=",
"None",
",",
"options",
"=",
"None",
",",
"schedule_time",
"=",
"None",
",",
"limit",
"=",
"None",
")",
":",
"_vars",
"=",
"_vars",
"or",
"{",
"}",
"options",
"=",
"optio... | 55.181818 | 24.818182 |
def read_file(file_name, encoding='utf-8'):
"""
读文本文件
:param encoding:
:param file_name:
:return:
"""
with open(file_name, 'rb') as f:
data = f.read()
if encoding is not None:
data = data.decode(encoding)
return data | [
"def",
"read_file",
"(",
"file_name",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"with",
"open",
"(",
"file_name",
",",
"'rb'",
")",
"as",
"f",
":",
"data",
"=",
"f",
".",
"read",
"(",
")",
"if",
"encoding",
"is",
"not",
"None",
":",
"data",
"=",
... | 18.357143 | 17.357143 |
def digest_json(soup):
"""digest in article json format"""
abstract_tags = raw_parser.abstract(soup, abstract_type="executive-summary")
abstract_json = None
for tag in abstract_tags:
abstract_json = render_abstract_json(tag)
return abstract_json | [
"def",
"digest_json",
"(",
"soup",
")",
":",
"abstract_tags",
"=",
"raw_parser",
".",
"abstract",
"(",
"soup",
",",
"abstract_type",
"=",
"\"executive-summary\"",
")",
"abstract_json",
"=",
"None",
"for",
"tag",
"in",
"abstract_tags",
":",
"abstract_json",
"=",
... | 38.142857 | 15.714286 |
def check_bam(bam, samtype="bam"):
"""Check if bam file is valid.
Bam file should:
- exists
- has an index (create if necessary)
- is sorted by coordinate
- has at least one mapped read
"""
ut.check_existance(bam)
samfile = pysam.AlignmentFile(bam, "rb")
if not samfile.has_index... | [
"def",
"check_bam",
"(",
"bam",
",",
"samtype",
"=",
"\"bam\"",
")",
":",
"ut",
".",
"check_existance",
"(",
"bam",
")",
"samfile",
"=",
"pysam",
".",
"AlignmentFile",
"(",
"bam",
",",
"\"rb\"",
")",
"if",
"not",
"samfile",
".",
"has_index",
"(",
")",
... | 44.68 | 21.92 |
def kruskal_align(U, V, permute_U=False, permute_V=False):
"""Aligns two KTensors and returns a similarity score.
Parameters
----------
U : KTensor
First kruskal tensor to align.
V : KTensor
Second kruskal tensor to align.
permute_U : bool
If True, modifies 'U' to align ... | [
"def",
"kruskal_align",
"(",
"U",
",",
"V",
",",
"permute_U",
"=",
"False",
",",
"permute_V",
"=",
"False",
")",
":",
"# Compute similarity matrices.",
"unrm",
"=",
"[",
"f",
"/",
"np",
".",
"linalg",
".",
"norm",
"(",
"f",
",",
"axis",
"=",
"0",
")"... | 30.689655 | 21.804598 |
def is_child_of_book(self, id_, book_id):
"""Tests if a book is a direct child of another.
arg: id (osid.id.Id): an ``Id``
arg: book_id (osid.id.Id): the ``Id`` of a book
return: (boolean) - ``true`` if the ``id`` is a child of
``book_id,`` ``false`` otherwise
... | [
"def",
"is_child_of_book",
"(",
"self",
",",
"id_",
",",
"book_id",
")",
":",
"# Implemented from template for",
"# osid.resource.BinHierarchySession.is_child_of_bin",
"if",
"self",
".",
"_catalog_session",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_catalog_sess... | 49.7 | 18.45 |
def custom_server_error(request, template_name='500.html', admin_template_name='500A.html'):
"""
500 error handler. Displays a full trackback for superusers and the first line of the
traceback for staff members.
Templates: `500.html` or `500A.html` (admin)
Context: trace
Holds the traceback... | [
"def",
"custom_server_error",
"(",
"request",
",",
"template_name",
"=",
"'500.html'",
",",
"admin_template_name",
"=",
"'500A.html'",
")",
":",
"trace",
"=",
"None",
"if",
"request",
".",
"user",
".",
"is_authenticated",
"(",
")",
"and",
"(",
"request",
".",
... | 41.423077 | 23.576923 |
def increment(itr, n=1, format_msg="{}. "):
"""Similar to enumerate but will set format_msg.format(n) into the prefix on
each iteration
:Example:
for v in increment(["foo", "bar"]):
echo.out(v) # 1. foo\n2. bar
:param itr: iterator, any iterator you want to set a numeric prefix on ... | [
"def",
"increment",
"(",
"itr",
",",
"n",
"=",
"1",
",",
"format_msg",
"=",
"\"{}. \"",
")",
":",
"for",
"i",
",",
"v",
"in",
"enumerate",
"(",
"itr",
",",
"n",
")",
":",
"with",
"prefix",
"(",
"format_msg",
",",
"i",
")",
":",
"yield",
"v"
] | 36.611111 | 17.888889 |
def derive_field_name(self, field_name):
"""Derives a new event from this one setting the ``field_name`` attribute.
Args:
field_name (Union[amazon.ion.symbols.SymbolToken, unicode]): The field name to set.
Returns:
IonEvent: The newly generated event.
"""
... | [
"def",
"derive_field_name",
"(",
"self",
",",
"field_name",
")",
":",
"cls",
"=",
"type",
"(",
"self",
")",
"# We use ordinals to avoid thunk materialization.",
"return",
"cls",
"(",
"self",
"[",
"0",
"]",
",",
"self",
"[",
"1",
"]",
",",
"self",
"[",
"2",... | 29.777778 | 19.833333 |
def _new_chart_graphicFrame(self, rId, x, y, cx, cy):
"""
Return a newly created `p:graphicFrame` element having the specified
position and size and containing the chart identified by *rId*.
"""
id_, name = self.shape_id, self.name
return CT_GraphicalObjectFrame.new_chart... | [
"def",
"_new_chart_graphicFrame",
"(",
"self",
",",
"rId",
",",
"x",
",",
"y",
",",
"cx",
",",
"cy",
")",
":",
"id_",
",",
"name",
"=",
"self",
".",
"shape_id",
",",
"self",
".",
"name",
"return",
"CT_GraphicalObjectFrame",
".",
"new_chart_graphicFrame",
... | 41.888889 | 15.222222 |
def get_teams():
"""
:return: all knows teams
"""
LOGGER.debug("TeamService.get_teams")
args = {'http_operation': 'GET', 'operation_path': ''}
response = TeamService.requester.call(args)
ret = None
if response.rc == 0:
ret = []
for ... | [
"def",
"get_teams",
"(",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"TeamService.get_teams\"",
")",
"args",
"=",
"{",
"'http_operation'",
":",
"'GET'",
",",
"'operation_path'",
":",
"''",
"}",
"response",
"=",
"TeamService",
".",
"requester",
".",
"call",
"(",... | 40.277778 | 16.944444 |
def get_mean_and_std(dataset):
"""Compute the mean and std value of dataset."""
dataloader = torch.utils.data.DataLoader(
dataset, batch_size=1, shuffle=True, num_workers=2
)
mean = torch.zeros(3)
std = torch.zeros(3)
print("==> Computing mean and std..")
for inputs, _ in dataloader:... | [
"def",
"get_mean_and_std",
"(",
"dataset",
")",
":",
"dataloader",
"=",
"torch",
".",
"utils",
".",
"data",
".",
"DataLoader",
"(",
"dataset",
",",
"batch_size",
"=",
"1",
",",
"shuffle",
"=",
"True",
",",
"num_workers",
"=",
"2",
")",
"mean",
"=",
"to... | 33.666667 | 12.2 |
def tag_analysis(self):
"""Tag ``words`` layer with morphological analysis attributes."""
if not self.is_tagged(WORDS):
self.tokenize_words()
sentences = self.divide(WORDS, SENTENCES)
for sentence in sentences:
texts = [word[TEXT] for word in sentence]
... | [
"def",
"tag_analysis",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_tagged",
"(",
"WORDS",
")",
":",
"self",
".",
"tokenize_words",
"(",
")",
"sentences",
"=",
"self",
".",
"divide",
"(",
"WORDS",
",",
"SENTENCES",
")",
"for",
"sentence",
"in",... | 45.333333 | 11.583333 |
def serverTickle(self, enable, timeout_millis=0, stay_lit=False, start_pos=0, end_pos=16):
"""Enable/disable servertickle / serverdown watchdog
:param: enable: Set True to enable serverTickle
:param: timeout_millis: millisecs until servertickle is triggered
:param: stay_lit: Set True to ... | [
"def",
"serverTickle",
"(",
"self",
",",
"enable",
",",
"timeout_millis",
"=",
"0",
",",
"stay_lit",
"=",
"False",
",",
"start_pos",
"=",
"0",
",",
"end_pos",
"=",
"16",
")",
":",
"if",
"(",
"self",
".",
"dev",
"==",
"None",
")",
":",
"return",
"''... | 53 | 18.1875 |
def make_stats(data, perfile, fsamplehits, fbarhits, fmisses, fdbars):
"""
Write stats and stores to Assembly object.
"""
## out file
outhandle = os.path.join(data.dirs.fastqs, 's1_demultiplex_stats.txt')
outfile = open(outhandle, 'w')
## write the header for file stats -------------------... | [
"def",
"make_stats",
"(",
"data",
",",
"perfile",
",",
"fsamplehits",
",",
"fbarhits",
",",
"fmisses",
",",
"fdbars",
")",
":",
"## out file",
"outhandle",
"=",
"os",
".",
"path",
".",
"join",
"(",
"data",
".",
"dirs",
".",
"fastqs",
",",
"'s1_demultiple... | 37.796748 | 19.276423 |
def _encapsulate_item_for_combinfunc(item):
"""
This function has been extracted in order to
make Github issue #28 easier to investigate.
It replaces the following two lines of code,
which occur twice in method genmatrix, just
before the invocation of combinfunc.
if not hasattr(item, '... | [
"def",
"_encapsulate_item_for_combinfunc",
"(",
"item",
")",
":",
"encapsulated_item",
"=",
"None",
"if",
"(",
"not",
"hasattr",
"(",
"item",
",",
"'__iter__'",
")",
"or",
"isinstance",
"(",
"item",
",",
"tuple",
")",
"or",
"isinstance",
"(",
"item",
",",
... | 35.485714 | 11.428571 |
def get_equipment(self, **kwargs):
"""
Return list environments related with environment vip
"""
uri = 'api/v3/equipment/'
uri = self.prepare_url(uri, kwargs)
return super(ApiEquipment, self).get(uri) | [
"def",
"get_equipment",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"uri",
"=",
"'api/v3/equipment/'",
"uri",
"=",
"self",
".",
"prepare_url",
"(",
"uri",
",",
"kwargs",
")",
"return",
"super",
"(",
"ApiEquipment",
",",
"self",
")",
".",
"get",
"("... | 26.888889 | 14 |
def parallel_map(function, sequence, numcores=None):
"""
A parallelized version of the native Python map function that
utilizes the Python multiprocessing module to divide and
conquer sequence.
parallel_map does not yet support multiple argument sequences.
:param function: callable function that accepts ... | [
"def",
"parallel_map",
"(",
"function",
",",
"sequence",
",",
"numcores",
"=",
"None",
")",
":",
"if",
"not",
"callable",
"(",
"function",
")",
":",
"raise",
"TypeError",
"(",
"\"input function '%s' is not callable\"",
"%",
"repr",
"(",
"function",
")",
")",
... | 33.140351 | 21.491228 |
def IsKeyPressed(key: int) -> bool:
"""
key: int, a value in class `Keys`.
Return bool.
"""
state = ctypes.windll.user32.GetAsyncKeyState(key)
return bool(state & 0x8000) | [
"def",
"IsKeyPressed",
"(",
"key",
":",
"int",
")",
"->",
"bool",
":",
"state",
"=",
"ctypes",
".",
"windll",
".",
"user32",
".",
"GetAsyncKeyState",
"(",
"key",
")",
"return",
"bool",
"(",
"state",
"&",
"0x8000",
")"
] | 26.857143 | 7.714286 |
def split_parameter_types(parameters):
"""Split a parameter types declaration into individual types.
The input is the left hand side of a signature (the part before the arrow),
excluding the parentheses.
:sig: (str) -> List[str]
:param parameters: Comma separated parameter types.
:return: Para... | [
"def",
"split_parameter_types",
"(",
"parameters",
")",
":",
"if",
"parameters",
"==",
"\"\"",
":",
"return",
"[",
"]",
"# only consider the top level commas, ignore the ones in []",
"commas",
"=",
"[",
"]",
"bracket_depth",
"=",
"0",
"for",
"i",
",",
"char",
"in"... | 27.9375 | 18.5 |
def _print_cline(self, buf, i, icol):
"""
Print clines after multirow-blocks are finished
"""
for cl in self.clinebuf:
if cl[0] == i:
buf.write('\\cline{{{cl:d}-{icol:d}}}\n'
.format(cl=cl[1], icol=icol))
# remove entries that... | [
"def",
"_print_cline",
"(",
"self",
",",
"buf",
",",
"i",
",",
"icol",
")",
":",
"for",
"cl",
"in",
"self",
".",
"clinebuf",
":",
"if",
"cl",
"[",
"0",
"]",
"==",
"i",
":",
"buf",
".",
"write",
"(",
"'\\\\cline{{{cl:d}-{icol:d}}}\\n'",
".",
"format",... | 40.3 | 11.1 |
def get_init_container(self,
init_command,
init_args,
env_vars,
context_mounts,
persistence_outputs,
persistence_data):
"""Pod init container for sett... | [
"def",
"get_init_container",
"(",
"self",
",",
"init_command",
",",
"init_args",
",",
"env_vars",
",",
"context_mounts",
",",
"persistence_outputs",
",",
"persistence_data",
")",
":",
"env_vars",
"=",
"to_list",
"(",
"env_vars",
",",
"check_none",
"=",
"True",
"... | 40.333333 | 9.952381 |
def _results(self, dict={}):
"""Helper to merge a dict with cross-plugin defaults.
All plugin sub-classes share some config values, i.e. alias, url,
login and password. This help should be used in the :collect: method
of any Plugin implementation.
>>> import rapport.plugin
... | [
"def",
"_results",
"(",
"self",
",",
"dict",
"=",
"{",
"}",
")",
":",
"results",
"=",
"{",
"\"plugin\"",
":",
"str",
"(",
"self",
")",
",",
"\"alias\"",
":",
"self",
".",
"alias",
",",
"\"url\"",
":",
"self",
".",
"url",
",",
"\"login\"",
":",
"s... | 51.05 | 26.45 |
def negative_inference(self, content_id):
'''Return a generator of inferred negative label relationships
centered on ``content_id``.
Negative labels are inferred by getting all other content ids
connected to ``content_id`` through a negative label, then
running :meth:`LabelStore... | [
"def",
"negative_inference",
"(",
"self",
",",
"content_id",
")",
":",
"neg_labels",
"=",
"ifilter",
"(",
"lambda",
"l",
":",
"l",
".",
"value",
"==",
"CorefValue",
".",
"Negative",
",",
"self",
".",
"directly_connected",
"(",
"content_id",
")",
")",
"for"... | 46.3125 | 20.6875 |
def mapCellsToPoints(self):
"""
Transform cell data (i.e., data specified per cell)
into point data (i.e., data specified at cell points).
The method of transformation is based on averaging the data values
of all cells using a particular point.
"""
c2p = vtk.vtkCe... | [
"def",
"mapCellsToPoints",
"(",
"self",
")",
":",
"c2p",
"=",
"vtk",
".",
"vtkCellDataToPointData",
"(",
")",
"c2p",
".",
"SetInputData",
"(",
"self",
".",
"polydata",
"(",
"False",
")",
")",
"c2p",
".",
"Update",
"(",
")",
"return",
"self",
".",
"upda... | 40.454545 | 11.727273 |
def forward(self, x):
"""Compute forward-pass of this module on ``x``.
Parameters
----------
x : `torch.autograd.variable.Variable`
Input of this layer. The contained tensor must have shape
``extra_shape + operator.domain.shape``, and
``len(extra_shap... | [
"def",
"forward",
"(",
"self",
",",
"x",
")",
":",
"in_shape",
"=",
"x",
".",
"data",
".",
"shape",
"op_in_shape",
"=",
"self",
".",
"op_func",
".",
"operator",
".",
"domain",
".",
"shape",
"op_out_shape",
"=",
"self",
".",
"op_func",
".",
"operator",
... | 34.387097 | 20.204301 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.