text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def genIndex(folder,forceIDs=[]):
"""expects a folder of ABFs."""
if not os.path.exists(folder+"/swhlab4/"):
print(" !! cannot index if no /swhlab4/")
return
timestart=cm.timethis()
files=glob.glob(folder+"/*.*") #ABF folder
files.extend(glob.glob(folder+"/swhlab4/*.*"))
print(" ... | [
"def",
"genIndex",
"(",
"folder",
",",
"forceIDs",
"=",
"[",
"]",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"folder",
"+",
"\"/swhlab4/\"",
")",
":",
"print",
"(",
"\" !! cannot index if no /swhlab4/\"",
")",
"return",
"timestart",
"=",... | 36.3125 | 12.71875 |
def get_container_file_download_url(cluster, environ, topology, container,
path, role=None):
'''
:param cluster:
:param environ:
:param topology:
:param container:
:param path:
:param role:
:return:
'''
params = dict(
cluster=cluster,
environ=environ,
... | [
"def",
"get_container_file_download_url",
"(",
"cluster",
",",
"environ",
",",
"topology",
",",
"container",
",",
"path",
",",
"role",
"=",
"None",
")",
":",
"params",
"=",
"dict",
"(",
"cluster",
"=",
"cluster",
",",
"environ",
"=",
"environ",
",",
"topol... | 24.153846 | 23.076923 |
def readline(self, size = -1):
"""This reads and returns one entire line. A trailing newline is kept
in the string, but may be absent when a file ends with an incomplete
line. Note: This readline() looks for a \\r\\n pair even on UNIX
because this is what the pseudo tty device returns. S... | [
"def",
"readline",
"(",
"self",
",",
"size",
"=",
"-",
"1",
")",
":",
"if",
"size",
"==",
"0",
":",
"return",
"self",
".",
"_empty_buffer",
"index",
"=",
"self",
".",
"expect",
"(",
"[",
"self",
".",
"_pty_newline",
",",
"self",
".",
"delimiter",
"... | 54.875 | 23.9375 |
def get(cls, user_id, github_id=None, name=None, check_owner=True):
"""Return a repository.
:param integer user_id: User identifier.
:param integer github_id: GitHub repository identifier.
:param str name: GitHub repository full name.
:returns: The repository object.
:ra... | [
"def",
"get",
"(",
"cls",
",",
"user_id",
",",
"github_id",
"=",
"None",
",",
"name",
"=",
"None",
",",
"check_owner",
"=",
"True",
")",
":",
"repo",
"=",
"cls",
".",
"query",
".",
"filter",
"(",
"(",
"Repository",
".",
"github_id",
"==",
"github_id"... | 48.083333 | 19.583333 |
def _replace_variable_with_pattern(match):
"""Replace a variable match with a pattern that can be used to validate it.
Args:
match (re.Match): A regular expression match
Returns:
str: A regular expression pattern that can be used to validate the
variable in an expanded path.
... | [
"def",
"_replace_variable_with_pattern",
"(",
"match",
")",
":",
"positional",
"=",
"match",
".",
"group",
"(",
"\"positional\"",
")",
"name",
"=",
"match",
".",
"group",
"(",
"\"name\"",
")",
"template",
"=",
"match",
".",
"group",
"(",
"\"template\"",
")",... | 34.068966 | 18 |
def exp_transform(params):
"""Transform parameters into exp-scale weights."""
weights = np.exp(np.asarray(params) - np.mean(params))
return (len(weights) / weights.sum()) * weights | [
"def",
"exp_transform",
"(",
"params",
")",
":",
"weights",
"=",
"np",
".",
"exp",
"(",
"np",
".",
"asarray",
"(",
"params",
")",
"-",
"np",
".",
"mean",
"(",
"params",
")",
")",
"return",
"(",
"len",
"(",
"weights",
")",
"/",
"weights",
".",
"su... | 47.25 | 10.75 |
def submit_metric(self, name, snmp_value, forced_type, tags=None):
'''
Convert the values reported as pysnmp-Managed Objects to values and
report them to the aggregator
'''
tags = [] if tags is None else tags
if reply_invalid(snmp_value):
# Metrics not present... | [
"def",
"submit_metric",
"(",
"self",
",",
"name",
",",
"snmp_value",
",",
"forced_type",
",",
"tags",
"=",
"None",
")",
":",
"tags",
"=",
"[",
"]",
"if",
"tags",
"is",
"None",
"else",
"tags",
"if",
"reply_invalid",
"(",
"snmp_value",
")",
":",
"# Metri... | 39.97561 | 20.121951 |
def set(self, dict_name, key, value, priority=None):
'''Set a single value for a single key.
This requires a session lock.
:param str dict_name: name of the dictionary to update
:param str key: key to update
:param str value: value to assign to `key`
:param int priority... | [
"def",
"set",
"(",
"self",
",",
"dict_name",
",",
"key",
",",
"value",
",",
"priority",
"=",
"None",
")",
":",
"if",
"priority",
"is",
"not",
"None",
":",
"priorities",
"=",
"{",
"key",
":",
"priority",
"}",
"else",
":",
"priorities",
"=",
"None",
... | 33.9375 | 19.0625 |
def reaction_signature(eq, direction=False, stoichiometry=False):
"""Return unique signature object for :class:`Reaction`.
Signature objects are hashable, and compare equal only if the reactions
are considered the same according to the specified rules.
Args:
direction: Include reaction directi... | [
"def",
"reaction_signature",
"(",
"eq",
",",
"direction",
"=",
"False",
",",
"stoichiometry",
"=",
"False",
")",
":",
"def",
"compounds_sig",
"(",
"compounds",
")",
":",
"if",
"stoichiometry",
":",
"return",
"tuple",
"(",
"sorted",
"(",
"compounds",
")",
"... | 32.37931 | 20.344828 |
def check_pypi_updates(dependencies):
"""Return a list of dependencies to upgrade."""
dependencies_up_to_date = []
for dependency in dependencies.get('pypi', []):
# get latest version from PyPI api
try:
latest_version = get_latest_version_number(dependency.project_name)
e... | [
"def",
"check_pypi_updates",
"(",
"dependencies",
")",
":",
"dependencies_up_to_date",
"=",
"[",
"]",
"for",
"dependency",
"in",
"dependencies",
".",
"get",
"(",
"'pypi'",
",",
"[",
"]",
")",
":",
"# get latest version from PyPI api",
"try",
":",
"latest_version",... | 48.514286 | 22.142857 |
def tag_path(cls, project, incident, tag):
"""Return a fully-qualified tag string."""
return google.api_core.path_template.expand(
"projects/{project}/incidents/{incident}/tags/{tag}",
project=project,
incident=incident,
tag=tag,
) | [
"def",
"tag_path",
"(",
"cls",
",",
"project",
",",
"incident",
",",
"tag",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"projects/{project}/incidents/{incident}/tags/{tag}\"",
",",
"project",
"=",
"project",
",",
"i... | 37 | 14 |
def cleanup(self):
"""
Cleans up the key value store. In detail:
1. Deletes all key store references for image_files that do not exist
and all key references for its thumbnails *and* their image_files.
2. Deletes or updates all invalid thumbnail keys
"""
for ke... | [
"def",
"cleanup",
"(",
"self",
")",
":",
"for",
"key",
"in",
"self",
".",
"_find_keys",
"(",
"identity",
"=",
"'image'",
")",
":",
"image_file",
"=",
"self",
".",
"_get",
"(",
"key",
")",
"if",
"image_file",
"and",
"not",
"image_file",
".",
"exists",
... | 41.736842 | 21.473684 |
def _fast_dataset(
variables: 'OrderedDict[Any, Variable]',
coord_variables: Mapping[Any, Variable],
) -> 'Dataset':
"""Create a dataset as quickly as possible.
Beware: the `variables` OrderedDict is modified INPLACE.
"""
from .dataset import Dataset
variables.update(coord_variables)
co... | [
"def",
"_fast_dataset",
"(",
"variables",
":",
"'OrderedDict[Any, Variable]'",
",",
"coord_variables",
":",
"Mapping",
"[",
"Any",
",",
"Variable",
"]",
",",
")",
"->",
"'Dataset'",
":",
"from",
".",
"dataset",
"import",
"Dataset",
"variables",
".",
"update",
... | 34.25 | 13.083333 |
def make_type_error(cls, msg, *args, **kwargs):
"""A helper method to generate an exception type for type checking errors.
This method uses `cls.type_check_error_type` to ensure that type checking errors can be caught
with a reliable exception type. The type returned by `cls.type_check_error_type` should e... | [
"def",
"make_type_error",
"(",
"cls",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"cls",
".",
"type_check_error_type",
"(",
"cls",
".",
"__name__",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 62.25 | 31.625 |
def add_cxnSp(self, id_, name, type_member, x, y, cx, cy, flipH, flipV):
"""
Append a new ``<p:cxnSp>`` shape to the group/shapetree having the
properties specified in call.
"""
prst = MSO_CONNECTOR_TYPE.to_xml(type_member)
cxnSp = CT_Connector.new_cxnSp(
id_,... | [
"def",
"add_cxnSp",
"(",
"self",
",",
"id_",
",",
"name",
",",
"type_member",
",",
"x",
",",
"y",
",",
"cx",
",",
"cy",
",",
"flipH",
",",
"flipV",
")",
":",
"prst",
"=",
"MSO_CONNECTOR_TYPE",
".",
"to_xml",
"(",
"type_member",
")",
"cxnSp",
"=",
"... | 39.454545 | 14.727273 |
def _probe_characteristics(self, conn, services, timeout=5.0):
"""Probe gatt services for all associated characteristics in a BLE device
Args:
conn (int): the connection handle to probe
services (dict): a dictionary of services produced by probe_services()
timeout (f... | [
"def",
"_probe_characteristics",
"(",
"self",
",",
"conn",
",",
"services",
",",
"timeout",
"=",
"5.0",
")",
":",
"for",
"service",
"in",
"services",
".",
"values",
"(",
")",
":",
"success",
",",
"result",
"=",
"self",
".",
"_enumerate_handles",
"(",
"co... | 39.26087 | 21.26087 |
def set_widgets(self):
"""Set widgets on the Extra Keywords tab."""
existing_inasafe_field = self.parent.get_existing_keyword(
'inasafe_fields')
# Remove old container and parameter
if self.parameter_container:
self.kwExtraKeywordsGridLayout.removeWidget(
... | [
"def",
"set_widgets",
"(",
"self",
")",
":",
"existing_inasafe_field",
"=",
"self",
".",
"parent",
".",
"get_existing_keyword",
"(",
"'inasafe_fields'",
")",
"# Remove old container and parameter",
"if",
"self",
".",
"parameter_container",
":",
"self",
".",
"kwExtraKe... | 44.316667 | 16.25 |
def describe_route_table(route_table_id=None, route_table_name=None,
tags=None, region=None, key=None, keyid=None,
profile=None):
'''
Given route table properties, return route table details if matching table(s) exist.
.. versionadded:: 2015.8.0
CLI Ex... | [
"def",
"describe_route_table",
"(",
"route_table_id",
"=",
"None",
",",
"route_table_name",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"s... | 37.322034 | 26.983051 |
def intersection(self, other, sort=False):
"""
Form the intersection of two Index objects.
Parameters
----------
other : Index or array-like
sort : False or None, default False
Sort the resulting index if possible
.. versionadded:: 0.24.0
... | [
"def",
"intersection",
"(",
"self",
",",
"other",
",",
"sort",
"=",
"False",
")",
":",
"self",
".",
"_validate_sort_keyword",
"(",
"sort",
")",
"if",
"self",
".",
"equals",
"(",
"other",
")",
":",
"return",
"self",
".",
"_get_reconciled_name_object",
"(",
... | 33.746269 | 18.373134 |
def _PrintEventsStatus(self, events_status):
"""Prints the status of the events.
Args:
events_status (EventsStatus): events status.
"""
if events_status:
table_view = views.CLITabularTableView(
column_names=['Events:', 'Filtered', 'In time slice', 'Duplicates',
... | [
"def",
"_PrintEventsStatus",
"(",
"self",
",",
"events_status",
")",
":",
"if",
"events_status",
":",
"table_view",
"=",
"views",
".",
"CLITabularTableView",
"(",
"column_names",
"=",
"[",
"'Events:'",
",",
"'Filtered'",
",",
"'In time slice'",
",",
"'Duplicates'"... | 36.047619 | 15.571429 |
def get_boto_ses_connection():
"""
Shortcut for instantiating and returning a boto SESConnection object.
:rtype: boto.ses.SESConnection
:returns: A boto SESConnection object, from which email sending is done.
"""
access_key_id = getattr(
settings, 'CUCUMBER_SES_ACCESS_KEY_ID',
... | [
"def",
"get_boto_ses_connection",
"(",
")",
":",
"access_key_id",
"=",
"getattr",
"(",
"settings",
",",
"'CUCUMBER_SES_ACCESS_KEY_ID'",
",",
"getattr",
"(",
"settings",
",",
"'AWS_ACCESS_KEY_ID'",
",",
"None",
")",
")",
"access_key",
"=",
"getattr",
"(",
"settings... | 32.689655 | 15.862069 |
def can(self, permission, obj, **kwargs):
"""Check if we can do something with an object.
:param permission: The permission to look for.
:param obj: The object to check the ACL of.
:param **kwargs: The context to pass to predicates.
>>> auth.can('read', some_object)
>>>... | [
"def",
"can",
"(",
"self",
",",
"permission",
",",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"context",
"=",
"{",
"'user'",
":",
"current_user",
"}",
"for",
"func",
"in",
"self",
".",
"context_processors",
":",
"context",
".",
"update",
"(",
"func",
... | 35.277778 | 15.611111 |
def train(self, corpus=None, method='auto', clear_buffer=True, params=None):
"""
Create an indexing model. Will overwrite the model if it already exists.
All indexes become invalid, because documents in them use a now-obsolete
representation.
The model is trained on documents pr... | [
"def",
"train",
"(",
"self",
",",
"corpus",
"=",
"None",
",",
"method",
"=",
"'auto'",
",",
"clear_buffer",
"=",
"True",
",",
"params",
"=",
"None",
")",
":",
"if",
"corpus",
"is",
"not",
"None",
":",
"# use the supplied corpus only (erase existing buffer, if ... | 44.607143 | 20.392857 |
def is_address_reserved(self, address):
"""
Determines if an address belongs to a reserved page.
@note: Returns always C{False} for kernel mode addresses.
@type address: int
@param address: Memory address to query.
@rtype: bool
@return: C{True} if the address... | [
"def",
"is_address_reserved",
"(",
"self",
",",
"address",
")",
":",
"try",
":",
"mbi",
"=",
"self",
".",
"mquery",
"(",
"address",
")",
"except",
"WindowsError",
":",
"e",
"=",
"sys",
".",
"exc_info",
"(",
")",
"[",
"1",
"]",
"if",
"e",
".",
"wine... | 29.863636 | 18.409091 |
def _calc_delta(self,ensemble,scaling_matrix=None):
'''
calc the scaled ensemble differences from the mean
'''
mean = np.array(ensemble.mean(axis=0))
delta = ensemble.as_pyemu_matrix()
for i in range(ensemble.shape[0]):
delta.x[i,:] -= mean
if scaling... | [
"def",
"_calc_delta",
"(",
"self",
",",
"ensemble",
",",
"scaling_matrix",
"=",
"None",
")",
":",
"mean",
"=",
"np",
".",
"array",
"(",
"ensemble",
".",
"mean",
"(",
"axis",
"=",
"0",
")",
")",
"delta",
"=",
"ensemble",
".",
"as_pyemu_matrix",
"(",
"... | 38.333333 | 13 |
def check_pool(lb, name):
'''
Check to see if a pool exists
CLI Examples:
.. code-block:: bash
salt-run f5.check_pool load_balancer pool_name
'''
if __opts__['load_balancers'].get(lb, None):
(username, password) = list(__opts__['load_balancers'][lb].values())
else:
... | [
"def",
"check_pool",
"(",
"lb",
",",
"name",
")",
":",
"if",
"__opts__",
"[",
"'load_balancers'",
"]",
".",
"get",
"(",
"lb",
",",
"None",
")",
":",
"(",
"username",
",",
"password",
")",
"=",
"list",
"(",
"__opts__",
"[",
"'load_balancers'",
"]",
"[... | 27.5625 | 23.6875 |
def setNsProp(self, node, name, value):
"""Set (or reset) an attribute carried by a node. The ns
structure must be in scope, this is not checked """
if node is None: node__o = None
else: node__o = node._o
ret = libxml2mod.xmlSetNsProp(node__o, self._o, name, value)
if ... | [
"def",
"setNsProp",
"(",
"self",
",",
"node",
",",
"name",
",",
"value",
")",
":",
"if",
"node",
"is",
"None",
":",
"node__o",
"=",
"None",
"else",
":",
"node__o",
"=",
"node",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"xmlSetNsProp",
"(",
"node__o",... | 46.555556 | 9.888889 |
async def _RPC_handler(self, request: Dict[str, Any]):
"""用于调用函数并执行.同时如果执行出错也负责将错误转化为对应的调用错误返回给客户端.
执行成功后根据结果进行不同的处理,如果注册的是函数,实例中的方法,或者协程,则获取计算得的结果,并返回给客户端.
如果是异步生成器函数,那么返回的就是一个对应的异步生成器,我们通过对其包装后循环调用实现流传输.
Parameters:
request (Dict[str, Any]): - python字典形式的请求
Raise... | [
"async",
"def",
"_RPC_handler",
"(",
"self",
",",
"request",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
":",
"ID",
"=",
"request",
".",
"get",
"(",
"\"ID\"",
")",
"method",
"=",
"request",
".",
"get",
"(",
"\"METHOD\"",
")",
"with_return",
"=",
... | 35.411765 | 14.364706 |
def OnText(self, event):
"""Text event method evals the cell and updates the grid"""
if not self.ignore_changes:
post_command_event(self, self.CodeEntryMsg, code=event.GetString())
self.main_window.grid.grid_renderer.cell_cache.clear()
event.Skip() | [
"def",
"OnText",
"(",
"self",
",",
"event",
")",
":",
"if",
"not",
"self",
".",
"ignore_changes",
":",
"post_command_event",
"(",
"self",
",",
"self",
".",
"CodeEntryMsg",
",",
"code",
"=",
"event",
".",
"GetString",
"(",
")",
")",
"self",
".",
"main_w... | 31.888889 | 24.666667 |
def _translate(self, options):
"""
Perform translation of feed options passed in as keyword
arguments to CouchDB/Cloudant equivalent.
"""
translation = dict()
for key, val in iteritems_(options):
self._validate(key, val, feed_arg_types(self._source))
... | [
"def",
"_translate",
"(",
"self",
",",
"options",
")",
":",
"translation",
"=",
"dict",
"(",
")",
"for",
"key",
",",
"val",
"in",
"iteritems_",
"(",
"options",
")",
":",
"self",
".",
"_validate",
"(",
"key",
",",
"val",
",",
"feed_arg_types",
"(",
"s... | 41.705882 | 12.764706 |
def _AcceptResponses(self, expected_header, info_cb, timeout_ms=None):
"""Accepts responses until the expected header or a FAIL.
Args:
expected_header: OKAY or DATA
info_cb: Optional callback for text sent from the bootloader.
timeout_ms: Timeout in milliseconds to wait fo... | [
"def",
"_AcceptResponses",
"(",
"self",
",",
"expected_header",
",",
"info_cb",
",",
"timeout_ms",
"=",
"None",
")",
":",
"while",
"True",
":",
"response",
"=",
"self",
".",
"usb",
".",
"BulkRead",
"(",
"64",
",",
"timeout_ms",
"=",
"timeout_ms",
")",
"h... | 42.472222 | 19.916667 |
def OnSelectCard(self, event):
"""Called when the user selects a card in the tree."""
item = event.GetItem()
if item:
itemdata = self.readertreepanel.cardtreectrl.GetItemPyData(item)
if isinstance(itemdata, smartcard.Card.Card):
self.dialogpanel.OnSelectCa... | [
"def",
"OnSelectCard",
"(",
"self",
",",
"event",
")",
":",
"item",
"=",
"event",
".",
"GetItem",
"(",
")",
"if",
"item",
":",
"itemdata",
"=",
"self",
".",
"readertreepanel",
".",
"cardtreectrl",
".",
"GetItemPyData",
"(",
"item",
")",
"if",
"isinstance... | 44.444444 | 16.888889 |
def find_match(self):
"""Load the config and find a matching rule.
returns the results of find_match_command, a dict of
the command and (in the future) other metadata.
"""
self.load()
for yamldoc in self.yamldocs:
self.logdebug('\nchecking rule """%s"""\n' %... | [
"def",
"find_match",
"(",
"self",
")",
":",
"self",
".",
"load",
"(",
")",
"for",
"yamldoc",
"in",
"self",
".",
"yamldocs",
":",
"self",
".",
"logdebug",
"(",
"'\\nchecking rule \"\"\"%s\"\"\"\\n'",
"%",
"yamldoc",
")",
"if",
"not",
"yamldoc",
":",
"contin... | 33.227273 | 17.318182 |
def of_definition(service_def):
"""Create a connection to a Streaming Analytics service.
The single service is defined by `service_def` which can be one of
* The `service credentials` copied from the `Service credentials` page of the service console (not the Streams console). Credentials ... | [
"def",
"of_definition",
"(",
"service_def",
")",
":",
"vcap_services",
"=",
"streamsx",
".",
"topology",
".",
"context",
".",
"_vcap_from_service_definition",
"(",
"service_def",
")",
"service_name",
"=",
"streamsx",
".",
"topology",
".",
"context",
".",
"_name_fr... | 63.411765 | 49.941176 |
def factory(cls, data_class, **kwargs):
"""Creates a ``DCCGraph``, a root :class:`Node`: and the node's
associated data class instance. This factory is used to get around
the chicken-and-egg problem of the ``DCCGraph`` and ``Nodes`` within
it having pointers to each other.
:par... | [
"def",
"factory",
"(",
"cls",
",",
"data_class",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"issubclass",
"(",
"data_class",
",",
"BaseNodeData",
")",
":",
"raise",
"AttributeError",
"(",
"'data_class must be a BaseNodeData extender'",
")",
"content_type",
... | 45.36 | 20.32 |
def run(self, jid=None):
'''
Execute the overall routine, print results via outputters
'''
if self.opts.get('list_hosts'):
self._get_roster()
ret = {}
for roster_file in self.__parsed_rosters:
if roster_file.startswith('#'):
... | [
"def",
"run",
"(",
"self",
",",
"jid",
"=",
"None",
")",
":",
"if",
"self",
".",
"opts",
".",
"get",
"(",
"'list_hosts'",
")",
":",
"self",
".",
"_get_roster",
"(",
")",
"ret",
"=",
"{",
"}",
"for",
"roster_file",
"in",
"self",
".",
"__parsed_roste... | 36.567568 | 16.891892 |
def get_scope_name(self):
"""
Get current scope and return it as a valid function name.
"""
name = 'validate_' + unquote(self.resolution_scope).replace('~1', '_').replace('~0', '_')
name = re.sub(r'[:/#\.\-\%]', '_', name)
name = name.lower().rstrip('_')
re... | [
"def",
"get_scope_name",
"(",
"self",
")",
":",
"name",
"=",
"'validate_'",
"+",
"unquote",
"(",
"self",
".",
"resolution_scope",
")",
".",
"replace",
"(",
"'~1'",
",",
"'_'",
")",
".",
"replace",
"(",
"'~0'",
",",
"'_'",
")",
"name",
"=",
"re",
".",... | 40.25 | 16 |
def build_plane_arrays(x, y, qlist):
"""Build a 2-D array out of data taken in the same plane, for contour
plotting.
"""
if type(qlist) is not list:
return_list = False
qlist = [qlist]
else:
return_list = True
xv = x[np.where(y==y[0])[0]]
yv = y[np.where(x==... | [
"def",
"build_plane_arrays",
"(",
"x",
",",
"y",
",",
"qlist",
")",
":",
"if",
"type",
"(",
"qlist",
")",
"is",
"not",
"list",
":",
"return_list",
"=",
"False",
"qlist",
"=",
"[",
"qlist",
"]",
"else",
":",
"return_list",
"=",
"True",
"xv",
"=",
"x... | 30.47619 | 10.857143 |
def read(self):
"""Read version from version file
:rtype : Version
:return:
"""
with self._path.open(mode='r') as fh:
version = fh.read().strip()
return Version(version) | [
"def",
"read",
"(",
"self",
")",
":",
"with",
"self",
".",
"_path",
".",
"open",
"(",
"mode",
"=",
"'r'",
")",
"as",
"fh",
":",
"version",
"=",
"fh",
".",
"read",
"(",
")",
".",
"strip",
"(",
")",
"return",
"Version",
"(",
"version",
")"
] | 24.666667 | 13.333333 |
def is_date_ranges_intersection(t1start, t1end, t2start, t2end):
"""
Проверяем совпадают ли периоды
"""
return (t1start <= t2start <= t1end) or (t2start <= t1start <= t2end) | [
"def",
"is_date_ranges_intersection",
"(",
"t1start",
",",
"t1end",
",",
"t2start",
",",
"t2end",
")",
":",
"return",
"(",
"t1start",
"<=",
"t2start",
"<=",
"t1end",
")",
"or",
"(",
"t2start",
"<=",
"t1start",
"<=",
"t2end",
")"
] | 37.2 | 12.4 |
def SetSelected( self, node, point=None, propagate=True ):
"""Set the given node selected in the square-map"""
if node == self.selectedNode:
return
self.selectedNode = node
self.UpdateDrawing()
if node:
wx.PostEvent( self, SquareSelectionEvent( node=node, ... | [
"def",
"SetSelected",
"(",
"self",
",",
"node",
",",
"point",
"=",
"None",
",",
"propagate",
"=",
"True",
")",
":",
"if",
"node",
"==",
"self",
".",
"selectedNode",
":",
"return",
"self",
".",
"selectedNode",
"=",
"node",
"self",
".",
"UpdateDrawing",
... | 42.25 | 17.125 |
def wait_for_compose(self, compose_id,
burst_retry=1,
burst_length=30,
slow_retry=10,
timeout=1800):
"""Wait for compose request to finalize
:param compose_id: int, compose ID to wait for
:param ... | [
"def",
"wait_for_compose",
"(",
"self",
",",
"compose_id",
",",
"burst_retry",
"=",
"1",
",",
"burst_length",
"=",
"30",
",",
"slow_retry",
"=",
"10",
",",
"timeout",
"=",
"1800",
")",
":",
"logger",
".",
"debug",
"(",
"\"Getting compose information for inform... | 45.773585 | 18.056604 |
def load_module(self, name):
"""Load a namespace module as if coming from an empty file.
"""
_verbose_message('namespace module loaded with path {!r}', self.path)
# Adjusting code from LoaderBasics
if name in sys.modules:
mod = sys.modules[name]
self.exec... | [
"def",
"load_module",
"(",
"self",
",",
"name",
")",
":",
"_verbose_message",
"(",
"'namespace module loaded with path {!r}'",
",",
"self",
".",
"path",
")",
"# Adjusting code from LoaderBasics",
"if",
"name",
"in",
"sys",
".",
"modules",
":",
"mod",
"=",
"sys",
... | 42.676471 | 23.205882 |
def __add_morph_features(self, token_dict, feature_string,
feature_format='unknown'):
"""
Parameters
----------
token_dict : dict
the node attribute dict belonging to a token node
feature_string : str
a string representing the ... | [
"def",
"__add_morph_features",
"(",
"self",
",",
"token_dict",
",",
"feature_string",
",",
"feature_format",
"=",
"'unknown'",
")",
":",
"assert",
"feature_format",
"in",
"(",
"'attrib_val'",
",",
"'val_only'",
",",
"'unknown'",
")",
"def",
"add_val_only_features",
... | 45.846154 | 20.692308 |
def do_mumble(self, args):
"""Mumbles what you tell me to."""
repetitions = args.repeat or 1
for i in range(min(repetitions, self.maxrepeats)):
output = []
if random.random() < .33:
output.append(random.choice(self.MUMBLE_FIRST))
for word in ar... | [
"def",
"do_mumble",
"(",
"self",
",",
"args",
")",
":",
"repetitions",
"=",
"args",
".",
"repeat",
"or",
"1",
"for",
"i",
"in",
"range",
"(",
"min",
"(",
"repetitions",
",",
"self",
".",
"maxrepeats",
")",
")",
":",
"output",
"=",
"[",
"]",
"if",
... | 42.928571 | 9.785714 |
async def setRemoteDescription(self, sessionDescription):
"""
Changes the remote description associated with the connection.
:param: sessionDescription: An :class:`RTCSessionDescription` created from
information received over the signaling channel.
""... | [
"async",
"def",
"setRemoteDescription",
"(",
"self",
",",
"sessionDescription",
")",
":",
"# parse and validate description",
"description",
"=",
"sdp",
".",
"SessionDescription",
".",
"parse",
"(",
"sessionDescription",
".",
"sdp",
")",
"description",
".",
"type",
... | 44.147059 | 17.705882 |
def dimension_values(self, dimension, expanded=True, flat=True):
"""Return the values along the requested dimension.
Concatenates values on all nodes with requested dimension.
Args:
dimension: The dimension to return values for
expanded (bool, optional): Whether to expa... | [
"def",
"dimension_values",
"(",
"self",
",",
"dimension",
",",
"expanded",
"=",
"True",
",",
"flat",
"=",
"True",
")",
":",
"dimension",
"=",
"self",
".",
"get_dimension",
"(",
"dimension",
",",
"strict",
"=",
"True",
")",
".",
"name",
"all_dims",
"=",
... | 47.178571 | 21.964286 |
def save_docs(self, files=None, output_dir=None):
"""
Save documentation files for codebase into `output_dir`. If output
dir is None, it'll refrain from building the index page and build
the file(s) in the current directory.
If `files` is None, it'll build all files in the code... | [
"def",
"save_docs",
"(",
"self",
",",
"files",
"=",
"None",
",",
"output_dir",
"=",
"None",
")",
":",
"if",
"output_dir",
":",
"try",
":",
"os",
".",
"mkdir",
"(",
"output_dir",
")",
"except",
"OSError",
":",
"pass",
"try",
":",
"import",
"pkg_resource... | 37.547619 | 20.357143 |
def main(argv=None, directory=None):
"""
Main entry point for the tool, used by setup.py
Returns a value that can be passed into exit() specifying
the exit code.
1 is an error
0 is successful run
"""
logging.basicConfig(format='%(message)s')
argv = argv or sys.argv
... | [
"def",
"main",
"(",
"argv",
"=",
"None",
",",
"directory",
"=",
"None",
")",
":",
"logging",
".",
"basicConfig",
"(",
"format",
"=",
"'%(message)s'",
")",
"argv",
"=",
"argv",
"or",
"sys",
".",
"argv",
"arg_dict",
"=",
"parse_coverage_args",
"(",
"argv",... | 32.2 | 13.7 |
def dict(self):
"""Return dotenv as dict"""
if self._dict:
return self._dict
values = OrderedDict(self.parse())
self._dict = resolve_nested_variables(values)
return self._dict | [
"def",
"dict",
"(",
"self",
")",
":",
"if",
"self",
".",
"_dict",
":",
"return",
"self",
".",
"_dict",
"values",
"=",
"OrderedDict",
"(",
"self",
".",
"parse",
"(",
")",
")",
"self",
".",
"_dict",
"=",
"resolve_nested_variables",
"(",
"values",
")",
... | 27.625 | 15.5 |
def find_window_id(pattern, method='mru', error='raise'):
"""
xprop -id 0x00a00007 | grep "WM_CLASS(STRING)"
"""
import utool as ut
winid_candidates = XCtrl.findall_window_ids(pattern)
if len(winid_candidates) == 0:
if error == 'raise':
availab... | [
"def",
"find_window_id",
"(",
"pattern",
",",
"method",
"=",
"'mru'",
",",
"error",
"=",
"'raise'",
")",
":",
"import",
"utool",
"as",
"ut",
"winid_candidates",
"=",
"XCtrl",
".",
"findall_window_ids",
"(",
"pattern",
")",
"if",
"len",
"(",
"winid_candidates... | 42.772727 | 14.772727 |
def stem(self, word):
"""
Stem a Finnish word and return the stemmed form.
:param word: The word that is stemmed.
:type word: str or unicode
:return: The stemmed form.
:rtype: unicode
"""
word = word.lower()
step3_success = False
r1, r2... | [
"def",
"stem",
"(",
"self",
",",
"word",
")",
":",
"word",
"=",
"word",
".",
"lower",
"(",
")",
"step3_success",
"=",
"False",
"r1",
",",
"r2",
"=",
"self",
".",
"_r1r2_standard",
"(",
"word",
",",
"self",
".",
"__vowels",
")",
"# STEP 1: Particles etc... | 34.303318 | 14.218009 |
def apply(self, func, args=(), kwds=dict()):
"""Equivalent of the apply() builtin function. It blocks till
the result is ready."""
return self.apply_async(func, args, kwds).get() | [
"def",
"apply",
"(",
"self",
",",
"func",
",",
"args",
"=",
"(",
")",
",",
"kwds",
"=",
"dict",
"(",
")",
")",
":",
"return",
"self",
".",
"apply_async",
"(",
"func",
",",
"args",
",",
"kwds",
")",
".",
"get",
"(",
")"
] | 49.75 | 4.75 |
def execute(self, *args):
"""Executes single command and returns result."""
command, kwargs = self.parse(*args)
return self._commands.execute(command, **kwargs) | [
"def",
"execute",
"(",
"self",
",",
"*",
"args",
")",
":",
"command",
",",
"kwargs",
"=",
"self",
".",
"parse",
"(",
"*",
"args",
")",
"return",
"self",
".",
"_commands",
".",
"execute",
"(",
"command",
",",
"*",
"*",
"kwargs",
")"
] | 45.25 | 8.5 |
def _modifier(self, operator, params):
'''
$orderby: sorts the results of a query in ascending (1) or descending (-1) order.
'''
if operator == '$orderby':
order_types = {-1: 'DESC', 1: 'ASC'}
if not isinstance(params, dict):
raise RuntimeError... | [
"def",
"_modifier",
"(",
"self",
",",
"operator",
",",
"params",
")",
":",
"if",
"operator",
"==",
"'$orderby'",
":",
"order_types",
"=",
"{",
"-",
"1",
":",
"'DESC'",
",",
"1",
":",
"'ASC'",
"}",
"if",
"not",
"isinstance",
"(",
"params",
",",
"dict"... | 44.333333 | 26.333333 |
def union_overlapping(intervals):
"""Union any overlapping intervals in the given set."""
disjoint_intervals = []
for interval in intervals:
if disjoint_intervals and disjoint_intervals[-1].overlaps(interval):
disjoint_intervals[-1] = disjoint_intervals[-1].union(interval)
else:... | [
"def",
"union_overlapping",
"(",
"intervals",
")",
":",
"disjoint_intervals",
"=",
"[",
"]",
"for",
"interval",
"in",
"intervals",
":",
"if",
"disjoint_intervals",
"and",
"disjoint_intervals",
"[",
"-",
"1",
"]",
".",
"overlaps",
"(",
"interval",
")",
":",
"... | 35.363636 | 20.545455 |
def insert_resources(self, resources):
"""insert_resources(resources)
Insert all resources entries in the list RESOURCES into the
database. Each element in RESOURCES should be a tuple:
(resource, value)
Where RESOURCE is a string and VALUE can be any Python value.
... | [
"def",
"insert_resources",
"(",
"self",
",",
"resources",
")",
":",
"for",
"res",
",",
"value",
"in",
"resources",
":",
"self",
".",
"insert",
"(",
"res",
",",
"value",
")"
] | 27.428571 | 21.642857 |
def get_password_authentication_key(self, username, password, server_b_value, salt):
"""
Calculates the final hkdf based on computed S value, and computed U value and the key
:param {String} username Username.
:param {String} password Password.
:param {Long integer} server_b_valu... | [
"def",
"get_password_authentication_key",
"(",
"self",
",",
"username",
",",
"password",
",",
"server_b_value",
",",
"salt",
")",
":",
"u_value",
"=",
"calculate_u",
"(",
"self",
".",
"large_a_value",
",",
"server_b_value",
")",
"if",
"u_value",
"==",
"0",
":"... | 53.681818 | 23.318182 |
def destroy_volumes(role):
""" Destroys all volumes on all the slaves in the cluster for the role.
"""
state = dcos_agents_state()
if not state or 'slaves' not in state.keys():
return False
all_success = True
for agent in state['slaves']:
if not destroy_volume(agent, role):
... | [
"def",
"destroy_volumes",
"(",
"role",
")",
":",
"state",
"=",
"dcos_agents_state",
"(",
")",
"if",
"not",
"state",
"or",
"'slaves'",
"not",
"in",
"state",
".",
"keys",
"(",
")",
":",
"return",
"False",
"all_success",
"=",
"True",
"for",
"agent",
"in",
... | 32.636364 | 9.727273 |
def _fmt_serialization_call(self, data_type, input_value, serialize, depth=0):
"""Returns the appropriate serialization / deserialization method
call for the given data type."""
data_type, _ = unwrap_nullable(data_type)
serializer_func = 'serialize' if serialize else 'deserialize'
... | [
"def",
"_fmt_serialization_call",
"(",
"self",
",",
"data_type",
",",
"input_value",
",",
"serialize",
",",
"depth",
"=",
"0",
")",
":",
"data_type",
",",
"_",
"=",
"unwrap_nullable",
"(",
"data_type",
")",
"serializer_func",
"=",
"'serialize'",
"if",
"seriali... | 46.903226 | 18.548387 |
def xstep(self):
r"""Minimise Augmented Lagrangian with respect to :math:`\mathbf{x}`.
"""
self.cgit = None
self.YU[:] = self.Y - self.U
b = self.ZSf + self.rho*sl.rfftn(self.YU, None, self.cri.axisN)
self.Xf[:], cgit = sl.solvemdbi_cg(self.Zf, self.rho, b,
... | [
"def",
"xstep",
"(",
"self",
")",
":",
"self",
".",
"cgit",
"=",
"None",
"self",
".",
"YU",
"[",
":",
"]",
"=",
"self",
".",
"Y",
"-",
"self",
".",
"U",
"b",
"=",
"self",
".",
"ZSf",
"+",
"self",
".",
"rho",
"*",
"sl",
".",
"rfftn",
"(",
... | 45.357143 | 20.928571 |
def tmarker(self, lat, long, text, color=None, icon=None, style=None):
"""
Returns the map with a text marker to the default map
"""
try:
self.dsmap = self._marker(
lat, long, text, self.dsmap, color, icon, True, style)
return self.dsmap
ex... | [
"def",
"tmarker",
"(",
"self",
",",
"lat",
",",
"long",
",",
"text",
",",
"color",
"=",
"None",
",",
"icon",
"=",
"None",
",",
"style",
"=",
"None",
")",
":",
"try",
":",
"self",
".",
"dsmap",
"=",
"self",
".",
"_marker",
"(",
"lat",
",",
"long... | 39.6 | 15.6 |
def print_stats(correctness, confidence, name):
"""
Prints out accuracy, coverage, etc. statistics
:param correctness: ndarray
One bool per example specifying whether it was correctly classified
:param confidence: ndarray
The probability associated with each prediction
:param name: str
The name of... | [
"def",
"print_stats",
"(",
"correctness",
",",
"confidence",
",",
"name",
")",
":",
"accuracy",
"=",
"correctness",
".",
"mean",
"(",
")",
"wrongness",
"=",
"1",
"-",
"correctness",
"denom1",
"=",
"np",
".",
"maximum",
"(",
"1",
",",
"wrongness",
".",
... | 43.333333 | 15.454545 |
def home(self, *args, **kwargs):
"""
Home robot's head and plunger motors.
"""
# Home gantry first to avoid colliding with labware
# and to make sure tips are not in the liquid while
# homing plungers. Z/A axis will automatically home before X/Y
self.poses = self... | [
"def",
"home",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Home gantry first to avoid colliding with labware",
"# and to make sure tips are not in the liquid while",
"# homing plungers. Z/A axis will automatically home before X/Y",
"self",
".",
"poses",
... | 44.045455 | 20.318182 |
def assign_power_curve(self, wake_losses_model='power_efficiency_curve',
smoothing=False, block_width=0.5,
standard_deviation_method='turbulence_intensity',
smoothing_order='wind_farm_power_curves',
turbulence_in... | [
"def",
"assign_power_curve",
"(",
"self",
",",
"wake_losses_model",
"=",
"'power_efficiency_curve'",
",",
"smoothing",
"=",
"False",
",",
"block_width",
"=",
"0.5",
",",
"standard_deviation_method",
"=",
"'turbulence_intensity'",
",",
"smoothing_order",
"=",
"'wind_farm... | 53.321678 | 21.160839 |
def have_environment_marker_support():
"""
Check whether setuptools has support for PEP-426 environment marker support.
Based on the ``setup.py`` script of the ``pytest`` package:
https://bitbucket.org/pytest-dev/pytest/src/default/setup.py
"""
try:
from pkg_resources import parse_versi... | [
"def",
"have_environment_marker_support",
"(",
")",
":",
"try",
":",
"from",
"pkg_resources",
"import",
"parse_version",
"from",
"setuptools",
"import",
"__version__",
"return",
"parse_version",
"(",
"__version__",
")",
">=",
"parse_version",
"(",
"'0.7.2'",
")",
"e... | 35.692308 | 18.153846 |
def call_actions_parallel(self, service_name, actions, **kwargs):
"""
Build and send multiple job requests to one service, each job with one action, to be executed in parallel, and
return once all responses have been received.
Returns a list of action responses, one for each action in t... | [
"def",
"call_actions_parallel",
"(",
"self",
",",
"service_name",
",",
"actions",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"call_actions_parallel_future",
"(",
"service_name",
",",
"actions",
",",
"*",
"*",
"kwargs",
")",
".",
"result",
"(",... | 61.047619 | 34.809524 |
def get_methods_class(self, class_name):
"""
Return all methods of a specific class
:param class_name: the class name
:type class_name: string
:rtype: a list with :class:`EncodedMethod` objects
"""
l = []
for i in self.get_classes():
for j in... | [
"def",
"get_methods_class",
"(",
"self",
",",
"class_name",
")",
":",
"l",
"=",
"[",
"]",
"for",
"i",
"in",
"self",
".",
"get_classes",
"(",
")",
":",
"for",
"j",
"in",
"i",
".",
"get_methods",
"(",
")",
":",
"if",
"class_name",
"==",
"j",
".",
"... | 26.5625 | 14.4375 |
def _mirror_idx_cov(self, f_values, idx1): # will most likely be removed
"""obsolete and subject to removal (TODO),
return indices for negative ("active") update of the covariance matrix
assuming that ``f_values[idx1[i]]`` and ``f_values[-1-i]`` are
the corresponding mirrored values
... | [
"def",
"_mirror_idx_cov",
"(",
"self",
",",
"f_values",
",",
"idx1",
")",
":",
"# will most likely be removed",
"idx2",
"=",
"np",
".",
"arange",
"(",
"len",
"(",
"f_values",
")",
"-",
"1",
",",
"len",
"(",
"f_values",
")",
"-",
"1",
"-",
"len",
"(",
... | 48.192308 | 26.230769 |
def before_app_first_request(self, f):
"""Like :meth:`Flask.before_first_request`. Such a function is
executed before the first request to the application.
"""
self.record_once(lambda s: s.app.before_first_request_funcs.append(f))
return f | [
"def",
"before_app_first_request",
"(",
"self",
",",
"f",
")",
":",
"self",
".",
"record_once",
"(",
"lambda",
"s",
":",
"s",
".",
"app",
".",
"before_first_request_funcs",
".",
"append",
"(",
"f",
")",
")",
"return",
"f"
] | 45.833333 | 14.166667 |
def remove(self, node):
"""Remove a node from the list.
The *node* argument must be a node that was previously inserted in the
list
"""
if node is None or node._prev == -1:
return
if node._next is None:
self._last = node._prev # last node
... | [
"def",
"remove",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
"is",
"None",
"or",
"node",
".",
"_prev",
"==",
"-",
"1",
":",
"return",
"if",
"node",
".",
"_next",
"is",
"None",
":",
"self",
".",
"_last",
"=",
"node",
".",
"_prev",
"# last no... | 30.555556 | 14.666667 |
def project(*descs, root_file=None):
"""
Make a new project, using recursion and alias resolution.
Use this function in preference to calling Project() directly.
"""
load.ROOT_FILE = root_file
desc = merge.merge(merge.DEFAULT_PROJECT, *descs)
path = desc.get('path', '')
if root_file:
... | [
"def",
"project",
"(",
"*",
"descs",
",",
"root_file",
"=",
"None",
")",
":",
"load",
".",
"ROOT_FILE",
"=",
"root_file",
"desc",
"=",
"merge",
".",
"merge",
"(",
"merge",
".",
"DEFAULT_PROJECT",
",",
"*",
"descs",
")",
"path",
"=",
"desc",
".",
"get... | 25.083333 | 18 |
def get_nova_endpoint(cls, json_resp, nova_api_version=None):
"""
Parse the service catalog returned by the Identity API for an endpoint matching
the Nova service with the requested version
Sends a CRITICAL service check when no viable candidates are found in the Catalog
"""
... | [
"def",
"get_nova_endpoint",
"(",
"cls",
",",
"json_resp",
",",
"nova_api_version",
"=",
"None",
")",
":",
"nova_version",
"=",
"nova_api_version",
"or",
"DEFAULT_NOVA_API_VERSION",
"catalog",
"=",
"json_resp",
".",
"get",
"(",
"'token'",
",",
"{",
"}",
")",
".... | 47.653846 | 22.807692 |
def delete(self, record_key):
''' a method to delete a file
:param record_key: string with name of file
:return: string reporting outcome
'''
title = '%s.delete' % self.__class__.__name__
# validate inputs
input_fields = {
'record_key': record_key
... | [
"def",
"delete",
"(",
"self",
",",
"record_key",
")",
":",
"title",
"=",
"'%s.delete'",
"%",
"self",
".",
"__class__",
".",
"__name__",
"# validate inputs",
"input_fields",
"=",
"{",
"'record_key'",
":",
"record_key",
"}",
"for",
"key",
",",
"value",
"in",
... | 30.365385 | 19.903846 |
def stderrHandler(level, object, category, file, line, message):
"""
A log handler that writes to stderr.
@type level: string
@type object: string (or None)
@type category: string
@type message: string
"""
o = ""
if object:
o = '"' + object + '"'
where = "(%s:%d)... | [
"def",
"stderrHandler",
"(",
"level",
",",
"object",
",",
"category",
",",
"file",
",",
"line",
",",
"message",
")",
":",
"o",
"=",
"\"\"",
"if",
"object",
":",
"o",
"=",
"'\"'",
"+",
"object",
"+",
"'\"'",
"where",
"=",
"\"(%s:%d)\"",
"%",
"(",
"f... | 30.387097 | 19.354839 |
def generate_n_and_k_counters(max_order, species, central_symbols_prefix="M_", raw_symbols_prefix="x_"):
r"""
Makes a counter for central moments (n_counter) and a counter for raw moment (k_counter).
Each is a list of :class:`~means.approximation.ode_problem.Moment`s.
Therefore, each :cl... | [
"def",
"generate_n_and_k_counters",
"(",
"max_order",
",",
"species",
",",
"central_symbols_prefix",
"=",
"\"M_\"",
",",
"raw_symbols_prefix",
"=",
"\"x_\"",
")",
":",
"n_moments",
"=",
"max_order",
"+",
"1",
"# first order moments are always 1",
"k_counter",
"=",
"["... | 52.571429 | 32.061224 |
def get_rounded(self, digits):
""" Return a vector with the elements rounded to the given number of digits. """
result = self.copy()
result.round(digits)
return result | [
"def",
"get_rounded",
"(",
"self",
",",
"digits",
")",
":",
"result",
"=",
"self",
".",
"copy",
"(",
")",
"result",
".",
"round",
"(",
"digits",
")",
"return",
"result"
] | 39 | 10.6 |
def _complete_el(self, symbol, attribute, fullsymbol):
"""Suggests a list of completions based on the el_* attributes
of the user_context."""
if symbol != fullsymbol:
#We have a sym%sym%... chain and the completion just needs to
#be a member variable or method of the type... | [
"def",
"_complete_el",
"(",
"self",
",",
"symbol",
",",
"attribute",
",",
"fullsymbol",
")",
":",
"if",
"symbol",
"!=",
"fullsymbol",
":",
"#We have a sym%sym%... chain and the completion just needs to",
"#be a member variable or method of the type being referenced.",
"return",... | 50.210526 | 19.421053 |
def delete_pool_member(hostname, username, password, name, member):
'''
Delete an existing pool member.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to be modified
... | [
"def",
"delete_pool_member",
"(",
"hostname",
",",
"username",
",",
"password",
",",
"name",
",",
"member",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"False",
",",
"'comment'",
":",
"''",
... | 30.092308 | 21.476923 |
def _sub(cmd, *sections):
"""Build Subcmd instance."""
cmd_func = cmd if isfunction(cmd) else cmd.cmd
return Subcmd(baredoc(cmd), *sections, func=cmd_func) | [
"def",
"_sub",
"(",
"cmd",
",",
"*",
"sections",
")",
":",
"cmd_func",
"=",
"cmd",
"if",
"isfunction",
"(",
"cmd",
")",
"else",
"cmd",
".",
"cmd",
"return",
"Subcmd",
"(",
"baredoc",
"(",
"cmd",
")",
",",
"*",
"sections",
",",
"func",
"=",
"cmd_fun... | 41 | 10.5 |
def inFocus(self):
"""Set GUI on-top flag"""
previous_flags = self.window.flags()
self.window.setFlags(previous_flags |
QtCore.Qt.WindowStaysOnTopHint) | [
"def",
"inFocus",
"(",
"self",
")",
":",
"previous_flags",
"=",
"self",
".",
"window",
".",
"flags",
"(",
")",
"self",
".",
"window",
".",
"setFlags",
"(",
"previous_flags",
"|",
"QtCore",
".",
"Qt",
".",
"WindowStaysOnTopHint",
")"
] | 40 | 10.2 |
def maybe_run(self, job):
"""check location dependencies, and run if they are met."""
msg_id = job.msg_id
self.log.debug("Attempting to assign task %s", msg_id)
if not self.targets:
# no engines, definitely can't run
return False
if job.follow or ... | [
"def",
"maybe_run",
"(",
"self",
",",
"job",
")",
":",
"msg_id",
"=",
"job",
".",
"msg_id",
"self",
".",
"log",
".",
"debug",
"(",
"\"Attempting to assign task %s\"",
",",
"msg_id",
")",
"if",
"not",
"self",
".",
"targets",
":",
"# no engines, definitely can... | 40.181818 | 14.927273 |
def process_composite_comment(self, level, comments, key):
"""
Process comments for composites such as MAP, LAYER etc.
"""
if key not in comments:
comment = ""
else:
value = comments[key]
spacer = self.whitespace(level, 0)
if isins... | [
"def",
"process_composite_comment",
"(",
"self",
",",
"level",
",",
"comments",
",",
"key",
")",
":",
"if",
"key",
"not",
"in",
"comments",
":",
"comment",
"=",
"\"\"",
"else",
":",
"value",
"=",
"comments",
"[",
"key",
"]",
"spacer",
"=",
"self",
".",... | 32.882353 | 17.588235 |
def getDynLocal(name):
'''
Dynamically import a python module and return a local.
Example:
cls = getDynLocal('foopkg.barmod.BlahClass')
blah = cls()
'''
if name.find('.') == -1:
return None
modname, objname = name.rsplit('.', 1)
mod = getDynMod(modname)
if mod... | [
"def",
"getDynLocal",
"(",
"name",
")",
":",
"if",
"name",
".",
"find",
"(",
"'.'",
")",
"==",
"-",
"1",
":",
"return",
"None",
"modname",
",",
"objname",
"=",
"name",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"mod",
"=",
"getDynMod",
"(",
"modna... | 19.526316 | 23.842105 |
def updateNewCredentialValues(self):
"""
Set the new credential values to the credentials to use, and delete the new ones
"""
credentials_base = "disk.0.os.credentials."
new_credentials_base = "disk.0.os.credentials.new."
for elem in ['password', 'public_key', 'private_... | [
"def",
"updateNewCredentialValues",
"(",
"self",
")",
":",
"credentials_base",
"=",
"\"disk.0.os.credentials.\"",
"new_credentials_base",
"=",
"\"disk.0.os.credentials.new.\"",
"for",
"elem",
"in",
"[",
"'password'",
",",
"'public_key'",
",",
"'private_key'",
"]",
":",
... | 44.333333 | 23.166667 |
def find_subdirs(startdir='.', recursion_depth=None):
"""Find all subdirectory of a directory.
Inputs:
startdir: directory to start with. Defaults to the current folder.
recursion_depth: number of levels to traverse. None is infinite.
Output: a list of absolute names of subfolders.
Ex... | [
"def",
"find_subdirs",
"(",
"startdir",
"=",
"'.'",
",",
"recursion_depth",
"=",
"None",
")",
":",
"startdir",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"startdir",
")",
"direct_subdirs",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"startdir",
... | 36.896552 | 20.310345 |
def consider_member(name_member, member, module, class_=None):
"""Return |True| if the given member should be added to the
substitutions. If not return |False|.
Some examples based on the site-package |numpy|:
>>> from hydpy.core.autodoctools import Substituter
>>> import numpy... | [
"def",
"consider_member",
"(",
"name_member",
",",
"member",
",",
"module",
",",
"class_",
"=",
"None",
")",
":",
"if",
"name_member",
".",
"startswith",
"(",
"'_'",
")",
":",
"return",
"False",
"if",
"inspect",
".",
"ismodule",
"(",
"member",
")",
":",
... | 30.84 | 18.52 |
def main():
"""Main function to sweep parameters of a certain algorithm."""
parser = argparse.ArgumentParser(
description="Runs the speficied algorithm(s) on the MSAF "
"formatted dataset.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("in_path",
... | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"Runs the speficied algorithm(s) on the MSAF \"",
"\"formatted dataset.\"",
",",
"formatter_class",
"=",
"argparse",
".",
"ArgumentDefaultsHelpFormatter",
")",
"pars... | 41.818182 | 12.054545 |
def _check_pypi_version(self):
"""
When the version is out of date or we have trouble retrieving it print a error to stderr and pause.
"""
try:
check_version()
except VersionException as err:
print(str(err), file=sys.stderr)
time.sleep(TWO_SECO... | [
"def",
"_check_pypi_version",
"(",
"self",
")",
":",
"try",
":",
"check_version",
"(",
")",
"except",
"VersionException",
"as",
"err",
":",
"print",
"(",
"str",
"(",
"err",
")",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"time",
".",
"sleep",
"(",
... | 35.111111 | 14.222222 |
def valid_audio(y, mono=True):
'''Validate whether a variable contains valid, mono audio data.
Parameters
----------
y : np.ndarray
The input data to validate
mono : bool
Whether or not to force monophonic audio
Returns
-------
valid : bool
True if all tests pass
... | [
"def",
"valid_audio",
"(",
"y",
",",
"mono",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"y",
",",
"np",
".",
"ndarray",
")",
":",
"raise",
"ParameterError",
"(",
"'data must be of type numpy.ndarray'",
")",
"if",
"not",
"np",
".",
"issubdtype",... | 27.677419 | 24.096774 |
def gcs_files(prefix_filter=None):
"""List all files in GCS bucket."""
top_level_xml_str = download_gcs_file("", prefix_filter=prefix_filter)
xml_root = ElementTree.fromstring(top_level_xml_str)
filenames = [el[0].text for el in xml_root if el.tag.endswith("Contents")]
return filenames | [
"def",
"gcs_files",
"(",
"prefix_filter",
"=",
"None",
")",
":",
"top_level_xml_str",
"=",
"download_gcs_file",
"(",
"\"\"",
",",
"prefix_filter",
"=",
"prefix_filter",
")",
"xml_root",
"=",
"ElementTree",
".",
"fromstring",
"(",
"top_level_xml_str",
")",
"filenam... | 48.5 | 18.333333 |
def _configMailer(self):
""" Config Mailer Class """
self._MAILER = Mailer(self.MAILER_HOST, self.MAILER_PORT)
self._MAILER.login(self.MAILER_USER, self.MAILER_PWD) | [
"def",
"_configMailer",
"(",
"self",
")",
":",
"self",
".",
"_MAILER",
"=",
"Mailer",
"(",
"self",
".",
"MAILER_HOST",
",",
"self",
".",
"MAILER_PORT",
")",
"self",
".",
"_MAILER",
".",
"login",
"(",
"self",
".",
"MAILER_USER",
",",
"self",
".",
"MAILE... | 46.25 | 15.5 |
def get_marker_height(self):
"""
Gets the height of message marker.
"""
return self.editor.viewport().height() / TextHelper(
self.editor).line_count() | [
"def",
"get_marker_height",
"(",
"self",
")",
":",
"return",
"self",
".",
"editor",
".",
"viewport",
"(",
")",
".",
"height",
"(",
")",
"/",
"TextHelper",
"(",
"self",
".",
"editor",
")",
".",
"line_count",
"(",
")"
] | 31.5 | 6.166667 |
def normalize_mode(mode):
'''
Return a mode value, normalized to a string and containing a leading zero
if it does not have one.
Allow "keep" as a valid mode (used by file state/module to preserve mode
from the Salt fileserver in file states).
'''
if mode is None:
return None
if... | [
"def",
"normalize_mode",
"(",
"mode",
")",
":",
"if",
"mode",
"is",
"None",
":",
"return",
"None",
"if",
"not",
"isinstance",
"(",
"mode",
",",
"six",
".",
"string_types",
")",
":",
"mode",
"=",
"six",
".",
"text_type",
"(",
"mode",
")",
"if",
"six",... | 37.705882 | 22.058824 |
def payload(self):
"""The payload property automatically decodes the encapsulated data."""
if self.args_rdf_name:
# Now try to create the correct RDFValue.
result_cls = self.classes.get(self.args_rdf_name, rdfvalue.RDFString)
result = result_cls.FromSerializedString(
self.Get("args"... | [
"def",
"payload",
"(",
"self",
")",
":",
"if",
"self",
".",
"args_rdf_name",
":",
"# Now try to create the correct RDFValue.",
"result_cls",
"=",
"self",
".",
"classes",
".",
"get",
"(",
"self",
".",
"args_rdf_name",
",",
"rdfvalue",
".",
"RDFString",
")",
"re... | 39.222222 | 16.888889 |
def top_parents(papers, topn=20, verbose=False):
"""
Returns a list of :class:`.Paper` that cite the topn most cited papers.
Parameters
----------
papers : list
A list of :class:`.Paper` objects.
topn : int or float {0.-1.}
Number (int) or percentage (float) of top-cited papers.... | [
"def",
"top_parents",
"(",
"papers",
",",
"topn",
"=",
"20",
",",
"verbose",
"=",
"False",
")",
":",
"if",
"verbose",
":",
"print",
"\"Getting parents of top \"",
"+",
"unicode",
"(",
"topn",
")",
"+",
"\" most cited papers.\"",
"top",
",",
"counts",
"=",
... | 29.722222 | 21.5 |
def get_person_by_regid(self, regid):
"""
Returns a restclients.Person object for the given regid. If the
regid isn't found, or if there is an error communicating with the PWS,
a DataFailureException will be thrown.
"""
if not self.valid_uwregid(regid):
raise... | [
"def",
"get_person_by_regid",
"(",
"self",
",",
"regid",
")",
":",
"if",
"not",
"self",
".",
"valid_uwregid",
"(",
"regid",
")",
":",
"raise",
"InvalidRegID",
"(",
"regid",
")",
"url",
"=",
"\"{}/{}/full.json\"",
".",
"format",
"(",
"PERSON_PREFIX",
",",
"... | 39.25 | 19.375 |
def score_pairwise(aseq, bseq):
"""Compute pairwise distances between two sequences (raw strings)."""
assert len(aseq) == len(bseq)
# Affine gap penalties -- default values from EMBOSS needle/water
GAP_OPEN = -10.0
GAP_EXTEND = -0.5
GAP_CHARS = frozenset('-.')
score = 0.0
in_gap = True... | [
"def",
"score_pairwise",
"(",
"aseq",
",",
"bseq",
")",
":",
"assert",
"len",
"(",
"aseq",
")",
"==",
"len",
"(",
"bseq",
")",
"# Affine gap penalties -- default values from EMBOSS needle/water",
"GAP_OPEN",
"=",
"-",
"10.0",
"GAP_EXTEND",
"=",
"-",
"0.5",
"GAP_... | 31.5 | 20.411765 |
def solve(self):
'''
Solves a one period consumption saving problem with risky income and
shocks to medical need.
Parameters
----------
None
Returns
-------
solution : ConsumerSolution
The solution to the one period problem, including... | [
"def",
"solve",
"(",
"self",
")",
":",
"aLvl",
",",
"trash",
"=",
"self",
".",
"prepareToCalcEndOfPrdvP",
"(",
")",
"EndOfPrdvP",
"=",
"self",
".",
"calcEndOfPrdvP",
"(",
")",
"if",
"self",
".",
"vFuncBool",
":",
"self",
".",
"makeEndOfPrdvFunc",
"(",
"E... | 37.064516 | 21.83871 |
def ToJSon(self, columns_order=None, order_by=()):
"""Returns a string that can be used in a JS DataTable constructor.
This method writes a JSON string that can be passed directly into a Google
Visualization API DataTable constructor. Use this output if you are
hosting the visualization HTML on your si... | [
"def",
"ToJSon",
"(",
"self",
",",
"columns_order",
"=",
"None",
",",
"order_by",
"=",
"(",
")",
")",
":",
"encoded_response_str",
"=",
"DataTableJSONEncoder",
"(",
")",
".",
"encode",
"(",
"self",
".",
"_ToJSonObj",
"(",
"columns_order",
",",
"order_by",
... | 44.142857 | 22 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.