text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def enable_pyglet(self, app=None):
"""Enable event loop integration with pyglet.
Parameters
----------
app : ignored
Ignored, it's only a placeholder to keep the call signature of all
gui activation methods consistent, which simplifies the logic of
suppo... | [
"def",
"enable_pyglet",
"(",
"self",
",",
"app",
"=",
"None",
")",
":",
"from",
"pydev_ipython",
".",
"inputhookpyglet",
"import",
"inputhook_pyglet",
"self",
".",
"set_inputhook",
"(",
"inputhook_pyglet",
")",
"self",
".",
"_current_gui",
"=",
"GUI_PYGLET",
"re... | 32.47619 | 22 |
def stop_deps(self, conf, images):
"""Stop the containers for all our dependencies"""
for dependency, _ in conf.dependency_images():
self.stop_deps(images[dependency], images)
try:
self.stop_container(images[dependency], fail_on_bad_exit=True, fail_reason="Failed ... | [
"def",
"stop_deps",
"(",
"self",
",",
"conf",
",",
"images",
")",
":",
"for",
"dependency",
",",
"_",
"in",
"conf",
".",
"dependency_images",
"(",
")",
":",
"self",
".",
"stop_deps",
"(",
"images",
"[",
"dependency",
"]",
",",
"images",
")",
"try",
"... | 61.6 | 32.4 |
def key_on(self, value):
"""
:param value: str of which column to key the rows on like a dictionary
:return: None
"""
if isinstance(value, BASESTRING):
value = (value,)
self._key_on = value | [
"def",
"key_on",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"BASESTRING",
")",
":",
"value",
"=",
"(",
"value",
",",
")",
"self",
".",
"_key_on",
"=",
"value"
] | 30.25 | 12.25 |
def showToolTip( text,
point = None,
anchor = None,
parent = None,
background = None,
foreground = None,
key = None,
seconds = 5 ):
""... | [
"def",
"showToolTip",
"(",
"text",
",",
"point",
"=",
"None",
",",
"anchor",
"=",
"None",
",",
"parent",
"=",
"None",
",",
"background",
"=",
"None",
",",
"foreground",
"=",
"None",
",",
"key",
"=",
"None",
",",
"seconds",
"=",
"5",
")",
":",
"if",... | 33.885714 | 12.885714 |
def fix_ar_sample_workflow(brain_or_object):
"""Re-set the state of an AR, Sample and SamplePartition to match the
least-early state of all contained valid/current analyses. Ignores
retracted/rejected/cancelled analyses.
"""
def log_change_state(ar_id, obj_id, src, dst):
msg = "While fixing... | [
"def",
"fix_ar_sample_workflow",
"(",
"brain_or_object",
")",
":",
"def",
"log_change_state",
"(",
"ar_id",
",",
"obj_id",
",",
"src",
",",
"dst",
")",
":",
"msg",
"=",
"\"While fixing {ar_id}: \"",
"\"state changed for {obj_id}: \"",
"\"{src} -> {dst}\"",
".",
"forma... | 38.203704 | 15.5 |
def assert_not_exists(path, sep='.'):
"""
If path exists, modify to add a counter in the filename. Useful
for preventing accidental overrides. For example, if `file.txt`
exists, check if `file.1.txt` also exists. Repeat until we find
a non-existing version, such as `file.12.txt`.
Parameters
... | [
"def",
"assert_not_exists",
"(",
"path",
",",
"sep",
"=",
"'.'",
")",
":",
"name",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"path",
")",
"i",
"=",
"1",
"while",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"path",
"... | 28 | 21.217391 |
def replace_return_line_item_by_id(cls, return_line_item_id, return_line_item, **kwargs):
"""Replace ReturnLineItem
Replace all attributes of ReturnLineItem
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> ... | [
"def",
"replace_return_line_item_by_id",
"(",
"cls",
",",
"return_line_item_id",
",",
"return_line_item",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"ret... | 51.818182 | 28.363636 |
def hourly_relative_humidity(self):
"""A data collection containing hourly relative humidity over they day."""
dpt_data = self._humidity_condition.hourly_dew_point_values(
self._dry_bulb_condition)
rh_data = [rel_humid_from_db_dpt(x, y) for x, y in zip(
self._dry_bulb_con... | [
"def",
"hourly_relative_humidity",
"(",
"self",
")",
":",
"dpt_data",
"=",
"self",
".",
"_humidity_condition",
".",
"hourly_dew_point_values",
"(",
"self",
".",
"_dry_bulb_condition",
")",
"rh_data",
"=",
"[",
"rel_humid_from_db_dpt",
"(",
"x",
",",
"y",
")",
"f... | 56.125 | 12.875 |
def getFactory(self):
"""
Return a server factory which creates AMP protocol instances.
"""
factory = ServerFactory()
def protocol():
proto = CredReceiver()
proto.portal = Portal(
self.loginSystem,
[self.loginSystem,
... | [
"def",
"getFactory",
"(",
"self",
")",
":",
"factory",
"=",
"ServerFactory",
"(",
")",
"def",
"protocol",
"(",
")",
":",
"proto",
"=",
"CredReceiver",
"(",
")",
"proto",
".",
"portal",
"=",
"Portal",
"(",
"self",
".",
"loginSystem",
",",
"[",
"self",
... | 31.357143 | 10.785714 |
async def random(offset=0., width=1., interval=0.1):
"""Generate a stream of random numbers."""
while True:
await asyncio.sleep(interval)
yield offset + width * random_module.random() | [
"async",
"def",
"random",
"(",
"offset",
"=",
"0.",
",",
"width",
"=",
"1.",
",",
"interval",
"=",
"0.1",
")",
":",
"while",
"True",
":",
"await",
"asyncio",
".",
"sleep",
"(",
"interval",
")",
"yield",
"offset",
"+",
"width",
"*",
"random_module",
"... | 40.6 | 10.6 |
def _branch_name(cls, version):
"""Defines a mapping between versions and branches.
In particular, `-dev` suffixed releases always live on master. Any other (modern) release
lives in a branch.
"""
suffix = version.public[len(version.base_version):]
components = version.base_version.split('.') +... | [
"def",
"_branch_name",
"(",
"cls",
",",
"version",
")",
":",
"suffix",
"=",
"version",
".",
"public",
"[",
"len",
"(",
"version",
".",
"base_version",
")",
":",
"]",
"components",
"=",
"version",
".",
"base_version",
".",
"split",
"(",
"'.'",
")",
"+",... | 43.3125 | 19.6875 |
def get_by_username(self, username):
"""Retrieve user by username"""
res = filter(lambda x: x.username == username, self.users.values())
if len(res) > 0:
return res[0]
return None | [
"def",
"get_by_username",
"(",
"self",
",",
"username",
")",
":",
"res",
"=",
"filter",
"(",
"lambda",
"x",
":",
"x",
".",
"username",
"==",
"username",
",",
"self",
".",
"users",
".",
"values",
"(",
")",
")",
"if",
"len",
"(",
"res",
")",
">",
"... | 36.333333 | 15.166667 |
def _missing_(cls, value):
"""Lookup function used when value is not found."""
if not (isinstance(value, int) and 0x00 <= value <= 0xFF):
raise ValueError('%r is not a valid %s' % (value, cls.__name__))
if 0x0D <= value <= 0xEF:
extend_enum(cls, 'Unassigned [0x%s]' % hex(... | [
"def",
"_missing_",
"(",
"cls",
",",
"value",
")",
":",
"if",
"not",
"(",
"isinstance",
"(",
"value",
",",
"int",
")",
"and",
"0x00",
"<=",
"value",
"<=",
"0xFF",
")",
":",
"raise",
"ValueError",
"(",
"'%r is not a valid %s'",
"%",
"(",
"value",
",",
... | 50.5 | 21.25 |
def as_action_description(self):
"""
Get the action description.
Returns a dictionary describing the action.
"""
description = {
self.name: {
'href': self.href_prefix + self.href,
'timeRequested': self.time_requested,
'... | [
"def",
"as_action_description",
"(",
"self",
")",
":",
"description",
"=",
"{",
"self",
".",
"name",
":",
"{",
"'href'",
":",
"self",
".",
"href_prefix",
"+",
"self",
".",
"href",
",",
"'timeRequested'",
":",
"self",
".",
"time_requested",
",",
"'status'",... | 27.904762 | 17.809524 |
def synchronized(lock):
""" Synchronization decorator.
Allos to set a mutex on any function
"""
@simple_decorator
def wrap(function_target):
"""Decorator wrapper"""
def new_function(*args, **kw):
"""Decorated function with Mutex"""
lock.acquire()
... | [
"def",
"synchronized",
"(",
"lock",
")",
":",
"@",
"simple_decorator",
"def",
"wrap",
"(",
"function_target",
")",
":",
"\"\"\"Decorator wrapper\"\"\"",
"def",
"new_function",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"\"\"\"Decorated function with Mutex\"\... | 29.4375 | 9.875 |
def dump_encoding( file, encoding_name, encoding_list ):
"""dump a given encoding"""
write = file.write
write( " /* the following are indices into the SID name table */\n" )
write( " static const unsigned short " + encoding_name +
"[" + repr( len( encoding_list ) ) + "] =\n" )
write( " {\n" )
... | [
"def",
"dump_encoding",
"(",
"file",
",",
"encoding_name",
",",
"encoding_list",
")",
":",
"write",
"=",
"file",
".",
"write",
"write",
"(",
"\" /* the following are indices into the SID name table */\\n\"",
")",
"write",
"(",
"\" static const unsigned short \"",
"+",
... | 24.227273 | 22.818182 |
def output_stderr(self, text):
"*text* should be bytes"
binary_stderr.write(b''.join([
self._red,
b't=%07d' % (time.time() - self._t0),
self._reset,
b' ',
text,
]))
binary_stderr.flush() | [
"def",
"output_stderr",
"(",
"self",
",",
"text",
")",
":",
"binary_stderr",
".",
"write",
"(",
"b''",
".",
"join",
"(",
"[",
"self",
".",
"_red",
",",
"b't=%07d'",
"%",
"(",
"time",
".",
"time",
"(",
")",
"-",
"self",
".",
"_t0",
")",
",",
"self... | 26.9 | 14.9 |
def resume_writing(self, exc=None):
'''Resume writing.
Successive calls to this method will fails unless
:meth:`pause_writing` is called first.
'''
assert self._paused
self._paused = False
waiter = self._waiter
if waiter is not None:
self._wai... | [
"def",
"resume_writing",
"(",
"self",
",",
"exc",
"=",
"None",
")",
":",
"assert",
"self",
".",
"_paused",
"self",
".",
"_paused",
"=",
"False",
"waiter",
"=",
"self",
".",
"_waiter",
"if",
"waiter",
"is",
"not",
"None",
":",
"self",
".",
"_waiter",
... | 31.611111 | 12.166667 |
def parse_dbus_address(address):
"""Parse a D-BUS address string into a list of addresses."""
if address == 'session':
address = os.environ.get('DBUS_SESSION_BUS_ADDRESS')
if not address:
raise ValueError('$DBUS_SESSION_BUS_ADDRESS not set')
elif address == 'system':
addr... | [
"def",
"parse_dbus_address",
"(",
"address",
")",
":",
"if",
"address",
"==",
"'session'",
":",
"address",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'DBUS_SESSION_BUS_ADDRESS'",
")",
"if",
"not",
"address",
":",
"raise",
"ValueError",
"(",
"'$DBUS_SESSION_B... | 41.83871 | 17.193548 |
def comment(self, format, *args):
"""
Add a comment to hash table before saving to disk. You can add as many
comment lines as you like. These comment lines are discarded when loading
the file. If you use a null format, all comments are deleted.
"""
return lib.zhashx_comment(self._as_para... | [
"def",
"comment",
"(",
"self",
",",
"format",
",",
"*",
"args",
")",
":",
"return",
"lib",
".",
"zhashx_comment",
"(",
"self",
".",
"_as_parameter_",
",",
"format",
",",
"*",
"args",
")"
] | 48 | 18.285714 |
def get_root_path():
"""Get the root path for the application."""
root_path = __file__
return os.path.dirname(os.path.realpath(root_path)) | [
"def",
"get_root_path",
"(",
")",
":",
"root_path",
"=",
"__file__",
"return",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"root_path",
")",
")"
] | 36.75 | 12.75 |
def _request_sender(self, packet: dict):
"""
Sends a request to a server from a ServiceClient
auto dispatch method called from self.send()
"""
node_id = self._get_node_id_for_packet(packet)
client_protocol = self._client_protocols.get(node_id)
if node_id and clie... | [
"def",
"_request_sender",
"(",
"self",
",",
"packet",
":",
"dict",
")",
":",
"node_id",
"=",
"self",
".",
"_get_node_id_for_packet",
"(",
"packet",
")",
"client_protocol",
"=",
"self",
".",
"_client_protocols",
".",
"get",
"(",
"node_id",
")",
"if",
"node_id... | 41.95 | 15.55 |
def equal(x, y):
"""
Return True if x == y and False otherwise.
This function returns False whenever x and/or y is a NaN.
"""
x = BigFloat._implicit_convert(x)
y = BigFloat._implicit_convert(y)
return mpfr.mpfr_equal_p(x, y) | [
"def",
"equal",
"(",
"x",
",",
"y",
")",
":",
"x",
"=",
"BigFloat",
".",
"_implicit_convert",
"(",
"x",
")",
"y",
"=",
"BigFloat",
".",
"_implicit_convert",
"(",
"y",
")",
"return",
"mpfr",
".",
"mpfr_equal_p",
"(",
"x",
",",
"y",
")"
] | 24.5 | 14.3 |
def step_group(k):
"""Do a single iteration over cbpdn and ccmod steps that can be
performed independently for each slice `k` of the input data set.
"""
cbpdn_xstep(k)
if mp_xrlx != 1.0:
cbpdn_relax(k)
cbpdn_ystep(k)
cbpdn_ustep(k)
ccmod_setcoef(k)
ccmod_xstep(k)
if mp_d... | [
"def",
"step_group",
"(",
"k",
")",
":",
"cbpdn_xstep",
"(",
"k",
")",
"if",
"mp_xrlx",
"!=",
"1.0",
":",
"cbpdn_relax",
"(",
"k",
")",
"cbpdn_ystep",
"(",
"k",
")",
"cbpdn_ustep",
"(",
"k",
")",
"ccmod_setcoef",
"(",
"k",
")",
"ccmod_xstep",
"(",
"k... | 24.357143 | 19.357143 |
def set(self, values):
""" set new values (values have to be iterable)
"""
if not hasattr(values, '__iter__') or isinstance(values, string_types):
raise SchemaError("Wrong value '%s' for field '%s'" % (values, self._ftype))
# check data are valid before deleting the data
... | [
"def",
"set",
"(",
"self",
",",
"values",
")",
":",
"if",
"not",
"hasattr",
"(",
"values",
",",
"'__iter__'",
")",
"or",
"isinstance",
"(",
"values",
",",
"string_types",
")",
":",
"raise",
"SchemaError",
"(",
"\"Wrong value '%s' for field '%s'\"",
"%",
"(",... | 45.181818 | 17.909091 |
def list(self, entityid=None):
"""
Return the entity with the given entity ID in short form. If no entity
ID is given, all records are listed.
It returns a dictionary of the form:
{eid : {'id' :
'isActive' :
'name' :
'revisionNr' :
'state' :
'type' :
}}
"""
params = {}
if ent... | [
"def",
"list",
"(",
"self",
",",
"entityid",
"=",
"None",
")",
":",
"params",
"=",
"{",
"}",
"if",
"entityid",
":",
"params",
"[",
"'name'",
"]",
"=",
"entityid",
"data",
"=",
"self",
".",
"_http_req",
"(",
"'connections'",
",",
"params",
"=",
"param... | 26.76 | 19 |
def __init_from_np2d(self, mat, params_str, ref_dataset):
"""Initialize data from a 2-D numpy matrix."""
if len(mat.shape) != 2:
raise ValueError('Input numpy.ndarray must be 2 dimensional')
self.handle = ctypes.c_void_p()
if mat.dtype == np.float32 or mat.dtype == np.float6... | [
"def",
"__init_from_np2d",
"(",
"self",
",",
"mat",
",",
"params_str",
",",
"ref_dataset",
")",
":",
"if",
"len",
"(",
"mat",
".",
"shape",
")",
"!=",
"2",
":",
"raise",
"ValueError",
"(",
"'Input numpy.ndarray must be 2 dimensional'",
")",
"self",
".",
"han... | 40.913043 | 16.478261 |
def _get_all_relationships(self):
"""Return all relationships seen in GO Dag subset."""
relationships_all = set()
for goterm in self.go2obj.values():
if goterm.relationship:
relationships_all.update(goterm.relationship)
if goterm.relationship_rev:
... | [
"def",
"_get_all_relationships",
"(",
"self",
")",
":",
"relationships_all",
"=",
"set",
"(",
")",
"for",
"goterm",
"in",
"self",
".",
"go2obj",
".",
"values",
"(",
")",
":",
"if",
"goterm",
".",
"relationship",
":",
"relationships_all",
".",
"update",
"("... | 44.666667 | 8.555556 |
def endless_permutations(N, random_state=None):
"""
Generate an endless sequence of random integers from permutations of the
set [0, ..., N).
If we call this N times, we will sweep through the entire set without
replacement, on the (N+1)th call a new permutation will be created, etc.
Parameter... | [
"def",
"endless_permutations",
"(",
"N",
",",
"random_state",
"=",
"None",
")",
":",
"generator",
"=",
"check_random_state",
"(",
"random_state",
")",
"while",
"True",
":",
"batch_inds",
"=",
"generator",
".",
"permutation",
"(",
"N",
")",
"for",
"b",
"in",
... | 26.64 | 21.6 |
def delete(self, id, **kwargs):
"""Delete an object on the server.
Args:
id: ID of the object to delete
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabDeleteErro... | [
"def",
"delete",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"id",
"is",
"None",
":",
"path",
"=",
"self",
".",
"path",
"else",
":",
"if",
"not",
"isinstance",
"(",
"id",
",",
"int",
")",
":",
"id",
"=",
"id",
".",
"repla... | 33.388889 | 17 |
def delete_all_thumbnails(path, recursive=True):
"""
Delete all files within a path which match the thumbnails pattern.
By default, matching files from all sub-directories are also removed. To
only remove from the path directory, set recursive=False.
"""
total = 0
for thumbs in all_thumbnai... | [
"def",
"delete_all_thumbnails",
"(",
"path",
",",
"recursive",
"=",
"True",
")",
":",
"total",
"=",
"0",
"for",
"thumbs",
"in",
"all_thumbnails",
"(",
"path",
",",
"recursive",
"=",
"recursive",
")",
".",
"values",
"(",
")",
":",
"total",
"+=",
"_delete_... | 37.909091 | 20.454545 |
def network_interface_get(name, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Get details about a specific network interface.
:param name: The name of the network interface to query.
:param resource_group: The resource group name assigned to the
network interface.
CLI Exa... | [
"def",
"network_interface_get",
"(",
"name",
",",
"resource_group",
",",
"*",
"*",
"kwargs",
")",
":",
"netconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'network'",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"nic",
"=",
"netconn",
".",
... | 27.533333 | 24.933333 |
def trim_srna_sample(data):
"""
Remove 3' adapter for smallRNA-seq
Uses cutadapt but with different parameters than for other pipelines.
"""
data = umi_transform(data)
in_file = data["files"][0]
names = data["rgnames"]['sample']
work_dir = os.path.join(dd.get_work_dir(data), "trimmed")
... | [
"def",
"trim_srna_sample",
"(",
"data",
")",
":",
"data",
"=",
"umi_transform",
"(",
"data",
")",
"in_file",
"=",
"data",
"[",
"\"files\"",
"]",
"[",
"0",
"]",
"names",
"=",
"data",
"[",
"\"rgnames\"",
"]",
"[",
"'sample'",
"]",
"work_dir",
"=",
"os",
... | 50.710526 | 20.552632 |
def get_warning_choice(self, message, short_message,
style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_WARNING):
"""Launches proceeding dialog and returns True if ok to proceed"""
dlg = GMD.GenericMessageDialog(self.main_window, message,
short_m... | [
"def",
"get_warning_choice",
"(",
"self",
",",
"message",
",",
"short_message",
",",
"style",
"=",
"wx",
".",
"YES_NO",
"|",
"wx",
".",
"NO_DEFAULT",
"|",
"wx",
".",
"ICON_WARNING",
")",
":",
"dlg",
"=",
"GMD",
".",
"GenericMessageDialog",
"(",
"self",
"... | 34.666667 | 24 |
def is_time_included(self, time):
"""Check if time is included in analysis period.
Return True if time is inside this analysis period,
otherwise return False
Args:
time: A DateTime to be tested
Returns:
A boolean. True if time is included in analysis pe... | [
"def",
"is_time_included",
"(",
"self",
",",
"time",
")",
":",
"if",
"self",
".",
"_timestamps_data",
"is",
"None",
":",
"self",
".",
"_calculate_timestamps",
"(",
")",
"# time filtering in Ladybug Tools is slightly different than \"normal\"",
"# filtering since start hour ... | 37.684211 | 18.368421 |
def request(self, endpoint):
"""Perform a request for the APIRequest instance 'endpoint'.
Parameters
----------
endpoint : APIRequest
The endpoint parameter contains an instance of an APIRequest
containing the endpoint, method and optionally other parameters
... | [
"def",
"request",
"(",
"self",
",",
"endpoint",
")",
":",
"method",
"=",
"endpoint",
".",
"method",
"method",
"=",
"method",
".",
"lower",
"(",
")",
"params",
"=",
"None",
"try",
":",
"params",
"=",
"getattr",
"(",
"endpoint",
",",
"\"params\"",
")",
... | 33.68254 | 18.555556 |
def convert_tanh(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert tanh layer.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with k... | [
"def",
"convert_tanh",
"(",
"params",
",",
"w_name",
",",
"scope_name",
",",
"inputs",
",",
"layers",
",",
"weights",
",",
"names",
")",
":",
"print",
"(",
"'Converting tanh ...'",
")",
"if",
"names",
"==",
"'short'",
":",
"tf_name",
"=",
"'TANH'",
"+",
... | 30 | 14.916667 |
def getStats(self):
"""
Returns the GA4GH protocol representation of this read group set's
ReadStats.
"""
stats = protocol.ReadStats()
stats.aligned_read_count = self._numAlignedReads
stats.unaligned_read_count = self._numUnalignedReads
return stats | [
"def",
"getStats",
"(",
"self",
")",
":",
"stats",
"=",
"protocol",
".",
"ReadStats",
"(",
")",
"stats",
".",
"aligned_read_count",
"=",
"self",
".",
"_numAlignedReads",
"stats",
".",
"unaligned_read_count",
"=",
"self",
".",
"_numUnalignedReads",
"return",
"s... | 33.888889 | 15.222222 |
def register_get(self, regex, callback):
"""
Register a regex for processing HTTP GET
requests. If the callback is None, any
existing registration is removed.
"""
if callback is None: # pragma: no cover
... | [
"def",
"register_get",
"(",
"self",
",",
"regex",
",",
"callback",
")",
":",
"if",
"callback",
"is",
"None",
":",
"# pragma: no cover",
"if",
"regex",
"in",
"self",
".",
"get_registrations",
":",
"del",
"self",
".",
"get_registrations",
"[",
"regex",
"]",
... | 44.545455 | 15.090909 |
def send_result_email(self, sender=None):
"""Sends an email to admins indicating this Pipeline has completed.
For developer convenience. Automatically called from finalized for root
Pipelines that do not override the default action.
Args:
sender: (optional) Override the sender's email address.
... | [
"def",
"send_result_email",
"(",
"self",
",",
"sender",
"=",
"None",
")",
":",
"status",
"=",
"'successful'",
"if",
"self",
".",
"was_aborted",
":",
"status",
"=",
"'aborted'",
"app_id",
"=",
"os",
".",
"environ",
"[",
"'APPLICATION_ID'",
"]",
"shard_index",... | 27.491525 | 20.898305 |
def tokenize(self):
"""Tokenizes all multiword names in the list of Units.
Modifies:
- (indirectly) self.unit_list, by combining words into compound words.
This is done because many names may be composed of multiple words, e.g.,
'grizzly bear'. In order to count the number ... | [
"def",
"tokenize",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"quiet",
":",
"print",
"print",
"\"Finding compound words...\"",
"# lists of animal names containing 2-5 separate words",
"compound_word_dict",
"=",
"{",
"}",
"for",
"compound_length",
"in",
"range",
... | 50.904762 | 26.5 |
def update_allocated_node_name(self, base_name):
"""
Updates a node name or generate a new if no node
name is available.
:param base_name: new node base name
"""
if base_name is None:
return None
base_name = re.sub(r"[ ]", "", base_name)
if b... | [
"def",
"update_allocated_node_name",
"(",
"self",
",",
"base_name",
")",
":",
"if",
"base_name",
"is",
"None",
":",
"return",
"None",
"base_name",
"=",
"re",
".",
"sub",
"(",
"r\"[ ]\"",
",",
"\"\"",
",",
"base_name",
")",
"if",
"base_name",
"in",
"self",
... | 47.567568 | 22 |
async def get_constants(self):
'''Get clash royale constants.'''
url = self.BASE + '/constants'
data = await self.request(url)
return Constants(self, data) | [
"async",
"def",
"get_constants",
"(",
"self",
")",
":",
"url",
"=",
"self",
".",
"BASE",
"+",
"'/constants'",
"data",
"=",
"await",
"self",
".",
"request",
"(",
"url",
")",
"return",
"Constants",
"(",
"self",
",",
"data",
")"
] | 26.142857 | 14.142857 |
def _parse_license_name(long_name):
''' Check if the license name on the PyPI licenses list. Prepends 'OSI
Approved :: ' if required. If the license is 'Other/Proprietary License' or
unknow, asummes that is a private license.
'''
licenses_path = utils.get_data_dir() / 'license_list.txt'
with lic... | [
"def",
"_parse_license_name",
"(",
"long_name",
")",
":",
"licenses_path",
"=",
"utils",
".",
"get_data_dir",
"(",
")",
"/",
"'license_list.txt'",
"with",
"licenses_path",
".",
"open",
"(",
"'rt'",
")",
"as",
"f",
":",
"licenses",
"=",
"[",
"line",
".",
"s... | 37.157895 | 23.052632 |
def dynacRepresentation(self):
"""
Return the Dynac representation of this accelerating gap instance.
"""
details = [
self.gapID.val,
self.energy.val,
self.beta.val,
self.L.val,
self.TTF.val,
self.TTFprime.val,
... | [
"def",
"dynacRepresentation",
"(",
"self",
")",
":",
"details",
"=",
"[",
"self",
".",
"gapID",
".",
"val",
",",
"self",
".",
"energy",
".",
"val",
",",
"self",
".",
"beta",
".",
"val",
",",
"self",
".",
"L",
".",
"val",
",",
"self",
".",
"TTF",
... | 27.434783 | 13 |
def tap(self, on_element):
"""
Taps on a given element.
:Args:
- on_element: The element to tap.
"""
self._actions.append(lambda: self._driver.execute(
Command.SINGLE_TAP, {'element': on_element.id}))
return self | [
"def",
"tap",
"(",
"self",
",",
"on_element",
")",
":",
"self",
".",
"_actions",
".",
"append",
"(",
"lambda",
":",
"self",
".",
"_driver",
".",
"execute",
"(",
"Command",
".",
"SINGLE_TAP",
",",
"{",
"'element'",
":",
"on_element",
".",
"id",
"}",
"... | 27.3 | 14.9 |
def _get_preprocessed(self, data):
"""
Returns:
(DeveloperPackage, new_data) 2-tuple IFF the preprocess function
changed the package; otherwise None.
"""
from rez.serialise import process_python_objects
from rez.utils.data_utils import get_dict_diff_str
... | [
"def",
"_get_preprocessed",
"(",
"self",
",",
"data",
")",
":",
"from",
"rez",
".",
"serialise",
"import",
"process_python_objects",
"from",
"rez",
".",
"utils",
".",
"data_utils",
"import",
"get_dict_diff_str",
"from",
"copy",
"import",
"deepcopy",
"with",
"add... | 36.696203 | 22.164557 |
def apply_config(self, applicator):
"""
Replace any config tokens in the file's path with values from the config.
"""
if type(self._fpath) == str:
self._fpath = applicator.apply(self._fpath) | [
"def",
"apply_config",
"(",
"self",
",",
"applicator",
")",
":",
"if",
"type",
"(",
"self",
".",
"_fpath",
")",
"==",
"str",
":",
"self",
".",
"_fpath",
"=",
"applicator",
".",
"apply",
"(",
"self",
".",
"_fpath",
")"
] | 38.166667 | 10.833333 |
def user_sentiments_most_frequent(
self,
username = None,
single_most_frequent = True
):
"""
This function returns the most frequent calculated sentiments expressed
in tweets of a specified user. By default, the single most frequent
sentiment i... | [
"def",
"user_sentiments_most_frequent",
"(",
"self",
",",
"username",
"=",
"None",
",",
"single_most_frequent",
"=",
"True",
")",
":",
"try",
":",
"sentiment_frequencies",
"=",
"collections",
".",
"Counter",
"(",
"self",
".",
"user_sentiments",
"(",
"username",
... | 37.409091 | 18.227273 |
def event(self, utype, **kw):
'''
Make a meta-event with a utype of @type. **@kw works the same as for
pygame.event.Event().
'''
d = {'utype': utype}
d.update(kw)
pygame.event.post(pygame.event.Event(METAEVENT, d)) | [
"def",
"event",
"(",
"self",
",",
"utype",
",",
"*",
"*",
"kw",
")",
":",
"d",
"=",
"{",
"'utype'",
":",
"utype",
"}",
"d",
".",
"update",
"(",
"kw",
")",
"pygame",
".",
"event",
".",
"post",
"(",
"pygame",
".",
"event",
".",
"Event",
"(",
"M... | 33 | 21 |
def _extract_sections(data_block):
'''Make a list of sections from an SWC-style data wrapper block'''
structure_block = data_block[:, COLS.TYPE:COLS.COL_COUNT].astype(np.int)
# SWC ID -> structure_block position
id_map = {-1: -1}
for i, row in enumerate(structure_block):
id_map[row[ID]] = i... | [
"def",
"_extract_sections",
"(",
"data_block",
")",
":",
"structure_block",
"=",
"data_block",
"[",
":",
",",
"COLS",
".",
"TYPE",
":",
"COLS",
".",
"COL_COUNT",
"]",
".",
"astype",
"(",
"np",
".",
"int",
")",
"# SWC ID -> structure_block position",
"id_map",
... | 33.26087 | 19.521739 |
def angle_between(v1, v2):
"""Returns the angle in radians between vectors 'v1' and 'v2'.
>>> angle_between((1, 0, 0), (0, 1, 0))
1.5707963267948966
>>> angle_between((1, 0, 0), (1, 0, 0))
0.0
>>> angle_between((1, 0, 0), (-1, 0, 0))
3.141592653589793
"""
v1_u = unit_vector(v1)
... | [
"def",
"angle_between",
"(",
"v1",
",",
"v2",
")",
":",
"v1_u",
"=",
"unit_vector",
"(",
"v1",
")",
"v2_u",
"=",
"unit_vector",
"(",
"v2",
")",
"# Don't use `np.dot`, does not work with all shapes",
"angle",
"=",
"np",
".",
"arccos",
"(",
"np",
".",
"inner",... | 27.8125 | 15.25 |
def _coerce_scalar_to_index(self, item):
"""
We need to coerce a scalar to a compat for our index type.
Parameters
----------
item : scalar item to coerce
"""
dtype = self.dtype
if self._is_numeric_dtype and isna(item):
# We can't coerce to t... | [
"def",
"_coerce_scalar_to_index",
"(",
"self",
",",
"item",
")",
":",
"dtype",
"=",
"self",
".",
"dtype",
"if",
"self",
".",
"_is_numeric_dtype",
"and",
"isna",
"(",
"item",
")",
":",
"# We can't coerce to the numeric dtype of \"self\" (unless",
"# it's float) if ther... | 31.4375 | 19.8125 |
def color(number):
"""
Returns a function that colors a string with a number from 0 to 255.
"""
if supports_256():
template = "\033[38;5;{number}m{text}\033[0m"
else:
template = "\033[{number}m{text}\033[0m"
def _color(text):
if not all([sys.stdout.isatty(), sys.stderr.is... | [
"def",
"color",
"(",
"number",
")",
":",
"if",
"supports_256",
"(",
")",
":",
"template",
"=",
"\"\\033[38;5;{number}m{text}\\033[0m\"",
"else",
":",
"template",
"=",
"\"\\033[{number}m{text}\\033[0m\"",
"def",
"_color",
"(",
"text",
")",
":",
"if",
"not",
"all"... | 30.928571 | 18.071429 |
def _forward_pass(self, images):
""" Forward pass a list of images through the CNN """
# form image array
num_images = len(images)
if num_images == 0:
return None
for image in images:
if not isinstance(image, Image):
new_images = []
... | [
"def",
"_forward_pass",
"(",
"self",
",",
"images",
")",
":",
"# form image array",
"num_images",
"=",
"len",
"(",
"images",
")",
"if",
"num_images",
"==",
"0",
":",
"return",
"None",
"for",
"image",
"in",
"images",
":",
"if",
"not",
"isinstance",
"(",
"... | 41.277778 | 17.805556 |
def from_file(self, ifile, codec='ascii'):
"""Read textgrid from stream.
:param file ifile: Stream to read from.
:param str codec: Text encoding for the input. Note that this will be
ignored for binary TextGrids.
"""
if ifile.read(12) == b'ooBinaryFile':
... | [
"def",
"from_file",
"(",
"self",
",",
"ifile",
",",
"codec",
"=",
"'ascii'",
")",
":",
"if",
"ifile",
".",
"read",
"(",
"12",
")",
"==",
"b'ooBinaryFile'",
":",
"def",
"bin2str",
"(",
"ifile",
")",
":",
"textlen",
"=",
"struct",
".",
"unpack",
"(",
... | 49.695122 | 15.719512 |
def args_length(min_len, max_len, *args):
"""
检查参数长度
"""
not_null(*args)
if not all(map(lambda v: min_len <= len(v) <= max_len, args)):
raise ValueError("Argument length must be between {0} and {1}!".format(min_len, max_len)) | [
"def",
"args_length",
"(",
"min_len",
",",
"max_len",
",",
"*",
"args",
")",
":",
"not_null",
"(",
"*",
"args",
")",
"if",
"not",
"all",
"(",
"map",
"(",
"lambda",
"v",
":",
"min_len",
"<=",
"len",
"(",
"v",
")",
"<=",
"max_len",
",",
"args",
")"... | 32.25 | 21.25 |
def advance(self):
"""Advance the base iterator, publish to constituent iterators."""
elem = next(self._iterable)
for deque in self._deques:
deque.append(elem) | [
"def",
"advance",
"(",
"self",
")",
":",
"elem",
"=",
"next",
"(",
"self",
".",
"_iterable",
")",
"for",
"deque",
"in",
"self",
".",
"_deques",
":",
"deque",
".",
"append",
"(",
"elem",
")"
] | 38.2 | 8.6 |
def plot_all_stops(g, ax=None, scalebar=False):
"""
Parameters
----------
g: A gtfspy.gtfs.GTFS object
ax: matplotlib.Axes object, optional
If None, a new figure and an axis is created, otherwise results are plotted on the axis.
scalebar: bool, optional
Whether to include a scale... | [
"def",
"plot_all_stops",
"(",
"g",
",",
"ax",
"=",
"None",
",",
"scalebar",
"=",
"False",
")",
":",
"assert",
"(",
"isinstance",
"(",
"g",
",",
"GTFS",
")",
")",
"lon_min",
",",
"lon_max",
",",
"lat_min",
",",
"lat_max",
"=",
"get_spatial_bounds",
"(",... | 28.212121 | 18.515152 |
def _i2c_start(self):
"""Send I2C start signal. Must be called within a transaction start/end.
"""
# Set SCL high and SDA low, repeat 4 times to stay in this state for a
# short period of time.
self._ft232h.output_pins({0: GPIO.HIGH, 1: GPIO.LOW}, write=False)
self._comma... | [
"def",
"_i2c_start",
"(",
"self",
")",
":",
"# Set SCL high and SDA low, repeat 4 times to stay in this state for a",
"# short period of time.",
"self",
".",
"_ft232h",
".",
"output_pins",
"(",
"{",
"0",
":",
"GPIO",
".",
"HIGH",
",",
"1",
":",
"GPIO",
".",
"LOW",
... | 57.9 | 22.4 |
async def authenticate_token_service_url(auth_header: str, credentials: CredentialProvider, service_url: str, channel_id: str) -> ClaimsIdentity:
""" Validate the incoming Auth Header
Validate the incoming Auth Header as a token sent from the Bot Framework Service.
A token issued by the Bot Fra... | [
"async",
"def",
"authenticate_token_service_url",
"(",
"auth_header",
":",
"str",
",",
"credentials",
":",
"CredentialProvider",
",",
"service_url",
":",
"str",
",",
"channel_id",
":",
"str",
")",
"->",
"ClaimsIdentity",
":",
"identity",
"=",
"await",
"asyncio",
... | 47.72 | 28.76 |
def array_ratio_std(values_n, sigmas_n, values_d, sigmas_d):
r"""Gives error on the ratio of 2 floats or 2 1-dimensional arrays given
their values and uncertainties. This assumes the covariance = 0, and that
the input uncertainties are small compared to the corresponding input
values. _n and _d denote t... | [
"def",
"array_ratio_std",
"(",
"values_n",
",",
"sigmas_n",
",",
"values_d",
",",
"sigmas_d",
")",
":",
"std",
"=",
"np",
".",
"sqrt",
"(",
"(",
"sigmas_n",
"/",
"values_n",
")",
"**",
"2",
"+",
"(",
"sigmas_d",
"/",
"values_d",
")",
"**",
"2",
")",
... | 36.44 | 19.28 |
def fw_rule_update(self, data, fw_name=None):
"""Top level rule update routine. """
LOG.debug("FW Update Debug")
self._fw_rule_update(fw_name, data) | [
"def",
"fw_rule_update",
"(",
"self",
",",
"data",
",",
"fw_name",
"=",
"None",
")",
":",
"LOG",
".",
"debug",
"(",
"\"FW Update Debug\"",
")",
"self",
".",
"_fw_rule_update",
"(",
"fw_name",
",",
"data",
")"
] | 42.25 | 3 |
def get(cls, session, team_id):
"""Return a specific team.
Args:
session (requests.sessions.Session): Authenticated session.
team_id (int): The ID of the team to get.
Returns:
helpscout.models.Person: A person singleton representing the team,
... | [
"def",
"get",
"(",
"cls",
",",
"session",
",",
"team_id",
")",
":",
"return",
"cls",
"(",
"'/teams/%d.json'",
"%",
"team_id",
",",
"singleton",
"=",
"True",
",",
"session",
"=",
"session",
",",
")"
] | 29.8125 | 19.25 |
def update_suggestions(self, text=""):
"""
* from previous activity | set time | minutes ago | start now
* to ongoing | set time
* activity
* [@category]
* #tags, #tags, #tags
* we will leave description for later
all our mag... | [
"def",
"update_suggestions",
"(",
"self",
",",
"text",
"=",
"\"\"",
")",
":",
"res",
"=",
"[",
"]",
"fact",
"=",
"Fact",
"(",
"text",
")",
"now",
"=",
"dt",
".",
"datetime",
".",
"now",
"(",
")",
"# figure out what we are looking for",
"# time -> activity[... | 35.142857 | 21.696429 |
def _pdf(self, xloc, left, right, cache):
"""
Probability density function.
Example:
>>> print(chaospy.Uniform().pdf([-0.5, 0.5, 1.5, 2.5]))
[0. 1. 0. 0.]
>>> print(Mul(chaospy.Uniform(), 2).pdf([-0.5, 0.5, 1.5, 2.5]))
[0. 0.5 0.5 0. ]
... | [
"def",
"_pdf",
"(",
"self",
",",
"xloc",
",",
"left",
",",
"right",
",",
"cache",
")",
":",
"left",
"=",
"evaluation",
".",
"get_forward_cache",
"(",
"left",
",",
"cache",
")",
"right",
"=",
"evaluation",
".",
"get_forward_cache",
"(",
"right",
",",
"c... | 37.492063 | 18.984127 |
def expanded_indexer(key, ndim):
"""Given a key for indexing an ndarray, return an equivalent key which is a
tuple with length equal to the number of dimensions.
The expansion is done by replacing all `Ellipsis` items with the right
number of full slices and then padding the key with full slices so tha... | [
"def",
"expanded_indexer",
"(",
"key",
",",
"ndim",
")",
":",
"if",
"not",
"isinstance",
"(",
"key",
",",
"tuple",
")",
":",
"# numpy treats non-tuple keys equivalent to tuples of length 1",
"key",
"=",
"(",
"key",
",",
")",
"new_key",
"=",
"[",
"]",
"# handli... | 39.714286 | 17.214286 |
def prepare_to_store(self, entity, value):
"""Prepare `value` for storage. Called by the Model for each
Property, value pair it contains before handing the data off
to an adapter.
Parameters:
entity(Model): The entity to which the value belongs.
value: The value bei... | [
"def",
"prepare_to_store",
"(",
"self",
",",
"entity",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
"and",
"not",
"self",
".",
"optional",
":",
"raise",
"RuntimeError",
"(",
"f\"Property {self.name_on_model} requires a value.\"",
")",
"return",
"value"
] | 34.473684 | 19.842105 |
def dumps(self, obj):
'''
Serialize and encrypt a python object
'''
return self.encrypt(self.PICKLE_PAD + self.serial.dumps(obj)) | [
"def",
"dumps",
"(",
"self",
",",
"obj",
")",
":",
"return",
"self",
".",
"encrypt",
"(",
"self",
".",
"PICKLE_PAD",
"+",
"self",
".",
"serial",
".",
"dumps",
"(",
"obj",
")",
")"
] | 31.4 | 22.2 |
def train(self, net_sizes, epochs, batchsize):
""" Initialize the base trainer """
self.trainer = ClassificationTrainer(self.data, self.targets, net_sizes)
self.trainer.learn(epochs, batchsize)
return self.trainer.evaluate(batchsize) | [
"def",
"train",
"(",
"self",
",",
"net_sizes",
",",
"epochs",
",",
"batchsize",
")",
":",
"self",
".",
"trainer",
"=",
"ClassificationTrainer",
"(",
"self",
".",
"data",
",",
"self",
".",
"targets",
",",
"net_sizes",
")",
"self",
".",
"trainer",
".",
"... | 52.2 | 11.6 |
def flip_one(self, tour):
""" Test flipping every single contig sequentially to see if score
improves.
"""
n_accepts = n_rejects = 0
any_tag_ACCEPT = False
for i, t in enumerate(tour):
if i == 0:
score, = self.evaluate_tour_Q(tour)
... | [
"def",
"flip_one",
"(",
"self",
",",
"tour",
")",
":",
"n_accepts",
"=",
"n_rejects",
"=",
"0",
"any_tag_ACCEPT",
"=",
"False",
"for",
"i",
",",
"t",
"in",
"enumerate",
"(",
"tour",
")",
":",
"if",
"i",
"==",
"0",
":",
"score",
",",
"=",
"self",
... | 38.576923 | 11 |
def window_handles(self):
"""
Returns the handles of all windows within the current session.
:Usage:
::
driver.window_handles
"""
if self.w3c:
return self.execute(Command.W3C_GET_WINDOW_HANDLES)['value']
else:
return s... | [
"def",
"window_handles",
"(",
"self",
")",
":",
"if",
"self",
".",
"w3c",
":",
"return",
"self",
".",
"execute",
"(",
"Command",
".",
"W3C_GET_WINDOW_HANDLES",
")",
"[",
"'value'",
"]",
"else",
":",
"return",
"self",
".",
"execute",
"(",
"Command",
".",
... | 27.384615 | 22 |
def get_replicas(self, service_id: str) -> str:
"""Get the replication level of a service.
Args:
service_id (str): docker swarm service id
Returns:
str, replication level of the service
"""
# Initialising empty list
replicas = []
# Rais... | [
"def",
"get_replicas",
"(",
"self",
",",
"service_id",
":",
"str",
")",
"->",
"str",
":",
"# Initialising empty list",
"replicas",
"=",
"[",
"]",
"# Raise an exception if we are not a manager",
"if",
"not",
"self",
".",
"_manager",
":",
"raise",
"RuntimeError",
"(... | 31.913043 | 19.608696 |
def FromTextFormat(cls, text):
"""Parse this object from a text representation."""
tmp = cls.protobuf() # pylint: disable=not-callable
text_format.Merge(text, tmp)
return cls.FromSerializedString(tmp.SerializeToString()) | [
"def",
"FromTextFormat",
"(",
"cls",
",",
"text",
")",
":",
"tmp",
"=",
"cls",
".",
"protobuf",
"(",
")",
"# pylint: disable=not-callable",
"text_format",
".",
"Merge",
"(",
"text",
",",
"tmp",
")",
"return",
"cls",
".",
"FromSerializedString",
"(",
"tmp",
... | 38.833333 | 15.666667 |
def dump_all_outputs(self, job, target, abspaths=None):
""" Specialized dumping strategy - copy the entire working directory, then discard
the input files that came along for the ride.
Not used if there are absolute paths
This is slow and wasteful if there are big input files
"... | [
"def",
"dump_all_outputs",
"(",
"self",
",",
"job",
",",
"target",
",",
"abspaths",
"=",
"None",
")",
":",
"import",
"os",
"import",
"shutil",
"from",
"pathlib",
"import",
"Path",
"root",
"=",
"Path",
"(",
"native_str",
"(",
"target",
")",
")",
"true_out... | 34.439024 | 15.634146 |
def setModel(self, model):
"Sets the StimulusModel for this editor"
self._model = model
self.ui.aofsSpnbx.setValue(model.samplerate()) | [
"def",
"setModel",
"(",
"self",
",",
"model",
")",
":",
"self",
".",
"_model",
"=",
"model",
"self",
".",
"ui",
".",
"aofsSpnbx",
".",
"setValue",
"(",
"model",
".",
"samplerate",
"(",
")",
")"
] | 38.75 | 12.25 |
def cmd_wp_changealt(self, args):
'''handle wp change target alt of multiple waypoints'''
if len(args) < 2:
print("usage: wp changealt WPNUM NEWALT <NUMWP>")
return
idx = int(args[0])
if idx < 1 or idx > self.wploader.count():
print("Invalid wp number ... | [
"def",
"cmd_wp_changealt",
"(",
"self",
",",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"<",
"2",
":",
"print",
"(",
"\"usage: wp changealt WPNUM NEWALT <NUMWP>\"",
")",
"return",
"idx",
"=",
"int",
"(",
"args",
"[",
"0",
"]",
")",
"if",
"idx",
"... | 40 | 18.066667 |
def render_image1(self, rgbobj, dst_x, dst_y):
"""Render the image represented by (rgbobj) at dst_x, dst_y
in the pixel space.
NOTE: this version uses a Figure.FigImage to render the image.
"""
self.logger.debug("redraw surface")
if self.figure is None:
retur... | [
"def",
"render_image1",
"(",
"self",
",",
"rgbobj",
",",
"dst_x",
",",
"dst_y",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"redraw surface\"",
")",
"if",
"self",
".",
"figure",
"is",
"None",
":",
"return",
"## left, bottom, width, height = self.ax_i... | 37.030303 | 19.333333 |
def __look_up_geom(self, geomType):
""" compares the geometry object's type verse the JSOn
specs for geometry types
Inputs:
geomType - string - geometry object's type
Returns:
string JSON geometry type or None if not an allowed type
"""
... | [
"def",
"__look_up_geom",
"(",
"self",
",",
"geomType",
")",
":",
"if",
"geomType",
".",
"lower",
"(",
")",
"==",
"\"point\"",
":",
"return",
"\"esriGeometryPoint\"",
"elif",
"geomType",
".",
"lower",
"(",
")",
"==",
"\"polyline\"",
":",
"return",
"\"esriGeom... | 35.789474 | 10.578947 |
def persist_time(run, session, timings):
"""
Persist the run results in the database.
Args:
run: The run we attach this timing results to.
session: The db transaction we belong to.
timings: The timing measurements we want to store.
"""
from benchbuild.utils import schema as ... | [
"def",
"persist_time",
"(",
"run",
",",
"session",
",",
"timings",
")",
":",
"from",
"benchbuild",
".",
"utils",
"import",
"schema",
"as",
"s",
"for",
"timing",
"in",
"timings",
":",
"session",
".",
"add",
"(",
"s",
".",
"Metric",
"(",
"name",
"=",
"... | 34.388889 | 18.611111 |
def has_length(value,
minimum = None,
maximum = None,
**kwargs):
"""Indicate whether ``value`` has a length greater than or equal to a
supplied ``minimum`` and/or less than or equal to ``maximum``.
.. note::
This function works on any ``value`` that suppo... | [
"def",
"has_length",
"(",
"value",
",",
"minimum",
"=",
"None",
",",
"maximum",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"minimum",
"is",
"None",
"and",
"maximum",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'minimum and maximum cannot bot... | 37.823529 | 22.137255 |
def load_by_pub_key(self, public_key):
"""
This method will load a SSHKey object from DigitalOcean
from a public_key. This method will avoid problems like
uploading the same public_key twice.
"""
data = self.get_data("account/keys/")
for jsoned in dat... | [
"def",
"load_by_pub_key",
"(",
"self",
",",
"public_key",
")",
":",
"data",
"=",
"self",
".",
"get_data",
"(",
"\"account/keys/\"",
")",
"for",
"jsoned",
"in",
"data",
"[",
"'ssh_keys'",
"]",
":",
"if",
"jsoned",
".",
"get",
"(",
"'public_key'",
",",
"\"... | 35.357143 | 12.642857 |
def center(self, coords):
""" center the map on a "map pixel"
"""
x, y = [round(i, 0) for i in coords]
self.view_rect.center = x, y
tw, th = self.data.tile_size
left, ox = divmod(x, tw)
top, oy = divmod(y, th)
vec = int(ox / 2), int(oy)
iso = v... | [
"def",
"center",
"(",
"self",
",",
"coords",
")",
":",
"x",
",",
"y",
"=",
"[",
"round",
"(",
"i",
",",
"0",
")",
"for",
"i",
"in",
"coords",
"]",
"self",
".",
"view_rect",
".",
"center",
"=",
"x",
",",
"y",
"tw",
",",
"th",
"=",
"self",
".... | 32.833333 | 17.261905 |
def linear_exprs(A, x, b=None, rref=False, Matrix=None):
""" Returns Ax - b
Parameters
----------
A : matrix_like of numbers
Of shape (len(b), len(x)).
x : iterable of symbols
b : array_like of numbers (default: None)
When ``None``, assume zeros of length ``len(x)``.
Matrix ... | [
"def",
"linear_exprs",
"(",
"A",
",",
"x",
",",
"b",
"=",
"None",
",",
"rref",
"=",
"False",
",",
"Matrix",
"=",
"None",
")",
":",
"if",
"b",
"is",
"None",
":",
"b",
"=",
"[",
"0",
"]",
"*",
"len",
"(",
"x",
")",
"if",
"rref",
":",
"rA",
... | 31 | 20 |
def _write_transport(self, string):
"""Convenience function to write to the transport"""
if isinstance(string, str): # we need to convert to bytes
self.transport.write(string.encode('utf-8'))
else:
self.transport.write(string) | [
"def",
"_write_transport",
"(",
"self",
",",
"string",
")",
":",
"if",
"isinstance",
"(",
"string",
",",
"str",
")",
":",
"# we need to convert to bytes",
"self",
".",
"transport",
".",
"write",
"(",
"string",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"else... | 45 | 12.333333 |
def remove_api_keys_from_group(self, group_id, body, **kwargs): # noqa: E501
"""Remove API keys from a group. # noqa: E501
An endpoint for removing API keys from groups. **Example usage:** `curl -X DELETE https://api.us-east-1.mbedcloud.com/v3/policy-groups/{group-id}/api-keys -d '[0162056a9a1586f3... | [
"def",
"remove_api_keys_from_group",
"(",
"self",
",",
"group_id",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'asynchronous'",
")",
":",
"retu... | 63.590909 | 37.818182 |
def multiply(lhs, rhs):
"""Returns element-wise product of the input arrays with broadcasting.
Equivalent to ``lhs * rhs`` and ``mx.nd.broadcast_mul(lhs, rhs)``
when shapes of lhs and rhs do not match. If lhs.shape == rhs.shape,
this is equivalent to ``mx.nd.elemwise_mul(lhs, rhs)``
..... | [
"def",
"multiply",
"(",
"lhs",
",",
"rhs",
")",
":",
"# pylint: disable= no-member, protected-access",
"if",
"isinstance",
"(",
"lhs",
",",
"NDArray",
")",
"and",
"isinstance",
"(",
"rhs",
",",
"NDArray",
")",
"and",
"lhs",
".",
"shape",
"==",
"rhs",
".",
... | 30.493827 | 17.395062 |
def _streaming_request_iterable(self, config, requests):
"""A generator that yields the config followed by the requests.
Args:
config (~.speech_v1.types.StreamingRecognitionConfig): The
configuration to use for the stream.
requests (Iterable[~.speech_v1.types.Str... | [
"def",
"_streaming_request_iterable",
"(",
"self",
",",
"config",
",",
"requests",
")",
":",
"yield",
"self",
".",
"types",
".",
"StreamingRecognizeRequest",
"(",
"streaming_config",
"=",
"config",
")",
"for",
"request",
"in",
"requests",
":",
"yield",
"request"... | 42.176471 | 20.882353 |
def consumer(self, name):
"""
Create a new consumer for the :py:class:`ConsumerGroup`.
:param name: name of consumer
:returns: a :py:class:`ConsumerGroup` using the given consumer name.
"""
return type(self)(self.database, self.name, self.keys, name) | [
"def",
"consumer",
"(",
"self",
",",
"name",
")",
":",
"return",
"type",
"(",
"self",
")",
"(",
"self",
".",
"database",
",",
"self",
".",
"name",
",",
"self",
".",
"keys",
",",
"name",
")"
] | 36.5 | 18.25 |
def _get_default_cache_dir(self):
"""
Returns default cache directory (data directory)
:raises: CacheFileError when default cached file does not is exist
:return: path to default cache directory
:rtype: str
"""
return os.path.join(os.path.dirname(__file__), self... | [
"def",
"_get_default_cache_dir",
"(",
"self",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"self",
".",
"_DATA_DIR",
")"
] | 32.2 | 19.6 |
def _unescape_match(self, match):
"""Given an re.Match, unescape the escape code it represents."""
char = match.group(1)
if char in self.ESCAPE_LOOKUP:
return self.ESCAPE_LOOKUP[char]
elif not char:
raise KatcpSyntaxError("Escape slash at end of argument.")
... | [
"def",
"_unescape_match",
"(",
"self",
",",
"match",
")",
":",
"char",
"=",
"match",
".",
"group",
"(",
"1",
")",
"if",
"char",
"in",
"self",
".",
"ESCAPE_LOOKUP",
":",
"return",
"self",
".",
"ESCAPE_LOOKUP",
"[",
"char",
"]",
"elif",
"not",
"char",
... | 44 | 14.888889 |
def list(self, device=values.unset, sim=values.unset, status=values.unset,
direction=values.unset, limit=None, page_size=None):
"""
Lists CommandInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before... | [
"def",
"list",
"(",
"self",
",",
"device",
"=",
"values",
".",
"unset",
",",
"sim",
"=",
"values",
".",
"unset",
",",
"status",
"=",
"values",
".",
"unset",
",",
"direction",
"=",
"values",
".",
"unset",
",",
"limit",
"=",
"None",
",",
"page_size",
... | 47.206897 | 23.758621 |
def rvs(self, size=1, param=None):
"""Gives a set of random values drawn from this distribution.
Parameters
----------
size : {1, int}
The number of values to generate; default is 1.
param : {None, string}
If provided, will just return values for the give... | [
"def",
"rvs",
"(",
"self",
",",
"size",
"=",
"1",
",",
"param",
"=",
"None",
")",
":",
"if",
"param",
"is",
"not",
"None",
":",
"dtype",
"=",
"[",
"(",
"param",
",",
"float",
")",
"]",
"else",
":",
"dtype",
"=",
"[",
"(",
"p",
",",
"float",
... | 37.633333 | 20.366667 |
def expect(qubits, meas):
"For the VQE simulation without sampling."
result = {}
i = np.arange(len(qubits))
meas = tuple(meas)
def to_mask(n):
return reduce(lambda acc, im: acc | (n & (1 << im[0])) << (im[1] - im[0]), enumerate(meas), 0)
def to_key(k):
return tuple(1 if k & (1 ... | [
"def",
"expect",
"(",
"qubits",
",",
"meas",
")",
":",
"result",
"=",
"{",
"}",
"i",
"=",
"np",
".",
"arange",
"(",
"len",
"(",
"qubits",
")",
")",
"meas",
"=",
"tuple",
"(",
"meas",
")",
"def",
"to_mask",
"(",
"n",
")",
":",
"return",
"reduce"... | 29.6 | 21.8 |
def get_go_server(settings=None):
"""Returns a `gocd.Server` configured by the `settings`
object.
Args:
settings: a `gocd_cli.settings.Settings` object.
Default: if falsey calls `get_settings`.
Returns:
gocd.Server: a configured gocd.Server instance
"""
if not settings:
... | [
"def",
"get_go_server",
"(",
"settings",
"=",
"None",
")",
":",
"if",
"not",
"settings",
":",
"settings",
"=",
"get_settings",
"(",
")",
"return",
"gocd",
".",
"Server",
"(",
"settings",
".",
"get",
"(",
"'server'",
")",
",",
"user",
"=",
"settings",
"... | 24.894737 | 18.157895 |
def create(self, **kwargs):
"""Create a new Application.
Args:
**kwargs: Arbitrary keyword arguments, including:
name (str): A name for the new Application.
Returns:
A round.Application object if successful.
"""
resource = self.resource.create(kwa... | [
"def",
"create",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"resource",
"=",
"self",
".",
"resource",
".",
"create",
"(",
"kwargs",
")",
"if",
"'admin_token'",
"in",
"kwargs",
":",
"resource",
".",
"context",
".",
"authorize",
"(",
"'Gem-Application... | 35.764706 | 17.470588 |
def make_spark_lines(table,filename,sc,**kwargs):
spark_output = True
lines_out_count = False
extrema = False
for key,value in kwargs.iteritems():
if key == 'lines_out_count':
lines_out_count = value
if key == 'extrema':
extrema = value
# removing datetime references from imported postgis database
# CUR... | [
"def",
"make_spark_lines",
"(",
"table",
",",
"filename",
",",
"sc",
",",
"*",
"*",
"kwargs",
")",
":",
"spark_output",
"=",
"True",
"lines_out_count",
"=",
"False",
"extrema",
"=",
"False",
"for",
"key",
",",
"value",
"in",
"kwargs",
".",
"iteritems",
"... | 26.175926 | 22.509259 |
def locate_cuda():
"""Locate the CUDA environment on the system
If a valid cuda installation is found this returns a dict with keys 'home', 'nvcc', 'include',
and 'lib64' and values giving the absolute path to each directory.
Starts by looking for the CUDAHOME env variable. If not found, everything is... | [
"def",
"locate_cuda",
"(",
")",
":",
"nvcc_bin",
"=",
"'nvcc'",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"\"win\"",
")",
":",
"nvcc_bin",
"=",
"'nvcc.exe'",
"# first check if the CUDAHOME env variable is in use",
"if",
"'CUDAHOME'",
"in",
"os",
".",
... | 38.314815 | 20.259259 |
def classify_fit(fqdn, result, *argl, **argd):
"""Analyzes the result of a classification algorithm's fitting. See also
:func:`fit` for explanation of arguments.
"""
if len(argl) > 2:
#Usually fit is called with fit(machine, Xtrain, ytrain).
yP = argl[2]
out = _generic_fit(fqdn, resu... | [
"def",
"classify_fit",
"(",
"fqdn",
",",
"result",
",",
"*",
"argl",
",",
"*",
"*",
"argd",
")",
":",
"if",
"len",
"(",
"argl",
")",
">",
"2",
":",
"#Usually fit is called with fit(machine, Xtrain, ytrain).",
"yP",
"=",
"argl",
"[",
"2",
"]",
"out",
"=",... | 40.777778 | 14.888889 |
def create_model(self, ModelName, PrimaryContainer, *args, **kwargs): # pylint: disable=unused-argument
"""Create a Local Model Object
Args:
ModelName (str): the Model Name
PrimaryContainer (dict): a SageMaker primary container definition
"""
LocalSagemakerClien... | [
"def",
"create_model",
"(",
"self",
",",
"ModelName",
",",
"PrimaryContainer",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=unused-argument",
"LocalSagemakerClient",
".",
"_models",
"[",
"ModelName",
"]",
"=",
"_LocalModel",
"(",
"Mode... | 47 | 27.625 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.