text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def stop(self):
"""Stop the process."""
logger.info("stopping process")
self.watcher.stop()
os.kill(self.child_pid, signal.SIGTERM) | [
"def",
"stop",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"\"stopping process\"",
")",
"self",
".",
"watcher",
".",
"stop",
"(",
")",
"os",
".",
"kill",
"(",
"self",
".",
"child_pid",
",",
"signal",
".",
"SIGTERM",
")"
] | 31.8 | 0.01227 |
def main(command_line_args=None):
'''Connor entry point. See help for more info'''
log = None
if not command_line_args:
command_line_args = sys.argv
try:
start_time = time.time()
args = parse_command_line_args(command_line_args)
log = utils.Logger(args)
command_va... | [
"def",
"main",
"(",
"command_line_args",
"=",
"None",
")",
":",
"log",
"=",
"None",
"if",
"not",
"command_line_args",
":",
"command_line_args",
"=",
"sys",
".",
"argv",
"try",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"args",
"=",
"parse_com... | 45.458333 | 0.005832 |
def apply_security_groups(name, security_groups, region=None, key=None,
keyid=None, profile=None):
'''
Apply security groups to ELB.
CLI example:
.. code-block:: bash
salt myminion boto_elb.apply_security_groups myelb '["mysecgroup1"]'
'''
conn = _get_conn(re... | [
"def",
"apply_security_groups",
"(",
"name",
",",
"security_groups",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"ke... | 33.916667 | 0.001195 |
def data_to_uuid(data):
"""Convert an array of binary data to the iBeacon uuid format."""
string = data_to_hexstring(data)
return string[0:8]+'-'+string[8:12]+'-'+string[12:16]+'-'+string[16:20]+'-'+string[20:32] | [
"def",
"data_to_uuid",
"(",
"data",
")",
":",
"string",
"=",
"data_to_hexstring",
"(",
"data",
")",
"return",
"string",
"[",
"0",
":",
"8",
"]",
"+",
"'-'",
"+",
"string",
"[",
"8",
":",
"12",
"]",
"+",
"'-'",
"+",
"string",
"[",
"12",
":",
"16",... | 55.25 | 0.008929 |
def findNextPoint(DiscFac,Rfree,CRRA,PermGroFacCmp,UnempPrb,Rnrm,Beth,cNext,mNext,MPCnext,PFMPC):
'''
Calculates what consumption, market resources, and the marginal propensity
to consume must have been in the previous period given model parameters and
values of market resources, consumption, and MPC to... | [
"def",
"findNextPoint",
"(",
"DiscFac",
",",
"Rfree",
",",
"CRRA",
",",
"PermGroFacCmp",
",",
"UnempPrb",
",",
"Rnrm",
",",
"Beth",
",",
"cNext",
",",
"mNext",
",",
"MPCnext",
",",
"PFMPC",
")",
":",
"uPP",
"=",
"lambda",
"x",
":",
"utilityPP",
"(",
... | 41.795918 | 0.010973 |
def flanking(args):
"""
%prog flanking bedfile [options]
Get up to n features (upstream or downstream or both) flanking a given position.
"""
from numpy import array, argsort
p = OptionParser(flanking.__doc__)
p.add_option("--chrom", default=None, type="string",
help="chrom nam... | [
"def",
"flanking",
"(",
"args",
")",
":",
"from",
"numpy",
"import",
"array",
",",
"argsort",
"p",
"=",
"OptionParser",
"(",
"flanking",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--chrom\"",
",",
"default",
"=",
"None",
",",
"type",
"=",
"\"... | 34.732143 | 0.0075 |
def iskip( value, iterable ):
""" Skips all values in 'iterable' matching the given 'value'. """
for e in iterable:
if value is None:
if e is None:
continue
elif e == value:
continue
yield e | [
"def",
"iskip",
"(",
"value",
",",
"iterable",
")",
":",
"for",
"e",
"in",
"iterable",
":",
"if",
"value",
"is",
"None",
":",
"if",
"e",
"is",
"None",
":",
"continue",
"elif",
"e",
"==",
"value",
":",
"continue",
"yield",
"e"
] | 26.3 | 0.011029 |
def warsaw_up_to_warsaw(C, parameters=None, sectors=None):
"""Translate from the 'Warsaw up' basis to the Warsaw basis.
Parameters used:
- `Vus`, `Vub`, `Vcb`, `gamma`: elements of the unitary CKM matrix (defined
as the mismatch between left-handed quark mass matrix diagonalization
matrices).
... | [
"def",
"warsaw_up_to_warsaw",
"(",
"C",
",",
"parameters",
"=",
"None",
",",
"sectors",
"=",
"None",
")",
":",
"C_in",
"=",
"smeftutil",
".",
"wcxf2arrays_symmetrized",
"(",
"C",
")",
"p",
"=",
"default_parameters",
".",
"copy",
"(",
")",
"if",
"parameters... | 43 | 0.001083 |
def create_event_handler(event_type, handler):
"""Register a comm and return a serializable object with target name"""
target_name = '{hash}_{event_type}'.format(hash=hash(handler), event_type=event_type)
def handle_comm_opened(comm, msg):
@comm.on_msg
def _handle_msg(msg):
dat... | [
"def",
"create_event_handler",
"(",
"event_type",
",",
"handler",
")",
":",
"target_name",
"=",
"'{hash}_{event_type}'",
".",
"format",
"(",
"hash",
"=",
"hash",
"(",
"handler",
")",
",",
"event_type",
"=",
"event_type",
")",
"def",
"handle_comm_opened",
"(",
... | 36.090909 | 0.004908 |
def _head(self, client_kwargs):
"""
Returns object HTTP header.
Args:
client_kwargs (dict): Client arguments.
Returns:
dict: HTTP header.
"""
with _handle_client_exception():
# Object
if 'obj' in client_kwargs:
... | [
"def",
"_head",
"(",
"self",
",",
"client_kwargs",
")",
":",
"with",
"_handle_client_exception",
"(",
")",
":",
"# Object",
"if",
"'obj'",
"in",
"client_kwargs",
":",
"return",
"self",
".",
"client",
".",
"head_object",
"(",
"*",
"*",
"client_kwargs",
")",
... | 26.117647 | 0.004348 |
def fromtab(args):
"""
%prog fromtab tabfile fastafile
Convert 2-column sequence file to FASTA format. One usage for this is to
generatea `adapters.fasta` for TRIMMOMATIC.
"""
p = OptionParser(fromtab.__doc__)
p.set_sep(sep=None)
p.add_option("--noheader", default=False, action="store_t... | [
"def",
"fromtab",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"fromtab",
".",
"__doc__",
")",
"p",
".",
"set_sep",
"(",
"sep",
"=",
"None",
")",
"p",
".",
"add_option",
"(",
"\"--noheader\"",
",",
"default",
"=",
"False",
",",
"action",
"="... | 28.25 | 0.002566 |
async def scalar(self, query, *multiparams, **params):
"""Executes a SQL query and returns a scalar value."""
res = await self.execute(query, *multiparams, **params)
return (await res.scalar()) | [
"async",
"def",
"scalar",
"(",
"self",
",",
"query",
",",
"*",
"multiparams",
",",
"*",
"*",
"params",
")",
":",
"res",
"=",
"await",
"self",
".",
"execute",
"(",
"query",
",",
"*",
"multiparams",
",",
"*",
"*",
"params",
")",
"return",
"(",
"await... | 53.5 | 0.009217 |
def _org_path(self, which, payload):
"""A helper method for generating paths with organization IDs in them.
:param which: A path such as "manifest_history" that has an
organization ID in it.
:param payload: A dict with an "organization_id" key in it.
:returns: A string. The ... | [
"def",
"_org_path",
"(",
"self",
",",
"which",
",",
"payload",
")",
":",
"return",
"Subscription",
"(",
"self",
".",
"_server_config",
",",
"organization",
"=",
"payload",
"[",
"'organization_id'",
"]",
",",
")",
".",
"path",
"(",
"which",
")"
] | 36.384615 | 0.004124 |
def timestamp_normalized(self):
"""
we're expecting self.timestamp to be either a long, int, a datetime, or a timedelta
:return:
"""
if not self.timestamp:
return None
if isinstance(self.timestamp, six.integer_types):
return self.timestamp
... | [
"def",
"timestamp_normalized",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"timestamp",
":",
"return",
"None",
"if",
"isinstance",
"(",
"self",
".",
"timestamp",
",",
"six",
".",
"integer_types",
")",
":",
"return",
"self",
".",
"timestamp",
"if",
"... | 30.529412 | 0.005607 |
def thirds(reference_labels, estimated_labels):
"""Compare chords along root & third relationships.
Examples
--------
>>> (ref_intervals,
... ref_labels) = mir_eval.io.load_labeled_intervals('ref.lab')
>>> (est_intervals,
... est_labels) = mir_eval.io.load_labeled_intervals('est.lab')
... | [
"def",
"thirds",
"(",
"reference_labels",
",",
"estimated_labels",
")",
":",
"validate",
"(",
"reference_labels",
",",
"estimated_labels",
")",
"ref_roots",
",",
"ref_semitones",
"=",
"encode_many",
"(",
"reference_labels",
",",
"False",
")",
"[",
":",
"2",
"]",... | 37.355556 | 0.00058 |
def dates_in_range(start_date, end_date):
"""Returns all dates between two dates.
Inclusive of the start date but not the end date.
Args:
start_date (datetime.date)
end_date (datetime.date)
Returns:
(list) of datetime.date objects
"""
return [
start_date + time... | [
"def",
"dates_in_range",
"(",
"start_date",
",",
"end_date",
")",
":",
"return",
"[",
"start_date",
"+",
"timedelta",
"(",
"n",
")",
"for",
"n",
"in",
"range",
"(",
"int",
"(",
"(",
"end_date",
"-",
"start_date",
")",
".",
"days",
")",
")",
"]"
] | 23.5625 | 0.002551 |
def trigger_deleted(self, filepath):
"""Triggers deleted event if the flie doesn't exist."""
if not os.path.exists(filepath):
self._trigger('deleted', filepath) | [
"def",
"trigger_deleted",
"(",
"self",
",",
"filepath",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"filepath",
")",
":",
"self",
".",
"_trigger",
"(",
"'deleted'",
",",
"filepath",
")"
] | 46.25 | 0.010638 |
def stage_tc_associations(self, entity1, entity2):
"""Add an attribute to a resource.
Args:
entity1 (str): A Redis variable containing a TCEntity.
entity2 (str): A Redis variable containing a TCEntity.
"""
# resource 1
entity1 = self.tcex.playbook.read(en... | [
"def",
"stage_tc_associations",
"(",
"self",
",",
"entity1",
",",
"entity2",
")",
":",
"# resource 1",
"entity1",
"=",
"self",
".",
"tcex",
".",
"playbook",
".",
"read",
"(",
"entity1",
")",
"entity1_id",
"=",
"entity1",
".",
"get",
"(",
"'id'",
")",
"en... | 36.425532 | 0.001138 |
def regex_replace(regex, repl, text):
r"""
thin wrapper around re.sub
regex_replace
MULTILINE and DOTALL are on by default in all util_regex functions
Args:
regex (str): pattern to find
repl (str): replace pattern with this
text (str): text to modify
Returns:
s... | [
"def",
"regex_replace",
"(",
"regex",
",",
"repl",
",",
"text",
")",
":",
"return",
"re",
".",
"sub",
"(",
"regex",
",",
"repl",
",",
"text",
",",
"*",
"*",
"RE_KWARGS",
")"
] | 30.219512 | 0.000782 |
def login_user(self, request):
"""
Try to login user by net identity.
Do nothing in case of failure.
"""
# only actavted users can login if activation required.
user = auth.authenticate(identity=self.identity, provider=self.provider)
if user and settings.ACTIVATIO... | [
"def",
"login_user",
"(",
"self",
",",
"request",
")",
":",
"# only actavted users can login if activation required.",
"user",
"=",
"auth",
".",
"authenticate",
"(",
"identity",
"=",
"self",
".",
"identity",
",",
"provider",
"=",
"self",
".",
"provider",
")",
"i... | 37.25 | 0.00491 |
def get_all_delivery_notes(self, params=None):
"""
Get all delivery notes
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param params: search params
:return: list
"""... | [
"def",
"get_all_delivery_notes",
"(",
"self",
",",
"params",
"=",
"None",
")",
":",
"if",
"not",
"params",
":",
"params",
"=",
"{",
"}",
"return",
"self",
".",
"_iterate_through_pages",
"(",
"self",
".",
"get_delivery_notes_per_page",
",",
"resource",
"=",
"... | 32.625 | 0.005587 |
def _firestore_api(self):
"""Lazy-loading getter GAPIC Firestore API.
Returns:
~.gapic.firestore.v1beta1.firestore_client.FirestoreClient: The
GAPIC client with the credentials of the current client.
"""
if self._firestore_api_internal is None:
self._... | [
"def",
"_firestore_api",
"(",
"self",
")",
":",
"if",
"self",
".",
"_firestore_api_internal",
"is",
"None",
":",
"self",
".",
"_firestore_api_internal",
"=",
"firestore_client",
".",
"FirestoreClient",
"(",
"credentials",
"=",
"self",
".",
"_credentials",
")",
"... | 36.230769 | 0.004141 |
def get_revisions(page):
"""Extract the revisions of a page.
Args:
page: a string
Returns:
a list of strings
"""
start_string = " <revision>\n"
end_string = " </revision>\n"
ret = []
current_pos = 0
while True:
start_pos = page.find(start_string, current_pos)
if start_pos == -1:... | [
"def",
"get_revisions",
"(",
"page",
")",
":",
"start_string",
"=",
"\" <revision>\\n\"",
"end_string",
"=",
"\" </revision>\\n\"",
"ret",
"=",
"[",
"]",
"current_pos",
"=",
"0",
"while",
"True",
":",
"start_pos",
"=",
"page",
".",
"find",
"(",
"start_st... | 23.857143 | 0.017274 |
def from_project_path(cls, path):
"""Utility for finding a virtualenv location based on a project path"""
path = vistir.compat.Path(path)
if path.name == 'Pipfile':
pipfile_path = path
path = path.parent
else:
pipfile_path = path / 'Pipfile'
pi... | [
"def",
"from_project_path",
"(",
"cls",
",",
"path",
")",
":",
"path",
"=",
"vistir",
".",
"compat",
".",
"Path",
"(",
"path",
")",
"if",
"path",
".",
"name",
"==",
"'Pipfile'",
":",
"pipfile_path",
"=",
"path",
"path",
"=",
"path",
".",
"parent",
"e... | 47.583333 | 0.002575 |
def get_strain_label(entry, viral=False):
"""Try to extract a strain from an assemly summary entry.
First this checks 'infraspecific_name', then 'isolate', then
it tries to get it from 'organism_name'. If all fails, it
falls back to just returning the assembly accesion number.
"""
def get_strai... | [
"def",
"get_strain_label",
"(",
"entry",
",",
"viral",
"=",
"False",
")",
":",
"def",
"get_strain",
"(",
"entry",
")",
":",
"strain",
"=",
"entry",
"[",
"'infraspecific_name'",
"]",
"if",
"strain",
"!=",
"''",
":",
"strain",
"=",
"strain",
".",
"split",
... | 31.875 | 0.000951 |
async def AddUnits(self, application, num_units, placement):
'''
application : str
num_units : int
placement : typing.Sequence[~Placement]
Returns -> typing.Sequence[str]
'''
# map input types to rpc msg
_params = dict()
msg = dict(type='Applicatio... | [
"async",
"def",
"AddUnits",
"(",
"self",
",",
"application",
",",
"num_units",
",",
"placement",
")",
":",
"# map input types to rpc msg",
"_params",
"=",
"dict",
"(",
")",
"msg",
"=",
"dict",
"(",
"type",
"=",
"'Application'",
",",
"request",
"=",
"'AddUnit... | 33 | 0.003273 |
def get_settings(profile, section, store='local'):
'''
Get the firewall property from the specified profile in the specified store
as returned by ``netsh advfirewall``.
Args:
profile (str):
The firewall profile to query. Valid options are:
- domain
- public... | [
"def",
"get_settings",
"(",
"profile",
",",
"section",
",",
"store",
"=",
"'local'",
")",
":",
"# validate input",
"if",
"profile",
".",
"lower",
"(",
")",
"not",
"in",
"(",
"'domain'",
",",
"'public'",
",",
"'private'",
")",
":",
"raise",
"ValueError",
... | 35.077922 | 0.00072 |
def get_valid_value(self, direct_value, config_section,
config_option_name, default_value):
"""Returns a value that can be used as a parameter in client or
server. If a direct_value is given, that value will be returned
instead of the value from the config file. If the ap... | [
"def",
"get_valid_value",
"(",
"self",
",",
"direct_value",
",",
"config_section",
",",
"config_option_name",
",",
"default_value",
")",
":",
"ARG_MSG",
"=",
"\"Using given value '{0}' for {1}\"",
"CONF_MSG",
"=",
"\"Using value '{0}' from configuration file {1} for {2}\"",
"... | 51.756757 | 0.001538 |
def triggered(self):
"""Test if we should trigger our operation.
We test the trigger condition on each of our inputs and then
combine those triggers using our configured trigger combiner
to get an overall result for whether this node is triggered.
Returns:
bool: Tru... | [
"def",
"triggered",
"(",
"self",
")",
":",
"trigs",
"=",
"[",
"x",
"[",
"1",
"]",
".",
"triggered",
"(",
"x",
"[",
"0",
"]",
")",
"for",
"x",
"in",
"self",
".",
"inputs",
"]",
"if",
"self",
".",
"trigger_combiner",
"==",
"self",
".",
"OrTriggerCo... | 32.235294 | 0.003546 |
def _set_params(self):
"""
Overriden to account for the fact the fit with volume**(2/3) instead
of volume.
"""
deriv0 = np.poly1d(self.eos_params)
deriv1 = np.polyder(deriv0, 1)
deriv2 = np.polyder(deriv1, 1)
deriv3 = np.polyder(deriv2, 1)
for x i... | [
"def",
"_set_params",
"(",
"self",
")",
":",
"deriv0",
"=",
"np",
".",
"poly1d",
"(",
"self",
".",
"eos_params",
")",
"deriv1",
"=",
"np",
".",
"polyder",
"(",
"deriv0",
",",
"1",
")",
"deriv2",
"=",
"np",
".",
"polyder",
"(",
"deriv1",
",",
"1",
... | 32.04 | 0.002424 |
async def reload_modules(self, pathlist):
"""
Reload modules with a full path in the pathlist
"""
loadedModules = []
failures = []
for path in pathlist:
p, module = findModule(path, False)
if module is not None and hasattr(module, '_instance') and ... | [
"async",
"def",
"reload_modules",
"(",
"self",
",",
"pathlist",
")",
":",
"loadedModules",
"=",
"[",
"]",
"failures",
"=",
"[",
"]",
"for",
"path",
"in",
"pathlist",
":",
"p",
",",
"module",
"=",
"findModule",
"(",
"path",
",",
"False",
")",
"if",
"m... | 49.621951 | 0.003855 |
def C0t_(self):
""" Time-lagged covariance matrix """
self._check_estimated()
return self._rc.cov_XY(bessel=self.bessel) | [
"def",
"C0t_",
"(",
"self",
")",
":",
"self",
".",
"_check_estimated",
"(",
")",
"return",
"self",
".",
"_rc",
".",
"cov_XY",
"(",
"bessel",
"=",
"self",
".",
"bessel",
")"
] | 35.25 | 0.013889 |
def translate_value(document_field, form_value):
"""
Given a document_field and a form_value this will translate the value
to the correct result for mongo to use.
"""
value = form_value
if isinstance(document_field, ReferenceField):
value = document_field.document_type.objects.get(id=for... | [
"def",
"translate_value",
"(",
"document_field",
",",
"form_value",
")",
":",
"value",
"=",
"form_value",
"if",
"isinstance",
"(",
"document_field",
",",
"ReferenceField",
")",
":",
"value",
"=",
"document_field",
".",
"document_type",
".",
"objects",
".",
"get"... | 40.111111 | 0.00542 |
def list_remotes(device=None, address=None):
"""
List the available remotes.
All parameters are passed to irsend. See the man page for irsend
for details about their usage.
Parameters
----------
device: str
address: str
Returns
-------
[str]
Notes
-----
No att... | [
"def",
"list_remotes",
"(",
"device",
"=",
"None",
",",
"address",
"=",
"None",
")",
":",
"output",
"=",
"_call",
"(",
"[",
"\"list\"",
",",
"\"\"",
",",
"\"\"",
"]",
",",
"None",
",",
"device",
",",
"address",
")",
"remotes",
"=",
"[",
"l",
".",
... | 23.44 | 0.003279 |
def add_jac(self, m, val, row, col):
"""Add tuples (val, row, col) to the Jacobian matrix ``m``
Implemented in numpy.arrays for temporary storage.
"""
assert m in ('Fx', 'Fy', 'Gx', 'Gy', 'Fx0', 'Fy0', 'Gx0', 'Gy0'), \
'Wrong Jacobian matrix name <{0}>'.format(m)
if... | [
"def",
"add_jac",
"(",
"self",
",",
"m",
",",
"val",
",",
"row",
",",
"col",
")",
":",
"assert",
"m",
"in",
"(",
"'Fx'",
",",
"'Fy'",
",",
"'Gx'",
",",
"'Gy'",
",",
"'Fx0'",
",",
"'Fy0'",
",",
"'Gx0'",
",",
"'Gy0'",
")",
",",
"'Wrong Jacobian mat... | 42.428571 | 0.003295 |
def geq_multiple(self, other):
"""
Return the next multiple of this time value,
greater than or equal to ``other``.
If ``other`` is zero, return this time value.
:rtype: :class:`~aeneas.exacttiming.TimeValue`
"""
if other == TimeValue("0.000"):
return... | [
"def",
"geq_multiple",
"(",
"self",
",",
"other",
")",
":",
"if",
"other",
"==",
"TimeValue",
"(",
"\"0.000\"",
")",
":",
"return",
"self",
"return",
"int",
"(",
"math",
".",
"ceil",
"(",
"other",
"/",
"self",
")",
")",
"*",
"self"
] | 33.272727 | 0.005319 |
def import_module(module_path):
"""
Try to import and return the given module, if it exists, None if it doesn't
exist
:raises ImportError: When imported module contains errors
"""
if six.PY2:
try:
return importlib.import_module(module_path)
except ImportError:
... | [
"def",
"import_module",
"(",
"module_path",
")",
":",
"if",
"six",
".",
"PY2",
":",
"try",
":",
"return",
"importlib",
".",
"import_module",
"(",
"module_path",
")",
"except",
"ImportError",
":",
"tb",
"=",
"sys",
".",
"exc_info",
"(",
")",
"[",
"2",
"... | 30.315789 | 0.001684 |
def get_block_adjustments(crypto, points=None, intervals=None, **modes):
"""
This utility is used to determine the actual block rate. The output can be
directly copied to the `blocktime_adjustments` setting.
"""
from moneywagon import get_block
all_points = []
if intervals:
latest_b... | [
"def",
"get_block_adjustments",
"(",
"crypto",
",",
"points",
"=",
"None",
",",
"intervals",
"=",
"None",
",",
"*",
"*",
"modes",
")",
":",
"from",
"moneywagon",
"import",
"get_block",
"all_points",
"=",
"[",
"]",
"if",
"intervals",
":",
"latest_block_height... | 32.351351 | 0.004055 |
def compose(layers, bbox=None, layer_filter=None, color=None, **kwargs):
"""
Compose layers to a single :py:class:`PIL.Image`.
If the layers do not have visible pixels, the function returns `None`.
Example::
image = compose([layer1, layer2])
In order to skip some layers, pass `layer_filte... | [
"def",
"compose",
"(",
"layers",
",",
"bbox",
"=",
"None",
",",
"layer_filter",
"=",
"None",
",",
"color",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"PIL",
"import",
"Image",
"if",
"not",
"hasattr",
"(",
"layers",
",",
"'__iter__'",
")"... | 30.873418 | 0.000397 |
def _update_partition_srvc_node_ip(self, tenant_name, srvc_ip,
vrf_prof=None, part_name=None):
"""Function to update srvc_node address of partition. """
self.dcnm_obj.update_project(tenant_name, part_name,
service_node_ip=srvc_i... | [
"def",
"_update_partition_srvc_node_ip",
"(",
"self",
",",
"tenant_name",
",",
"srvc_ip",
",",
"vrf_prof",
"=",
"None",
",",
"part_name",
"=",
"None",
")",
":",
"self",
".",
"dcnm_obj",
".",
"update_project",
"(",
"tenant_name",
",",
"part_name",
",",
"service... | 62.142857 | 0.006803 |
def replace_find(self, focus_replace_text=False, replace_all=False):
"""Replace and find"""
if (self.editor is not None):
replace_text = to_text_string(self.replace_text.currentText())
search_text = to_text_string(self.search_text.currentText())
re_pattern = None... | [
"def",
"replace_find",
"(",
"self",
",",
"focus_replace_text",
"=",
"False",
",",
"replace_all",
"=",
"False",
")",
":",
"if",
"(",
"self",
".",
"editor",
"is",
"not",
"None",
")",
":",
"replace_text",
"=",
"to_text_string",
"(",
"self",
".",
"replace_text... | 47.590909 | 0.000702 |
def IfContainer(cls, ifc: IfContainer, ctx: SerializerCtx):
"""
Srialize IfContainer instance
"""
childCtx = ctx.withIndent()
def asHdl(statements):
return [cls.asHdl(s, childCtx) for s in statements]
try:
cond = cls.condAsHdl(ifc.cond, True, ctx... | [
"def",
"IfContainer",
"(",
"cls",
",",
"ifc",
":",
"IfContainer",
",",
"ctx",
":",
"SerializerCtx",
")",
":",
"childCtx",
"=",
"ctx",
".",
"withIndent",
"(",
")",
"def",
"asHdl",
"(",
"statements",
")",
":",
"return",
"[",
"cls",
".",
"asHdl",
"(",
"... | 31.162791 | 0.001447 |
def compute_wed(self):
"""
Computes weight error derivative for all connections in
self.connections starting with the last connection.
"""
if len(self.cacheConnections) != 0:
changeConnections = self.cacheConnections
else:
changeConnections = self.... | [
"def",
"compute_wed",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"cacheConnections",
")",
"!=",
"0",
":",
"changeConnections",
"=",
"self",
".",
"cacheConnections",
"else",
":",
"changeConnections",
"=",
"self",
".",
"connections",
"for",
"connect... | 44.85 | 0.00655 |
def join_accesses(unique_id, accesses, from_date, until_date, dayly_granularity):
"""
Esse metodo recebe 1 ou mais chaves para um documento em específico para que
os acessos sejam recuperados no Ratchet e consolidados em um unico id.
Esse processo é necessário pois os acessos de um documento podem ser r... | [
"def",
"join_accesses",
"(",
"unique_id",
",",
"accesses",
",",
"from_date",
",",
"until_date",
",",
"dayly_granularity",
")",
":",
"logger",
".",
"debug",
"(",
"'joining accesses for: %s'",
"%",
"unique_id",
")",
"joined_data",
"=",
"{",
"}",
"listed_data",
"="... | 36.322581 | 0.002594 |
def cpu_percent(interval=0.1, per_cpu=False):
'''
Return the percent of time the CPU is busy.
interval
the number of seconds to sample CPU usage over
per_cpu
if True return an array of CPU percent busy for each CPU, otherwise
aggregate all percents into one number
CLI Examp... | [
"def",
"cpu_percent",
"(",
"interval",
"=",
"0.1",
",",
"per_cpu",
"=",
"False",
")",
":",
"if",
"per_cpu",
":",
"result",
"=",
"list",
"(",
"psutil",
".",
"cpu_percent",
"(",
"interval",
",",
"True",
")",
")",
"else",
":",
"result",
"=",
"psutil",
"... | 24.666667 | 0.001859 |
def enable_service(conn, service='ceph'):
"""
Enable a service on a remote host depending on the type of init system.
Obviously, this should be done for RHEL/Fedora/CentOS systems.
This function does not do any kind of detection.
"""
if is_systemd(conn):
remoto.process.run(
... | [
"def",
"enable_service",
"(",
"conn",
",",
"service",
"=",
"'ceph'",
")",
":",
"if",
"is_systemd",
"(",
"conn",
")",
":",
"remoto",
".",
"process",
".",
"run",
"(",
"conn",
",",
"[",
"'systemctl'",
",",
"'enable'",
",",
"'{service}'",
".",
"format",
"(... | 25.8 | 0.001495 |
def set_title(self, title=None):
"""
Sets the title on the current axes.
Parameters
----------
title: string, default: None
Add title to figure or if None leave untitled.
"""
title = self.title or title
if title is not None:
self.a... | [
"def",
"set_title",
"(",
"self",
",",
"title",
"=",
"None",
")",
":",
"title",
"=",
"self",
".",
"title",
"or",
"title",
"if",
"title",
"is",
"not",
"None",
":",
"self",
".",
"ax",
".",
"set_title",
"(",
"title",
")"
] | 27.25 | 0.005917 |
def get_data_statistics(interpreted_files):
'''Quick and dirty function to give as redmine compatible iverview table
'''
print '| *File Name* | *File Size* | *Times Stamp* | *Events* | *Bad Events* | *Measurement time* | *# SR* | *Hits* |' # Mean Tot | Mean rel. BCID'
for interpreted_file in interprete... | [
"def",
"get_data_statistics",
"(",
"interpreted_files",
")",
":",
"print",
"'| *File Name* | *File Size* | *Times Stamp* | *Events* | *Bad Events* | *Measurement time* | *# SR* | *Hits* |'",
"# Mean Tot | Mean rel. BCID'",
"for",
"interpreted_file",
"in",
"interpreted_files",
":",
"with"... | 87.722222 | 0.005013 |
def GetDictToFormat(self):
"""Return a copy of self as a dict, suitable for passing to FormatProblem"""
d = {}
for k, v in self.__dict__.items():
# TODO: Better handling of unicode/utf-8 within Schedule objects.
# Concatinating a unicode and utf-8 str object causes an exception such
# as "... | [
"def",
"GetDictToFormat",
"(",
"self",
")",
":",
"d",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"self",
".",
"__dict__",
".",
"items",
"(",
")",
":",
"# TODO: Better handling of unicode/utf-8 within Schedule objects.",
"# Concatinating a unicode and utf-8 str object ... | 53.923077 | 0.014025 |
def delete_container(self, container):
"""Delete container
:param container: container name (Container is equivalent to
Bucket term in Amazon).
"""
try:
LOG.debug('delete_container() with %s is success.', self.driver)
return self.driver.... | [
"def",
"delete_container",
"(",
"self",
",",
"container",
")",
":",
"try",
":",
"LOG",
".",
"debug",
"(",
"'delete_container() with %s is success.'",
",",
"self",
".",
"driver",
")",
"return",
"self",
".",
"driver",
".",
"delete_container",
"(",
"container",
"... | 41.5 | 0.003929 |
def get_tamil_words_iterable( letters ):
""" given a list of UTF-8 letters section them into words, grouping them at spaces """
#punctuations = u'-,+,/,*,>,<,_,],[,{,},(,)'.split(',')+[',']
#isspace_or_tamil = lambda x: not x in punctuations and tamil.utf8.istamil(x)
# correct... | [
"def",
"get_tamil_words_iterable",
"(",
"letters",
")",
":",
"#punctuations = u'-,+,/,*,>,<,_,],[,{,},(,)'.split(',')+[',']",
"#isspace_or_tamil = lambda x: not x in punctuations and tamil.utf8.istamil(x)",
"# correct algorithm for get-tamil-words",
"buf",
"=",
"[",
"]",
"for",
"idx",
... | 40.6875 | 0.025526 |
def _merge_and_bgzip(orig_files, out_file, base_file, ext=""):
"""Merge a group of gzipped input files into a final bgzipped output.
Also handles providing unique names for each input file to avoid
collisions on multi-region output. Handles renaming with awk magic from:
https://www.biostars.org/p/68477... | [
"def",
"_merge_and_bgzip",
"(",
"orig_files",
",",
"out_file",
",",
"base_file",
",",
"ext",
"=",
"\"\"",
")",
":",
"assert",
"out_file",
".",
"endswith",
"(",
"\".gz\"",
")",
"full_file",
"=",
"out_file",
".",
"replace",
"(",
"\".gz\"",
",",
"\"\"",
")",
... | 44.272727 | 0.003015 |
def preemptable(self):
"""
Whether the job can be run on a preemptable node.
"""
if self._preemptable is not None:
return self._preemptable
elif self._config is not None:
return self._config.defaultPreemptable
else:
raise AttributeError... | [
"def",
"preemptable",
"(",
"self",
")",
":",
"if",
"self",
".",
"_preemptable",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_preemptable",
"elif",
"self",
".",
"_config",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_config",
".",
"defaultPree... | 36.7 | 0.007979 |
def set(self, key, value, **kw):
"""Place a value in the cache.
:param key: the value's key.
:param value: the value.
:param \**kw: cache configuration arguments.
"""
self.impl.set(key, value, **self._get_cache_kw(kw, None)) | [
"def",
"set",
"(",
"self",
",",
"key",
",",
"value",
",",
"*",
"*",
"kw",
")",
":",
"self",
".",
"impl",
".",
"set",
"(",
"key",
",",
"value",
",",
"*",
"*",
"self",
".",
"_get_cache_kw",
"(",
"kw",
",",
"None",
")",
")"
] | 26.6 | 0.010909 |
def deploy_docker(self, dockerfile_path, virtualbox_name='default'):
''' a method to deploy app to heroku using docker '''
title = '%s.deploy_docker' % self.__class__.__name__
# validate inputs
input_fields = {
'dockerfile_path': dockerfile_path,
'virtualb... | [
"def",
"deploy_docker",
"(",
"self",
",",
"dockerfile_path",
",",
"virtualbox_name",
"=",
"'default'",
")",
":",
"title",
"=",
"'%s.deploy_docker'",
"%",
"self",
".",
"__class__",
".",
"__name__",
"# validate inputs\r",
"input_fields",
"=",
"{",
"'dockerfile_path'",... | 44.395062 | 0.004625 |
def get_tunnel_statistics_output_tunnel_stat_tx_frames(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_tunnel_statistics = ET.Element("get_tunnel_statistics")
config = get_tunnel_statistics
output = ET.SubElement(get_tunnel_statistics, "outpu... | [
"def",
"get_tunnel_statistics_output_tunnel_stat_tx_frames",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_tunnel_statistics",
"=",
"ET",
".",
"Element",
"(",
"\"get_tunnel_statistics\"",
")",
"co... | 43.846154 | 0.003436 |
def stop(self):
"""
Terminate the WAMP session
.. note::
If the :meth:`AutobahnSync.run` has been run with ``blocking=True``,
it will returns then.
"""
if not self._started:
raise NotRunningError("This AutobahnSync instance is not started")
... | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_started",
":",
"raise",
"NotRunningError",
"(",
"\"This AutobahnSync instance is not started\"",
")",
"self",
".",
"_callbacks_runner",
".",
"stop",
"(",
")",
"self",
".",
"_started",
"=",
"Fals... | 31.166667 | 0.007792 |
def answerUnsupported(self, message, preferred_association_type=None,
preferred_session_type=None):
"""Respond to this request indicating that the association
type or association session type is not supported."""
if self.message.isOpenID1():
raise ProtocolEr... | [
"def",
"answerUnsupported",
"(",
"self",
",",
"message",
",",
"preferred_association_type",
"=",
"None",
",",
"preferred_session_type",
"=",
"None",
")",
":",
"if",
"self",
".",
"message",
".",
"isOpenID1",
"(",
")",
":",
"raise",
"ProtocolError",
"(",
"self",... | 40.2 | 0.003645 |
def call_remote_api(self, func_name, *args, **kwargs):
""" Calls any remote API func in a thread_safe way.
:param str func_name: name of the remote API func to call
:param args: args to pass to the remote API call
:param kwargs: args to pass to the remote API call
.. note:: You... | [
"def",
"call_remote_api",
"(",
"self",
",",
"func_name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"f",
"=",
"getattr",
"(",
"remote_api",
",",
"func_name",
")",
"mode",
"=",
"self",
".",
"_extract_mode",
"(",
"kwargs",
")",
"kwargs",
"[",
... | 34.568182 | 0.001598 |
def map_legacy_frequencies(form, field):
''' Map legacy frequencies to new ones'''
if field.data in LEGACY_FREQUENCIES:
field.data = LEGACY_FREQUENCIES[field.data] | [
"def",
"map_legacy_frequencies",
"(",
"form",
",",
"field",
")",
":",
"if",
"field",
".",
"data",
"in",
"LEGACY_FREQUENCIES",
":",
"field",
".",
"data",
"=",
"LEGACY_FREQUENCIES",
"[",
"field",
".",
"data",
"]"
] | 44 | 0.005587 |
def macro_list(self, args: argparse.Namespace) -> None:
"""List some or all macros"""
if args.name:
for cur_name in utils.remove_duplicates(args.name):
if cur_name in self.macros:
self.poutput("macro create {} {}".format(cur_name, self.macros[cur_name].val... | [
"def",
"macro_list",
"(",
"self",
",",
"args",
":",
"argparse",
".",
"Namespace",
")",
"->",
"None",
":",
"if",
"args",
".",
"name",
":",
"for",
"cur_name",
"in",
"utils",
".",
"remove_duplicates",
"(",
"args",
".",
"name",
")",
":",
"if",
"cur_name",
... | 54.25 | 0.007553 |
def stop(name, call=None, session=None):
'''
Stop a vm
.. code-block:: bash
salt-cloud -a stop xenvm01
'''
if call == 'function':
raise SaltCloudException(
'The show_instnce function must be called with -a or --action.'
)
return shutdown(name, call, sessio... | [
"def",
"stop",
"(",
"name",
",",
"call",
"=",
"None",
",",
"session",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'function'",
":",
"raise",
"SaltCloudException",
"(",
"'The show_instnce function must be called with -a or --action.'",
")",
"return",
"shutdown",
"(... | 20.533333 | 0.003106 |
def update(self, document_id, update_spec, namespace, timestamp):
"""Apply updates given in update_spec to the document whose id
matches that of doc.
"""
db, coll = self._db_and_collection(namespace)
meta_collection_name = self._get_meta_collection(namespace)
self.meta... | [
"def",
"update",
"(",
"self",
",",
"document_id",
",",
"update_spec",
",",
"namespace",
",",
"timestamp",
")",
":",
"db",
",",
"coll",
"=",
"self",
".",
"_db_and_collection",
"(",
"namespace",
")",
"meta_collection_name",
"=",
"self",
".",
"_get_meta_collectio... | 33.413793 | 0.002006 |
def match_level(self, overlay):
"""
Given an overlay, return the match level and applicable slice
of the overall overlay. The level an integer if there is a
match or None if there is no match.
The level integer is the number of matching components. Higher
values indicate... | [
"def",
"match_level",
"(",
"self",
",",
"overlay",
")",
":",
"slice_width",
"=",
"len",
"(",
"self",
".",
"_pattern_spec",
")",
"if",
"slice_width",
">",
"len",
"(",
"overlay",
")",
":",
"return",
"None",
"# Check all the possible slices and return the best matchi... | 40.304348 | 0.004215 |
def quiet_reset_backend(self, reset_interps=True):
"""
Doesn't update plots or logger or any visable data but resets all
measurement data, hierarchy data, and optionally resets
intepretations.
Parameters
----------
reset_interps : bool to tell the function to res... | [
"def",
"quiet_reset_backend",
"(",
"self",
",",
"reset_interps",
"=",
"True",
")",
":",
"new_Data_info",
"=",
"self",
".",
"get_data_info",
"(",
")",
"new_Data",
",",
"new_Data_hierarchy",
"=",
"self",
".",
"get_data",
"(",
")",
"if",
"not",
"new_Data",
":",... | 39.391304 | 0.002154 |
def intelligently_find_filenames(line, TeX=False, ext=False,
commas_okay=False):
"""Intelligently find filenames.
Find the filename in the line. We don't support all filenames! Just eps
and ps for now.
:param: line (string): the line we want to get a filename out of
... | [
"def",
"intelligently_find_filenames",
"(",
"line",
",",
"TeX",
"=",
"False",
",",
"ext",
"=",
"False",
",",
"commas_okay",
"=",
"False",
")",
":",
"files_included",
"=",
"[",
"'ERROR'",
"]",
"if",
"commas_okay",
":",
"valid_for_filename",
"=",
"'\\\\s*[A-Za-z... | 36.15625 | 0.000841 |
def set_mode(self, mode):
"""Set hparams with the given mode."""
log_info("Setting T2TModel mode to '%s'", mode)
hparams = hparams_lib.copy_hparams(self._original_hparams)
hparams.add_hparam("mode", mode)
# When not in training mode, set all forms of dropout to zero.
if mode != tf.estimator.Mode... | [
"def",
"set_mode",
"(",
"self",
",",
"mode",
")",
":",
"log_info",
"(",
"\"Setting T2TModel mode to '%s'\"",
",",
"mode",
")",
"hparams",
"=",
"hparams_lib",
".",
"copy_hparams",
"(",
"self",
".",
"_original_hparams",
")",
"hparams",
".",
"add_hparam",
"(",
"\... | 44.75 | 0.007299 |
def _get_archiver_metrics(self, key, db):
"""Use COMMON_ARCHIVER_METRICS to read from pg_stat_archiver as
defined in 9.4 (first version to have this table).
Uses a dictionary to save the result for each instance
"""
# While there's only one set for now, prepare for future additio... | [
"def",
"_get_archiver_metrics",
"(",
"self",
",",
"key",
",",
"db",
")",
":",
"# While there's only one set for now, prepare for future additions to",
"# the table, mirroring _get_bgw_metrics()",
"metrics",
"=",
"self",
".",
"archiver_metrics",
".",
"get",
"(",
"key",
")",
... | 43.551724 | 0.003873 |
def _compute_distance_term(self, C, mag, rrup):
"""
Compute second and third terms in equation 1, p. 901.
"""
term1 = C['b'] * rrup
term2 = - np.log(rrup + C['c'] * np.exp(C['d'] * mag))
return term1 + term2 | [
"def",
"_compute_distance_term",
"(",
"self",
",",
"C",
",",
"mag",
",",
"rrup",
")",
":",
"term1",
"=",
"C",
"[",
"'b'",
"]",
"*",
"rrup",
"term2",
"=",
"-",
"np",
".",
"log",
"(",
"rrup",
"+",
"C",
"[",
"'c'",
"]",
"*",
"np",
".",
"exp",
"(... | 31.125 | 0.007813 |
def luminosity_within_circle_in_units(self, radius: dim.Length, unit_luminosity='eps', kpc_per_arcsec=None,
exposure_time=None):
"""Integrate the light profile to compute the total luminosity within a circle of specified radius. This is \
centred on the light pr... | [
"def",
"luminosity_within_circle_in_units",
"(",
"self",
",",
"radius",
":",
"dim",
".",
"Length",
",",
"unit_luminosity",
"=",
"'eps'",
",",
"kpc_per_arcsec",
"=",
"None",
",",
"exposure_time",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"radius",
... | 51.357143 | 0.006826 |
def play(self, sound):
""" Adds and plays a new Sound to the Sampler.
:param sound: sound to play
.. note:: If the sound is already playing, it will restart from the beginning.
"""
self.is_done.clear() # hold is_done until the sound is played
if self.sr != sou... | [
"def",
"play",
"(",
"self",
",",
"sound",
")",
":",
"self",
".",
"is_done",
".",
"clear",
"(",
")",
"# hold is_done until the sound is played",
"if",
"self",
".",
"sr",
"!=",
"sound",
".",
"sr",
":",
"raise",
"ValueError",
"(",
"'You can only play sound with a... | 33.47619 | 0.005533 |
def load_genotypes(self, pheno_covar):
"""Load all data into memory and propagate valid individuals to \
pheno_covar.
:param pheno_covar: Phenotype/covariate object is updated with subject
information
:return: None
"""
first_genotype = 6
pheno_col =... | [
"def",
"load_genotypes",
"(",
"self",
",",
"pheno_covar",
")",
":",
"first_genotype",
"=",
"6",
"pheno_col",
"=",
"5",
"if",
"not",
"DataParser",
".",
"has_sex",
":",
"first_genotype",
"-=",
"1",
"pheno_col",
"-=",
"1",
"if",
"not",
"DataParser",
".",
"has... | 39.787879 | 0.002675 |
def getParameter(self, name):
"""
Get the parameter with the corresponding name.
Args:
name: Name of the parameter to be found.
Raises:
TypeError: if the specified parameter does not exist.
"""
return lock_and_call(
lambda: Parameter(... | [
"def",
"getParameter",
"(",
"self",
",",
"name",
")",
":",
"return",
"lock_and_call",
"(",
"lambda",
":",
"Parameter",
"(",
"self",
".",
"_impl",
".",
"getParameter",
"(",
"name",
")",
")",
",",
"self",
".",
"_lock",
")"
] | 26.5 | 0.005208 |
def nplnpt(linpt, lindir, point):
"""
Find the nearest point on a line to a specified point,
and find the distance between the two points.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/nplnpt_c.html
:param linpt: Point on a line
:type linpt: 3-Element Array of floats
:param lindi... | [
"def",
"nplnpt",
"(",
"linpt",
",",
"lindir",
",",
"point",
")",
":",
"linpt",
"=",
"stypes",
".",
"toDoubleVector",
"(",
"linpt",
")",
"lindir",
"=",
"stypes",
".",
"toDoubleVector",
"(",
"lindir",
")",
"point",
"=",
"stypes",
".",
"toDoubleVector",
"("... | 35.72 | 0.001091 |
def get_subscribers(self):
"""Get per-instance subscribers from the signal.
"""
data = self.signal.instance_subscribers
if self.instance not in data:
data[self.instance] = MethodAwareWeakList()
return data[self.instance] | [
"def",
"get_subscribers",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"signal",
".",
"instance_subscribers",
"if",
"self",
".",
"instance",
"not",
"in",
"data",
":",
"data",
"[",
"self",
".",
"instance",
"]",
"=",
"MethodAwareWeakList",
"(",
")",
"r... | 38 | 0.007353 |
def update_bugs(self, ids, updates):
"""
A thin wrapper around bugzilla Bug.update(). Used to update all
values of an existing bug report, as well as add comments.
The dictionary passed to this function should be generated with
build_update(), otherwise we cannot guarantee back ... | [
"def",
"update_bugs",
"(",
"self",
",",
"ids",
",",
"updates",
")",
":",
"tmp",
"=",
"updates",
".",
"copy",
"(",
")",
"tmp",
"[",
"\"ids\"",
"]",
"=",
"self",
".",
"_listify",
"(",
"ids",
")",
"return",
"self",
".",
"_proxy",
".",
"Bug",
".",
"u... | 37.333333 | 0.004357 |
def format(self, record):
"""Customize the message format based on the log level."""
if isinstance(self.fmt, dict):
self._fmt = self.fmt[record.levelname]
if sys.version_info > (3, 2):
# Update self._style because we've changed self._fmt
# (code ba... | [
"def",
"format",
"(",
"self",
",",
"record",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"fmt",
",",
"dict",
")",
":",
"self",
".",
"_fmt",
"=",
"self",
".",
"fmt",
"[",
"record",
".",
"levelname",
"]",
"if",
"sys",
".",
"version_info",
">",
... | 44.833333 | 0.002427 |
def group(self):
"Group inherited from items"
if self._group:
return self._group
group = get_ndmapping_label(self, 'group') if len(self) else None
if group is None:
return type(self).__name__
return group | [
"def",
"group",
"(",
"self",
")",
":",
"if",
"self",
".",
"_group",
":",
"return",
"self",
".",
"_group",
"group",
"=",
"get_ndmapping_label",
"(",
"self",
",",
"'group'",
")",
"if",
"len",
"(",
"self",
")",
"else",
"None",
"if",
"group",
"is",
"None... | 32.75 | 0.011152 |
def cache_connect(database=None):
"""Returns a connection object to a sqlite database.
Args:
database (str, optional): The path to the database the user wishes
to connect to. If not specified, a default is chosen using
:func:`.cache_file`. If the special database name ':memory:'... | [
"def",
"cache_connect",
"(",
"database",
"=",
"None",
")",
":",
"if",
"database",
"is",
"None",
":",
"database",
"=",
"cache_file",
"(",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"database",
")",
":",
"# just connect to the database as-is",
"conn",
... | 29.322581 | 0.001065 |
def visit_Num(self, node):
"""
Set type for number.
It could be int, long or float so we use the default python to pythonic
type converter.
"""
ty = type(node.n)
sty = pytype_to_ctype(ty)
if node in self.immediates:
sty = "std::integral_consta... | [
"def",
"visit_Num",
"(",
"self",
",",
"node",
")",
":",
"ty",
"=",
"type",
"(",
"node",
".",
"n",
")",
"sty",
"=",
"pytype_to_ctype",
"(",
"ty",
")",
"if",
"node",
"in",
"self",
".",
"immediates",
":",
"sty",
"=",
"\"std::integral_constant<%s, %s>\"",
... | 30.153846 | 0.00495 |
def to_representation(self, obj):
""" convert value to representation.
DRF ModelField uses ``value_to_string`` for this purpose. Mongoengine fields do not have such method.
This implementation uses ``django.utils.encoding.smart_text`` to convert everything to text, while keeping json-safe type... | [
"def",
"to_representation",
"(",
"self",
",",
"obj",
")",
":",
"value",
"=",
"self",
".",
"model_field",
".",
"__get__",
"(",
"obj",
",",
"None",
")",
"return",
"smart_text",
"(",
"value",
",",
"strings_only",
"=",
"True",
")"
] | 53.833333 | 0.009132 |
def run_forever(
lcdproc='', mpd='', lcdproc_screen=DEFAULT_LCD_SCREEN_NAME,
lcdproc_charset=DEFAULT_LCDPROC_CHARSET,
lcdd_debug=False,
pattern='', patterns=[],
refresh=DEFAULT_REFRESH,
backlight_on=DEFAULT_BACKLIGHT_ON,
priority_playing=DEFAULT_PRIORITY,
... | [
"def",
"run_forever",
"(",
"lcdproc",
"=",
"''",
",",
"mpd",
"=",
"''",
",",
"lcdproc_screen",
"=",
"DEFAULT_LCD_SCREEN_NAME",
",",
"lcdproc_charset",
"=",
"DEFAULT_LCDPROC_CHARSET",
",",
"lcdd_debug",
"=",
"False",
",",
"pattern",
"=",
"''",
",",
"patterns",
... | 32.433735 | 0.00036 |
def login(self, email, password, max_tries=5):
"""
Uses `email` and `password` to login the user (If the user is already logged in, this will do a re-login)
:param email: Facebook `email` or `id` or `phone number`
:param password: Facebook account password
:param max_tries: Maxi... | [
"def",
"login",
"(",
"self",
",",
"email",
",",
"password",
",",
"max_tries",
"=",
"5",
")",
":",
"self",
".",
"onLoggingIn",
"(",
"email",
"=",
"email",
")",
"if",
"max_tries",
"<",
"1",
":",
"raise",
"FBchatUserError",
"(",
"\"Cannot login: max_tries sho... | 36.638889 | 0.002954 |
def __openlib(self):
'''
Actual (lazy) dlopen() only when an attribute is accessed
'''
if self.__getattribute__('_libloaded'):
return
libpath_list = self.__get_libres()
for p in libpath_list:
try:
libres = resource_filename(self._mo... | [
"def",
"__openlib",
"(",
"self",
")",
":",
"if",
"self",
".",
"__getattribute__",
"(",
"'_libloaded'",
")",
":",
"return",
"libpath_list",
"=",
"self",
".",
"__get_libres",
"(",
")",
"for",
"p",
"in",
"libpath_list",
":",
"try",
":",
"libres",
"=",
"reso... | 39.135135 | 0.003369 |
def install_dependencies(self):
''' Creates a virtualenv and installs requirements '''
# If virtualenv is set to skip then do nothing
if self._skip_virtualenv:
LOG.info('Skip Virtualenv set ... nothing to do')
return
has_reqs = _isfile(self._requirements_file) or... | [
"def",
"install_dependencies",
"(",
"self",
")",
":",
"# If virtualenv is set to skip then do nothing",
"if",
"self",
".",
"_skip_virtualenv",
":",
"LOG",
".",
"info",
"(",
"'Skip Virtualenv set ... nothing to do'",
")",
"return",
"has_reqs",
"=",
"_isfile",
"(",
"self"... | 46.411765 | 0.002484 |
def pprint(self, ind):
"""pretty prints the tree with indentation"""
pp = pprint.PrettyPrinter(indent=ind)
pp.pprint(self.tree) | [
"def",
"pprint",
"(",
"self",
",",
"ind",
")",
":",
"pp",
"=",
"pprint",
".",
"PrettyPrinter",
"(",
"indent",
"=",
"ind",
")",
"pp",
".",
"pprint",
"(",
"self",
".",
"tree",
")"
] | 37 | 0.013245 |
def _draw_rectangle(data, obj, draw_options):
"""Return the PGFPlots code for rectangles.
"""
# Objects with labels are plot objects (from bar charts, etc). Even those without
# labels explicitly set have a label of "_nolegend_". Everything else should be
# skipped because they likely correspong t... | [
"def",
"_draw_rectangle",
"(",
"data",
",",
"obj",
",",
"draw_options",
")",
":",
"# Objects with labels are plot objects (from bar charts, etc). Even those without",
"# labels explicitly set have a label of \"_nolegend_\". Everything else should be",
"# skipped because they likely corresp... | 36.292683 | 0.002618 |
def create_noop_node():
"""
Creates a noop node that can be added to a DAX doing nothing. The reason
for using this is if a minifollowups dax contains no triggers currently
the dax will contain no jobs and be invalid. By adding a noop node we
ensure that such daxes will actually run if one adds one ... | [
"def",
"create_noop_node",
"(",
")",
":",
"exe",
"=",
"wdax",
".",
"Executable",
"(",
"'NOOP'",
")",
"pfn",
"=",
"distutils",
".",
"spawn",
".",
"find_executable",
"(",
"'true'",
")",
"exe",
".",
"add_pfn",
"(",
"pfn",
")",
"node",
"=",
"wdax",
".",
... | 40.285714 | 0.001733 |
def _parse_sections(self):
""" parse sections and TOC """
def _list_to_dict(_dict, path, sec):
tmp = _dict
for elm in path[:-1]:
tmp = tmp[elm]
tmp[sec] = OrderedDict()
self._sections = list()
section_regexp = r"\n==* .* ==*\n" # '==... | [
"def",
"_parse_sections",
"(",
"self",
")",
":",
"def",
"_list_to_dict",
"(",
"_dict",
",",
"path",
",",
"sec",
")",
":",
"tmp",
"=",
"_dict",
"for",
"elm",
"in",
"path",
"[",
":",
"-",
"1",
"]",
":",
"tmp",
"=",
"tmp",
"[",
"elm",
"]",
"tmp",
... | 32.065217 | 0.001316 |
def from_uci(cls, uci: str) -> "Move":
"""
Parses an UCI string.
:raises: :exc:`ValueError` if the UCI string is invalid.
"""
if uci == "0000":
return cls.null()
elif len(uci) == 4 and "@" == uci[1]:
drop = PIECE_SYMBOLS.index(uci[0].lower())
... | [
"def",
"from_uci",
"(",
"cls",
",",
"uci",
":",
"str",
")",
"->",
"\"Move\"",
":",
"if",
"uci",
"==",
"\"0000\"",
":",
"return",
"cls",
".",
"null",
"(",
")",
"elif",
"len",
"(",
"uci",
")",
"==",
"4",
"and",
"\"@\"",
"==",
"uci",
"[",
"1",
"]"... | 42 | 0.006127 |
def get(self):
"""
Loads the configuration and returns it as a dictionary
"""
with open(self.filename, 'r') as f:
self.config = ujson.load(f)
return self.config | [
"def",
"get",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"filename",
",",
"'r'",
")",
"as",
"f",
":",
"self",
".",
"config",
"=",
"ujson",
".",
"load",
"(",
"f",
")",
"return",
"self",
".",
"config"
] | 29.428571 | 0.009434 |
def _parse_sections(morph_fd):
'''returns array of all the sections that exist
The format is nested lists that correspond to the s-expressions
'''
sections = []
token_iter = _get_tokens(morph_fd)
for token in token_iter:
if token == '(': # find top-level sections
section = ... | [
"def",
"_parse_sections",
"(",
"morph_fd",
")",
":",
"sections",
"=",
"[",
"]",
"token_iter",
"=",
"_get_tokens",
"(",
"morph_fd",
")",
"for",
"token",
"in",
"token_iter",
":",
"if",
"token",
"==",
"'('",
":",
"# find top-level sections",
"section",
"=",
"_p... | 35.230769 | 0.002128 |
def filter_threshold(df, inst_rc, threshold, num_occur=1):
'''
Filter a network's rows or cols based on num_occur values being above a
threshold (in absolute_value)
'''
from copy import deepcopy
inst_df = deepcopy(df['mat'])
if inst_rc == 'col':
inst_df = inst_df.transpose()
inst_df = inst_df.abs... | [
"def",
"filter_threshold",
"(",
"df",
",",
"inst_rc",
",",
"threshold",
",",
"num_occur",
"=",
"1",
")",
":",
"from",
"copy",
"import",
"deepcopy",
"inst_df",
"=",
"deepcopy",
"(",
"df",
"[",
"'mat'",
"]",
")",
"if",
"inst_rc",
"==",
"'col'",
":",
"ins... | 26.942308 | 0.014463 |
def github_gfonts_ttFont(ttFont, license):
"""Get a TTFont object of a font downloaded
from Google Fonts git repository.
"""
if not license:
return
from fontbakery.utils import download_file
from fontTools.ttLib import TTFont
from urllib.request import HTTPError
LICENSE_DIRECTORY = {
"OFL.tx... | [
"def",
"github_gfonts_ttFont",
"(",
"ttFont",
",",
"license",
")",
":",
"if",
"not",
"license",
":",
"return",
"from",
"fontbakery",
".",
"utils",
"import",
"download_file",
"from",
"fontTools",
".",
"ttLib",
"import",
"TTFont",
"from",
"urllib",
".",
"request... | 28.923077 | 0.015444 |
def view_dep(self, dep):
"""View the given department on the department page
:param dep: the dep to view
:type dep: :class:`jukeboxcore.djadapter.models.Department`
:returns: None
:rtype: None
:raises: None
"""
log.debug('Viewing department %s', dep.name)... | [
"def",
"view_dep",
"(",
"self",
",",
"dep",
")",
":",
"log",
".",
"debug",
"(",
"'Viewing department %s'",
",",
"dep",
".",
"name",
")",
"self",
".",
"cur_dep",
"=",
"None",
"self",
".",
"pages_tabw",
".",
"setCurrentIndex",
"(",
"6",
")",
"self",
".",... | 39.931034 | 0.00253 |
def get_backend(alias):
"""
Returns ``Repository`` class identified by the given alias or raises
VCSError if alias is not recognized or backend class cannot be imported.
"""
if alias not in settings.BACKENDS:
raise VCSError("Given alias '%s' is not recognized! Allowed aliases:\n"
... | [
"def",
"get_backend",
"(",
"alias",
")",
":",
"if",
"alias",
"not",
"in",
"settings",
".",
"BACKENDS",
":",
"raise",
"VCSError",
"(",
"\"Given alias '%s' is not recognized! Allowed aliases:\\n\"",
"\"%s\"",
"%",
"(",
"alias",
",",
"pformat",
"(",
"settings",
".",
... | 41.909091 | 0.004246 |
def Animation_resolveAnimation(self, animationId):
"""
Function path: Animation.resolveAnimation
Domain: Animation
Method name: resolveAnimation
Parameters:
Required arguments:
'animationId' (type: string) -> Animation id.
Returns:
'remoteObject' (type: Runtime.RemoteObject) -> Correspon... | [
"def",
"Animation_resolveAnimation",
"(",
"self",
",",
"animationId",
")",
":",
"assert",
"isinstance",
"(",
"animationId",
",",
"(",
"str",
",",
")",
")",
",",
"\"Argument 'animationId' must be of type '['str']'. Received type: '%s'\"",
"%",
"type",
"(",
"animationId",... | 32.95 | 0.042773 |
def band_path(self, band_id, for_gdal=False, absolute=False):
"""Return paths of given band's jp2 files for all granules."""
band_id = str(band_id).zfill(2)
if not isinstance(band_id, str) or band_id not in BAND_IDS:
raise ValueError("band ID not valid: %s" % band_id)
if self... | [
"def",
"band_path",
"(",
"self",
",",
"band_id",
",",
"for_gdal",
"=",
"False",
",",
"absolute",
"=",
"False",
")",
":",
"band_id",
"=",
"str",
"(",
"band_id",
")",
".",
"zfill",
"(",
"2",
")",
"if",
"not",
"isinstance",
"(",
"band_id",
",",
"str",
... | 41.152778 | 0.000659 |
def _spec_from_modpath(modpath, path=None, context=None):
"""given a mod path (i.e. split module / package name), return the
corresponding spec
this function is used internally, see `file_from_modpath`'s
documentation for more information
"""
assert modpath
location = None
if context is... | [
"def",
"_spec_from_modpath",
"(",
"modpath",
",",
"path",
"=",
"None",
",",
"context",
"=",
"None",
")",
":",
"assert",
"modpath",
"location",
"=",
"None",
"if",
"context",
"is",
"not",
"None",
":",
"try",
":",
"found_spec",
"=",
"spec",
".",
"find_spec"... | 39.212121 | 0.001508 |
def _check_command_response(response, msg=None, allowable_errors=None,
parse_write_concern_error=False):
"""Check the response to a command for errors.
"""
if "ok" not in response:
# Server didn't recognize our message as a command.
raise OperationFailure(response... | [
"def",
"_check_command_response",
"(",
"response",
",",
"msg",
"=",
"None",
",",
"allowable_errors",
"=",
"None",
",",
"parse_write_concern_error",
"=",
"False",
")",
":",
"if",
"\"ok\"",
"not",
"in",
"response",
":",
"# Server didn't recognize our message as a comman... | 42.222222 | 0.000367 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.