text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def get_default_locale_callable():
"""
Wrapper function so that the default mapping is only built when needed
"""
exec_dir = os.path.dirname(os.path.realpath(__file__))
xml_path = os.path.join(exec_dir, 'data', 'FacebookLocales.xml')
fb_locales = _build_locale_table(xml_path)
def default_l... | [
"def",
"get_default_locale_callable",
"(",
")",
":",
"exec_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"__file__",
")",
")",
"xml_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"exec_dir",
",",
"'data'"... | 34.516129 | 16.193548 |
def register(self, key, value):
""" Registers a callable with the specified key.
`key`
String key to identify a callable.
`value`
Callable object.
"""
self._actions[key] = value
# invalidate cache of results for existing key
... | [
"def",
"register",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"self",
".",
"_actions",
"[",
"key",
"]",
"=",
"value",
"# invalidate cache of results for existing key",
"if",
"key",
"in",
"self",
".",
"_cache",
":",
"del",
"self",
".",
"_cache",
"[",
... | 26.428571 | 16.357143 |
def base64_process(**kwargs):
"""
Process base64 file io
"""
str_fileToSave = ""
str_fileToRead = ""
str_action = "encode"
data = None
for k,v in kwargs.items():
if k == 'action': str_action = v
if k == 'payloadBytes'... | [
"def",
"base64_process",
"(",
"*",
"*",
"kwargs",
")",
":",
"str_fileToSave",
"=",
"\"\"",
"str_fileToRead",
"=",
"\"\"",
"str_action",
"=",
"\"encode\"",
"data",
"=",
"None",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"k"... | 35.647059 | 16.313725 |
def add_cookie(self, key, value, **attrs):
'''
Finer control over cookies. Allow specifying an Morsel arguments.
'''
if attrs:
c = Morsel()
c.set(key, value, **attrs)
self.cookies[key] = c
else:
self.cookies[key] = value | [
"def",
"add_cookie",
"(",
"self",
",",
"key",
",",
"value",
",",
"*",
"*",
"attrs",
")",
":",
"if",
"attrs",
":",
"c",
"=",
"Morsel",
"(",
")",
"c",
".",
"set",
"(",
"key",
",",
"value",
",",
"*",
"*",
"attrs",
")",
"self",
".",
"cookies",
"[... | 30 | 17.2 |
def _format_job_instance(job):
'''
Helper to format a job instance
'''
if not job:
ret = {'Error': 'Cannot contact returner or no job with this jid'}
return ret
ret = {'Function': job.get('fun', 'unknown-function'),
'Arguments': list(job.get('arg', [])),
# unli... | [
"def",
"_format_job_instance",
"(",
"job",
")",
":",
"if",
"not",
"job",
":",
"ret",
"=",
"{",
"'Error'",
":",
"'Cannot contact returner or no job with this jid'",
"}",
"return",
"ret",
"ret",
"=",
"{",
"'Function'",
":",
"job",
".",
"get",
"(",
"'fun'",
","... | 31.88 | 19.88 |
def is_valid_host(value):
"""Check if given value is a valid host string.
:param value: a value to test
:returns: True if the value is valid
"""
host_validators = validators.ipv4, validators.ipv6, validators.domain
return any(f(value) for f in host_validators) | [
"def",
"is_valid_host",
"(",
"value",
")",
":",
"host_validators",
"=",
"validators",
".",
"ipv4",
",",
"validators",
".",
"ipv6",
",",
"validators",
".",
"domain",
"return",
"any",
"(",
"f",
"(",
"value",
")",
"for",
"f",
"in",
"host_validators",
")"
] | 34.75 | 13 |
def _find_devices_win(self):
"""Find devices on Windows."""
self._find_xinput()
self._detect_gamepads()
self._count_devices()
if self._raw_device_counts['keyboards'] > 0:
self.keyboards.append(Keyboard(
self,
"/dev/input/by-id/usb-A_Nic... | [
"def",
"_find_devices_win",
"(",
"self",
")",
":",
"self",
".",
"_find_xinput",
"(",
")",
"self",
".",
"_detect_gamepads",
"(",
")",
"self",
".",
"_count_devices",
"(",
")",
"if",
"self",
".",
"_raw_device_counts",
"[",
"'keyboards'",
"]",
">",
"0",
":",
... | 36.928571 | 15.357143 |
def run_kernel(self, func, c_args, threads, grid):
"""runs the kernel once, returns whatever the kernel returns
:param func: A C function compiled for this specific configuration
:type func: ctypes._FuncPtr
:param c_args: A list of arguments to the function, order should match the
... | [
"def",
"run_kernel",
"(",
"self",
",",
"func",
",",
"c_args",
",",
"threads",
",",
"grid",
")",
":",
"logging",
".",
"debug",
"(",
"\"run_kernel\"",
")",
"logging",
".",
"debug",
"(",
"\"arguments=\"",
"+",
"str",
"(",
"[",
"str",
"(",
"arg",
".",
"c... | 37.535714 | 24.071429 |
def run_server(dbpath=os.path.expanduser(config.dbserver.file),
dbhostport=None, loglevel='WARN'):
"""
Run the DbServer on the given database file and port. If not given,
use the settings in openquake.cfg.
"""
if dbhostport: # assume a string of the form "dbhost:port"
dbhost,... | [
"def",
"run_server",
"(",
"dbpath",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"config",
".",
"dbserver",
".",
"file",
")",
",",
"dbhostport",
"=",
"None",
",",
"loglevel",
"=",
"'WARN'",
")",
":",
"if",
"dbhostport",
":",
"# assume a string of the fo... | 36.366667 | 17.1 |
def _copyToNewWorkingDir(newdir,input):
""" Copy input file and all related files necessary for processing to the new working directory.
This function works in a greedy manner, in that all files associated
with all inputs(have the same rootname) will be copied to the new
working directory.
... | [
"def",
"_copyToNewWorkingDir",
"(",
"newdir",
",",
"input",
")",
":",
"flist",
"=",
"[",
"]",
"if",
"'_asn.fits'",
"in",
"input",
":",
"asndict",
"=",
"asnutil",
".",
"readASNTable",
"(",
"input",
",",
"None",
")",
"flist",
".",
"append",
"(",
"input",
... | 40.894737 | 14.315789 |
def fix_groups(groups):
"""Takes care of strange group numbers."""
_groups = []
for g in groups:
try:
if not float(g) > 0:
_groups.append(1000)
else:
_groups.append(int(g))
except TypeError as e:
logging.info("Error in readi... | [
"def",
"fix_groups",
"(",
"groups",
")",
":",
"_groups",
"=",
"[",
"]",
"for",
"g",
"in",
"groups",
":",
"try",
":",
"if",
"not",
"float",
"(",
"g",
")",
">",
"0",
":",
"_groups",
".",
"append",
"(",
"1000",
")",
"else",
":",
"_groups",
".",
"a... | 29.933333 | 14.866667 |
def handle_activity_legacy(_: str, __: int, tokens: ParseResults) -> ParseResults:
"""Handle BEL 1.0 activities."""
legacy_cls = language.activity_labels[tokens[MODIFIER]]
tokens[MODIFIER] = ACTIVITY
tokens[EFFECT] = {
NAME: legacy_cls,
NAMESPACE: BEL_DEFAULT_NAMESPACE
}
log.log(... | [
"def",
"handle_activity_legacy",
"(",
"_",
":",
"str",
",",
"__",
":",
"int",
",",
"tokens",
":",
"ParseResults",
")",
"->",
"ParseResults",
":",
"legacy_cls",
"=",
"language",
".",
"activity_labels",
"[",
"tokens",
"[",
"MODIFIER",
"]",
"]",
"tokens",
"["... | 37.7 | 18.1 |
def allocate(self, handles, initial=False, params={}):
"""Call from main thread. Initiate a request for more environments"""
assert all(re.search('^\d+$', h) for h in handles), "All handles must be numbers: {}".format(handles)
self.requests.put(('allocate', (handles, initial, params))) | [
"def",
"allocate",
"(",
"self",
",",
"handles",
",",
"initial",
"=",
"False",
",",
"params",
"=",
"{",
"}",
")",
":",
"assert",
"all",
"(",
"re",
".",
"search",
"(",
"'^\\d+$'",
",",
"h",
")",
"for",
"h",
"in",
"handles",
")",
",",
"\"All handles m... | 76.75 | 27.5 |
def mutate_rows(
self,
table_name,
entries,
app_profile_id=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Mutates multiple rows in a batch. Each individual row is muta... | [
"def",
"mutate_rows",
"(",
"self",
",",
"table_name",
",",
"entries",
",",
"app_profile_id",
"=",
"None",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"... | 43.235955 | 25.707865 |
def cli():
"""Function for cli"""
epilog = ('The actions are:\n'
'\tnew\t\tCreate a new torn app\n'
'\trun\t\tRun the app and start a Web server for development\n'
'\tcontroller\tCreate a new controller\n'
'\tversion\t\treturns the current version of torn\n')
... | [
"def",
"cli",
"(",
")",
":",
"epilog",
"=",
"(",
"'The actions are:\\n'",
"'\\tnew\\t\\tCreate a new torn app\\n'",
"'\\trun\\t\\tRun the app and start a Web server for development\\n'",
"'\\tcontroller\\tCreate a new controller\\n'",
"'\\tversion\\t\\treturns the current version of torn\\n'... | 42.666667 | 18.740741 |
def _do_comment(self, node):
'''_do_comment(self, node) -> None
Process a comment node. Render a leading or trailing #xA if the
document order of the comment is greater or lesser (respectively)
than the document element.
'''
if not _in_subset(self.subset, node): return
... | [
"def",
"_do_comment",
"(",
"self",
",",
"node",
")",
":",
"if",
"not",
"_in_subset",
"(",
"self",
".",
"subset",
",",
"node",
")",
":",
"return",
"if",
"self",
".",
"comments",
":",
"W",
"=",
"self",
".",
"write",
"if",
"self",
".",
"documentOrder",
... | 39.142857 | 17.857143 |
def new(self, length, fp, manage_fp, offset):
# type: (int, BinaryIO, bool, int) -> None
'''
Initialize a new Inode.
Parameters:
None.
Returns:
Nothing.
'''
if self._initialized:
raise pycdlibexception.PyCdlibInternalError('Inode is ... | [
"def",
"new",
"(",
"self",
",",
"length",
",",
"fp",
",",
"manage_fp",
",",
"offset",
")",
":",
"# type: (int, BinaryIO, bool, int) -> None",
"if",
"self",
".",
"_initialized",
":",
"raise",
"pycdlibexception",
".",
"PyCdlibInternalError",
"(",
"'Inode is already in... | 26.047619 | 21.952381 |
def firmware_autoupgrade_params_username(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
firmware = ET.SubElement(config, "firmware", xmlns="urn:brocade.com:mgmt:brocade-firmware")
autoupgrade_params = ET.SubElement(firmware, "autoupgrade-params")
... | [
"def",
"firmware_autoupgrade_params_username",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"firmware",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"firmware\"",
",",
"xmlns",
"=",
"\"... | 46 | 19 |
def ServiceAccountCredentialsFromP12File(
service_account_name, private_key_filename, scopes, user_agent):
"""Create a new credential from the named .p12 keyfile."""
private_key_filename = os.path.expanduser(private_key_filename)
scopes = util.NormalizeScopes(scopes)
if oauth2client.__version__ ... | [
"def",
"ServiceAccountCredentialsFromP12File",
"(",
"service_account_name",
",",
"private_key_filename",
",",
"scopes",
",",
"user_agent",
")",
":",
"private_key_filename",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"private_key_filename",
")",
"scopes",
"=",
"ut... | 47.315789 | 15.421053 |
def subject_id(self):
""" The name of the subject can be in either of
BaseID, NameID or EncryptedID
:return: The identifier if there is one
"""
if "subject" in self.message.keys():
_subj = self.message.subject
if "base_id" in _subj.keys() and _subj.base_... | [
"def",
"subject_id",
"(",
"self",
")",
":",
"if",
"\"subject\"",
"in",
"self",
".",
"message",
".",
"keys",
"(",
")",
":",
"_subj",
"=",
"self",
".",
"message",
".",
"subject",
"if",
"\"base_id\"",
"in",
"_subj",
".",
"keys",
"(",
")",
"and",
"_subj"... | 33.95 | 12.25 |
def ToJson(self):
"""
Convert object members to a dictionary that can be parsed as JSON.
Returns:
dict:
"""
jsn = super(MinerTransaction, self).ToJson()
jsn['nonce'] = self.Nonce
return jsn | [
"def",
"ToJson",
"(",
"self",
")",
":",
"jsn",
"=",
"super",
"(",
"MinerTransaction",
",",
"self",
")",
".",
"ToJson",
"(",
")",
"jsn",
"[",
"'nonce'",
"]",
"=",
"self",
".",
"Nonce",
"return",
"jsn"
] | 25 | 18.4 |
def log(message: str, *args: str, category: str='info', logger_name: str='pgevents'):
"""Log a message to the given logger.
If debug has not been enabled, this method will not log a message.
Parameters
----------
message: str
Message, with or without formatters, to print.
args: Any
... | [
"def",
"log",
"(",
"message",
":",
"str",
",",
"*",
"args",
":",
"str",
",",
"category",
":",
"str",
"=",
"'info'",
",",
"logger_name",
":",
"str",
"=",
"'pgevents'",
")",
":",
"global",
"_DEBUG_ENABLED",
"if",
"_DEBUG_ENABLED",
":",
"level",
"=",
"log... | 33.1875 | 23.375 |
def enrich_pubmed_citations(manager,
graph,
group_size: Optional[int] = None,
sleep_time: Optional[int] = None,
) -> Set[str]:
"""Overwrite all PubMed citations with values from NCBI's eUtils lookup servi... | [
"def",
"enrich_pubmed_citations",
"(",
"manager",
",",
"graph",
",",
"group_size",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"sleep_time",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
")",
"->",
"Set",
"[",
"str",
"]",
":",
"pmids",
... | 42.466667 | 25.233333 |
def resolve(self, pid):
"""Get Object Locations for Object."""
client = d1_cli.impl.client.CLICNClient(
**self._cn_client_connect_params_from_session()
)
object_location_list_pyxb = client.resolve(pid)
for location in object_location_list_pyxb.objectLocation:
... | [
"def",
"resolve",
"(",
"self",
",",
"pid",
")",
":",
"client",
"=",
"d1_cli",
".",
"impl",
".",
"client",
".",
"CLICNClient",
"(",
"*",
"*",
"self",
".",
"_cn_client_connect_params_from_session",
"(",
")",
")",
"object_location_list_pyxb",
"=",
"client",
"."... | 44.75 | 16 |
def fit(
model_matrix,
response,
model,
model_coefficients_start=None,
predicted_linear_response_start=None,
l2_regularizer=None,
dispersion=None,
offset=None,
convergence_criteria_fn=None,
learning_rate=None,
fast_unsafe_numerics=True,
maximum_iterations=None,
name=N... | [
"def",
"fit",
"(",
"model_matrix",
",",
"response",
",",
"model",
",",
"model_coefficients_start",
"=",
"None",
",",
"predicted_linear_response_start",
"=",
"None",
",",
"l2_regularizer",
"=",
"None",
",",
"dispersion",
"=",
"None",
",",
"offset",
"=",
"None",
... | 39.285068 | 21.113122 |
def _got_srv(self, addrs):
"""Handle SRV lookup result.
:Parameters:
- `addrs`: properly sorted list of (hostname, port) tuples
"""
with self.lock:
if not addrs:
self._dst_service = None
if self._dst_port:
self.... | [
"def",
"_got_srv",
"(",
"self",
",",
"addrs",
")",
":",
"with",
"self",
".",
"lock",
":",
"if",
"not",
"addrs",
":",
"self",
".",
"_dst_service",
"=",
"None",
"if",
"self",
".",
"_dst_port",
":",
"self",
".",
"_dst_nameports",
"=",
"[",
"(",
"self",
... | 43.4 | 17.28 |
def remove_edges(self, from_idx, to_idx, symmetric=False, copy=False):
'''Removes all from->to and to->from edges.
Note: the symmetric kwarg is unused.'''
flat_inds = self._pairs.dot((self._num_vertices, 1))
# convert to sorted order and flatten
to_remove = (np.minimum(from_idx, to_idx) * self._num_... | [
"def",
"remove_edges",
"(",
"self",
",",
"from_idx",
",",
"to_idx",
",",
"symmetric",
"=",
"False",
",",
"copy",
"=",
"False",
")",
":",
"flat_inds",
"=",
"self",
".",
"_pairs",
".",
"dot",
"(",
"(",
"self",
".",
"_num_vertices",
",",
"1",
")",
")",
... | 46.416667 | 12.083333 |
def shared(self, value, name=None):
"""
Create a shared theano scalar value.
"""
if type(value) == int:
final_value = np.array(value, dtype="int32")
elif type(value) == float:
final_value = np.array(value, dtype=env.FLOATX)
else:
final_... | [
"def",
"shared",
"(",
"self",
",",
"value",
",",
"name",
"=",
"None",
")",
":",
"if",
"type",
"(",
"value",
")",
"==",
"int",
":",
"final_value",
"=",
"np",
".",
"array",
"(",
"value",
",",
"dtype",
"=",
"\"int32\"",
")",
"elif",
"type",
"(",
"va... | 31.333333 | 12.333333 |
def is_done(self):
"""
Returns True if the read stream is done (either it's returned EOF or
the pump doesn't have wait_for_output set), and the write
side does not have pending bytes to send.
"""
return (not self.wait_for_output or self.eof) and \
not (ha... | [
"def",
"is_done",
"(",
"self",
")",
":",
"return",
"(",
"not",
"self",
".",
"wait_for_output",
"or",
"self",
".",
"eof",
")",
"and",
"not",
"(",
"hasattr",
"(",
"self",
".",
"to_stream",
",",
"'needs_write'",
")",
"and",
"self",
".",
"to_stream",
".",
... | 42.444444 | 22.666667 |
def respect_language(language):
"""Context manager that changes the current translation language for
all code inside the following block.
Can e.g. be used inside tasks like this::
from celery import task
from djcelery.common import respect_language
@task
def my_task(langua... | [
"def",
"respect_language",
"(",
"language",
")",
":",
"if",
"language",
":",
"prev",
"=",
"translation",
".",
"get_language",
"(",
")",
"translation",
".",
"activate",
"(",
"language",
")",
"try",
":",
"yield",
"finally",
":",
"translation",
".",
"activate",... | 25.652174 | 16.217391 |
def connections_to_object(self, to_obj):
"""
Returns a ``Connection`` query set matching all connections with
the given object as a destination.
"""
self._validate_ctypes(None, to_obj)
return self.connections.filter(to_pk=to_obj.pk) | [
"def",
"connections_to_object",
"(",
"self",
",",
"to_obj",
")",
":",
"self",
".",
"_validate_ctypes",
"(",
"None",
",",
"to_obj",
")",
"return",
"self",
".",
"connections",
".",
"filter",
"(",
"to_pk",
"=",
"to_obj",
".",
"pk",
")"
] | 39.142857 | 7.428571 |
def operation_file(uploader, cmd, filename=''):
"""File operations"""
if cmd == 'list':
operation_list(uploader)
if cmd == 'do':
for path in filename:
uploader.file_do(path)
elif cmd == 'format':
uploader.file_format()
elif cmd == 'remove':
for path in fil... | [
"def",
"operation_file",
"(",
"uploader",
",",
"cmd",
",",
"filename",
"=",
"''",
")",
":",
"if",
"cmd",
"==",
"'list'",
":",
"operation_list",
"(",
"uploader",
")",
"if",
"cmd",
"==",
"'do'",
":",
"for",
"path",
"in",
"filename",
":",
"uploader",
".",... | 29.6 | 10.333333 |
def get_bounces(api_key=None, secure=None, test=None, **request_args):
'''Get a paginated list of bounces.
:param api_key: Your Postmark API key. Required, if `test` is not `True`.
:param secure: Use the https scheme for the Postmark API.
Defaults to `True`
:param test: Use the Postmark Test AP... | [
"def",
"get_bounces",
"(",
"api_key",
"=",
"None",
",",
"secure",
"=",
"None",
",",
"test",
"=",
"None",
",",
"*",
"*",
"request_args",
")",
":",
"return",
"_default_bounces",
".",
"get",
"(",
"api_key",
"=",
"api_key",
",",
"secure",
"=",
"secure",
",... | 45.461538 | 20.692308 |
def allocated_chunks(self):
"""
Returns an iterator over all the allocated chunks in the heap.
"""
raise NotImplementedError("%s not implemented for %s" % (self.allocated_chunks.__func__.__name__,
self.__class__.__name__)) | [
"def",
"allocated_chunks",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"%s not implemented for %s\"",
"%",
"(",
"self",
".",
"allocated_chunks",
".",
"__func__",
".",
"__name__",
",",
"self",
".",
"__class__",
".",
"__name__",
")",
")"
] | 52.333333 | 26.333333 |
def out_degree_iter(self, nbunch=None, t=None):
"""Return an iterator for (node, out_degree) at time t.
The node out degree is the number of interactions outgoing from the node in a given timeframe.
Parameters
----------
nbunch : iterable container, optional (default=all nodes)... | [
"def",
"out_degree_iter",
"(",
"self",
",",
"nbunch",
"=",
"None",
",",
"t",
"=",
"None",
")",
":",
"if",
"nbunch",
"is",
"None",
":",
"nodes_nbrs",
"=",
"self",
".",
"_succ",
".",
"items",
"(",
")",
"else",
":",
"nodes_nbrs",
"=",
"(",
"(",
"n",
... | 30.44898 | 21.591837 |
def _dt_to_epoch(self, dt):
"""
Convert a offset-aware datetime to POSIX time.
"""
if PY2:
# The input datetime is from botocore unmarshalling and it is
# offset-aware so the timedelta of subtracting this time
# to 01/01/1970 using the same tzinfo give... | [
"def",
"_dt_to_epoch",
"(",
"self",
",",
"dt",
")",
":",
"if",
"PY2",
":",
"# The input datetime is from botocore unmarshalling and it is",
"# offset-aware so the timedelta of subtracting this time",
"# to 01/01/1970 using the same tzinfo gives us",
"# Unix Time (also known as POSIX Time... | 43.714286 | 17.428571 |
def scp_push(self, src, dest, progress=False, preserve_times=True):
""" Purpose: Makes an SCP push request for the specified file(s)/dir.
@param src: string containing the source file or directory
@type src: str
@param dest: destination string of where to put the file(s)/dir
@ty... | [
"def",
"scp_push",
"(",
"self",
",",
"src",
",",
"dest",
",",
"progress",
"=",
"False",
",",
"preserve_times",
"=",
"True",
")",
":",
"# set up the progress callback if they want to see the process",
"if",
"progress",
"is",
"True",
":",
"self",
".",
"_scp",
".",... | 44.483871 | 17.774194 |
def _provider_state_fixtures_with_params(
provider_state_fixture_by_descriptor: Dict[str, ProviderStateFixture],
provider_states: Tuple[ProviderState, ...]
) -> List[Tuple[ProviderStateFixture, Dict]]:
"""Get a list of provider states fixtures for an interaction with their parameters.
Raises an ... | [
"def",
"_provider_state_fixtures_with_params",
"(",
"provider_state_fixture_by_descriptor",
":",
"Dict",
"[",
"str",
",",
"ProviderStateFixture",
"]",
",",
"provider_states",
":",
"Tuple",
"[",
"ProviderState",
",",
"...",
"]",
")",
"->",
"List",
"[",
"Tuple",
"[",
... | 52.518519 | 21.62963 |
def variance(numbers, type='population'):
"""
Calculates the population or sample variance of a list of numbers.
A large number means the results are all over the place, while a
small number means the results are comparatively close to the average.
Args:
numbers: a list of integers or floa... | [
"def",
"variance",
"(",
"numbers",
",",
"type",
"=",
"'population'",
")",
":",
"mean",
"=",
"average",
"(",
"numbers",
")",
"variance",
"=",
"0",
"for",
"number",
"in",
"numbers",
":",
"variance",
"+=",
"(",
"mean",
"-",
"number",
")",
"**",
"2",
"if... | 30.074074 | 21.259259 |
def _filter_statements(statements, agents):
"""Return INDRA Statements which have Agents in the given list.
Only statements are returned in which all appearing Agents as in the
agents list.
Parameters
----------
statements : list[indra.statements.Statement]
A list of INDRA Statements t... | [
"def",
"_filter_statements",
"(",
"statements",
",",
"agents",
")",
":",
"filtered_statements",
"=",
"[",
"]",
"for",
"s",
"in",
"stmts",
":",
"if",
"all",
"(",
"[",
"a",
"is",
"not",
"None",
"for",
"a",
"in",
"s",
".",
"agent_list",
"(",
")",
"]",
... | 32.791667 | 19.291667 |
def get_fresh_primary_tumors(biospecimen):
"""Filter biospecimen data to only keep non-FFPE primary tumor samples.
Parameters
----------
biospecimen : `pandas.DataFrame`
The biospecimen data frame. This type of data frame is returned by
:meth:`get_biospecimen_data`.
Returns... | [
"def",
"get_fresh_primary_tumors",
"(",
"biospecimen",
")",
":",
"df",
"=",
"biospecimen",
"# use shorter variable name",
"# get rid of FFPE samples",
"num_before",
"=",
"len",
"(",
"df",
".",
"index",
")",
"df",
"=",
"df",
".",
"loc",
"[",
"~",
"df",
"[",
"'i... | 32.064516 | 18.580645 |
def foldl(f: Callable[[T, U], T], x: T, xs: Iterable[U]) -> T:
""" Returns the accumulated result of a binary function applied to elements
of an iterable.
.. math::
foldl(f, x_0, [x_1, x_2, x_3]) = f(f(f(f(x_0, x_1), x_2), x_3)
Examples
--------
>>> from delphi.utils.fp import foldl
... | [
"def",
"foldl",
"(",
"f",
":",
"Callable",
"[",
"[",
"T",
",",
"U",
"]",
",",
"T",
"]",
",",
"x",
":",
"T",
",",
"xs",
":",
"Iterable",
"[",
"U",
"]",
")",
"->",
"T",
":",
"return",
"reduce",
"(",
"f",
",",
"xs",
",",
"x",
")"
] | 24.6875 | 23.1875 |
def detect(self):
"""
Resolve the hostname to an IP address through the operating system.
Depending on the 'family' option, either ipv4 or ipv6 resolution is
carried out.
If multiple IP addresses are found, the first one is returned.
:return: ip address
"""
... | [
"def",
"detect",
"(",
"self",
")",
":",
"theip",
"=",
"next",
"(",
"iter",
"(",
"resolve",
"(",
"self",
".",
"opts_hostname",
",",
"self",
".",
"opts_family",
")",
")",
",",
"None",
")",
"self",
".",
"set_current_value",
"(",
"theip",
")",
"return",
... | 31.571429 | 24.142857 |
def _isrc_long(name=None):
"""
Creates the grammar for a short ISRC code.
ISRC stands for International Standard Recording Code, which is the
standard ISO 3901. This stores information identifying a particular
recording.
This variant contain no separator for the parts, and follows the pattern:... | [
"def",
"_isrc_long",
"(",
"name",
"=",
"None",
")",
":",
"config",
"=",
"CWRTables",
"(",
")",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"'ISRC Field'",
"country",
"=",
"config",
".",
"get_data",
"(",
"'isrc_country_code'",
")",
"# registrant = basic.alp... | 24.541667 | 20.041667 |
def set_child_value(
self, sensor_id, child_id, value_type, value, **kwargs):
"""Add a command to set a sensor value, to the queue.
A queued command will be sent to the sensor when the gateway
thread has sent all previously queued commands.
If the sensor attribute new_state... | [
"def",
"set_child_value",
"(",
"self",
",",
"sensor_id",
",",
"child_id",
",",
"value_type",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"is_sensor",
"(",
"sensor_id",
",",
"child_id",
")",
":",
"return",
"if",
"self",
".... | 45.954545 | 21.136364 |
def delete_proxy(self, id, **kwargs): # noqa: E501
"""Delete a specific proxy # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_proxy(id, async_req=True)... | [
"def",
"delete_proxy",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"delete_proxy_wi... | 39.857143 | 17.333333 |
def load_xmatch_external_catalogs(xmatchto, xmatchkeys, outfile=None):
'''This loads the external xmatch catalogs into a dict for use in an xmatch.
Parameters
----------
xmatchto : list of str
This is a list of paths to all the catalog text files that will be
loaded.
The text ... | [
"def",
"load_xmatch_external_catalogs",
"(",
"xmatchto",
",",
"xmatchkeys",
",",
"outfile",
"=",
"None",
")",
":",
"outdict",
"=",
"{",
"}",
"for",
"xc",
",",
"xk",
"in",
"zip",
"(",
"xmatchto",
",",
"xmatchkeys",
")",
":",
"parsed_catdef",
"=",
"_parse_xm... | 37.534722 | 24.951389 |
def get_contribution(self, url):
"""Get the details of a particular contribution given it's
url"""
result = self.api_request(url)
# add the contrib id into the metadata
result['id'] = os.path.split(result['url'])[1]
return result | [
"def",
"get_contribution",
"(",
"self",
",",
"url",
")",
":",
"result",
"=",
"self",
".",
"api_request",
"(",
"url",
")",
"# add the contrib id into the metadata",
"result",
"[",
"'id'",
"]",
"=",
"os",
".",
"path",
".",
"split",
"(",
"result",
"[",
"'url'... | 27.2 | 16.9 |
def critical(self, event=None, *args, **kw):
"""
Process event and call :meth:`logging.Logger.critical` with the result.
"""
if not self._logger.isEnabledFor(logging.CRITICAL):
return
kw = self._add_base_info(kw)
kw['level'] = "critical"
return self._... | [
"def",
"critical",
"(",
"self",
",",
"event",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"if",
"not",
"self",
".",
"_logger",
".",
"isEnabledFor",
"(",
"logging",
".",
"CRITICAL",
")",
":",
"return",
"kw",
"=",
"self",
".",
"_a... | 35.8 | 16.4 |
def bitpos(self, key, bit, start=None, end=None):
"""Find first bit set or clear in a string.
:raises ValueError: if bit is not 0 or 1
"""
if bit not in (1, 0):
raise ValueError("bit argument must be either 1 or 0")
bytes_range = []
if start is not None:
... | [
"def",
"bitpos",
"(",
"self",
",",
"key",
",",
"bit",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
")",
":",
"if",
"bit",
"not",
"in",
"(",
"1",
",",
"0",
")",
":",
"raise",
"ValueError",
"(",
"\"bit argument must be either 1 or 0\"",
")",
"by... | 34.75 | 12.25 |
def parquet(self, *paths):
"""Loads Parquet files, returning the result as a :class:`DataFrame`.
You can set the following Parquet-specific option(s) for reading Parquet files:
* ``mergeSchema``: sets whether we should merge schemas collected from all \
Parquet part-files. T... | [
"def",
"parquet",
"(",
"self",
",",
"*",
"paths",
")",
":",
"return",
"self",
".",
"_df",
"(",
"self",
".",
"_jreader",
".",
"parquet",
"(",
"_to_seq",
"(",
"self",
".",
"_spark",
".",
"_sc",
",",
"paths",
")",
")",
")"
] | 55.769231 | 32.538462 |
def urquhart_graph(X, weighted=False):
'''Urquhart graph: made from the 2 shortest edges of each Delaunay triangle.
'''
e1, e2 = _delaunay_edges(X)
w = paired_distances(X[e1], X[e2])
mask = np.ones_like(w, dtype=bool)
bad_inds = w.reshape((-1, 3)).argmax(axis=1) + np.arange(0, len(e1), 3)
mask[bad_... | [
"def",
"urquhart_graph",
"(",
"X",
",",
"weighted",
"=",
"False",
")",
":",
"e1",
",",
"e2",
"=",
"_delaunay_edges",
"(",
"X",
")",
"w",
"=",
"paired_distances",
"(",
"X",
"[",
"e1",
"]",
",",
"X",
"[",
"e2",
"]",
")",
"mask",
"=",
"np",
".",
"... | 41.846154 | 18 |
def get_app_key(self):
"""
If app_key is not provided will look in environment
variables for username.
"""
if self.app_key is None:
if os.environ.get(self.username):
self.app_key = os.environ.get(self.username)
else:
raise A... | [
"def",
"get_app_key",
"(",
"self",
")",
":",
"if",
"self",
".",
"app_key",
"is",
"None",
":",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"self",
".",
"username",
")",
":",
"self",
".",
"app_key",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"sel... | 33.6 | 11 |
def _read_from_buffer(self, pos: int) -> None:
"""Attempts to complete the currently-pending read from the buffer.
The argument is either a position in the read buffer or None,
as returned by _find_read_pos.
"""
self._read_bytes = self._read_delimiter = self._read_regex = None
... | [
"def",
"_read_from_buffer",
"(",
"self",
",",
"pos",
":",
"int",
")",
"->",
"None",
":",
"self",
".",
"_read_bytes",
"=",
"self",
".",
"_read_delimiter",
"=",
"self",
".",
"_read_regex",
"=",
"None",
"self",
".",
"_read_partial",
"=",
"False",
"self",
".... | 42.555556 | 13.222222 |
def value_percent(self):
"""
[float] 获得该持仓的实时市场价值在股票投资组合价值中所占比例,取值范围[0, 1]
"""
accounts = Environment.get_instance().portfolio.accounts
if DEFAULT_ACCOUNT_TYPE.STOCK.name not in accounts:
return 0
total_value = accounts[DEFAULT_ACCOUNT_TYPE.STOCK.name].total_v... | [
"def",
"value_percent",
"(",
"self",
")",
":",
"accounts",
"=",
"Environment",
".",
"get_instance",
"(",
")",
".",
"portfolio",
".",
"accounts",
"if",
"DEFAULT_ACCOUNT_TYPE",
".",
"STOCK",
".",
"name",
"not",
"in",
"accounts",
":",
"return",
"0",
"total_valu... | 43.333333 | 17.777778 |
def _protected_log(x1):
"""Closure of log for zero arguments."""
with np.errstate(divide='ignore', invalid='ignore'):
return np.where(np.abs(x1) > 0.001, np.log(np.abs(x1)), 0.) | [
"def",
"_protected_log",
"(",
"x1",
")",
":",
"with",
"np",
".",
"errstate",
"(",
"divide",
"=",
"'ignore'",
",",
"invalid",
"=",
"'ignore'",
")",
":",
"return",
"np",
".",
"where",
"(",
"np",
".",
"abs",
"(",
"x1",
")",
">",
"0.001",
",",
"np",
... | 47.5 | 15 |
def get_knobs_current_as_table(cls):
"""
Renders current knob values in table
:return:
"""
knob_list = [
{
'Knob': name,
'Description': cls.get_registered_knob(name).description,
'Value': cls.get_registered_knob(name)()... | [
"def",
"get_knobs_current_as_table",
"(",
"cls",
")",
":",
"knob_list",
"=",
"[",
"{",
"'Knob'",
":",
"name",
",",
"'Description'",
":",
"cls",
".",
"get_registered_knob",
"(",
"name",
")",
".",
"description",
",",
"'Value'",
":",
"cls",
".",
"get_registered... | 32.571429 | 19 |
def config(show, reset, **params):
"""Inspect and configure parameters in your local sentinelhub configuration file
\b
Example:
sentinelhub.config --show
sentinelhub.config --instance_id <new instance id>
sentinelhub.config --max_download_attempts 5 --download_sleep_time 20 --download_tim... | [
"def",
"config",
"(",
"show",
",",
"reset",
",",
"*",
"*",
"params",
")",
":",
"sh_config",
"=",
"SHConfig",
"(",
")",
"if",
"reset",
":",
"sh_config",
".",
"reset",
"(",
")",
"for",
"param",
",",
"value",
"in",
"params",
".",
"items",
"(",
")",
... | 32.948718 | 18.974359 |
def ingest_dark(self):
"""Process dark."""
self.dark = extract_dark(self.hdulist[0].header, self.hdulist[1])
# If BIAS or DARK, set dark to zeros
if self.dark is None:
self.dark = np.zeros_like(self.science)
return
# Apply the dark subtraction if necess... | [
"def",
"ingest_dark",
"(",
"self",
")",
":",
"self",
".",
"dark",
"=",
"extract_dark",
"(",
"self",
".",
"hdulist",
"[",
"0",
"]",
".",
"header",
",",
"self",
".",
"hdulist",
"[",
"1",
"]",
")",
"# If BIAS or DARK, set dark to zeros",
"if",
"self",
".",
... | 33.5 | 19 |
def get_lines(self):
"""
Returns a list of string representations of the atomic configuration
information(x, y, z, ipot, atom_symbol, distance, id).
Returns:
list: list of strings, sorted by the distance from the absorbing
atom.
"""
lines = [[... | [
"def",
"get_lines",
"(",
"self",
")",
":",
"lines",
"=",
"[",
"[",
"\"{:f}\"",
".",
"format",
"(",
"self",
".",
"_cluster",
"[",
"0",
"]",
".",
"x",
")",
",",
"\"{:f}\"",
".",
"format",
"(",
"self",
".",
"_cluster",
"[",
"0",
"]",
".",
"y",
")"... | 44.761905 | 21.142857 |
def get_item(self):
"""Returns the item to send back into the workflow generator."""
if self.was_list:
result = ResultList()
for item in self:
if isinstance(item, WorkflowItem):
if item.done and not item.error:
result.ap... | [
"def",
"get_item",
"(",
"self",
")",
":",
"if",
"self",
".",
"was_list",
":",
"result",
"=",
"ResultList",
"(",
")",
"for",
"item",
"in",
"self",
":",
"if",
"isinstance",
"(",
"item",
",",
"WorkflowItem",
")",
":",
"if",
"item",
".",
"done",
"and",
... | 40.722222 | 15.055556 |
def _elim_adj(adj, n):
"""eliminates a variable, acting on the adj matrix of G,
returning set of edges that were added.
Parameters
----------
adj: dict
A dict of the form {v: neighbors, ...} where v are
vertices in a graph and neighbors is a set.
Returns
----------
new_... | [
"def",
"_elim_adj",
"(",
"adj",
",",
"n",
")",
":",
"neighbors",
"=",
"adj",
"[",
"n",
"]",
"new_edges",
"=",
"set",
"(",
")",
"for",
"u",
",",
"v",
"in",
"itertools",
".",
"combinations",
"(",
"neighbors",
",",
"2",
")",
":",
"if",
"v",
"not",
... | 25.518519 | 18.888889 |
def with_url(self, url):
"""Sets the request's URL and returns the request itself.
Automatically sets the Host header according to the URL.
Keyword arguments:
url -- a string representing the URL the set for the request
"""
self.url = URL(url)
self.header["Host"]... | [
"def",
"with_url",
"(",
"self",
",",
"url",
")",
":",
"self",
".",
"url",
"=",
"URL",
"(",
"url",
")",
"self",
".",
"header",
"[",
"\"Host\"",
"]",
"=",
"self",
".",
"url",
".",
"host",
"return",
"self"
] | 34.7 | 15.9 |
def get_flags(self, i, scoped=False):
"""Get flags."""
if scoped and not _SCOPED_FLAG_SUPPORT:
return None
index = i.index
value = ['(']
toggle = False
end = ':' if scoped else ')'
try:
c = next(i)
if c != '?':
... | [
"def",
"get_flags",
"(",
"self",
",",
"i",
",",
"scoped",
"=",
"False",
")",
":",
"if",
"scoped",
"and",
"not",
"_SCOPED_FLAG_SUPPORT",
":",
"return",
"None",
"index",
"=",
"i",
".",
"index",
"value",
"=",
"[",
"'('",
"]",
"toggle",
"=",
"False",
"en... | 30.833333 | 14.944444 |
def strftime(date_time=None, time_format=None):
"""
将 datetime 对象转换为 str
:param:
* date_time: (obj) datetime 对象
* time_format: (sting) 日期格式字符串
:return:
* date_time_str: (string) 日期字符串
"""
if not date_time:
datetime_now = da... | [
"def",
"strftime",
"(",
"date_time",
"=",
"None",
",",
"time_format",
"=",
"None",
")",
":",
"if",
"not",
"date_time",
":",
"datetime_now",
"=",
"datetime",
".",
"now",
"(",
")",
"else",
":",
"datetime_now",
"=",
"date_time",
"if",
"not",
"time_format",
... | 29.470588 | 11.705882 |
def QA_indicator_CCI(DataFrame, N=14):
"""
TYP:=(HIGH+LOW+CLOSE)/3;
CCI:(TYP-MA(TYP,N))/(0.015*AVEDEV(TYP,N));
"""
typ = (DataFrame['high'] + DataFrame['low'] + DataFrame['close']) / 3
cci = ((typ - MA(typ, N)) / (0.015 * AVEDEV(typ, N)))
a = 100
b = -100
return pd.DataFrame({
... | [
"def",
"QA_indicator_CCI",
"(",
"DataFrame",
",",
"N",
"=",
"14",
")",
":",
"typ",
"=",
"(",
"DataFrame",
"[",
"'high'",
"]",
"+",
"DataFrame",
"[",
"'low'",
"]",
"+",
"DataFrame",
"[",
"'close'",
"]",
")",
"/",
"3",
"cci",
"=",
"(",
"(",
"typ",
... | 26.461538 | 17.076923 |
def update_repodata(self, channels=None):
"""Update repodata from channels or use condarc channels if None."""
norm_channels = self.conda_get_condarc_channels(channels=channels,
normalize=True)
repodata_urls = self._set_repo_urls_from_chann... | [
"def",
"update_repodata",
"(",
"self",
",",
"channels",
"=",
"None",
")",
":",
"norm_channels",
"=",
"self",
".",
"conda_get_condarc_channels",
"(",
"channels",
"=",
"channels",
",",
"normalize",
"=",
"True",
")",
"repodata_urls",
"=",
"self",
".",
"_set_repo_... | 62.333333 | 16.333333 |
def filter_args_to_dict(filter_dict, accepted_filter_keys=[]):
"""Cast and validate filter args.
:param filter_dict: Filter kwargs
:param accepted_filter_keys: List of keys that are acceptable to use.
"""
out_dict = {}
for k, v in filter_dict.items():
# make sure that the filter k is a... | [
"def",
"filter_args_to_dict",
"(",
"filter_dict",
",",
"accepted_filter_keys",
"=",
"[",
"]",
")",
":",
"out_dict",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"filter_dict",
".",
"items",
"(",
")",
":",
"# make sure that the filter k is acceptable",
"# and that ... | 33.128205 | 19.384615 |
def unit_client(self):
# type: () -> TCPClient
"""Return a TCPClient with same settings of the batch TCP client"""
client = TCPClient(self.host, self.port, self.prefix)
self._configure_client(client)
return client | [
"def",
"unit_client",
"(",
"self",
")",
":",
"# type: () -> TCPClient",
"client",
"=",
"TCPClient",
"(",
"self",
".",
"host",
",",
"self",
".",
"port",
",",
"self",
".",
"prefix",
")",
"self",
".",
"_configure_client",
"(",
"client",
")",
"return",
"client... | 35.428571 | 15.571429 |
def x_forwarded_for(self):
"""X-Forwarded-For header value.
This is the amended header so that it contains the previous IP address
in the forwarding change.
"""
ip = self._request.META.get('REMOTE_ADDR')
current_xff = self.headers.get('X-Forwarded-For')
return ... | [
"def",
"x_forwarded_for",
"(",
"self",
")",
":",
"ip",
"=",
"self",
".",
"_request",
".",
"META",
".",
"get",
"(",
"'REMOTE_ADDR'",
")",
"current_xff",
"=",
"self",
".",
"headers",
".",
"get",
"(",
"'X-Forwarded-For'",
")",
"return",
"'%s, %s'",
"%",
"("... | 32.818182 | 21.090909 |
def onex(self):
"""
delete all X columns except the first one.
"""
xCols=[i for i in range(self.nCols) if self.colTypes[i]==3]
if len(xCols)>1:
for colI in xCols[1:][::-1]:
self.colDelete(colI) | [
"def",
"onex",
"(",
"self",
")",
":",
"xCols",
"=",
"[",
"i",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"nCols",
")",
"if",
"self",
".",
"colTypes",
"[",
"i",
"]",
"==",
"3",
"]",
"if",
"len",
"(",
"xCols",
")",
">",
"1",
":",
"for",
"co... | 31.75 | 10.25 |
def observe_reward_value(self, state_arr, action_arr):
'''
Compute the reward value.
Args:
state_arr: `np.ndarray` of state.
action_arr: `np.ndarray` of action.
Returns:
Reward value.
'''
if se... | [
"def",
"observe_reward_value",
"(",
"self",
",",
"state_arr",
",",
"action_arr",
")",
":",
"if",
"self",
".",
"__check_goal_flag",
"(",
"action_arr",
")",
"is",
"True",
":",
"return",
"1.0",
"else",
":",
"self",
".",
"__move_enemy",
"(",
"action_arr",
")",
... | 32.125 | 21.225 |
def remove_key(self, store_key):
"""Remove key in the context of the current transaction.
:param store_key: The key for the document in the store
:type store_key: str
"""
self._remove_cache[store_key] = True
if store_key in self._add_cache:
for hash_value in... | [
"def",
"remove_key",
"(",
"self",
",",
"store_key",
")",
":",
"self",
".",
"_remove_cache",
"[",
"store_key",
"]",
"=",
"True",
"if",
"store_key",
"in",
"self",
".",
"_add_cache",
":",
"for",
"hash_value",
"in",
"self",
".",
"_add_cache",
"[",
"store_key",... | 38.857143 | 13.5 |
def _or16(ins):
''' Compares & pops top 2 operands out of the stack, and checks
if the 1st operand OR (logical) 2nd operand (top of the stack),
pushes 0 if False, 1 if True.
16 bit un/signed version
Optimizations:
If any of the operators are constants: Returns either 0 or
... | [
"def",
"_or16",
"(",
"ins",
")",
":",
"op1",
",",
"op2",
"=",
"tuple",
"(",
"ins",
".",
"quad",
"[",
"2",
":",
"]",
")",
"if",
"_int_ops",
"(",
"op1",
",",
"op2",
")",
"is",
"not",
"None",
":",
"op1",
",",
"op2",
"=",
"_int_ops",
"(",
"op1",
... | 28.305556 | 18.861111 |
def anova(dv=None, between=None, data=None, detailed=False,
export_filename=None):
"""One-way and two-way ANOVA.
Parameters
----------
dv : string
Name of column in ``data`` containing the dependent variable.
between : string or list with two elements
Name of column(s) in ... | [
"def",
"anova",
"(",
"dv",
"=",
"None",
",",
"between",
"=",
"None",
",",
"data",
"=",
"None",
",",
"detailed",
"=",
"False",
",",
"export_filename",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"between",
",",
"list",
")",
":",
"if",
"len",
"("... | 38.381166 | 22.757848 |
def restart_stopped_apps():
'''
Restart all apps in stopped state
'''
cozy_apps = monitor.status(only_cozy=True)
for app in cozy_apps.keys():
state = cozy_apps[app]
if state == 'up':
next
elif state == 'down':
print 'Start {}'.format(app)
... | [
"def",
"restart_stopped_apps",
"(",
")",
":",
"cozy_apps",
"=",
"monitor",
".",
"status",
"(",
"only_cozy",
"=",
"True",
")",
"for",
"app",
"in",
"cozy_apps",
".",
"keys",
"(",
")",
":",
"state",
"=",
"cozy_apps",
"[",
"app",
"]",
"if",
"state",
"==",
... | 28.538462 | 12.692308 |
def dropStudyFromISA(studyNum, pathToISATABFile):
"""
This function removes a study from an ISA file
Typically, you should use the exploreISA function to check the contents
of the ISA file and retrieve the study number you are interested in!
Warning: this function deletes the given study and all its... | [
"def",
"dropStudyFromISA",
"(",
"studyNum",
",",
"pathToISATABFile",
")",
":",
"from",
"isatools",
"import",
"isatab",
"import",
"os",
"try",
":",
"isa",
"=",
"isatab",
".",
"load",
"(",
"pathToISATABFile",
",",
"skip_load_tables",
"=",
"True",
")",
"studies",... | 49.230769 | 22.230769 |
def _break_signals(self):
r"""Break N-dimensional signals into N 1D signals."""
for name in list(self.signals.keys()):
if self.signals[name].ndim == 2:
for i, signal_1d in enumerate(self.signals[name].T):
self.signals[name + '_' + str(i)] = signal_1d
... | [
"def",
"_break_signals",
"(",
"self",
")",
":",
"for",
"name",
"in",
"list",
"(",
"self",
".",
"signals",
".",
"keys",
"(",
")",
")",
":",
"if",
"self",
".",
"signals",
"[",
"name",
"]",
".",
"ndim",
"==",
"2",
":",
"for",
"i",
",",
"signal_1d",
... | 49.571429 | 11.428571 |
def _stub_attr(obj, attr_name):
'''
Stub an attribute of an object. Will return an existing stub if
there already is one.
'''
# Annoying circular reference requires importing here. Would like to see
# this cleaned up. @AW
from .mock import Mock
# Check to see if this a property, this ch... | [
"def",
"_stub_attr",
"(",
"obj",
",",
"attr_name",
")",
":",
"# Annoying circular reference requires importing here. Would like to see",
"# this cleaned up. @AW",
"from",
".",
"mock",
"import",
"Mock",
"# Check to see if this a property, this check is only for when dealing",
"# with ... | 38.148649 | 20.310811 |
def get_fullpath(self, withext=True):
"""Return the filepath with the filename
:param withext: If True, return with the fileextension.
:type withext: bool
:returns: None
:rtype: None
:raises: None
"""
p = self.get_path(self._obj)
n = self.get_name... | [
"def",
"get_fullpath",
"(",
"self",
",",
"withext",
"=",
"True",
")",
":",
"p",
"=",
"self",
".",
"get_path",
"(",
"self",
".",
"_obj",
")",
"n",
"=",
"self",
".",
"get_name",
"(",
"self",
".",
"_obj",
",",
"withext",
")",
"fp",
"=",
"os",
".",
... | 30.384615 | 12.307692 |
def start(self, block=True):
"""Start discovering and listing to connections."""
if self._state == INIT:
if not any(self.on_message.receivers_for(blinker.ANY)):
raise RuntimeError('no receivers connected to on_message')
self.logger.debug('starting %s...', self.na... | [
"def",
"start",
"(",
"self",
",",
"block",
"=",
"True",
")",
":",
"if",
"self",
".",
"_state",
"==",
"INIT",
":",
"if",
"not",
"any",
"(",
"self",
".",
"on_message",
".",
"receivers_for",
"(",
"blinker",
".",
"ANY",
")",
")",
":",
"raise",
"Runtime... | 33.52381 | 23.190476 |
def process(self, value, tag=None):
"""
Process (marshal) the tag with the specified value using the
optional type information.
@param value: The value (content) of the XML node.
@type value: (L{Object}|any)
@param tag: The (optional) tag name for the value. The default ... | [
"def",
"process",
"(",
"self",
",",
"value",
",",
"tag",
"=",
"None",
")",
":",
"content",
"=",
"Content",
"(",
"tag",
"=",
"tag",
",",
"value",
"=",
"value",
")",
"result",
"=",
"Core",
".",
"process",
"(",
"self",
",",
"content",
")",
"return",
... | 36.8 | 11.466667 |
def DOMDebugger_setDOMBreakpoint(self, nodeId, type):
"""
Function path: DOMDebugger.setDOMBreakpoint
Domain: DOMDebugger
Method name: setDOMBreakpoint
Parameters:
Required arguments:
'nodeId' (type: DOM.NodeId) -> Identifier of the node to set breakpoint on.
'type' (type: DOMBreakpointTyp... | [
"def",
"DOMDebugger_setDOMBreakpoint",
"(",
"self",
",",
"nodeId",
",",
"type",
")",
":",
"subdom_funcs",
"=",
"self",
".",
"synchronous_command",
"(",
"'DOMDebugger.setDOMBreakpoint'",
",",
"nodeId",
"=",
"nodeId",
",",
"type",
"=",
"type",
")",
"return",
"subd... | 33.411765 | 20.352941 |
def event_actions(self):
"""
Take actions for timed events
Returns
-------
None
"""
system = self.system
dae = system.dae
if self.switch:
system.Breaker.apply(self.t)
for item in system.check_event(self.t):
... | [
"def",
"event_actions",
"(",
"self",
")",
":",
"system",
"=",
"self",
".",
"system",
"dae",
"=",
"system",
".",
"dae",
"if",
"self",
".",
"switch",
":",
"system",
".",
"Breaker",
".",
"apply",
"(",
"self",
".",
"t",
")",
"for",
"item",
"in",
"syste... | 23.705882 | 15.470588 |
def store_meta(self,meta):
"Inplace method that adds meta information to the meta dictionary"
if self.meta is None:
self.meta = {}
self.meta.update(meta)
return self | [
"def",
"store_meta",
"(",
"self",
",",
"meta",
")",
":",
"if",
"self",
".",
"meta",
"is",
"None",
":",
"self",
".",
"meta",
"=",
"{",
"}",
"self",
".",
"meta",
".",
"update",
"(",
"meta",
")",
"return",
"self"
] | 34 | 17.333333 |
def datum_to_value(self, instance, datum):
"""Convert a given MAAS-side datum to a Python-side value.
:param instance: The `Object` instance on which this field is
currently operating. This method should treat it as read-only, for
example to perform validation with regards to ot... | [
"def",
"datum_to_value",
"(",
"self",
",",
"instance",
",",
"datum",
")",
":",
"if",
"datum",
"is",
"None",
":",
"return",
"[",
"]",
"if",
"not",
"isinstance",
"(",
"datum",
",",
"Sequence",
")",
":",
"raise",
"TypeError",
"(",
"\"datum must be a sequence,... | 43.52381 | 18.047619 |
def create(self):
""" Creates the database
>>> db.create()
True
"""
data = data={"db-name":self.db}
self.rest('POST', self.uri_str, status_codes=(200,201), data=data)
return True | [
"def",
"create",
"(",
"self",
")",
":",
"data",
"=",
"data",
"=",
"{",
"\"db-name\"",
":",
"self",
".",
"db",
"}",
"self",
".",
"rest",
"(",
"'POST'",
",",
"self",
".",
"uri_str",
",",
"status_codes",
"=",
"(",
"200",
",",
"201",
")",
",",
"data"... | 24.875 | 17 |
def set_origin(self, offset):
"""Applies a constant offset to all objects."""
offset = np.array(offset)
for node in self.worldbody.findall("./*[@pos]"):
cur_pos = string_to_array(node.get("pos"))
new_pos = cur_pos + offset
node.set("pos", array_to_string(new_p... | [
"def",
"set_origin",
"(",
"self",
",",
"offset",
")",
":",
"offset",
"=",
"np",
".",
"array",
"(",
"offset",
")",
"for",
"node",
"in",
"self",
".",
"worldbody",
".",
"findall",
"(",
"\"./*[@pos]\"",
")",
":",
"cur_pos",
"=",
"string_to_array",
"(",
"no... | 45.428571 | 9 |
def get_portchannel_info_by_intf_output_lacp_periodic_transmission_machine_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_portchannel_info_by_intf = ET.Element("get_portchannel_info_by_intf")
config = get_portchannel_info_by_intf
outpu... | [
"def",
"get_portchannel_info_by_intf_output_lacp_periodic_transmission_machine_state",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_portchannel_info_by_intf",
"=",
"ET",
".",
"Element",
"(",
"\"get_p... | 54.384615 | 25.384615 |
def main_target_default_build (self, specification, project):
""" Return the default build value to use when declaring a main target,
which is obtained by using specified value if not empty and parent's
default build attribute otherwise.
specification: Default build explicit... | [
"def",
"main_target_default_build",
"(",
"self",
",",
"specification",
",",
"project",
")",
":",
"assert",
"is_iterable_typed",
"(",
"specification",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"project",
",",
"ProjectTarget",
")",
"if",
"specification",
... | 53.461538 | 19.153846 |
def reduce_ticks(ax, which, maxticks=3):
"""Given a pyplot axis, resamples its `which`-axis ticks such that are at most
`maxticks` left.
Parameters
----------
ax : axis
The axis to adjust.
which : {'x' | 'y'}
Which axis to adjust.
maxticks : {3, int}
Maximum number o... | [
"def",
"reduce_ticks",
"(",
"ax",
",",
"which",
",",
"maxticks",
"=",
"3",
")",
":",
"ticks",
"=",
"getattr",
"(",
"ax",
",",
"'get_{}ticks'",
".",
"format",
"(",
"which",
")",
")",
"(",
")",
"if",
"len",
"(",
"ticks",
")",
">",
"maxticks",
":",
... | 29 | 15.15625 |
def unbounded(self):
"""Whether solution is unbounded"""
self._check_valid()
if self._ret_val != 0:
return self._ret_val == swiglpk.GLP_ENODFS
return swiglpk.glp_get_status(self._problem._p) == swiglpk.GLP_UNBND | [
"def",
"unbounded",
"(",
"self",
")",
":",
"self",
".",
"_check_valid",
"(",
")",
"if",
"self",
".",
"_ret_val",
"!=",
"0",
":",
"return",
"self",
".",
"_ret_val",
"==",
"swiglpk",
".",
"GLP_ENODFS",
"return",
"swiglpk",
".",
"glp_get_status",
"(",
"self... | 41.666667 | 15.5 |
def _get_mapping(self, schema):
"""Get mapping for given resource or item schema.
:param schema: resource or dict/list type item schema
"""
properties = {}
for field, field_schema in schema.items():
field_mapping = self._get_field_mapping(field_schema)
if... | [
"def",
"_get_mapping",
"(",
"self",
",",
"schema",
")",
":",
"properties",
"=",
"{",
"}",
"for",
"field",
",",
"field_schema",
"in",
"schema",
".",
"items",
"(",
")",
":",
"field_mapping",
"=",
"self",
".",
"_get_field_mapping",
"(",
"field_schema",
")",
... | 37.909091 | 13 |
def is_reduction(expr):
"""Check whether an expression is a reduction or not
Aggregations yield typed scalar expressions, since the result of an
aggregation is a single value. When creating an table expression
containing a GROUP BY equivalent, we need to be able to easily check
that we are looking ... | [
"def",
"is_reduction",
"(",
"expr",
")",
":",
"def",
"has_reduction",
"(",
"op",
")",
":",
"if",
"getattr",
"(",
"op",
",",
"'_reduction'",
",",
"False",
")",
":",
"return",
"True",
"for",
"arg",
"in",
"op",
".",
"args",
":",
"if",
"isinstance",
"(",... | 31.974359 | 25.948718 |
def foreach_sentence(layer, drop_factor=1.0):
"""Map a layer across sentences (assumes spaCy-esque .sents interface)"""
def sentence_fwd(docs, drop=0.0):
sents = []
lengths = []
for doc in docs:
doc_sents = [sent for sent in doc.sents if len(sent)]
subset = [
... | [
"def",
"foreach_sentence",
"(",
"layer",
",",
"drop_factor",
"=",
"1.0",
")",
":",
"def",
"sentence_fwd",
"(",
"docs",
",",
"drop",
"=",
"0.0",
")",
":",
"sents",
"=",
"[",
"]",
"lengths",
"=",
"[",
"]",
"for",
"doc",
"in",
"docs",
":",
"doc_sents",
... | 33.909091 | 16.545455 |
def source_list(source, source_hash, saltenv):
'''
Check the source list and return the source to use
CLI Example:
.. code-block:: bash
salt '*' file.source_list salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' base
'''
contextkey = '{0}_|-{1}_|-{2}'.format(source, source... | [
"def",
"source_list",
"(",
"source",
",",
"source_hash",
",",
"saltenv",
")",
":",
"contextkey",
"=",
"'{0}_|-{1}_|-{2}'",
".",
"format",
"(",
"source",
",",
"source_hash",
",",
"saltenv",
")",
"if",
"contextkey",
"in",
"__context__",
":",
"return",
"__context... | 45.962963 | 19.981481 |
def filenames(self):
"""Returns the filenames that this par2 file repairs."""
return [p.name for p in self.packets if isinstance(p, FileDescriptionPacket)] | [
"def",
"filenames",
"(",
"self",
")",
":",
"return",
"[",
"p",
".",
"name",
"for",
"p",
"in",
"self",
".",
"packets",
"if",
"isinstance",
"(",
"p",
",",
"FileDescriptionPacket",
")",
"]"
] | 56.333333 | 21.666667 |
def request(self, *args, **kwargs):
"""
The main purpose of this is to be a wrapper-like function to pass the api_token and all the other params to the
requests that are being made
:returns: An instance of RequestsHandler
"""
return RequestsHandler(*args, api_token=self.... | [
"def",
"request",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"RequestsHandler",
"(",
"*",
"args",
",",
"api_token",
"=",
"self",
".",
"api_token",
",",
"verify",
"=",
"self",
".",
"mist_client",
".",
"verify",
",",
"j... | 45.7 | 21.3 |
def tile(
sceneid, tile_x, tile_y, tile_z, bands=("4", "3", "2"), tilesize=256, pan=False
):
"""
Create mercator tile from Landsat-8 data.
Attributes
----------
sceneid : str
Landsat sceneid. For scenes after May 2017,
sceneid have to be LANDSAT_PRODUCT_ID.
tile_x : int
... | [
"def",
"tile",
"(",
"sceneid",
",",
"tile_x",
",",
"tile_y",
",",
"tile_z",
",",
"bands",
"=",
"(",
"\"4\"",
",",
"\"3\"",
",",
"\"2\"",
")",
",",
"tilesize",
"=",
"256",
",",
"pan",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"bands",
... | 33.846154 | 24.230769 |
def successful(self):
"""Property to tell if the run was successful: no failures."""
for result in self.results:
if result.code == ResultCode.FAILED:
return False
return True | [
"def",
"successful",
"(",
"self",
")",
":",
"for",
"result",
"in",
"self",
".",
"results",
":",
"if",
"result",
".",
"code",
"==",
"ResultCode",
".",
"FAILED",
":",
"return",
"False",
"return",
"True"
] | 36.833333 | 10.833333 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.