text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def obfn_cns(self):
r"""Compute constraint violation measure :math:`\| P(\mathbf{y})
- \mathbf{y}\|_2`.
"""
Y = self.obfn_gvar()
return np.linalg.norm((self.Pcn(Y) - Y)) | [
"def",
"obfn_cns",
"(",
"self",
")",
":",
"Y",
"=",
"self",
".",
"obfn_gvar",
"(",
")",
"return",
"np",
".",
"linalg",
".",
"norm",
"(",
"(",
"self",
".",
"Pcn",
"(",
"Y",
")",
"-",
"Y",
")",
")"
] | 29.142857 | 13.571429 |
def get_account_statement(
self, locale=None, from_record=None, record_count=None,
item_date_range=None, include_item=None, wallet=None):
"""Get account statement.
:param str locale: The language to be used where applicable
:param int from_record: Specifies the first rec... | [
"def",
"get_account_statement",
"(",
"self",
",",
"locale",
"=",
"None",
",",
"from_record",
"=",
"None",
",",
"record_count",
"=",
"None",
",",
"item_date_range",
"=",
"None",
",",
"include_item",
"=",
"None",
",",
"wallet",
"=",
"None",
")",
":",
"return... | 47.444444 | 22 |
def secrets_manager(*secret_names):
"""
Get secrets from the `AWS Secrets Manager <https://aws.amazon.com/secrets-manager/>`_.
Secrets are added to a dictionary named ``secrets`` on the context object.
This requires your lambda to have the ``secretsmanager:GetSecretValue`` permission for the
reque... | [
"def",
"secrets_manager",
"(",
"*",
"secret_names",
")",
":",
"def",
"wrapper_wrapper",
"(",
"handler",
")",
":",
"@",
"wraps",
"(",
"handler",
")",
"def",
"wrapper",
"(",
"event",
",",
"context",
")",
":",
"if",
"not",
"hasattr",
"(",
"context",
",",
... | 36.184211 | 23.236842 |
def _remove_dupes(self, phonetic):
"""Remove duplicates from a phonetic encoding list.
Parameters
----------
phonetic : str
A Beider-Morse phonetic encoding
Returns
-------
str
A Beider-Morse phonetic code
"""
alt_string ... | [
"def",
"_remove_dupes",
"(",
"self",
",",
"phonetic",
")",
":",
"alt_string",
"=",
"phonetic",
"alt_array",
"=",
"alt_string",
".",
"split",
"(",
"'|'",
")",
"result",
"=",
"'|'",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"alt_array",
")",
")",
":",
... | 23.375 | 17.708333 |
def s2dctmat(nfilt,ncep,freqstep):
"""Return the 'legacy' not-quite-DCT matrix used by Sphinx"""
melcos = numpy.empty((ncep, nfilt), 'double')
for i in range(0,ncep):
freq = numpy.pi * float(i) / nfilt
melcos[i] = numpy.cos(freq * numpy.arange(0.5, float(nfilt)+0.5, 1.0, 'double'))
melco... | [
"def",
"s2dctmat",
"(",
"nfilt",
",",
"ncep",
",",
"freqstep",
")",
":",
"melcos",
"=",
"numpy",
".",
"empty",
"(",
"(",
"ncep",
",",
"nfilt",
")",
",",
"'double'",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"ncep",
")",
":",
"freq",
"=",
"... | 44.625 | 13.25 |
def main():
"""pyprf_opt_brute entry point."""
# Get list of input arguments (without first one, which is the path to the
# function that is called): --NOTE: This is another way of accessing
# input arguments, but since we use 'argparse' it is redundant.
# lstArgs = sys.argv[1:]
strWelcome = 'p... | [
"def",
"main",
"(",
")",
":",
"# Get list of input arguments (without first one, which is the path to the",
"# function that is called): --NOTE: This is another way of accessing",
"# input arguments, but since we use 'argparse' it is redundant.",
"# lstArgs = sys.argv[1:]",
"strWelcome",
"=",
... | 43.938776 | 24.530612 |
def finished(experiment_name, reset=True):
"""
Track a conversion.
:param experiment_name: Name of the experiment.
:param reset: If set to `True` current user's session is reset so that they
may start the test again in the future. If set to `False` the user
will always see the alternat... | [
"def",
"finished",
"(",
"experiment_name",
",",
"reset",
"=",
"True",
")",
":",
"if",
"_exclude_visitor",
"(",
")",
":",
"return",
"redis",
"=",
"_get_redis_connection",
"(",
")",
"try",
":",
"experiment",
"=",
"Experiment",
".",
"find",
"(",
"redis",
",",... | 38.485714 | 17.742857 |
def addFASTAEditingCommandLineOptions(parser):
"""
Add standard FASTA editing command-line options to an argparse parser.
These are options that can be used to alter FASTA records, NOT options
that simply select or reject those things (for those see
addFASTAFilteringCommandLineOptions).
@param... | [
"def",
"addFASTAEditingCommandLineOptions",
"(",
"parser",
")",
":",
"# A mutually exclusive group for --keepSites, --keepSitesFile,",
"# --removeSites, and --removeSitesFile.",
"group",
"=",
"parser",
".",
"add_mutually_exclusive_group",
"(",
")",
"# In the 4 options below, the 'indic... | 45.976744 | 24.232558 |
def prepare_request_uri(self, uri, redirect_uri=None, scope=None,
state=None, **kwargs):
"""Prepare the implicit grant request URI.
The client constructs the request URI by adding the following
parameters to the query component of the authorization endpoint URI
... | [
"def",
"prepare_request_uri",
"(",
"self",
",",
"uri",
",",
"redirect_uri",
"=",
"None",
",",
"scope",
"=",
"None",
",",
"state",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"prepare_grant_uri",
"(",
"uri",
",",
"self",
".",
"client_id",
... | 62.744681 | 36.93617 |
def remove_object(self, obj):
"""Remove an object from the definition."""
self._objects.remove(obj)
self._pairs.difference_update((obj, p) for p in self._properties) | [
"def",
"remove_object",
"(",
"self",
",",
"obj",
")",
":",
"self",
".",
"_objects",
".",
"remove",
"(",
"obj",
")",
"self",
".",
"_pairs",
".",
"difference_update",
"(",
"(",
"obj",
",",
"p",
")",
"for",
"p",
"in",
"self",
".",
"_properties",
")"
] | 46.5 | 12.75 |
def virtual_resource(self):
"""
Available on a Master Engine only.
To get all virtual resources call::
engine.virtual_resource.all()
:raises UnsupportedEngineFeature: master engine only
:rtype: CreateCollection(VirtualResource)
"""
resource = create... | [
"def",
"virtual_resource",
"(",
"self",
")",
":",
"resource",
"=",
"create_collection",
"(",
"self",
".",
"get_relation",
"(",
"'virtual_resources'",
",",
"UnsupportedEngineFeature",
")",
",",
"VirtualResource",
")",
"resource",
".",
"_load_from_engine",
"(",
"self"... | 30 | 13.111111 |
def fast_sync_inspect_snapshot( snapshot_path ):
"""
Inspect a snapshot
Return useful information
Return {'status': True, 'signatures': ..., 'payload_size': ..., 'sig_append_offset': ..., 'hash': ...} on success
Return {'error': ...} on error
"""
with open(snapshot_path, 'r') as f:
i... | [
"def",
"fast_sync_inspect_snapshot",
"(",
"snapshot_path",
")",
":",
"with",
"open",
"(",
"snapshot_path",
",",
"'r'",
")",
"as",
"f",
":",
"info",
"=",
"fast_sync_inspect",
"(",
"f",
")",
"if",
"'error'",
"in",
"info",
":",
"log",
".",
"error",
"(",
"\"... | 37.833333 | 20.5 |
def add_arrow(self, x1, y1, x2, y2, side='left',
shape='full', color='black',
width=0.01, head_width=0.03, overhang=0, **kws):
"""add arrow supplied x, y position"""
dx, dy = x2-x1, y2-y1
axes = self.axes
if side == 'right':
axes = self.g... | [
"def",
"add_arrow",
"(",
"self",
",",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
",",
"side",
"=",
"'left'",
",",
"shape",
"=",
"'full'",
",",
"color",
"=",
"'black'",
",",
"width",
"=",
"0.01",
",",
"head_width",
"=",
"0.03",
",",
"overhang",
"=",
"... | 38.733333 | 11.8 |
def add_new_init_method(obj):
"""
Replace the existing obj.__init__() method with a new one
which calls the original one and in addition performs the
following actions:
(1) Finds all instances of tohu.BaseGenerator in the namespace
and collects them in the dictionary `self.field_gens`.
... | [
"def",
"add_new_init_method",
"(",
"obj",
")",
":",
"orig_init",
"=",
"obj",
".",
"__init__",
"def",
"new_init",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"logger",
".",
"debug",
"(",
"f\"Initialising new {self}\"",
")",
"# Call ori... | 36.706667 | 23.346667 |
def evecs(self):
"""
The eigenvectors of the parameter space.
This is a Dictionary of numpy.matrix
Each entry in the dictionary is as described under evals.
Each numpy.matrix contains the eigenvectors which, with the eigenvalues
in evals, are needed to rotate the
... | [
"def",
"evecs",
"(",
"self",
")",
":",
"if",
"self",
".",
"_evecs",
"is",
"None",
":",
"errMsg",
"=",
"\"The metric eigenvectors have not been set in the \"",
"errMsg",
"+=",
"\"metricParameters instance.\"",
"raise",
"ValueError",
"(",
"errMsg",
")",
"return",
"sel... | 43.357143 | 14.785714 |
def write(self, file_or_filename):
""" Writes case data to file in Excel format.
"""
self.book = Workbook()
self._write_data(None)
self.book.save(file_or_filename) | [
"def",
"write",
"(",
"self",
",",
"file_or_filename",
")",
":",
"self",
".",
"book",
"=",
"Workbook",
"(",
")",
"self",
".",
"_write_data",
"(",
"None",
")",
"self",
".",
"book",
".",
"save",
"(",
"file_or_filename",
")"
] | 33 | 4.333333 |
def generate_defect_structure(self, supercell=(1, 1, 1)):
"""
Returns Defective Vacancy structure, decorated with charge
Args:
supercell (int, [3x1], or [[]] (3x3)): supercell integer, vector, or scaling matrix
"""
defect_structure = self.bulk_structure.copy()
... | [
"def",
"generate_defect_structure",
"(",
"self",
",",
"supercell",
"=",
"(",
"1",
",",
"1",
",",
"1",
")",
")",
":",
"defect_structure",
"=",
"self",
".",
"bulk_structure",
".",
"copy",
"(",
")",
"defect_structure",
".",
"make_supercell",
"(",
"supercell",
... | 49.565217 | 23.304348 |
def _reflect_table(self):
"""Load the tables definition from the database."""
with self.db.lock:
try:
self._table = SQLATable(self.name,
self.db.metadata,
schema=self.db.schema,
... | [
"def",
"_reflect_table",
"(",
"self",
")",
":",
"with",
"self",
".",
"db",
".",
"lock",
":",
"try",
":",
"self",
".",
"_table",
"=",
"SQLATable",
"(",
"self",
".",
"name",
",",
"self",
".",
"db",
".",
"metadata",
",",
"schema",
"=",
"self",
".",
... | 40.5 | 14 |
def rmdir(self, pathobj):
"""
Removes a directory
"""
stat = self.stat(pathobj)
if not stat.is_dir:
raise OSError(20, "Not a directory: '%s'" % str(pathobj))
url = str(pathobj) + '/'
text, code = self.rest_del(url, session=pathobj.session, verify=pa... | [
"def",
"rmdir",
"(",
"self",
",",
"pathobj",
")",
":",
"stat",
"=",
"self",
".",
"stat",
"(",
"pathobj",
")",
"if",
"not",
"stat",
".",
"is_dir",
":",
"raise",
"OSError",
"(",
"20",
",",
"\"Not a directory: '%s'\"",
"%",
"str",
"(",
"pathobj",
")",
"... | 30.2 | 23 |
def ipv4_generate_random(total=100):
"""
The generator to produce random, unique IPv4 addresses that are not
defined (can be looked up using ipwhois).
Args:
total (:obj:`int`): The total number of IPv4 addresses to generate.
Yields:
str: The next IPv4 address.
"""
count = ... | [
"def",
"ipv4_generate_random",
"(",
"total",
"=",
"100",
")",
":",
"count",
"=",
"0",
"yielded",
"=",
"set",
"(",
")",
"while",
"count",
"<",
"total",
":",
"address",
"=",
"str",
"(",
"IPv4Address",
"(",
"random",
".",
"randint",
"(",
"0",
",",
"2",
... | 24.478261 | 23.347826 |
def select_group(self, group_id):
"""Copy the query and add filtering by group.
Example::
query = query.select_group('1234567')
:type group_id: str
:param group_id: The ID of a group to filter by.
:rtype: :class:`Query`
:returns: The new query object.
... | [
"def",
"select_group",
"(",
"self",
",",
"group_id",
")",
":",
"new_query",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
")",
"new_query",
".",
"_filter",
".",
"group_id",
"=",
"group_id",
"return",
"new_query"
] | 26.4375 | 16.3125 |
def get_renderers(self):
"""Optionally block Browsable API rendering. """
renderers = super(WithDynamicViewSetMixin, self).get_renderers()
if settings.ENABLE_BROWSABLE_API is False:
return [
r for r in renderers if not isinstance(r, BrowsableAPIRenderer)
]... | [
"def",
"get_renderers",
"(",
"self",
")",
":",
"renderers",
"=",
"super",
"(",
"WithDynamicViewSetMixin",
",",
"self",
")",
".",
"get_renderers",
"(",
")",
"if",
"settings",
".",
"ENABLE_BROWSABLE_API",
"is",
"False",
":",
"return",
"[",
"r",
"for",
"r",
"... | 39.444444 | 20.333333 |
def top(self, num, key=None):
"""
Get the top N elements from an RDD.
.. note:: This method should only be used if the resulting array is expected
to be small, as all the data is loaded into the driver's memory.
.. note:: It returns the list sorted in descending order.
... | [
"def",
"top",
"(",
"self",
",",
"num",
",",
"key",
"=",
"None",
")",
":",
"def",
"topIterator",
"(",
"iterator",
")",
":",
"yield",
"heapq",
".",
"nlargest",
"(",
"num",
",",
"iterator",
",",
"key",
"=",
"key",
")",
"def",
"merge",
"(",
"a",
",",... | 32.869565 | 22.347826 |
def _create_entry(entry_body):
''' Adds common part of entry to a given entry body and return the whole
xml. '''
updated_str = datetime.utcnow().isoformat()
if datetime.utcnow().utcoffset() is None:
updated_str += '+00:00'
entry_start = '''<?xml version="1.0" encoding="utf-8" standalone="ye... | [
"def",
"_create_entry",
"(",
"entry_body",
")",
":",
"updated_str",
"=",
"datetime",
".",
"utcnow",
"(",
")",
".",
"isoformat",
"(",
")",
"if",
"datetime",
".",
"utcnow",
"(",
")",
".",
"utcoffset",
"(",
")",
"is",
"None",
":",
"updated_str",
"+=",
"'+... | 53.538462 | 29.538462 |
def _special_dbkey_maps(dbkey, ref_file):
"""Avoid duplicate VEP information for databases with chromosome differences like hg19/GRCh37.
"""
remaps = {"hg19": "GRCh37",
"hg38-noalt": "hg38"}
if dbkey in remaps:
base_dir = os.path.normpath(os.path.join(os.path.dirname(ref_file), os.... | [
"def",
"_special_dbkey_maps",
"(",
"dbkey",
",",
"ref_file",
")",
":",
"remaps",
"=",
"{",
"\"hg19\"",
":",
"\"GRCh37\"",
",",
"\"hg38-noalt\"",
":",
"\"hg38\"",
"}",
"if",
"dbkey",
"in",
"remaps",
":",
"base_dir",
"=",
"os",
".",
"path",
".",
"normpath",
... | 43.5 | 17.777778 |
def locate(cls):
"""Locates the active PEX bootstrap.
:rtype: :class:`Bootstrap`
"""
if cls._INSTANCE is None:
bootstrap_path = __file__
module_import_path = __name__.split('.')
# For example, our __file__ might be requests.pex/.bootstrap/pex/bootstrap.pyc and our import
# path... | [
"def",
"locate",
"(",
"cls",
")",
":",
"if",
"cls",
".",
"_INSTANCE",
"is",
"None",
":",
"bootstrap_path",
"=",
"__file__",
"module_import_path",
"=",
"__name__",
".",
"split",
"(",
"'.'",
")",
"# For example, our __file__ might be requests.pex/.bootstrap/pex/bootstra... | 39.176471 | 24.176471 |
def quote(self) -> str:
"""Get a random quote.
:return: Quote from movie.
:Example:
"Bond... James Bond."
"""
quotes = self._data['quotes']
return self.random.choice(quotes) | [
"def",
"quote",
"(",
"self",
")",
"->",
"str",
":",
"quotes",
"=",
"self",
".",
"_data",
"[",
"'quotes'",
"]",
"return",
"self",
".",
"random",
".",
"choice",
"(",
"quotes",
")"
] | 22.6 | 13.7 |
def get_all_hits(self):
''' Get all HITs '''
if not self.connect_to_turk():
return False
try:
hits = []
paginator = self.mtc.get_paginator('list_hits')
for page in paginator.paginate():
hits.extend(page['HITs'])
except Excep... | [
"def",
"get_all_hits",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"connect_to_turk",
"(",
")",
":",
"return",
"False",
"try",
":",
"hits",
"=",
"[",
"]",
"paginator",
"=",
"self",
".",
"mtc",
".",
"get_paginator",
"(",
"'list_hits'",
")",
"for",
... | 31.214286 | 13.642857 |
def model_to_json(self, object, cleanup=True):
"""Take a model instance and return it as a json struct"""
model_name = type(object).__name__
if model_name not in self.swagger_dict['definitions']:
raise ValidationError("Swagger spec has no definition for model %s" % model_name)
... | [
"def",
"model_to_json",
"(",
"self",
",",
"object",
",",
"cleanup",
"=",
"True",
")",
":",
"model_name",
"=",
"type",
"(",
"object",
")",
".",
"__name__",
"if",
"model_name",
"not",
"in",
"self",
".",
"swagger_dict",
"[",
"'definitions'",
"]",
":",
"rais... | 50.363636 | 17.454545 |
def suppress_stdout():
"""
Context manager that suppresses stdout.
Examples:
>>> with suppress_stdout():
... print('Test print')
>>> print('test')
test
"""
save_stdout = sys.stdout
sys.stdout = DevNull()
yield
sys.stdout = save_stdout | [
"def",
"suppress_stdout",
"(",
")",
":",
"save_stdout",
"=",
"sys",
".",
"stdout",
"sys",
".",
"stdout",
"=",
"DevNull",
"(",
")",
"yield",
"sys",
".",
"stdout",
"=",
"save_stdout"
] | 18.125 | 18.125 |
def add_root(self, id_):
"""Adds a root node.
arg: id (osid.id.Id): the ``Id`` of the node
raise: AlreadyExists - ``id`` is already in hierarchy
raise: NotFound - ``id`` not found
raise: NullArgument - ``id`` is ``null``
raise: OperationFailed - unable to complete... | [
"def",
"add_root",
"(",
"self",
",",
"id_",
")",
":",
"if",
"(",
"bool",
"(",
"self",
".",
"_rls",
".",
"get_relationships_by_genus_type_for_source",
"(",
"id_",
",",
"self",
".",
"_relationship_type",
")",
".",
"available",
"(",
")",
")",
"or",
"bool",
... | 47.875 | 23.3125 |
def validate(message, **config):
""" Return true or false if the message is signed appropriately. """
if not _validate_implementations:
init(**config)
cfg = copy.deepcopy(config)
if 'gpg_home' not in cfg:
cfg['gpg_home'] = os.path.expanduser('~/.gnupg/')
if 'ssldir' not in cfg:
... | [
"def",
"validate",
"(",
"message",
",",
"*",
"*",
"config",
")",
":",
"if",
"not",
"_validate_implementations",
":",
"init",
"(",
"*",
"*",
"config",
")",
"cfg",
"=",
"copy",
".",
"deepcopy",
"(",
"config",
")",
"if",
"'gpg_home'",
"not",
"in",
"cfg",
... | 34.605263 | 19.973684 |
def reconnect_to_broker(self):
"""Connect or reconnect to broker"""
#print "CONNECT !"
if self.client:
self.poller.unregister(self.client)
self.client.close()
self.client = self.ctx.socket(zmq.DEALER)
self.client.linger = 0
self.client.connect(self... | [
"def",
"reconnect_to_broker",
"(",
"self",
")",
":",
"#print \"CONNECT !\"",
"if",
"self",
".",
"client",
":",
"self",
".",
"poller",
".",
"unregister",
"(",
"self",
".",
"client",
")",
"self",
".",
"client",
".",
"close",
"(",
")",
"self",
".",
"client"... | 39.166667 | 11.5 |
def fromrdd(rdd, nrecords=None, shape=None, index=None, labels=None, dtype=None, ordered=False):
"""
Load series data from a Spark RDD.
Assumes keys are tuples with increasing and unique indices,
and values are 1d ndarrays. Will try to infer properties
that are not explicitly provided.
Paramet... | [
"def",
"fromrdd",
"(",
"rdd",
",",
"nrecords",
"=",
"None",
",",
"shape",
"=",
"None",
",",
"index",
"=",
"None",
",",
"labels",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"ordered",
"=",
"False",
")",
":",
"from",
".",
"series",
"import",
"Serie... | 29.283333 | 21.55 |
def render(opts, functions, states=None, proxy=None, context=None):
'''
Returns the render modules
'''
if context is None:
context = {}
pack = {'__salt__': functions,
'__grains__': opts.get('grains', {}),
'__context__': context}
if states:
pack['__states... | [
"def",
"render",
"(",
"opts",
",",
"functions",
",",
"states",
"=",
"None",
",",
"proxy",
"=",
"None",
",",
"context",
"=",
"None",
")",
":",
"if",
"context",
"is",
"None",
":",
"context",
"=",
"{",
"}",
"pack",
"=",
"{",
"'__salt__'",
":",
"functi... | 28.757576 | 22.636364 |
def Sample(self):
"""Takes a sample for profiling."""
self._profiling_sample += 1
if self._profiling_sample >= self._profiling_sample_rate:
if self._heapy:
heap = self._heapy.heap()
heap.dump(self._sample_file)
self._profiling_sample = 0 | [
"def",
"Sample",
"(",
"self",
")",
":",
"self",
".",
"_profiling_sample",
"+=",
"1",
"if",
"self",
".",
"_profiling_sample",
">=",
"self",
".",
"_profiling_sample_rate",
":",
"if",
"self",
".",
"_heapy",
":",
"heap",
"=",
"self",
".",
"_heapy",
".",
"hea... | 27 | 17.1 |
def extract(fileobj, keywords, comment_tags, options):
"""Extracts translation messages from underscore template files.
This method does also extract django templates. If a template does not
contain any django translation tags we always fallback to underscore extraction.
This is a plugin to Babel, wri... | [
"def",
"extract",
"(",
"fileobj",
",",
"keywords",
",",
"comment_tags",
",",
"options",
")",
":",
"encoding",
"=",
"options",
".",
"get",
"(",
"'encoding'",
",",
"'utf-8'",
")",
"original_position",
"=",
"fileobj",
".",
"tell",
"(",
")",
"text",
"=",
"fi... | 35.64 | 21.04 |
def connect(self, chip_name, speed='auto', verbose=False):
"""Connects the J-Link to its target.
Args:
self (JLink): the ``JLink`` instance
chip_name (str): target chip name
speed (int): connection speed, one of ``{5-12000, 'auto', 'adaptive'}``
verbose (bool): b... | [
"def",
"connect",
"(",
"self",
",",
"chip_name",
",",
"speed",
"=",
"'auto'",
",",
"verbose",
"=",
"False",
")",
":",
"if",
"verbose",
":",
"self",
".",
"exec_command",
"(",
"'EnableRemarks = 1'",
")",
"# This is weird but is currently the only way to specify what t... | 33.555556 | 21.62963 |
def reset(self):
"""Reset the instance to begin sampling from scratch"""
self._sampled = [np.repeat(False, x) for x in self.sizes_]
self._n_sampled = np.zeros(self.n_strata_, dtype=int) | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"_sampled",
"=",
"[",
"np",
".",
"repeat",
"(",
"False",
",",
"x",
")",
"for",
"x",
"in",
"self",
".",
"sizes_",
"]",
"self",
".",
"_n_sampled",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"n_s... | 51.5 | 17.75 |
def _add_out_streams(self, spbl):
"""Adds outputs to a given protobuf Bolt or Spout message"""
if self.outputs is None:
return
# sanitize outputs and get a map <stream_id -> out fields>
output_map = self._sanitize_outputs()
for stream_id, out_fields in output_map.items():
out_stream = ... | [
"def",
"_add_out_streams",
"(",
"self",
",",
"spbl",
")",
":",
"if",
"self",
".",
"outputs",
"is",
"None",
":",
"return",
"# sanitize outputs and get a map <stream_id -> out fields>",
"output_map",
"=",
"self",
".",
"_sanitize_outputs",
"(",
")",
"for",
"stream_id",... | 39.416667 | 19.083333 |
def repository_factory(vcs_type, **kw):
"""
Instantiate a :class:`Repository` object based on the given type and arguments.
:param vcs_type: One of the strings 'bazaar', 'bzr', 'git', 'hg' or
'mercurial' or a subclass of :class:`Repository`.
:param kw: The keyword arguments to :fun... | [
"def",
"repository_factory",
"(",
"vcs_type",
",",
"*",
"*",
"kw",
")",
":",
"# Resolve VCS aliases to Repository subclasses.",
"if",
"isinstance",
"(",
"vcs_type",
",",
"string_types",
")",
":",
"vcs_type",
"=",
"vcs_type",
".",
"lower",
"(",
")",
"for",
"cls",... | 50.266667 | 20 |
def _joint_log_likelihood(self, X):
"""Calculate the posterior log probability of the samples X"""
check_is_fitted(self, "classes_")
X = check_array(X, accept_sparse='csr')
X_bin = self._transform_data(X)
n_classes, n_features = self.feature_log_prob_.shape
n_samples, n... | [
"def",
"_joint_log_likelihood",
"(",
"self",
",",
"X",
")",
":",
"check_is_fitted",
"(",
"self",
",",
"\"classes_\"",
")",
"X",
"=",
"check_array",
"(",
"X",
",",
"accept_sparse",
"=",
"'csr'",
")",
"X_bin",
"=",
"self",
".",
"_transform_data",
"(",
"X",
... | 33.772727 | 18.318182 |
def SetDeviceProperties(self, object_path, properties):
'''Convenience method to Set a device's properties.
object_path: the device to update
properties: dictionary of keys to dbus variants.
If the 1.0 API is being mocked, changing this property will trigger
the device's PropertiesChanged signal; ... | [
"def",
"SetDeviceProperties",
"(",
"self",
",",
"object_path",
",",
"properties",
")",
":",
"device",
"=",
"dbusmock",
".",
"get_object",
"(",
"object_path",
")",
"# set the properties",
"for",
"key",
",",
"value",
"in",
"properties",
".",
"items",
"(",
")",
... | 35.631579 | 21.421053 |
def createGenderPlot(bfile, intensities, problematic_samples, format,
out_prefix):
"""Creates the gender plot.
:param bfile: the prefix of the input binary file.
:param intensities: the file containing the intensities.
:param problematic_samples: the file containing the problematic... | [
"def",
"createGenderPlot",
"(",
"bfile",
",",
"intensities",
",",
"problematic_samples",
",",
"format",
",",
"out_prefix",
")",
":",
"gender_plot_options",
"=",
"[",
"\"--bfile\"",
",",
"bfile",
",",
"\"--intensities\"",
",",
"intensities",
",",
"\"--sex-problems\""... | 36.964286 | 18.607143 |
def general_neg_loglik(self, beta):
""" Calculates the negative log-likelihood of the model
Parameters
----------
beta : np.ndarray
Contains untransformed starting values for latent variables
Returns
----------
The negative logliklihood of the model
... | [
"def",
"general_neg_loglik",
"(",
"self",
",",
"beta",
")",
":",
"mu",
",",
"Y",
"=",
"self",
".",
"_model",
"(",
"beta",
")",
"parm",
"=",
"np",
".",
"array",
"(",
"[",
"self",
".",
"latent_variables",
".",
"z_list",
"[",
"k",
"]",
".",
"prior",
... | 42.611111 | 29.111111 |
def on_before_transform_template(self, template_dict):
"""
Hook method that runs before a template gets transformed. In this method, we parse and process Globals section
from the template (if present).
:param dict template_dict: SAM template as a dictionary
"""
try:
... | [
"def",
"on_before_transform_template",
"(",
"self",
",",
"template_dict",
")",
":",
"try",
":",
"global_section",
"=",
"Globals",
"(",
"template_dict",
")",
"except",
"InvalidGlobalsSectionException",
"as",
"ex",
":",
"raise",
"InvalidDocumentException",
"(",
"[",
"... | 41.809524 | 22.571429 |
def status(name, sig=None):
'''
Return the status for a service via rest_sample.
If the name contains globbing, a dict mapping service name to True/False
values is returned.
.. versionadded:: 2015.8.0
.. versionchanged:: 2018.3.0
The service name can now be a glob (e.g. ``salt*``)
... | [
"def",
"status",
"(",
"name",
",",
"sig",
"=",
"None",
")",
":",
"proxy_fn",
"=",
"'rest_sample.service_status'",
"contains_globbing",
"=",
"bool",
"(",
"re",
".",
"search",
"(",
"r'\\*|\\?|\\[.+\\]'",
",",
"name",
")",
")",
"if",
"contains_globbing",
":",
"... | 26.547619 | 20.880952 |
def get_tkd_value(tensor_keyed_dict, tensor, allclose_kwargs=None):
"""
Helper function to find a value in a tensor-keyed-
dictionary using an approximation to the key. This
is useful if rounding errors in construction occur
or hashing issues arise in tensor-keyed-dictionaries
(e. g. from symme... | [
"def",
"get_tkd_value",
"(",
"tensor_keyed_dict",
",",
"tensor",
",",
"allclose_kwargs",
"=",
"None",
")",
":",
"if",
"allclose_kwargs",
"is",
"None",
":",
"allclose_kwargs",
"=",
"{",
"}",
"for",
"tkey",
",",
"value",
"in",
"tensor_keyed_dict",
".",
"items",
... | 39.761905 | 13.952381 |
def task_add_user(self, *args, **kwargs):
"""Add users to the current task
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_task:
return
dialog = UserAdderDialog(task=self.cur_task)
dialog.exec_()
users = dialog.users
... | [
"def",
"task_add_user",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"cur_task",
":",
"return",
"dialog",
"=",
"UserAdderDialog",
"(",
"task",
"=",
"self",
".",
"cur_task",
")",
"dialog",
".",
"exec_",
"... | 28.0625 | 16.625 |
def reveal(
input_image: Union[str, IO[bytes]],
generator: Iterator[int],
shift: int = 0,
encoding: str = "UTF-8",
):
"""Find a message in an image (with the LSB technique).
"""
img = tools.open_image(input_image)
img_list = list(img.getdata())
width, height = img.size
buff, coun... | [
"def",
"reveal",
"(",
"input_image",
":",
"Union",
"[",
"str",
",",
"IO",
"[",
"bytes",
"]",
"]",
",",
"generator",
":",
"Iterator",
"[",
"int",
"]",
",",
"shift",
":",
"int",
"=",
"0",
",",
"encoding",
":",
"str",
"=",
"\"UTF-8\"",
",",
")",
":"... | 32.285714 | 16.4 |
def flood(im, regions=None, mode='max'):
r"""
Floods/fills each region in an image with a single value based on the
specific values in that region. The ``mode`` argument is used to
determine how the value is calculated.
Parameters
----------
im : array_like
An ND image with isolate... | [
"def",
"flood",
"(",
"im",
",",
"regions",
"=",
"None",
",",
"mode",
"=",
"'max'",
")",
":",
"mask",
"=",
"im",
">",
"0",
"if",
"regions",
"is",
"None",
":",
"labels",
",",
"N",
"=",
"spim",
".",
"label",
"(",
"mask",
")",
"else",
":",
"labels"... | 29.467742 | 20.774194 |
def _resume(self):
# type: (Descriptor) -> int
"""Resume a download, if possible
:param Descriptor self: this
:rtype: int or None
:return: verified download offset
"""
if self._resume_mgr is None or self._offset > 0 or self._finalized:
return None
... | [
"def",
"_resume",
"(",
"self",
")",
":",
"# type: (Descriptor) -> int",
"if",
"self",
".",
"_resume_mgr",
"is",
"None",
"or",
"self",
".",
"_offset",
">",
"0",
"or",
"self",
".",
"_finalized",
":",
"return",
"None",
"# check if path exists in resume db",
"rr",
... | 45.060606 | 14.252525 |
def sparse(x, rho, penalty):
"""
Proximal operator for the l1-norm: soft thresholding
Parameters
----------
penalty : float
Strength or weight on the l1-norm
"""
lmbda = penalty / rho
return (x - lmbda) * (x >= lmbda) + (x + lmbda) * (x <= -lmbda) | [
"def",
"sparse",
"(",
"x",
",",
"rho",
",",
"penalty",
")",
":",
"lmbda",
"=",
"penalty",
"/",
"rho",
"return",
"(",
"x",
"-",
"lmbda",
")",
"*",
"(",
"x",
">=",
"lmbda",
")",
"+",
"(",
"x",
"+",
"lmbda",
")",
"*",
"(",
"x",
"<=",
"-",
"lmb... | 23.166667 | 18.666667 |
def thread( mafs, species ):
"""
Restrict an list of alignments to a given list of species by:
1) Removing components for any other species
2) Remove any columns containing all gaps
Example:
>>> import bx.align.maf
>>> block1 = bx.align.maf.from_string( '''... | [
"def",
"thread",
"(",
"mafs",
",",
"species",
")",
":",
"for",
"m",
"in",
"mafs",
":",
"new_maf",
"=",
"deepcopy",
"(",
"m",
")",
"new_components",
"=",
"get_components_for_species",
"(",
"new_maf",
",",
"species",
")",
"if",
"new_components",
":",
"remove... | 44.087719 | 33.035088 |
def create_circuit_termination(circuit, interface, device, speed, xconnect_id=None, term_side='A'):
'''
.. versionadded:: 2019.2.0
Terminate a circuit on an interface
circuit
The name of the circuit
interface
The name of the interface to terminate on
device
The name of ... | [
"def",
"create_circuit_termination",
"(",
"circuit",
",",
"interface",
",",
"device",
",",
"speed",
",",
"xconnect_id",
"=",
"None",
",",
"term_side",
"=",
"'A'",
")",
":",
"nb_device",
"=",
"get_",
"(",
"'dcim'",
",",
"'devices'",
",",
"name",
"=",
"devic... | 33.306122 | 21.795918 |
def _has_perm(self, permission_name, view_menu_name):
"""
Whether the user has this perm
"""
if hasattr(self, 'perms'):
if (permission_name, view_menu_name) in self.perms:
return True
# rebuild the permissions set
self._get_and_cache_perms()
... | [
"def",
"_has_perm",
"(",
"self",
",",
"permission_name",
",",
"view_menu_name",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'perms'",
")",
":",
"if",
"(",
"permission_name",
",",
"view_menu_name",
")",
"in",
"self",
".",
"perms",
":",
"return",
"True",
... | 37.1 | 8.7 |
def scalar_pb(tag, data, description=None):
"""Create a scalar summary_pb2.Summary protobuf.
Arguments:
tag: String tag for the summary.
data: A 0-dimensional `np.array` or a compatible python number type.
description: Optional long-form description for this summary, as a
`str`. Markdown is suppo... | [
"def",
"scalar_pb",
"(",
"tag",
",",
"data",
",",
"description",
"=",
"None",
")",
":",
"arr",
"=",
"np",
".",
"array",
"(",
"data",
")",
"if",
"arr",
".",
"shape",
"!=",
"(",
")",
":",
"raise",
"ValueError",
"(",
"'Expected scalar shape for tensor, got ... | 37.931034 | 19.482759 |
def attach_storage(self, server, storage, storage_type, address):
"""
Attach a Storage object to a Server. Return a list of the server's storages.
"""
body = {'storage_device': {}}
if storage:
body['storage_device']['storage'] = str(storage)
if storage_type:
... | [
"def",
"attach_storage",
"(",
"self",
",",
"server",
",",
"storage",
",",
"storage_type",
",",
"address",
")",
":",
"body",
"=",
"{",
"'storage_device'",
":",
"{",
"}",
"}",
"if",
"storage",
":",
"body",
"[",
"'storage_device'",
"]",
"[",
"'storage'",
"]... | 37.529412 | 22.235294 |
def _alerter_thread_func(self) -> None:
""" Prints alerts and updates the prompt any time the prompt is showing """
self._alert_count = 0
self._next_alert_time = 0
while not self._stop_thread:
# Always acquire terminal_lock before printing alerts or updating the prompt
... | [
"def",
"_alerter_thread_func",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"_alert_count",
"=",
"0",
"self",
".",
"_next_alert_time",
"=",
"0",
"while",
"not",
"self",
".",
"_stop_thread",
":",
"# Always acquire terminal_lock before printing alerts or updating t... | 40.15625 | 21.8125 |
def modified_lines_from_udiff(udiff):
"""Extract from a udiff an iterator of tuples of (start, end) line
numbers."""
chunks = re.split('\n@@ [^\n]+\n', udiff)[1:]
line_numbers = re.findall('@@\s[+-]\d+,\d+ \+(\d+)', udiff)
line_numbers = list(map(int, line_numbers))
for c, start in zip(chunks,... | [
"def",
"modified_lines_from_udiff",
"(",
"udiff",
")",
":",
"chunks",
"=",
"re",
".",
"split",
"(",
"'\\n@@ [^\\n]+\\n'",
",",
"udiff",
")",
"[",
"1",
":",
"]",
"line_numbers",
"=",
"re",
".",
"findall",
"(",
"'@@\\s[+-]\\d+,\\d+ \\+(\\d+)'",
",",
"udiff",
"... | 41.8 | 14.933333 |
def create_plan(self, *, plan_code, description, interval, interval_count, max_payments_allowed,
payment_attempts_delay, plan_value, plan_tax, plan_tax_return_base, currency,
max_payment_attempts=None, max_pending_payments=None, trial_days=None):
"""
Creating a ne... | [
"def",
"create_plan",
"(",
"self",
",",
"*",
",",
"plan_code",
",",
"description",
",",
"interval",
",",
"interval_count",
",",
"max_payments_allowed",
",",
"payment_attempts_delay",
",",
"plan_value",
",",
"plan_tax",
",",
"plan_tax_return_base",
",",
"currency",
... | 38.716049 | 25.259259 |
def do_thing():
"""Execute command line cryptorito actions"""
if len(sys.argv) == 5 and sys.argv[1] == "encrypt_file":
encrypt_file(sys.argv[2], sys.argv[3], sys.argv[4])
elif len(sys.argv) == 4 and sys.argv[1] == "decrypt_file":
decrypt_file(sys.argv[2], sys.argv[3])
elif len(sys.argv) ... | [
"def",
"do_thing",
"(",
")",
":",
"if",
"len",
"(",
"sys",
".",
"argv",
")",
"==",
"5",
"and",
"sys",
".",
"argv",
"[",
"1",
"]",
"==",
"\"encrypt_file\"",
":",
"encrypt_file",
"(",
"sys",
".",
"argv",
"[",
"2",
"]",
",",
"sys",
".",
"argv",
"[... | 43.681818 | 16 |
def subscribe(self, *events: Union[Event, Pager]) -> Callable:
"""Call a function in response to an event.
If more than one event is given, `func` will be given
as many arguments as there are events.
If the pager calls notify, the decorated function will be called.
Parameters
... | [
"def",
"subscribe",
"(",
"self",
",",
"*",
"events",
":",
"Union",
"[",
"Event",
",",
"Pager",
"]",
")",
"->",
"Callable",
":",
"try",
":",
"first_event",
"=",
"events",
"[",
"0",
"]",
"except",
"IndexError",
":",
"raise",
"IndexError",
"(",
"'Must sub... | 37.373494 | 19.084337 |
def parse_args(args):
"""Parse command line parameters
Args:
args ([str]): Command line parameters as list of strings
Returns:
:obj:`argparse.Namespace`: command line parameters namespace
"""
parser = argparse.ArgumentParser(
description="Imports GramVaani data for Deep Speech"
... | [
"def",
"parse_args",
"(",
"args",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"Imports GramVaani data for Deep Speech\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--version\"",
",",
"action",
"=",
"\"version\"",
",",
"... | 25.833333 | 18.604167 |
def _transform(self, Y, scan_onsets, beta, beta0,
rho_e, sigma_e, rho_X, sigma2_X, rho_X0, sigma2_X0):
""" Given the data Y and the response amplitudes beta and beta0
estimated in the fit step, estimate the corresponding X and X0.
It is done by a forward-backward algor... | [
"def",
"_transform",
"(",
"self",
",",
"Y",
",",
"scan_onsets",
",",
"beta",
",",
"beta0",
",",
"rho_e",
",",
"sigma_e",
",",
"rho_X",
",",
"sigma2_X",
",",
"rho_X0",
",",
"sigma2_X0",
")",
":",
"logger",
".",
"info",
"(",
"'Transforming new data.'",
")"... | 45.730769 | 14.538462 |
def create_listeners(name, listeners, region=None, key=None, keyid=None,
profile=None):
'''
Create listeners on an ELB.
CLI example:
.. code-block:: bash
salt myminion boto_elb.create_listeners myelb '[["HTTPS", "HTTP", 443, 80, "arn:aws:iam::11 11111:server-certificate/... | [
"def",
"create_listeners",
"(",
"name",
",",
"listeners",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
... | 36.148148 | 26.962963 |
def make_nn_funs(layer_sizes, L2_reg, noise_variance, nonlinearity=np.tanh):
"""These functions implement a standard multi-layer perceptron,
vectorized over both training examples and weight samples."""
shapes = list(zip(layer_sizes[:-1], layer_sizes[1:]))
num_weights = sum((m+1)*n for m, n in shapes)
... | [
"def",
"make_nn_funs",
"(",
"layer_sizes",
",",
"L2_reg",
",",
"noise_variance",
",",
"nonlinearity",
"=",
"np",
".",
"tanh",
")",
":",
"shapes",
"=",
"list",
"(",
"zip",
"(",
"layer_sizes",
"[",
":",
"-",
"1",
"]",
",",
"layer_sizes",
"[",
"1",
":",
... | 43.344828 | 14.965517 |
def add_prefix(self, auth, attr, args=None):
""" Add a prefix and return its ID.
* `auth` [BaseAuth]
AAA options.
* `attr` [prefix_attr]
Prefix attributes.
* `args` [add_prefix_args]
Arguments explaining how the prefix should b... | [
"def",
"add_prefix",
"(",
"self",
",",
"auth",
",",
"attr",
",",
"args",
"=",
"None",
")",
":",
"if",
"args",
"is",
"None",
":",
"args",
"=",
"{",
"}",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"add_prefix called; attr: %s; args: %s\"",
"%",
"(",
"u... | 39.990148 | 22.433498 |
def heatmap(dm, partition=None, cmap=CM.Blues, fontsize=10):
""" heatmap(dm, partition=None, cmap=CM.Blues, fontsize=10)
Produce a 2D plot of the distance matrix, with values encoded by
coloured cells.
Args:
partition: treeCl.Partition object - if supplied, will reorder
... | [
"def",
"heatmap",
"(",
"dm",
",",
"partition",
"=",
"None",
",",
"cmap",
"=",
"CM",
".",
"Blues",
",",
"fontsize",
"=",
"10",
")",
":",
"assert",
"isinstance",
"(",
"dm",
",",
"DistanceMatrix",
")",
"datamax",
"=",
"float",
"(",
"np",
".",
"abs",
"... | 31.288462 | 21.980769 |
def get_configs(self):
"""Load all config files and return the configobjs
:returns: a list of configobjs
:raises: None
It always loads the coreconfig.
Then it looks for all configs inside the PLUGIN_CONFIG_DIR.
It will find the corresponding spec of the plugins.
... | [
"def",
"get_configs",
"(",
"self",
")",
":",
"# all loaded configs are stored in confs",
"confs",
"=",
"[",
"]",
"# always load core config. it is not part of the plugin configs",
"try",
":",
"confs",
".",
"append",
"(",
"iniconf",
".",
"get_core_config",
"(",
")",
")",... | 36.065574 | 18.04918 |
def QA_indicator_BIAS(DataFrame, N1, N2, N3):
'乖离率'
CLOSE = DataFrame['close']
BIAS1 = (CLOSE - MA(CLOSE, N1)) / MA(CLOSE, N1) * 100
BIAS2 = (CLOSE - MA(CLOSE, N2)) / MA(CLOSE, N2) * 100
BIAS3 = (CLOSE - MA(CLOSE, N3)) / MA(CLOSE, N3) * 100
DICT = {'BIAS1': BIAS1, 'BIAS2': BIAS2, 'BIAS3': BIAS3}... | [
"def",
"QA_indicator_BIAS",
"(",
"DataFrame",
",",
"N1",
",",
"N2",
",",
"N3",
")",
":",
"CLOSE",
"=",
"DataFrame",
"[",
"'close'",
"]",
"BIAS1",
"=",
"(",
"CLOSE",
"-",
"MA",
"(",
"CLOSE",
",",
"N1",
")",
")",
"/",
"MA",
"(",
"CLOSE",
",",
"N1",... | 38.111111 | 18.555556 |
def get_language_data(self, qid, lang, lang_data_type):
"""
get language data for specified qid
:param qid:
:param lang: language code
:param lang_data_type: 'label', 'description' or 'aliases'
:return: list of strings
If nothing is found:
If lang_data... | [
"def",
"get_language_data",
"(",
"self",
",",
"qid",
",",
"lang",
",",
"lang_data_type",
")",
":",
"self",
".",
"init_language_data",
"(",
"lang",
",",
"lang_data_type",
")",
"current_lang_data",
"=",
"self",
".",
"loaded_langs",
"[",
"lang",
"]",
"[",
"lang... | 41.210526 | 14.894737 |
def set(self, oid, value, value_type=None):
"""
Sets a single OID value. If you do not pass value_type hnmp will
try to guess the correct type. Autodetection is supported for:
* int and float (as Integer, fractional part will be discarded)
* IPv4 address (as IpAddress)
*... | [
"def",
"set",
"(",
"self",
",",
"oid",
",",
"value",
",",
"value_type",
"=",
"None",
")",
":",
"snmpsecurity",
"=",
"self",
".",
"_get_snmp_security",
"(",
")",
"if",
"value_type",
"is",
"None",
":",
"if",
"isinstance",
"(",
"value",
",",
"int",
")",
... | 36.636364 | 16.745455 |
def is_numeric(obj):
"""
This detects whether an input object is numeric or not.
:param obj: object to be tested.
"""
try:
obj+obj, obj-obj, obj*obj, obj**obj, obj/obj
except ZeroDivisionError:
return True
except Exception:
return False
else:
return True | [
"def",
"is_numeric",
"(",
"obj",
")",
":",
"try",
":",
"obj",
"+",
"obj",
",",
"obj",
"-",
"obj",
",",
"obj",
"*",
"obj",
",",
"obj",
"**",
"obj",
",",
"obj",
"/",
"obj",
"except",
"ZeroDivisionError",
":",
"return",
"True",
"except",
"Exception",
... | 21.857143 | 17.857143 |
def to_line_string(self, closed=True):
"""
Convert this polygon's `exterior` to a ``LineString`` instance.
Parameters
----------
closed : bool, optional
Whether to close the line string, i.e. to add the first point of
the `exterior` also as the last point... | [
"def",
"to_line_string",
"(",
"self",
",",
"closed",
"=",
"True",
")",
":",
"from",
"imgaug",
".",
"augmentables",
".",
"lines",
"import",
"LineString",
"if",
"not",
"closed",
"or",
"len",
"(",
"self",
".",
"exterior",
")",
"<=",
"1",
":",
"return",
"L... | 36.208333 | 21.208333 |
def patched_context(*module_names, **kwargs):
"""apply emulation patches only for a specific context
:param module_names: var-args for the modules to patch, as in :func:`patch`
:param local:
if True, unpatching is done on every switch-out, and re-patching on
every switch-in, so that they ar... | [
"def",
"patched_context",
"(",
"*",
"module_names",
",",
"*",
"*",
"kwargs",
")",
":",
"local",
"=",
"kwargs",
".",
"pop",
"(",
"'local'",
",",
"False",
")",
"if",
"kwargs",
":",
"raise",
"TypeError",
"(",
"\"patched_context() got an unexpected keyword \"",
"+... | 33.3 | 21.866667 |
def item_sectie_adapter(obj, request):
"""
Adapter for rendering an object of
:class: `crabpy.gateway.capakey.Sectie` to json.
"""
return {
'id': obj.id,
'afdeling': {
'id': obj.afdeling.id,
'naam': obj.afdeling.naam,
'gemeente': {
... | [
"def",
"item_sectie_adapter",
"(",
"obj",
",",
"request",
")",
":",
"return",
"{",
"'id'",
":",
"obj",
".",
"id",
",",
"'afdeling'",
":",
"{",
"'id'",
":",
"obj",
".",
"afdeling",
".",
"id",
",",
"'naam'",
":",
"obj",
".",
"afdeling",
".",
"naam",
... | 27.333333 | 12.222222 |
def checktypes(func):
"""Decorator to verify arguments and return types."""
sig = inspect.signature(func)
types = {}
for param in sig.parameters.values():
# Iterate through function's parameters and build the list of
# arguments types
param_type = param.annotation
if par... | [
"def",
"checktypes",
"(",
"func",
")",
":",
"sig",
"=",
"inspect",
".",
"signature",
"(",
"func",
")",
"types",
"=",
"{",
"}",
"for",
"param",
"in",
"sig",
".",
"parameters",
".",
"values",
"(",
")",
":",
"# Iterate through function's parameters and build th... | 42.051948 | 20.116883 |
def _pick_up_classes(modules, classnames):
""" Given a list of class names to retrieve, try to fetch them from the specified list of
modules and returns the list of the fetched classes.
"""
klasses = []
for classname in classnames:
klass = None
for module in modules:
... | [
"def",
"_pick_up_classes",
"(",
"modules",
",",
"classnames",
")",
":",
"klasses",
"=",
"[",
"]",
"for",
"classname",
"in",
"classnames",
":",
"klass",
"=",
"None",
"for",
"module",
"in",
"modules",
":",
"if",
"hasattr",
"(",
"module",
",",
"classname",
... | 37.647059 | 15.294118 |
def get_all_subscriptions(self, server_id):
"""
Return all indication subscriptions in a WBEM server.
This function contacts the WBEM server and retrieves the indication
subscriptions by enumerating the instances of CIM class
"CIM_IndicationSubscription" in the Interop namespace... | [
"def",
"get_all_subscriptions",
"(",
"self",
",",
"server_id",
")",
":",
"# Validate server_id",
"server",
"=",
"self",
".",
"_get_server",
"(",
"server_id",
")",
"return",
"server",
".",
"conn",
".",
"EnumerateInstances",
"(",
"SUBSCRIPTION_CLASSNAME",
",",
"name... | 31.666667 | 25.266667 |
def _validate_no_null_values(self):
"""
Loads the tables from the gtfs object and counts the number of rows that have null values in
fields that should not be null. Stores the number of null rows in warnings_container
"""
for table in DB_TABLE_NAMES:
null_not_ok_warni... | [
"def",
"_validate_no_null_values",
"(",
"self",
")",
":",
"for",
"table",
"in",
"DB_TABLE_NAMES",
":",
"null_not_ok_warning",
"=",
"\"Null values in must-have columns in table {table}\"",
".",
"format",
"(",
"table",
"=",
"table",
")",
"null_warn_warning",
"=",
"\"Null ... | 62.05 | 33.85 |
def scan_to_module(python_modules, module, ignore=tuple()):
"""
Scans `python_modules` with :py:func:`scan` and adds found providers
to `module`'s :py:attr:`wiring.configuration.Module.providers`.
`ignore` argument is passed through to :py:func:`scan`.
"""
def callback(specification, provider):... | [
"def",
"scan_to_module",
"(",
"python_modules",
",",
"module",
",",
"ignore",
"=",
"tuple",
"(",
")",
")",
":",
"def",
"callback",
"(",
"specification",
",",
"provider",
")",
":",
"module",
".",
"providers",
"[",
"specification",
"]",
"=",
"provider",
"sca... | 41.2 | 15.8 |
def print_to_tsplib(self, edges, tspfile, precision=0):
"""
See TSPlib format:
<https://www.iwr.uni-heidelberg.de/groups/comopt/software/TSPLIB95/>
NAME: bayg29
TYPE: TSP
COMMENT: 29 Cities in Bavaria, geographical distances
DIMENSION: 29
EDGE_WEIGHT_TYPE... | [
"def",
"print_to_tsplib",
"(",
"self",
",",
"edges",
",",
"tspfile",
",",
"precision",
"=",
"0",
")",
":",
"fw",
"=",
"must_open",
"(",
"tspfile",
",",
"\"w\"",
")",
"incident",
",",
"nodes",
"=",
"node_to_edge",
"(",
"edges",
",",
"directed",
"=",
"Fa... | 36.836735 | 16.755102 |
def find_cross_contamination(databases, pair, tmpdir='tmp', log='log.txt', threads=1):
"""
Usese mash to find out whether or not a sample has more than one genus present, indicating cross-contamination.
:param databases: A databases folder, which must contain refseq.msh, a mash sketch that has one represent... | [
"def",
"find_cross_contamination",
"(",
"databases",
",",
"pair",
",",
"tmpdir",
"=",
"'tmp'",
",",
"log",
"=",
"'log.txt'",
",",
"threads",
"=",
"1",
")",
":",
"genera_present",
"=",
"list",
"(",
")",
"out",
",",
"err",
",",
"cmd",
"=",
"mash",
".",
... | 54.138889 | 24.027778 |
def set_applications_from_meta(self, metadata, exclude=None):
"""
Parses meta and update or create each application
:param str metadata: path or url to meta.yml
:param list[str] exclude: List of application names, to exclude from meta.
This might be need... | [
"def",
"set_applications_from_meta",
"(",
"self",
",",
"metadata",
",",
"exclude",
"=",
"None",
")",
":",
"if",
"not",
"exclude",
":",
"exclude",
"=",
"[",
"]",
"if",
"metadata",
".",
"startswith",
"(",
"'http'",
")",
":",
"meta",
"=",
"yaml",
".",
"sa... | 42.409091 | 15.863636 |
def build_vep_string(vep_info, vep_columns):
"""
Build a vep string formatted string.
Take a list with vep annotations and build a new vep string
Args:
vep_info (list): A list with vep annotation dictionaries
vep_columns (list): A list with the vep column names found in the
... | [
"def",
"build_vep_string",
"(",
"vep_info",
",",
"vep_columns",
")",
":",
"logger",
"=",
"getLogger",
"(",
"__name__",
")",
"logger",
".",
"debug",
"(",
"\"Building vep string from {0}\"",
".",
"format",
"(",
"vep_info",
")",
")",
"logger",
".",
"debug",
"(",
... | 32.448276 | 20.448276 |
def find_peaks(data, threshold, box_size=3, footprint=None, mask=None,
border_width=None, npeaks=np.inf, centroid_func=None,
subpixel=False, error=None, wcs=None):
"""
Find local peaks in an image that are above above a specified
threshold value.
Peaks are the maxima above... | [
"def",
"find_peaks",
"(",
"data",
",",
"threshold",
",",
"box_size",
"=",
"3",
",",
"footprint",
"=",
"None",
",",
"mask",
"=",
"None",
",",
"border_width",
"=",
"None",
",",
"npeaks",
"=",
"np",
".",
"inf",
",",
"centroid_func",
"=",
"None",
",",
"s... | 40.005556 | 21.983333 |
def add_show_function(self, show_name, show_func):
"""
Appends a show function to the locally cached DesignDocument
shows dictionary.
:param show_name: Name used to identify the show function.
:param show_func: Javascript show function.
"""
if self.get_show_funct... | [
"def",
"add_show_function",
"(",
"self",
",",
"show_name",
",",
"show_func",
")",
":",
"if",
"self",
".",
"get_show_function",
"(",
"show_name",
")",
"is",
"not",
"None",
":",
"raise",
"CloudantArgumentError",
"(",
"110",
",",
"show_name",
")",
"self",
".",
... | 37.166667 | 17.833333 |
def include(_name_or_func, *args,
_module=None, _default='includeme', **kwargs):
""" Resolve and call functions
"""
if callable(_name_or_func):
resolved = _name_or_func
else:
resolved = resolve_str(_name_or_func, _module, _default)
resolved(*args, **kwargs) | [
"def",
"include",
"(",
"_name_or_func",
",",
"*",
"args",
",",
"_module",
"=",
"None",
",",
"_default",
"=",
"'includeme'",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"callable",
"(",
"_name_or_func",
")",
":",
"resolved",
"=",
"_name_or_func",
"else",
":"... | 29.7 | 14.8 |
def issue(self, invoice_id, **kwargs):
""""
Issues an invoice in draft state
Args:
invoice_id : Id for delete the invoice
Returns:
Its response is the invoice entity, similar to create/update API response. Its status now would be issued.
"""
url =... | [
"def",
"issue",
"(",
"self",
",",
"invoice_id",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"\"{}/{}/issue\"",
".",
"format",
"(",
"self",
".",
"base_url",
",",
"invoice_id",
")",
"return",
"self",
".",
"post_url",
"(",
"url",
",",
"{",
"}",
",",
... | 36.909091 | 19 |
def set_info_mapper_model(self, mapper, model):
"""Set the model for the info mapper
:param mapper: the mapper to update
:type mapper: QtGui.QDataWidgetMapper
:param model: The model to set
:type model: QtGui.QAbstractItemModel | None
:returns: None
:rtype: None
... | [
"def",
"set_info_mapper_model",
"(",
"self",
",",
"mapper",
",",
"model",
")",
":",
"# nothing changed. we can return.",
"# I noticed that when you set the model the very first time to None",
"# it printed a message:",
"# QObject::connect: Cannot connect (null)::dataChanged(QModelIndex,QMo... | 46.133333 | 18.911111 |
def handle_json_GET_boundboxstops(self, params):
"""Return a list of up to 'limit' stops within bounding box with 'n','e'
and 's','w' in the NE and SW corners. Does not handle boxes crossing
longitude line 180."""
schedule = self.server.schedule
n = float(params.get('n'))
e = float(params.get('e... | [
"def",
"handle_json_GET_boundboxstops",
"(",
"self",
",",
"params",
")",
":",
"schedule",
"=",
"self",
".",
"server",
".",
"schedule",
"n",
"=",
"float",
"(",
"params",
".",
"get",
"(",
"'n'",
")",
")",
"e",
"=",
"float",
"(",
"params",
".",
"get",
"... | 45 | 11.333333 |
def defer_sync(self, func):
"""
Arrange for `func()` to execute on :class:`Broker` thread, blocking the
current thread until a result or exception is available.
:returns:
Return value of `func()`.
"""
latch = Latch()
def wrapper():
try:
... | [
"def",
"defer_sync",
"(",
"self",
",",
"func",
")",
":",
"latch",
"=",
"Latch",
"(",
")",
"def",
"wrapper",
"(",
")",
":",
"try",
":",
"latch",
".",
"put",
"(",
"func",
"(",
")",
")",
"except",
"Exception",
":",
"latch",
".",
"put",
"(",
"sys",
... | 28.526316 | 15.473684 |
def check_for_lane_permission(self):
"""
One or more permissions can be associated with a lane
of a workflow. In a similar way, a lane can be
restricted with relation to other lanes of the workflow.
This method called on lane changes and checks user has
required permissi... | [
"def",
"check_for_lane_permission",
"(",
"self",
")",
":",
"# TODO: Cache lane_data in app memory",
"if",
"self",
".",
"current",
".",
"lane_permission",
":",
"log",
".",
"debug",
"(",
"\"HAS LANE PERM: %s\"",
"%",
"self",
".",
"current",
".",
"lane_permission",
")"... | 43.970588 | 21.147059 |
def unpack(self, unpacker):
"""
unpack the contents of this instance from the values in unpacker
"""
(a, b, c) = unpacker.unpack_struct(_HHH)
self.access_flags = a
self.name_ref = b
self.descriptor_ref = c
self.attribs.unpack(unpacker) | [
"def",
"unpack",
"(",
"self",
",",
"unpacker",
")",
":",
"(",
"a",
",",
"b",
",",
"c",
")",
"=",
"unpacker",
".",
"unpack_struct",
"(",
"_HHH",
")",
"self",
".",
"access_flags",
"=",
"a",
"self",
".",
"name_ref",
"=",
"b",
"self",
".",
"descriptor_... | 26.454545 | 15.545455 |
def alpha_blend(self, other):
"""Alpha-blend this color on the other one.
Args:
:other:
The grapefruit.Color to alpha-blend with this one.
Returns:
A grapefruit.Color instance which is the result of alpha-blending
this color on the other one.
>>> c1 = Color.from_rgb(1, 0.5, ... | [
"def",
"alpha_blend",
"(",
"self",
",",
"other",
")",
":",
"# get final alpha channel",
"fa",
"=",
"self",
".",
"__a",
"+",
"other",
".",
"__a",
"-",
"(",
"self",
".",
"__a",
"*",
"other",
".",
"__a",
")",
"# get percentage of source alpha compared to final al... | 27.25 | 20.75 |
def __make_another_index(self, list_of_entries, url=False, hs_admin=False):
'''
Find an index not yet used in the handle record and not reserved for
any (other) special type.
:param: list_of_entries: List of all entries to find which indices are
used already.
:pa... | [
"def",
"__make_another_index",
"(",
"self",
",",
"list_of_entries",
",",
"url",
"=",
"False",
",",
"hs_admin",
"=",
"False",
")",
":",
"start",
"=",
"2",
"# reserved indices:",
"reserved_for_url",
"=",
"set",
"(",
"[",
"1",
"]",
")",
"reserved_for_admin",
"=... | 36.4 | 22.1 |
def timesince_or_never(dt, default=None):
"""Call the Django ``timesince`` filter or a given default string.
It returns the string *default* if *dt* is not a valid ``date``
or ``datetime`` object.
When *default* is None, "Never" is returned.
"""
if default is None:
default = _("Never")
... | [
"def",
"timesince_or_never",
"(",
"dt",
",",
"default",
"=",
"None",
")",
":",
"if",
"default",
"is",
"None",
":",
"default",
"=",
"_",
"(",
"\"Never\"",
")",
"if",
"isinstance",
"(",
"dt",
",",
"datetime",
".",
"date",
")",
":",
"return",
"timesince",... | 29.071429 | 15.857143 |
def render(self):
"""
Find {{}} tokens; resolve then replace them as described elsewhere
Resolution is multi-pass: tokens may be nested to form parts of other tokens.
Token search steps when resolving symbols
- 1. lookups of AWS resource identifiers, such as a security group ID
- 2. secure ... | [
"def",
"render",
"(",
"self",
")",
":",
"# Ensure that our symbols are clean and are not from a previous template that was rendered",
"self",
".",
"symbols",
"=",
"set",
"(",
")",
"# Until all symbols are resolved or it is determined that some cannot be resolved, repeat:",
"go_again",
... | 50.12963 | 22.462963 |
def new(self):
# type: () -> None
'''
A method to create a new UDF Terminating Descriptor.
Parameters:
None.
Returns:
Nothing.
'''
if self._initialized:
raise pycdlibexception.PyCdlibInternalError('UDF Terminating Descriptor already ... | [
"def",
"new",
"(",
"self",
")",
":",
"# type: () -> None",
"if",
"self",
".",
"_initialized",
":",
"raise",
"pycdlibexception",
".",
"PyCdlibInternalError",
"(",
"'UDF Terminating Descriptor already initialized'",
")",
"self",
".",
"desc_tag",
"=",
"UDFTag",
"(",
")... | 27.352941 | 27.235294 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.