text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def rationalize_until(until=None):
"""
Rationalizes the `until` argument used by other functions. This function
accepts datetime and timedelta instances as well as integers representing
epoch values.
"""
if until is None:
until = "+inf"
elif isinstance(until, datetime):
until... | [
"def",
"rationalize_until",
"(",
"until",
"=",
"None",
")",
":",
"if",
"until",
"is",
"None",
":",
"until",
"=",
"\"+inf\"",
"elif",
"isinstance",
"(",
"until",
",",
"datetime",
")",
":",
"until",
"=",
"to_unix",
"(",
"until",
")",
"elif",
"isinstance",
... | 33.384615 | 14.615385 |
def get_main_app(argv=[]):
"""
Standard boilerplate Qt application code.
Do everything but app.exec_() -- so that we can test the application in one thread
"""
app = QApplication(argv)
app.setApplicationName(__appname__)
app.setWindowIcon(newIcon("app"))
# Tzutalin 201705+: Accept extra ... | [
"def",
"get_main_app",
"(",
"argv",
"=",
"[",
"]",
")",
":",
"app",
"=",
"QApplication",
"(",
"argv",
")",
"app",
".",
"setApplicationName",
"(",
"__appname__",
")",
"app",
".",
"setWindowIcon",
"(",
"newIcon",
"(",
"\"app\"",
")",
")",
"# Tzutalin 201705+... | 43.117647 | 16.058824 |
def c_to_p(self, var_c, pro_ac=None):
"""
Converts a c. SequenceVariant to a p. SequenceVariant on the specified protein accession
Author: Rudy Rico
:param SequenceVariant var_c: hgvsc tag
:param str pro_ac: protein accession
:rtype: hgvs.sequencevariant.SequenceVariant
... | [
"def",
"c_to_p",
"(",
"self",
",",
"var_c",
",",
"pro_ac",
"=",
"None",
")",
":",
"if",
"not",
"(",
"var_c",
".",
"type",
"==",
"\"c\"",
")",
":",
"raise",
"HGVSInvalidVariantError",
"(",
"\"Expected a cDNA (c.) variant; got \"",
"+",
"str",
"(",
"var_c",
... | 35.428571 | 21.714286 |
def convolve_image(image, kernel_image, crop=True):
"""
Convolve one image with another
ANTsR function: `convolveImage`
Arguments
---------
image : ANTsImage
image to convolve
kernel_image : ANTsImage
image acting as kernel
crop : boolean
whether to automatica... | [
"def",
"convolve_image",
"(",
"image",
",",
"kernel_image",
",",
"crop",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"image",
",",
"iio",
".",
"ANTsImage",
")",
":",
"raise",
"ValueError",
"(",
"'image must be ANTsImage type'",
")",
"if",
"not",
... | 32.732143 | 22.946429 |
def is_serializable_type(type_):
"""Return `True` if the given type's instances conform to the Serializable protocol.
:rtype: bool
"""
if not inspect.isclass(type_):
return Serializable.is_serializable(type_)
return issubclass(type_, Serializable) or hasattr(type_, '_asdict') | [
"def",
"is_serializable_type",
"(",
"type_",
")",
":",
"if",
"not",
"inspect",
".",
"isclass",
"(",
"type_",
")",
":",
"return",
"Serializable",
".",
"is_serializable",
"(",
"type_",
")",
"return",
"issubclass",
"(",
"type_",
",",
"Serializable",
")",
"or",
... | 37 | 14.625 |
def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_2_0):
"""
Read the data stream and decode the AttributeReference structure into
its parts.
Args:
input_buffer (stream): A data stream containing encoded object
data, supporting a read method.
... | [
"def",
"read",
"(",
"self",
",",
"input_buffer",
",",
"kmip_version",
"=",
"enums",
".",
"KMIPVersion",
".",
"KMIP_2_0",
")",
":",
"if",
"kmip_version",
"<",
"enums",
".",
"KMIPVersion",
".",
"KMIP_2_0",
":",
"raise",
"exceptions",
".",
"VersionNotSupported",
... | 37.590164 | 20.704918 |
def set_high_water_mark(socket, config):
""" Set a high water mark on the zmq socket. Do so in a way that is
cross-compatible with zeromq2 and zeromq3.
"""
if config['high_water_mark']:
if hasattr(zmq, 'HWM'):
# zeromq2
socket.setsockopt(zmq.HWM, config['high_water_mark... | [
"def",
"set_high_water_mark",
"(",
"socket",
",",
"config",
")",
":",
"if",
"config",
"[",
"'high_water_mark'",
"]",
":",
"if",
"hasattr",
"(",
"zmq",
",",
"'HWM'",
")",
":",
"# zeromq2",
"socket",
".",
"setsockopt",
"(",
"zmq",
".",
"HWM",
",",
"config"... | 37.307692 | 16 |
def diff_prof(step):
"""Diffusion.
Args:
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
Returns:
tuple of :class:`numpy.array`: the diffusion and the radial position
at which it is evaluated.
"""
rbot, rtop = misc.get_rbounds(step)
... | [
"def",
"diff_prof",
"(",
"step",
")",
":",
"rbot",
",",
"rtop",
"=",
"misc",
".",
"get_rbounds",
"(",
"step",
")",
"rad",
"=",
"step",
".",
"rprof",
"[",
"'r'",
"]",
".",
"values",
"+",
"rbot",
"tprof",
"=",
"step",
".",
"rprof",
"[",
"'Tmean'",
... | 33.8 | 15.9 |
def GetMemZippedMB(self):
'''Undocumented.'''
counter = c_uint()
ret = vmGuestLib.VMGuestLib_GetMemZippedMB(self.handle.value, byref(counter))
if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret)
return counter.value | [
"def",
"GetMemZippedMB",
"(",
"self",
")",
":",
"counter",
"=",
"c_uint",
"(",
")",
"ret",
"=",
"vmGuestLib",
".",
"VMGuestLib_GetMemZippedMB",
"(",
"self",
".",
"handle",
".",
"value",
",",
"byref",
"(",
"counter",
")",
")",
"if",
"ret",
"!=",
"VMGUESTL... | 44.166667 | 22.166667 |
def get_range_kwargs(self):
""" Convert row range object to dict which can be passed to
google.bigtable.v2.RowRange add method.
"""
range_kwargs = {}
if self.start_key is not None:
start_key_key = "start_key_open"
if self.start_inclusive:
s... | [
"def",
"get_range_kwargs",
"(",
"self",
")",
":",
"range_kwargs",
"=",
"{",
"}",
"if",
"self",
".",
"start_key",
"is",
"not",
"None",
":",
"start_key_key",
"=",
"\"start_key_open\"",
"if",
"self",
".",
"start_inclusive",
":",
"start_key_key",
"=",
"\"start_key... | 38.705882 | 10.235294 |
def monitor(name):
'''
Get the summary from module monit and try to see if service is
being monitored. If not then monitor the service.
'''
ret = {'result': None,
'name': name,
'comment': '',
'changes': {}
}
result = __salt__['monit.summary'](name)
... | [
"def",
"monitor",
"(",
"name",
")",
":",
"ret",
"=",
"{",
"'result'",
":",
"None",
",",
"'name'",
":",
"name",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"}",
"}",
"result",
"=",
"__salt__",
"[",
"'monit.summary'",
"]",
"(",
"name",
"... | 33.9375 | 19.5625 |
def RecursiveDownload(dir_obj,
target_dir,
max_depth=10,
depth=1,
overwrite=False,
max_threads=10):
"""Recursively downloads a file entry to the target path.
Args:
dir_obj: An aff4 object that contains... | [
"def",
"RecursiveDownload",
"(",
"dir_obj",
",",
"target_dir",
",",
"max_depth",
"=",
"10",
",",
"depth",
"=",
"1",
",",
"overwrite",
"=",
"False",
",",
"max_threads",
"=",
"10",
")",
":",
"if",
"not",
"isinstance",
"(",
"dir_obj",
",",
"aff4",
".",
"A... | 34.660377 | 17.377358 |
def import_metadata(self, elements):
"""Import information from GPX metadata.
Args:
elements (etree.Element): GPX metadata subtree
"""
metadata_elem = lambda name: etree.QName(GPX_NS, name)
for child in elements.getchildren():
tag_ns, tag_name = child.ta... | [
"def",
"import_metadata",
"(",
"self",
",",
"elements",
")",
":",
"metadata_elem",
"=",
"lambda",
"name",
":",
"etree",
".",
"QName",
"(",
"GPX_NS",
",",
"name",
")",
"for",
"child",
"in",
"elements",
".",
"getchildren",
"(",
")",
":",
"tag_ns",
",",
"... | 45.454545 | 16.431818 |
def activation(self, x, f="sigmoid", der=False):
"""
This function process values of layer outputs with activation function.
**Args:**
* `x` : array to process (1-dimensional array)
**Kwargs:**
* `f` : activation function
* `der` : normal output, or its deri... | [
"def",
"activation",
"(",
"self",
",",
"x",
",",
"f",
"=",
"\"sigmoid\"",
",",
"der",
"=",
"False",
")",
":",
"if",
"f",
"==",
"\"sigmoid\"",
":",
"if",
"der",
":",
"return",
"x",
"*",
"(",
"1",
"-",
"x",
")",
"return",
"1.",
"/",
"(",
"1",
"... | 25.037037 | 21.703704 |
def set_letter_literal_handle(self, tokens):
"""Process set literals."""
if len(tokens) == 1:
set_type = tokens[0]
if set_type == "s":
return "_coconut.set()"
elif set_type == "f":
return "_coconut.frozenset()"
else:
... | [
"def",
"set_letter_literal_handle",
"(",
"self",
",",
"tokens",
")",
":",
"if",
"len",
"(",
"tokens",
")",
"==",
"1",
":",
"set_type",
"=",
"tokens",
"[",
"0",
"]",
"if",
"set_type",
"==",
"\"s\"",
":",
"return",
"\"_coconut.set()\"",
"elif",
"set_type",
... | 43.904762 | 17.095238 |
def chain(*fs):
'''
Concatenate functions
'''
def chained(x):
for f in reversed(fs):
if f:
x=f(x)
return x
return chained | [
"def",
"chain",
"(",
"*",
"fs",
")",
":",
"def",
"chained",
"(",
"x",
")",
":",
"for",
"f",
"in",
"reversed",
"(",
"fs",
")",
":",
"if",
"f",
":",
"x",
"=",
"f",
"(",
"x",
")",
"return",
"x",
"return",
"chained"
] | 17.6 | 22.4 |
def blend_html_colour_to_white(html_colour, alpha):
"""
:param html_colour: Colour string like FF552B or #334455
:param alpha: Alpha value
:return: Html colour alpha blended onto white
"""
html_colour = html_colour.upper()
has_hash = False
if html_colour[0] == '#':
has_hash = Tru... | [
"def",
"blend_html_colour_to_white",
"(",
"html_colour",
",",
"alpha",
")",
":",
"html_colour",
"=",
"html_colour",
".",
"upper",
"(",
")",
"has_hash",
"=",
"False",
"if",
"html_colour",
"[",
"0",
"]",
"==",
"'#'",
":",
"has_hash",
"=",
"True",
"html_colour"... | 25.103448 | 16.206897 |
def create_order(cls, order, **kwargs):
"""Create Order
Create a new Order
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_order(order, async=True)
>>> result = thread.get()
... | [
"def",
"create_order",
"(",
"cls",
",",
"order",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_create_order_with_http_info",
"("... | 37.47619 | 17.571429 |
def _finish(self, forced=False):
""" Cleanup code after asked to stop producing.
Kwargs:
forced (bool): If True, we were forced to stop
"""
if hasattr(self, "_current_file_handle") and self._current_file_handle:
self._current_file_handle.close()
... | [
"def",
"_finish",
"(",
"self",
",",
"forced",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"\"_current_file_handle\"",
")",
"and",
"self",
".",
"_current_file_handle",
":",
"self",
".",
"_current_file_handle",
".",
"close",
"(",
")",
"if",
"s... | 34.733333 | 15.8 |
async def SetVolumeInfo(self, volumes):
'''
volumes : typing.Sequence[~Volume]
Returns -> typing.Sequence[~ErrorResult]
'''
# map input types to rpc msg
_params = dict()
msg = dict(type='StorageProvisioner',
request='SetVolumeInfo',
... | [
"async",
"def",
"SetVolumeInfo",
"(",
"self",
",",
"volumes",
")",
":",
"# map input types to rpc msg",
"_params",
"=",
"dict",
"(",
")",
"msg",
"=",
"dict",
"(",
"type",
"=",
"'StorageProvisioner'",
",",
"request",
"=",
"'SetVolumeInfo'",
",",
"version",
"=",... | 32.357143 | 10.214286 |
def log_status(self, in_sync=True, incremental=False, audit=False,
same=None, created=0, updated=0, deleted=0, to_delete=0):
"""Write log message regarding status in standard form.
Split this off so all messages from baseline/audit/incremental
are written in a consistent form... | [
"def",
"log_status",
"(",
"self",
",",
"in_sync",
"=",
"True",
",",
"incremental",
"=",
"False",
",",
"audit",
"=",
"False",
",",
"same",
"=",
"None",
",",
"created",
"=",
"0",
",",
"updated",
"=",
"0",
",",
"deleted",
"=",
"0",
",",
"to_delete",
"... | 44.3125 | 16.4375 |
def _eager_expr_from_flat_schema(flat_schema):
"""
:type flat_schema: dict
"""
result = []
for path, join_method in flat_schema.items():
if join_method == JOINED:
result.append(joinedload(path))
elif join_method == SUBQUERY:
result.append(subqueryload... | [
"def",
"_eager_expr_from_flat_schema",
"(",
"flat_schema",
")",
":",
"result",
"=",
"[",
"]",
"for",
"path",
",",
"join_method",
"in",
"flat_schema",
".",
"items",
"(",
")",
":",
"if",
"join_method",
"==",
"JOINED",
":",
"result",
".",
"append",
"(",
"join... | 33.357143 | 11.214286 |
def _transition_steps(self, brightness=None, color=None):
"""
Get the maximum number of steps needed for a transition.
:param brightness: The brightness to transition to (0.0-1.0).
:param color: The color to transition to.
:return: The maximum number of steps.
"""
... | [
"def",
"_transition_steps",
"(",
"self",
",",
"brightness",
"=",
"None",
",",
"color",
"=",
"None",
")",
":",
"values",
"=",
"[",
"]",
"if",
"brightness",
"is",
"not",
"None",
":",
"self",
".",
"_assert_is_brightness",
"(",
"brightness",
")",
"values",
"... | 34.238095 | 19.47619 |
def unmark_featured(self, request, queryset):
"""
Un-Mark selected featured posts.
"""
queryset.update(featured=False)
self.message_user(
request, _('Selected entries are no longer marked as featured.')) | [
"def",
"unmark_featured",
"(",
"self",
",",
"request",
",",
"queryset",
")",
":",
"queryset",
".",
"update",
"(",
"featured",
"=",
"False",
")",
"self",
".",
"message_user",
"(",
"request",
",",
"_",
"(",
"'Selected entries are no longer marked as featured.'",
"... | 35.571429 | 8.142857 |
def initiate_upgrade_action(self, components_mask, action):
""" Initiate Upgrade Action
components:
action:
ACTION_BACKUP_COMPONENT = 0x00
ACTION_PREPARE_COMPONENT = 0x01
ACTION_UPLOAD_FOR_UPGRADE = 0x02
ACTION_UPLOAD_FOR_COMPARE = 0x03
"""... | [
"def",
"initiate_upgrade_action",
"(",
"self",
",",
"components_mask",
",",
"action",
")",
":",
"if",
"action",
"in",
"(",
"ACTION_UPLOAD_FOR_UPGRADE",
",",
"ACTION_UPLOAD_FOR_COMPARE",
")",
":",
"if",
"self",
".",
"_get_component_count",
"(",
"components_mask",
")"... | 41.6875 | 19.5625 |
def _add_assert(self, **kwargs):
"""
if screenshot is None, only failed case will take screenshot
"""
# convert screenshot to relative path from <None|True|False|PIL.Image>
screenshot = kwargs.get('screenshot')
is_success = kwargs.get('success')
screenshot = (not ... | [
"def",
"_add_assert",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# convert screenshot to relative path from <None|True|False|PIL.Image>",
"screenshot",
"=",
"kwargs",
".",
"get",
"(",
"'screenshot'",
")",
"is_success",
"=",
"kwargs",
".",
"get",
"(",
"'success... | 51.411765 | 17.529412 |
def delete_edge(self, tail_node_or_ID, head_node_or_ID):
""" Removes an edge from the graph. Returns the deleted edge or None.
"""
if isinstance(tail_node_or_ID, Node):
tail_node = tail_node_or_ID
else:
tail_node = self.get_node(tail_node_or_ID)
if isinst... | [
"def",
"delete_edge",
"(",
"self",
",",
"tail_node_or_ID",
",",
"head_node_or_ID",
")",
":",
"if",
"isinstance",
"(",
"tail_node_or_ID",
",",
"Node",
")",
":",
"tail_node",
"=",
"tail_node_or_ID",
"else",
":",
"tail_node",
"=",
"self",
".",
"get_node",
"(",
... | 33.318182 | 17.227273 |
def _cmd(self, cmd, *args, **kw):
'''
write a single command, with variable number of arguments. after the
command, the device must return ACK
'''
ok = kw.setdefault('ok', False)
self._wakeup()
if args:
cmd = "%s %s" % (cmd, ' '.join(str(a) for a in a... | [
"def",
"_cmd",
"(",
"self",
",",
"cmd",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"ok",
"=",
"kw",
".",
"setdefault",
"(",
"'ok'",
",",
"False",
")",
"self",
".",
"_wakeup",
"(",
")",
"if",
"args",
":",
"cmd",
"=",
"\"%s %s\"",
"%",
"(... | 34.791667 | 16.291667 |
def add_to_matching_blacklist(session, term):
"""Add term to the matching blacklist.
This function adds a `term` to the matching blacklist.
The term to add cannot have a `None` or empty value,
on this case an `ValueError` will be raised.
:param session: database session
:param term: term, word... | [
"def",
"add_to_matching_blacklist",
"(",
"session",
",",
"term",
")",
":",
"if",
"term",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"'term' to blacklist cannot be None\"",
")",
"if",
"term",
"==",
"''",
":",
"raise",
"ValueError",
"(",
"\"'term' to blacklist... | 30.391304 | 20.782609 |
def system_monitor_mail_sfp_enable(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
system_monitor_mail = ET.SubElement(config, "system-monitor-mail", xmlns="urn:brocade.com:mgmt:brocade-system-monitor")
sfp = ET.SubElement(system_monitor_mail, "sfp")
... | [
"def",
"system_monitor_mail_sfp_enable",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"system_monitor_mail",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"system-monitor-mail\"",
",",
"xmln... | 44.4 | 18.7 |
def start_smart_disassemble(self, start_address, callback):
"""
Invok the callback function for every instruction disassembled at the
previously initialized smart session with the given offset from the
start address supplied (also in the initialization).
"""
_opcodes.sta... | [
"def",
"start_smart_disassemble",
"(",
"self",
",",
"start_address",
",",
"callback",
")",
":",
"_opcodes",
".",
"start_smart_disassemble",
"(",
"self",
".",
"_ptr",
",",
"start_address",
",",
"callback",
")"
] | 46.125 | 23.375 |
def get_encryption_key_status(self):
"""Read information about the current encryption key used by Vault.
Supported methods:
GET: /sys/key-status. Produces: 200 application/json
:return: JSON response with information regarding the current encryption key used by Vault.
:rtyp... | [
"def",
"get_encryption_key_status",
"(",
"self",
")",
":",
"api_path",
"=",
"'/v1/sys/key-status'",
"response",
"=",
"self",
".",
"_adapter",
".",
"get",
"(",
"url",
"=",
"api_path",
",",
")",
"return",
"response",
".",
"json",
"(",
")"
] | 33.642857 | 18.642857 |
def sources(self):
"""Return available sources of data."""
res = self.client.service.Sources(self.userdata, 0)
return [ustr(x[0]) for x in res[0]] | [
"def",
"sources",
"(",
"self",
")",
":",
"res",
"=",
"self",
".",
"client",
".",
"service",
".",
"Sources",
"(",
"self",
".",
"userdata",
",",
"0",
")",
"return",
"[",
"ustr",
"(",
"x",
"[",
"0",
"]",
")",
"for",
"x",
"in",
"res",
"[",
"0",
"... | 41.75 | 11 |
def attach(self, module_factory, name=None, **kwargs):
"""Attach a module to the pipeline system"""
if self.anybar: self.anybar.change("yellow")
fac = module_factory
if name is None:
name = fac.__name__
log.info("Attaching module '{0}'".format(name))
if (i... | [
"def",
"attach",
"(",
"self",
",",
"module_factory",
",",
"name",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"anybar",
":",
"self",
".",
"anybar",
".",
"change",
"(",
"\"yellow\"",
")",
"fac",
"=",
"module_factory",
"if",
"nam... | 40.031579 | 17.968421 |
def load(self):
""" Read pref dict stored on disk. Overwriting current values. """
if VERBOSE_PREF:
print('[pref.load()]')
#if not os.path.exists(self._intern.fpath):
# msg = '[pref] fpath=%r does not exist' % (self._intern.fpath)
# return msg
... | [
"def",
"load",
"(",
"self",
")",
":",
"if",
"VERBOSE_PREF",
":",
"print",
"(",
"'[pref.load()]'",
")",
"#if not os.path.exists(self._intern.fpath):",
"# msg = '[pref] fpath=%r does not exist' % (self._intern.fpath)",
"# return msg",
"fpath",
"=",
"self",
".",
"get_fpath... | 39.444444 | 16.407407 |
def Match(addr1, addr2):
"""Return true iff addr1 matches addr2."""
if _debug: Match._debug("Match %r %r", addr1, addr2)
if (addr2.addrType == Address.localBroadcastAddr):
# match any local station
return (addr1.addrType == Address.localStationAddr) or (addr1.addrType == Address.localBroadc... | [
"def",
"Match",
"(",
"addr1",
",",
"addr2",
")",
":",
"if",
"_debug",
":",
"Match",
".",
"_debug",
"(",
"\"Match %r %r\"",
",",
"addr1",
",",
"addr2",
")",
"if",
"(",
"addr2",
".",
"addrType",
"==",
"Address",
".",
"localBroadcastAddr",
")",
":",
"# ma... | 55.652174 | 23.565217 |
def _logger_api(self):
"""Add API logging handler."""
from .tcex_logger import TcExLogHandler, TcExLogFormatter
api = TcExLogHandler(self.session)
api.set_name('api')
api.setLevel(logging.DEBUG)
api.setFormatter(TcExLogFormatter())
self.log.addHandler(api) | [
"def",
"_logger_api",
"(",
"self",
")",
":",
"from",
".",
"tcex_logger",
"import",
"TcExLogHandler",
",",
"TcExLogFormatter",
"api",
"=",
"TcExLogHandler",
"(",
"self",
".",
"session",
")",
"api",
".",
"set_name",
"(",
"'api'",
")",
"api",
".",
"setLevel",
... | 33.888889 | 12.777778 |
def _get_template_dirs():
"""existing directories where to search for jinja2 templates. The order
is important. The first found template from the first found dir wins!"""
return filter(lambda x: os.path.exists(x), [
# user dir
os.path.join(os.path.expanduser('~'), '.py2pack', 'templates'),
... | [
"def",
"_get_template_dirs",
"(",
")",
":",
"return",
"filter",
"(",
"lambda",
"x",
":",
"os",
".",
"path",
".",
"exists",
"(",
"x",
")",
",",
"[",
"# user dir",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~'",... | 48.545455 | 17.727273 |
def get_octal(self, c, i):
"""Get octal."""
index = i.index
value = []
zero_count = 0
try:
if c == '0':
for x in range(3):
if c != '0':
break
value.append(c)
c = next(... | [
"def",
"get_octal",
"(",
"self",
",",
"c",
",",
"i",
")",
":",
"index",
"=",
"i",
".",
"index",
"value",
"=",
"[",
"]",
"zero_count",
"=",
"0",
"try",
":",
"if",
"c",
"==",
"'0'",
":",
"for",
"x",
"in",
"range",
"(",
"3",
")",
":",
"if",
"c... | 29.133333 | 16.066667 |
def scale_degree_to_semitone(scale_degree):
r"""Convert a scale degree to semitone.
Parameters
----------
scale degree : str
Spelling of a relative scale degree, e.g. 'b3', '7', '#5'
Returns
-------
semitone : int
Relative semitone of the scale degree, wrapped to a single o... | [
"def",
"scale_degree_to_semitone",
"(",
"scale_degree",
")",
":",
"semitone",
"=",
"0",
"offset",
"=",
"0",
"if",
"scale_degree",
".",
"startswith",
"(",
"\"#\"",
")",
":",
"offset",
"=",
"scale_degree",
".",
"count",
"(",
"\"#\"",
")",
"scale_degree",
"=",
... | 29.625 | 19.1875 |
def parse_keys_and_ranges(i_str, keyfunc, rangefunc):
'''Parse the :class:`from_kvlayer` input string.
This accepts two formats. In the textual format, it accepts any
number of stream IDs in timestamp-docid format, separated by ``,``
or ``;``, and processes those as individual stream IDs. In the
... | [
"def",
"parse_keys_and_ranges",
"(",
"i_str",
",",
"keyfunc",
",",
"rangefunc",
")",
":",
"while",
"i_str",
":",
"m",
"=",
"_STREAM_ID_RE",
".",
"match",
"(",
"i_str",
")",
"if",
"m",
":",
"# old style text stream_id",
"for",
"retval",
"in",
"keyfunc",
"(",
... | 36.764706 | 17.313725 |
def convertToPDF(self, from_page=0, to_page=-1, rotate=0):
"""Convert document to PDF selecting page range and optional rotation. Output bytes object."""
if self.isClosed or self.isEncrypted:
raise ValueError("operation illegal for closed / encrypted doc")
return _fitz.Document_conv... | [
"def",
"convertToPDF",
"(",
"self",
",",
"from_page",
"=",
"0",
",",
"to_page",
"=",
"-",
"1",
",",
"rotate",
"=",
"0",
")",
":",
"if",
"self",
".",
"isClosed",
"or",
"self",
".",
"isEncrypted",
":",
"raise",
"ValueError",
"(",
"\"operation illegal for c... | 59.5 | 22.5 |
def switch_on(self):
"""Turn the switch on."""
success = self.set_status(CONST.STATUS_OPEN_INT)
if success:
self._json_state['status'] = CONST.STATUS_OPEN
return success | [
"def",
"switch_on",
"(",
"self",
")",
":",
"success",
"=",
"self",
".",
"set_status",
"(",
"CONST",
".",
"STATUS_OPEN_INT",
")",
"if",
"success",
":",
"self",
".",
"_json_state",
"[",
"'status'",
"]",
"=",
"CONST",
".",
"STATUS_OPEN",
"return",
"success"
] | 26 | 21.625 |
def rdkitmol_Hs(self):
r'''RDKit object of the chemical, with hydrogen. If RDKit is not
available, holds None.
For examples of what can be done with RDKit, see
`their website <http://www.rdkit.org/docs/GettingStartedInPython.html>`_.
'''
if self.__rdkitmol_Hs:
... | [
"def",
"rdkitmol_Hs",
"(",
"self",
")",
":",
"if",
"self",
".",
"__rdkitmol_Hs",
":",
"return",
"self",
".",
"__rdkitmol_Hs",
"else",
":",
"try",
":",
"self",
".",
"__rdkitmol_Hs",
"=",
"Chem",
".",
"AddHs",
"(",
"self",
".",
"rdkitmol",
")",
"return",
... | 34.466667 | 20.466667 |
def split_by_fixed_size(infile, outfiles_prefix, chunk_size, tolerance, skip_if_all_Ns=False):
'''Splits fasta/q file into separate files, with up to (chunk_size + tolerance) bases in each file'''
file_count = 1
coords = []
small_sequences = [] # sequences shorter than chunk_size
seq_reader = sequ... | [
"def",
"split_by_fixed_size",
"(",
"infile",
",",
"outfiles_prefix",
",",
"chunk_size",
",",
"tolerance",
",",
"skip_if_all_Ns",
"=",
"False",
")",
":",
"file_count",
"=",
"1",
"coords",
"=",
"[",
"]",
"small_sequences",
"=",
"[",
"]",
"# sequences shorter than ... | 42.410714 | 22.410714 |
def end(self):
"""Union[Datetime, None]: Datetime when the stage ended."""
if self._properties.get("endMs") is None:
return None
return _helpers._datetime_from_microseconds(
int(self._properties.get("endMs")) * 1000.0
) | [
"def",
"end",
"(",
"self",
")",
":",
"if",
"self",
".",
"_properties",
".",
"get",
"(",
"\"endMs\"",
")",
"is",
"None",
":",
"return",
"None",
"return",
"_helpers",
".",
"_datetime_from_microseconds",
"(",
"int",
"(",
"self",
".",
"_properties",
".",
"ge... | 38.428571 | 15.714286 |
def _validate_num_clusters(num_clusters, initial_centers, num_rows):
"""
Validate the combination of the `num_clusters` and `initial_centers`
parameters in the Kmeans model create function. If the combination is
valid, determine and return the correct number of clusters.
Parameters
----------
... | [
"def",
"_validate_num_clusters",
"(",
"num_clusters",
",",
"initial_centers",
",",
"num_rows",
")",
":",
"## Basic validation",
"if",
"num_clusters",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"num_clusters",
",",
"int",
")",
":",
"raise",
"_ToolkitErro... | 36.482759 | 24.551724 |
def addScalarBar(self, c=None, title="", horizontal=False, vmin=None, vmax=None):
"""
Add a 2D scalar bar to actor.
.. hint:: |mesh_bands| |mesh_bands.py|_
"""
# book it, it will be created by Plotter.show() later
self.scalarbar = [c, title, horizontal, vmin, vmax]
... | [
"def",
"addScalarBar",
"(",
"self",
",",
"c",
"=",
"None",
",",
"title",
"=",
"\"\"",
",",
"horizontal",
"=",
"False",
",",
"vmin",
"=",
"None",
",",
"vmax",
"=",
"None",
")",
":",
"# book it, it will be created by Plotter.show() later",
"self",
".",
"scalar... | 36.222222 | 16.888889 |
def is_vowel(char):
"""
Check whether the character is a vowel letter.
"""
if is_letter(char, strict=True):
return char in chart.vowels
return False | [
"def",
"is_vowel",
"(",
"char",
")",
":",
"if",
"is_letter",
"(",
"char",
",",
"strict",
"=",
"True",
")",
":",
"return",
"char",
"in",
"chart",
".",
"vowels",
"return",
"False"
] | 18.625 | 14.125 |
def forward_message(self, peer: Peer, message: Message, on_success: callable=None):
"""
Use this method to forward messages of any kind.
:param peer: Peer to send forwarded message too.
:param message: Message to be forwarded.
:param on_success: Callback to call when call is com... | [
"def",
"forward_message",
"(",
"self",
",",
"peer",
":",
"Peer",
",",
"message",
":",
"Message",
",",
"on_success",
":",
"callable",
"=",
"None",
")",
":",
"botapi",
".",
"forward_message",
"(",
"peer",
".",
"id",
",",
"message",
".",
"sender",
".",
"i... | 44.272727 | 24.090909 |
def get(self, path_segment="", owner=None, app=None, sharing=None, **query):
"""Performs a GET operation on the path segment relative to this endpoint.
This method is named to match the HTTP method. This method makes at least
one roundtrip to the server, one additional round trip for
ea... | [
"def",
"get",
"(",
"self",
",",
"path_segment",
"=",
"\"\"",
",",
"owner",
"=",
"None",
",",
"app",
"=",
"None",
",",
"sharing",
"=",
"None",
",",
"*",
"*",
"query",
")",
":",
"# self.path to the Endpoint is relative in the SDK, so passing",
"# owner, app, shari... | 49.365079 | 22.238095 |
def list_surveys(): # noqa: E501
"""list the surveys available
List the surveys available # noqa: E501
:rtype: List[Survey]
"""
pm = PrecisionMapper(login=_LOGIN, password=_PASSWORD)
pm.sign_in()
surveys = pm.get_surveys()
shared_surveys = pm.get_shared_surveys()
survey_list = [... | [
"def",
"list_surveys",
"(",
")",
":",
"# noqa: E501",
"pm",
"=",
"PrecisionMapper",
"(",
"login",
"=",
"_LOGIN",
",",
"password",
"=",
"_PASSWORD",
")",
"pm",
".",
"sign_in",
"(",
")",
"surveys",
"=",
"pm",
".",
"get_surveys",
"(",
")",
"shared_surveys",
... | 29.52381 | 17.047619 |
def dP_Reader_Harris_Gallagher_wet_venturi_tube(D, Do, P1, P2, ml, mg, rhol,
rhog, H=1):
r'''Calculates the non-recoverable pressure drop of a wet gas venturi
nozzle based on the pressure drop and the geometry of the venturi nozzle,
the mass flow rates of li... | [
"def",
"dP_Reader_Harris_Gallagher_wet_venturi_tube",
"(",
"D",
",",
"Do",
",",
"P1",
",",
"P2",
",",
"ml",
",",
"mg",
",",
"rhol",
",",
"rhog",
",",
"H",
"=",
"1",
")",
":",
"dP",
"=",
"P1",
"-",
"P2",
"beta",
"=",
"Do",
"/",
"D",
"X",
"=",
"m... | 35.090909 | 24.931818 |
def serialize_instance(instance):
"""
Since Django 1.6 items added to the session are no longer pickled,
but JSON encoded by default. We are storing partially complete models
in the session (user, account, token, ...). We cannot use standard
Django serialization, as these are models are not "complet... | [
"def",
"serialize_instance",
"(",
"instance",
")",
":",
"ret",
"=",
"dict",
"(",
"[",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"instance",
".",
"__dict__",
".",
"items",
"(",
")",
"if",
"not",
"k",
".",
"startswith",
"(",
"'_'",
")",
... | 48.166667 | 17.833333 |
def merge_deltas(stmts_in):
"""Gather and merge original Influence delta information from evidence.
This function is only applicable to Influence Statements that have
subj and obj deltas. All other statement types are passed through unchanged.
Polarities and adjectives for subjects and objects respect... | [
"def",
"merge_deltas",
"(",
"stmts_in",
")",
":",
"stmts_out",
"=",
"[",
"]",
"for",
"stmt",
"in",
"stmts_in",
":",
"# This operation is only applicable to Influences",
"if",
"not",
"isinstance",
"(",
"stmt",
",",
"Influence",
")",
":",
"stmts_out",
".",
"append... | 41.492754 | 19.289855 |
def _retrieve_morpheus_entry(self, word):
"""Return Morpheus entry for word
Entry format: [(head word, tag, macronized form)]
:param word: unmacronized, lowercased word
:ptype word: string
:return: Morpheus entry in tuples
:rtype : list
"""
entry = self.... | [
"def",
"_retrieve_morpheus_entry",
"(",
"self",
",",
"word",
")",
":",
"entry",
"=",
"self",
".",
"macron_data",
".",
"get",
"(",
"word",
")",
"if",
"entry",
"is",
"None",
":",
"logger",
".",
"info",
"(",
"'No Morpheus entry found for {}.'",
".",
"format",
... | 33.529412 | 15.764706 |
def create_by_natural_key(self, *args):
"""
Create a new object from the provided natural key values. If the
natural key contains related objects, recursively get or create them by
their natural keys.
"""
kwargs = self.natural_key_kwargs(*args)
for name, rel_to ... | [
"def",
"create_by_natural_key",
"(",
"self",
",",
"*",
"args",
")",
":",
"kwargs",
"=",
"self",
".",
"natural_key_kwargs",
"(",
"*",
"args",
")",
"for",
"name",
",",
"rel_to",
"in",
"self",
".",
"model",
".",
"get_natural_key_info",
"(",
")",
":",
"if",
... | 38.75 | 16.95 |
def to_str(obj):
"""Attempts to convert given object to a string object
"""
if not isinstance(obj, str) and PY3 and isinstance(obj, bytes):
obj = obj.decode('utf-8')
return obj if isinstance(obj, string_types) else str(obj) | [
"def",
"to_str",
"(",
"obj",
")",
":",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"str",
")",
"and",
"PY3",
"and",
"isinstance",
"(",
"obj",
",",
"bytes",
")",
":",
"obj",
"=",
"obj",
".",
"decode",
"(",
"'utf-8'",
")",
"return",
"obj",
"if",
"i... | 40.333333 | 13.166667 |
def read(self, mode='r', *, buffering=-1, encoding=None, newline=None):
''' read data from the file. '''
with self.open(mode=mode, buffering=buffering, encoding=encoding, newline=newline) as fp:
return fp.read() | [
"def",
"read",
"(",
"self",
",",
"mode",
"=",
"'r'",
",",
"*",
",",
"buffering",
"=",
"-",
"1",
",",
"encoding",
"=",
"None",
",",
"newline",
"=",
"None",
")",
":",
"with",
"self",
".",
"open",
"(",
"mode",
"=",
"mode",
",",
"buffering",
"=",
"... | 59 | 25 |
def _asdict(self):
"""Return a dictionary representation of the current prompt."""
with self._cond:
if self._prompt is None:
return
return {'id': self._prompt.id,
'message': self._prompt.message,
'text-input': self._prompt.text_input} | [
"def",
"_asdict",
"(",
"self",
")",
":",
"with",
"self",
".",
"_cond",
":",
"if",
"self",
".",
"_prompt",
"is",
"None",
":",
"return",
"return",
"{",
"'id'",
":",
"self",
".",
"_prompt",
".",
"id",
",",
"'message'",
":",
"self",
".",
"_prompt",
"."... | 35.375 | 12.5 |
def main() -> None:
"""
Command-line processor. See ``--help`` for details.
"""
main_only_quicksetup_rootlogger()
wdcd_suffix = "_with_drop_create_database"
timeformat = "%Y%m%dT%H%M%S"
parser = argparse.ArgumentParser(
description="""
Back up a specific MySQL database. The r... | [
"def",
"main",
"(",
")",
"->",
"None",
":",
"main_only_quicksetup_rootlogger",
"(",
")",
"wdcd_suffix",
"=",
"\"_with_drop_create_database\"",
"timeformat",
"=",
"\"%Y%m%dT%H%M%S\"",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"\"\"\n ... | 39.959184 | 15.806122 |
def save_model(model_folder: str, model_name: str, model: Model,
compiler_options: Dict[str, str]) -> None:
"""
Saves a CasADi model to disk.
:param model_folder: Folder where the precompiled CasADi model will be stored.
:param model_name: Name of the model.
:param model: Model insta... | [
"def",
"save_model",
"(",
"model_folder",
":",
"str",
",",
"model_name",
":",
"str",
",",
"model",
":",
"Model",
",",
"compiler_options",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
")",
"->",
"None",
":",
"objects",
"=",
"{",
"'dae_residual'",
":",
"Non... | 39.848837 | 24.709302 |
def change_password(self, previous, new_password):
"""
Change the user's password and save to the database
:param previous: plain text previous password
:param new_password: plain text new password
:raises: ValidationError
"""
if not self.verify_password(previous... | [
"def",
"change_password",
"(",
"self",
",",
"previous",
",",
"new_password",
")",
":",
"if",
"not",
"self",
".",
"verify_password",
"(",
"previous",
")",
":",
"raise",
"exceptions",
".",
"Unauthorized",
"(",
"'Incorrect password'",
")",
"if",
"len",
"(",
"ne... | 39.826087 | 18.173913 |
def split_name(obj):
"""
If the supplied legislator/person object is missing 'first_name'
or 'last_name' then use name_tools to split.
"""
if obj['_type'] in ('person', 'legislator'):
for key in ('first_name', 'last_name'):
if key not in obj or not obj[key]:
# Nee... | [
"def",
"split_name",
"(",
"obj",
")",
":",
"if",
"obj",
"[",
"'_type'",
"]",
"in",
"(",
"'person'",
",",
"'legislator'",
")",
":",
"for",
"key",
"in",
"(",
"'first_name'",
",",
"'last_name'",
")",
":",
"if",
"key",
"not",
"in",
"obj",
"or",
"not",
... | 34.571429 | 15.571429 |
def get_group_node_size(node):
"""
Shared getter for AddrmapNode and RegfileNode's "size" property
"""
# After structural placement, children are sorted
if( not node.inst.children
or (not isinstance(node.inst.children[-1], comp.AddressableComponent))
):
# No addressable child exi... | [
"def",
"get_group_node_size",
"(",
"node",
")",
":",
"# After structural placement, children are sorted",
"if",
"(",
"not",
"node",
".",
"inst",
".",
"children",
"or",
"(",
"not",
"isinstance",
"(",
"node",
".",
"inst",
".",
"children",
"[",
"-",
"1",
"]",
"... | 32.176471 | 18.176471 |
def get_type(bind):
""" Detect the ideal type for the data, either using the explicit type
definition or the format (for date, date-time, not supported by JSON). """
types = bind.types + [bind.schema.get('format')]
for type_name in ('date-time', 'date', 'decimal', 'integer', 'boolean',
... | [
"def",
"get_type",
"(",
"bind",
")",
":",
"types",
"=",
"bind",
".",
"types",
"+",
"[",
"bind",
".",
"schema",
".",
"get",
"(",
"'format'",
")",
"]",
"for",
"type_name",
"in",
"(",
"'date-time'",
",",
"'date'",
",",
"'decimal'",
",",
"'integer'",
","... | 46.333333 | 12.555556 |
def _abort_workflow(pb: ProcessingBlock, workflow_stage_dict: dict,
docker: DockerSwarmClient):
"""Abort the workflow.
TODO(BMo): This function currently does nothing as the abort flag
is hardcoded to False!
This function is used by `execute_processing_block`.
Args:
... | [
"def",
"_abort_workflow",
"(",
"pb",
":",
"ProcessingBlock",
",",
"workflow_stage_dict",
":",
"dict",
",",
"docker",
":",
"DockerSwarmClient",
")",
":",
"# TODO(BMo) Ask the database if the abort flag on the PB is set.",
"_abort_flag",
"=",
"False",
"if",
"_abort_flag",
"... | 35.928571 | 23.178571 |
def _read_mode_tsopt(self, size, kind):
"""Read Timestamps option.
Positional arguments:
* size - int, length of option
* kind - int, 8 (Timestamps)
Returns:
* dict -- extracted Timestamps (TS) option
Structure of TCP TSopt [RFC 7323]:
+... | [
"def",
"_read_mode_tsopt",
"(",
"self",
",",
"size",
",",
"kind",
")",
":",
"temp",
"=",
"struct",
".",
"unpack",
"(",
"'>II'",
",",
"self",
".",
"_read_fileng",
"(",
"size",
")",
")",
"data",
"=",
"dict",
"(",
"kind",
"=",
"kind",
",",
"length",
"... | 36.774194 | 22.032258 |
def accum(subs, vals, func=np.sum, issorted=False, with_subs=False):
"""
NumPy implementation for Matlab's accumarray
"""
# sort accmap for ediff if not sorted
if not issorted:
sidx = lexsort(subs, axis=0)
subs = [sub[sidx] for sub in subs]
vals = vals[sidx]
idx = np.wher... | [
"def",
"accum",
"(",
"subs",
",",
"vals",
",",
"func",
"=",
"np",
".",
"sum",
",",
"issorted",
"=",
"False",
",",
"with_subs",
"=",
"False",
")",
":",
"# sort accmap for ediff if not sorted",
"if",
"not",
"issorted",
":",
"sidx",
"=",
"lexsort",
"(",
"su... | 30.272727 | 15.181818 |
def delete_sourcesystem_cd(cls, tables: I2B2Tables, sourcesystem_cd: str) -> int:
"""
Delete all records with the supplied sourcesystem_cd
:param tables: i2b2 sql connection
:param sourcesystem_cd: sourcesystem_cd to remove
:return: number or records that were deleted
"""... | [
"def",
"delete_sourcesystem_cd",
"(",
"cls",
",",
"tables",
":",
"I2B2Tables",
",",
"sourcesystem_cd",
":",
"str",
")",
"->",
"int",
":",
"return",
"cls",
".",
"_delete_sourcesystem_cd",
"(",
"tables",
".",
"crc_connection",
",",
"tables",
".",
"observation_fact... | 52.625 | 19.875 |
def get_dictkey(In, k, dtype):
"""
returns list of given key (k) from input list of dictionaries (In) in data type dtype. uses command:
get_dictkey(In,k,dtype). If dtype =="", data are strings; if "int", data are integers; if "f", data are floats.
"""
Out = []
for d in In:
if... | [
"def",
"get_dictkey",
"(",
"In",
",",
"k",
",",
"dtype",
")",
":",
"Out",
"=",
"[",
"]",
"for",
"d",
"in",
"In",
":",
"if",
"dtype",
"==",
"''",
":",
"Out",
".",
"append",
"(",
"d",
"[",
"k",
"]",
")",
"if",
"dtype",
"==",
"'f'",
":",
"if",... | 30.2 | 19.16 |
def histogram_bin_edges_minwidth(min_width, bins):
r'''
Merge bins with right-neighbour until each bin has a minimum width.
:arguments:
**bins** (``<array_like>``)
The bin-edges.
**min_width** (``<float>``)
The minimum bin width.
'''
# escape
if min_width is None : return bins
if min_width is ... | [
"def",
"histogram_bin_edges_minwidth",
"(",
"min_width",
",",
"bins",
")",
":",
"# escape",
"if",
"min_width",
"is",
"None",
":",
"return",
"bins",
"if",
"min_width",
"is",
"False",
":",
"return",
"bins",
"# keep removing where needed",
"while",
"True",
":",
"id... | 22.321429 | 26.75 |
def user_upsert(self, domain, userid, password=None, roles=None, name=None):
"""
Upsert a user in the cluster
:param AuthDomain domain: The authentication domain for the user.
:param userid: The user ID
:param password: The user password
:param roles: A list of roles. A ... | [
"def",
"user_upsert",
"(",
"self",
",",
"domain",
",",
"userid",
",",
"password",
"=",
"None",
",",
"roles",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"if",
"not",
"roles",
"or",
"not",
"isinstance",
"(",
"roles",
",",
"list",
")",
":",
"rai... | 36.403509 | 21.491228 |
def save_image(self, img, filename=None, dtype=None, fill_value=None,
floating_point=None, compute=True, **kwargs):
"""Save the image to the given ``filename`` in geotiff_ format.
Note for faster output and reduced memory usage the ``rasterio``
library must be installed. This... | [
"def",
"save_image",
"(",
"self",
",",
"img",
",",
"filename",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"fill_value",
"=",
"None",
",",
"floating_point",
"=",
"None",
",",
"compute",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"filename",
"="... | 47.116071 | 20.883929 |
def load_models(*chain, **kwargs):
"""
Decorator to load a chain of models from the given parameters. This works just like
:func:`load_model` and accepts the same parameters, with some small differences.
:param chain: The chain is a list of tuples of (``model``, ``attributes``, ``parameter``).
... | [
"def",
"load_models",
"(",
"*",
"chain",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"inner",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"decorated_function",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"permissions",
"=",
"None",... | 50.237288 | 19.830508 |
def _determine_chunk_to_make(write_dir):
"""
Returns the full path of the chunk to make (gs://...)
and a boolean, indicating whether we should wait for a new model
or if we're 'behind' and should just write out our current chunk immediately
True == write immediately.
"""
models = fsdb.get_mo... | [
"def",
"_determine_chunk_to_make",
"(",
"write_dir",
")",
":",
"models",
"=",
"fsdb",
".",
"get_models",
"(",
")",
"# Last model is N. N+1 (should be) training. We should gather games for N+2.",
"chunk_to_make",
"=",
"os",
".",
"path",
".",
"join",
"(",
"write_dir",
"... | 41.851852 | 12.296296 |
def get_html_string(self):
"""Generates if need be and returns a simpler html string with
extracted text"""
if self.__htmltree is not None:
return htmltostring(self.__htmltree)
else:
self.__make_tree()
return htmltostring(self.__htmltree) | [
"def",
"get_html_string",
"(",
"self",
")",
":",
"if",
"self",
".",
"__htmltree",
"is",
"not",
"None",
":",
"return",
"htmltostring",
"(",
"self",
".",
"__htmltree",
")",
"else",
":",
"self",
".",
"__make_tree",
"(",
")",
"return",
"htmltostring",
"(",
"... | 38.25 | 8.125 |
def transitions(self, current=True):
"""
Returns available transitions for the current state, as a dictionary of
name: :class:`StateTransitionWrapper`.
:param bool current: Limit to transitions available in ``obj.``
:meth:`~coaster.sqlalchemy.mixins.RoleMixin.current_access`
... | [
"def",
"transitions",
"(",
"self",
",",
"current",
"=",
"True",
")",
":",
"if",
"current",
"and",
"isinstance",
"(",
"self",
".",
"obj",
",",
"RoleMixin",
")",
":",
"proxy",
"=",
"self",
".",
"obj",
".",
"current_access",
"(",
")",
"else",
":",
"prox... | 50.058824 | 23.941176 |
def compute_topk_scores_and_seq(sequences, scores, scores_to_gather, flags,
beam_dim, prefix="default"):
"""Given sequences and scores, will gather the top k=beam size sequences.
This function is used to grow alive, and finished. It takes sequences,
scores, and flags, and returns ... | [
"def",
"compute_topk_scores_and_seq",
"(",
"sequences",
",",
"scores",
",",
"scores_to_gather",
",",
"flags",
",",
"beam_dim",
",",
"prefix",
"=",
"\"default\"",
")",
":",
"unused_batch_dim",
",",
"old_beam_dim",
",",
"unused_length_dim",
"=",
"sequences",
".",
"s... | 46.45283 | 22.490566 |
def safe_mult(a, b):
"""safe version of multiply"""
if isinstance(a, str) and isinstance(b, int) and len(a) * b > MAX_STR_LEN:
raise RuntimeError("String length exceeded, max string length is {}".format(MAX_STR_LEN))
return a * b | [
"def",
"safe_mult",
"(",
"a",
",",
"b",
")",
":",
"if",
"isinstance",
"(",
"a",
",",
"str",
")",
"and",
"isinstance",
"(",
"b",
",",
"int",
")",
"and",
"len",
"(",
"a",
")",
"*",
"b",
">",
"MAX_STR_LEN",
":",
"raise",
"RuntimeError",
"(",
"\"Stri... | 49 | 27.8 |
def _start_remote_debugging(port):
"""Sets up remote debugging using pydevd, connecting to localhost:`port`."""
try:
print("Connecting to remote debugger on localhost:{}.".format(port))
import pydevd # pylint: disable=g-import-not-at-top
pydevd.settrace(
"localhost",
port=port,
... | [
"def",
"_start_remote_debugging",
"(",
"port",
")",
":",
"try",
":",
"print",
"(",
"\"Connecting to remote debugger on localhost:{}.\"",
".",
"format",
"(",
"port",
")",
")",
"import",
"pydevd",
"# pylint: disable=g-import-not-at-top",
"pydevd",
".",
"settrace",
"(",
... | 37.4375 | 18.9375 |
def _get_intermediate_file(self, name, machine_and_compiler_dependent=True, binary=False,
fp=True):
"""
Create or open intermediate file (may be used for caching).
Will replace files older than kernel file, machine file or kerncraft version.
:param machin... | [
"def",
"_get_intermediate_file",
"(",
"self",
",",
"name",
",",
"machine_and_compiler_dependent",
"=",
"True",
",",
"binary",
"=",
"False",
",",
"fp",
"=",
"True",
")",
":",
"if",
"self",
".",
"_filename",
":",
"base_name",
"=",
"os",
".",
"path",
".",
"... | 40.4 | 23.2 |
def record_patch(rec, diff):
"""Return the JSON-compatible structure that results from applying the
changes in `diff` to the record `rec`. The parameters must be structures
compatible with json.dumps *or* strings compatible with json.loads. Note
that by design, `old == record_patch(new, record_diff(old,... | [
"def",
"record_patch",
"(",
"rec",
",",
"diff",
")",
":",
"rec",
",",
"diff",
"=",
"_norm_json_params",
"(",
"rec",
",",
"diff",
")",
"return",
"json_delta",
".",
"patch",
"(",
"rec",
",",
"diff",
",",
"in_place",
"=",
"False",
")"
] | 60.571429 | 14.571429 |
def preprocess_notebook(ntbk, cr):
"""
Process notebook object `ntbk` in preparation for conversion to an
rst document. This processing replaces links to online docs with
corresponding sphinx cross-references within the local docs.
Parameter `cr` is a CrossReferenceLookup object.
"""
# Ite... | [
"def",
"preprocess_notebook",
"(",
"ntbk",
",",
"cr",
")",
":",
"# Iterate over cells in notebook",
"for",
"n",
"in",
"range",
"(",
"len",
"(",
"ntbk",
"[",
"'cells'",
"]",
")",
")",
":",
"# Only process cells of type 'markdown'",
"if",
"ntbk",
"[",
"'cells'",
... | 43.666667 | 13.111111 |
def edit_service_group(self, loadbal_id, group_id, allocation=None,
port=None, routing_type=None, routing_method=None):
"""Edit an existing service group.
:param int loadbal_id: The id of the loadbal where the service resides
:param int group_id: The id of the service... | [
"def",
"edit_service_group",
"(",
"self",
",",
"loadbal_id",
",",
"group_id",
",",
"allocation",
"=",
"None",
",",
"port",
"=",
"None",
",",
"routing_type",
"=",
"None",
",",
"routing_method",
"=",
"None",
")",
":",
"mask",
"=",
"'virtualServers[serviceGroups[... | 47.516129 | 22.774194 |
def format_results(self, results):
"""
Format the ldap results object into somthing that is reasonable
"""
if not results:
return None
userdn = results[0][0]
userobj = results[0][1]
userobj['dn'] = userdn
keymap = self.config.get('KEY_MAP')
... | [
"def",
"format_results",
"(",
"self",
",",
"results",
")",
":",
"if",
"not",
"results",
":",
"return",
"None",
"userdn",
"=",
"results",
"[",
"0",
"]",
"[",
"0",
"]",
"userobj",
"=",
"results",
"[",
"0",
"]",
"[",
"1",
"]",
"userobj",
"[",
"'dn'",
... | 37.533333 | 22.466667 |
def computeEnvelope(self, placeCode):
"""
Compute an envelope for use in suppressing border cells.
:param placeCode: The place code representing the population the envelope
will be used for.
:return: A numpy array that can be elementwise-multiplied with activations
for the given... | [
"def",
"computeEnvelope",
"(",
"self",
",",
"placeCode",
")",
":",
"places",
"=",
"np",
".",
"abs",
"(",
"placeCode",
"-",
"0.5",
")",
"envelope",
"=",
"[",
"1",
"if",
"p",
"<",
"1",
"-",
"self",
".",
"envelopeWidth",
"else",
"np",
".",
"exp",
"(",... | 43.066667 | 16.666667 |
def clip_eta(eta, ord, eps):
"""
Helper function to clip the perturbation to epsilon norm ball.
:param eta: A tensor with the current perturbation.
:param ord: Order of the norm (mimics Numpy).
Possible values: np.inf, 1 or 2.
:param eps: Epsilon, bound of the perturbation.
"""
# Clipping p... | [
"def",
"clip_eta",
"(",
"eta",
",",
"ord",
",",
"eps",
")",
":",
"# Clipping perturbation eta to self.ord norm ball",
"if",
"ord",
"not",
"in",
"[",
"np",
".",
"inf",
",",
"1",
",",
"2",
"]",
":",
"raise",
"ValueError",
"(",
"'ord must be np.inf, 1, or 2.'",
... | 41 | 20.448276 |
def parse_angular_length_quantity(string_rep, unit=u.deg):
"""
Given a string that is either a number or a number and a unit, return a
Quantity of that string. e.g.:
23.9 -> 23.9*u.deg
50" -> 50*u.arcsec
"""
unit_mapping = {
'"': u.arcsec,
... | [
"def",
"parse_angular_length_quantity",
"(",
"string_rep",
",",
"unit",
"=",
"u",
".",
"deg",
")",
":",
"unit_mapping",
"=",
"{",
"'\"'",
":",
"u",
".",
"arcsec",
",",
"\"'\"",
":",
"u",
".",
"arcmin",
",",
"'d'",
":",
"u",
".",
"deg",
",",
"'r'",
... | 33.136364 | 15.5 |
def hardware_connector_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
hardware = ET.SubElement(config, "hardware", xmlns="urn:brocade.com:mgmt:brocade-hardware")
connector = ET.SubElement(hardware, "connector")
name = ET.SubElement(connecto... | [
"def",
"hardware_connector_name",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"hardware",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"hardware\"",
",",
"xmlns",
"=",
"\"urn:brocade.c... | 40.909091 | 14.272727 |
def from_message(self, message):
"""resume the account from standard message
这个是从数据库恢复账户时需要的"""
self.account_cookie = message.get('account_cookie', None)
self.portfolio_cookie = message.get('portfolio_cookie', None)
self.user_cookie = message.get('user_cookie', None)
self... | [
"def",
"from_message",
"(",
"self",
",",
"message",
")",
":",
"self",
".",
"account_cookie",
"=",
"message",
".",
"get",
"(",
"'account_cookie'",
",",
"None",
")",
"self",
".",
"portfolio_cookie",
"=",
"message",
".",
"get",
"(",
"'portfolio_cookie'",
",",
... | 49.540541 | 16.054054 |
def populate_iteration(self, iteration):
"""Pour the current data into the iteration object"""
cur_idx = iteration.cur_idx
genotypes = self.genotype_file.next().split()
iteration.chr, iteration.rsid, junk, iteration.pos = genotypes[0:4]
iteration.chr = int(iteration.chr)
... | [
"def",
"populate_iteration",
"(",
"self",
",",
"iteration",
")",
":",
"cur_idx",
"=",
"iteration",
".",
"cur_idx",
"genotypes",
"=",
"self",
".",
"genotype_file",
".",
"next",
"(",
")",
".",
"split",
"(",
")",
"iteration",
".",
"chr",
",",
"iteration",
"... | 46.166667 | 19.958333 |
def locate_spheres(image, feature_rad, dofilter=False, order=(3 ,3, 3),
trim_edge=True, **kwargs):
"""
Get an initial featuring of sphere positions in an image.
Parameters
-----------
image : :class:`peri.util.Image` object
Image object which defines the image file as we... | [
"def",
"locate_spheres",
"(",
"image",
",",
"feature_rad",
",",
"dofilter",
"=",
"False",
",",
"order",
"=",
"(",
"3",
",",
"3",
",",
"3",
")",
",",
"trim_edge",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"# We just want a smoothed field model of the ... | 41.693548 | 23.274194 |
def arff_to_orange_table(arff):
'''
Convert a string in arff format to an Orange table.
:param arff: string in arff format
:return: Orange data table object constructed from the arff string
:rtype: orange.ExampleTable
'''
with tempfile.NamedTemporaryFile(suffix='.arff', delete=... | [
"def",
"arff_to_orange_table",
"(",
"arff",
")",
":",
"with",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"suffix",
"=",
"'.arff'",
",",
"delete",
"=",
"True",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"arff",
")",
"f",
".",
"flush",
"(",
")",
"ta... | 30.214286 | 21.928571 |
def active_brokers(self):
"""Return set of brokers that are not inactive or decommissioned."""
return {
broker
for broker in self._brokers
if not broker.inactive and not broker.decommissioned
} | [
"def",
"active_brokers",
"(",
"self",
")",
":",
"return",
"{",
"broker",
"for",
"broker",
"in",
"self",
".",
"_brokers",
"if",
"not",
"broker",
".",
"inactive",
"and",
"not",
"broker",
".",
"decommissioned",
"}"
] | 35.285714 | 16.714286 |
def raw_pressure_send(self, time_usec, press_abs, press_diff1, press_diff2, temperature, force_mavlink1=False):
'''
The RAW pressure readings for the typical setup of one absolute
pressure and one differential pressure sensor. The
sensor values should be t... | [
"def",
"raw_pressure_send",
"(",
"self",
",",
"time_usec",
",",
"press_abs",
",",
"press_diff1",
",",
"press_diff2",
",",
"temperature",
",",
"force_mavlink1",
"=",
"False",
")",
":",
"return",
"self",
".",
"send",
"(",
"self",
".",
"raw_pressure_encode",
"(",... | 72.071429 | 49.5 |
def _pop_none(self, kwargs):
"""Remove default values (anything where the value is None). click is unfortunately bad at the way it
sends through unspecified defaults."""
for key, value in copy(kwargs).items():
# options with multiple=True return a tuple
if value is None o... | [
"def",
"_pop_none",
"(",
"self",
",",
"kwargs",
")",
":",
"for",
"key",
",",
"value",
"in",
"copy",
"(",
"kwargs",
")",
".",
"items",
"(",
")",
":",
"# options with multiple=True return a tuple",
"if",
"value",
"is",
"None",
"or",
"value",
"==",
"(",
")"... | 48.888889 | 5.666667 |
def project_local_dir(self):
""" location of the user local directory for the project
e.g., ~/.cumulusci/NPSP-Extension-Test/ """
# depending on where we are in bootstrapping the BaseGlobalConfig
# the canonical projectname could be located in one of two places
if self.project__... | [
"def",
"project_local_dir",
"(",
"self",
")",
":",
"# depending on where we are in bootstrapping the BaseGlobalConfig",
"# the canonical projectname could be located in one of two places",
"if",
"self",
".",
"project__name",
":",
"name",
"=",
"self",
".",
"project__name",
"else",... | 37.904762 | 21.952381 |
def getprefix(self, u):
"""
Get the prefix for the specified namespace (uri)
@param u: A namespace uri.
@type u: str
@return: The namspace.
@rtype: (prefix, uri).
"""
for ns in Namespace.all:
if u == ns[1]:
return ns[0]
... | [
"def",
"getprefix",
"(",
"self",
",",
"u",
")",
":",
"for",
"ns",
"in",
"Namespace",
".",
"all",
":",
"if",
"u",
"==",
"ns",
"[",
"1",
"]",
":",
"return",
"ns",
"[",
"0",
"]",
"for",
"ns",
"in",
"self",
".",
"prefixes",
":",
"if",
"u",
"==",
... | 29.066667 | 10.4 |
def incremental_value(self, slip_moment, mmax, mag_value, bbar, dbar):
"""
Returns the incremental rate with Mmax = Mag_value
"""
delta_m = mmax - mag_value
a_3 = self._get_a3(bbar, dbar, slip_moment, mmax)
return a_3 * bbar * (np.exp(bbar * delta_m) - 1.0) * (delta_m > 0... | [
"def",
"incremental_value",
"(",
"self",
",",
"slip_moment",
",",
"mmax",
",",
"mag_value",
",",
"bbar",
",",
"dbar",
")",
":",
"delta_m",
"=",
"mmax",
"-",
"mag_value",
"a_3",
"=",
"self",
".",
"_get_a3",
"(",
"bbar",
",",
"dbar",
",",
"slip_moment",
... | 45.285714 | 15.285714 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.