text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def on_click(self, event):
""" Override this method to do more interesting things with the event. """
DesktopNotification(
title=event.title,
body="{} until {}!".format(event.time_remaining, event.title),
icon='dialog-information',
urgency=1,
t... | [
"def",
"on_click",
"(",
"self",
",",
"event",
")",
":",
"DesktopNotification",
"(",
"title",
"=",
"event",
".",
"title",
",",
"body",
"=",
"\"{} until {}!\"",
".",
"format",
"(",
"event",
".",
"time_remaining",
",",
"event",
".",
"title",
")",
",",
"icon... | 37.888889 | 14.333333 |
def qgis_composer_html_renderer(impact_report, component):
"""HTML to PDF renderer using QGIS Composer.
Render using qgis composer for a given impact_report data and component
context for html input.
:param impact_report: ImpactReport contains data about the report that is
going to be generate... | [
"def",
"qgis_composer_html_renderer",
"(",
"impact_report",
",",
"component",
")",
":",
"context",
"=",
"component",
".",
"context",
"# QGIS3: not used",
"# qgis_composition_context = impact_report.qgis_composition_context",
"# create new layout with A4 portrait page",
"layout",
"=... | 36.986014 | 16.587413 |
def _init_weights(self,
X):
"""Set the weights and normalize data before starting training."""
X = np.asarray(X, dtype=np.float64)
if self.scaler is not None:
X = self.scaler.fit_transform(X)
if self.initializer is not None:
self.weights = ... | [
"def",
"_init_weights",
"(",
"self",
",",
"X",
")",
":",
"X",
"=",
"np",
".",
"asarray",
"(",
"X",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
"if",
"self",
".",
"scaler",
"is",
"not",
"None",
":",
"X",
"=",
"self",
".",
"scaler",
".",
"fit_t... | 29.066667 | 17.333333 |
def unsubscribe(self, transform="", downlink=False):
"""Unsubscribes from a previously subscribed stream. Note that the same values of transform
and downlink must be passed in order to do the correct unsubscribe::
s.subscribe(callback,transform="if last")
s.unsubscribe(transform... | [
"def",
"unsubscribe",
"(",
"self",
",",
"transform",
"=",
"\"\"",
",",
"downlink",
"=",
"False",
")",
":",
"streampath",
"=",
"self",
".",
"path",
"if",
"downlink",
":",
"streampath",
"+=",
"\"/downlink\"",
"return",
"self",
".",
"db",
".",
"unsubscribe",
... | 40.083333 | 16.416667 |
def check_with_pyflakes(source_code, filename=None):
"""Check source code with pyflakes
Returns an empty list if pyflakes is not installed"""
try:
if filename is None:
filename = '<string>'
try:
source_code += '\n'
except TypeError:
# Pyth... | [
"def",
"check_with_pyflakes",
"(",
"source_code",
",",
"filename",
"=",
"None",
")",
":",
"try",
":",
"if",
"filename",
"is",
"None",
":",
"filename",
"=",
"'<string>'",
"try",
":",
"source_code",
"+=",
"'\\n'",
"except",
"TypeError",
":",
"# Python 3\r",
"s... | 42.5625 | 17.833333 |
def delete_order_by_id(cls, order_id, **kwargs):
"""Delete Order
Delete an instance of Order by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_order_by_id(order_id, async=True)... | [
"def",
"delete_order_by_id",
"(",
"cls",
",",
"order_id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_delete_order_by_id_with_ht... | 39.809524 | 18.571429 |
def deepcopy(self):
"""
Create a deep copy of the PolygonsOnImage object.
Returns
-------
imgaug.PolygonsOnImage
Deep copy.
"""
# Manual copy is far faster than deepcopy for PolygonsOnImage,
# so use manual copy here too
polys = [poly... | [
"def",
"deepcopy",
"(",
"self",
")",
":",
"# Manual copy is far faster than deepcopy for PolygonsOnImage,",
"# so use manual copy here too",
"polys",
"=",
"[",
"poly",
".",
"deepcopy",
"(",
")",
"for",
"poly",
"in",
"self",
".",
"polygons",
"]",
"return",
"PolygonsOnI... | 28.714286 | 18.857143 |
def path(self, filename):
'''
This returns the absolute path of a file uploaded to this set. It
doesn't actually check whether said file exists.
:param filename: The filename to return the path for.
:param folder: The subfolder within the upload set previously used
... | [
"def",
"path",
"(",
"self",
",",
"filename",
")",
":",
"if",
"not",
"self",
".",
"backend",
".",
"root",
":",
"raise",
"OperationNotSupported",
"(",
"'Direct file access is not supported by '",
"+",
"self",
".",
"backend",
".",
"__class__",
".",
"__name__",
")... | 40.117647 | 22.823529 |
async def create_websocket_server(sock, filter=None): # pylint: disable=W0622
"""
A more low-level form of open_websocket_server.
You are responsible for closing this websocket.
"""
ws = Websocket()
await ws.start_server(sock, filter=filter)
return ws | [
"async",
"def",
"create_websocket_server",
"(",
"sock",
",",
"filter",
"=",
"None",
")",
":",
"# pylint: disable=W0622",
"ws",
"=",
"Websocket",
"(",
")",
"await",
"ws",
".",
"start_server",
"(",
"sock",
",",
"filter",
"=",
"filter",
")",
"return",
"ws"
] | 34.125 | 14.125 |
def from_hising(cls, h, J, offset=None):
"""Construct a binary polynomial from a higher-order Ising problem.
Args:
h (dict):
The linear biases.
J (dict):
The higher-order biases.
offset (optional, default=0.0):
Consta... | [
"def",
"from_hising",
"(",
"cls",
",",
"h",
",",
"J",
",",
"offset",
"=",
"None",
")",
":",
"poly",
"=",
"{",
"(",
"k",
",",
")",
":",
"v",
"for",
"k",
",",
"v",
"in",
"h",
".",
"items",
"(",
")",
"}",
"poly",
".",
"update",
"(",
"J",
")"... | 27.12 | 18.24 |
def update(self, date, data=None, inow=None):
"""
Update strategy. Updates prices, values, weight, etc.
"""
# resolve stale state
self.root.stale = False
# update helpers on date change
# also set newpt flag
newpt = False
if self.now == 0:
... | [
"def",
"update",
"(",
"self",
",",
"date",
",",
"data",
"=",
"None",
",",
"inow",
"=",
"None",
")",
":",
"# resolve stale state",
"self",
".",
"root",
".",
"stale",
"=",
"False",
"# update helpers on date change",
"# also set newpt flag",
"newpt",
"=",
"False"... | 34.825243 | 15.213592 |
def pageassert(func):
'''
Decorator that assert page number
'''
@wraps(func)
def wrapper(*args, **kwargs):
if args[0] < 1 or args[0] > 40:
raise ValueError('Page Number not found')
return func(*args, **kwargs)
return wrapper | [
"def",
"pageassert",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"args",
"[",
"0",
"]",
"<",
"1",
"or",
"args",
"[",
"0",
"]",
">",
"40",
":",
"raise",
... | 26.7 | 15.9 |
def get_upregulated_genes_network(self) -> Graph:
"""Get the graph of up-regulated genes.
:return Graph: Graph of up-regulated genes.
"""
logger.info("In get_upregulated_genes_network()")
deg_graph = self.graph.copy() # deep copy graph
not_diff_expr = self.graph.vs(up_... | [
"def",
"get_upregulated_genes_network",
"(",
"self",
")",
"->",
"Graph",
":",
"logger",
".",
"info",
"(",
"\"In get_upregulated_genes_network()\"",
")",
"deg_graph",
"=",
"self",
".",
"graph",
".",
"copy",
"(",
")",
"# deep copy graph",
"not_diff_expr",
"=",
"self... | 38.2 | 23.133333 |
def __retrieve(self, key):
''' Retrieve file location from cache DB
'''
with self.get_conn() as conn:
try:
c = conn.cursor()
if key is None:
c.execute("SELECT value FROM cache_entries WHERE key IS NULL")
else:
... | [
"def",
"__retrieve",
"(",
"self",
",",
"key",
")",
":",
"with",
"self",
".",
"get_conn",
"(",
")",
"as",
"conn",
":",
"try",
":",
"c",
"=",
"conn",
".",
"cursor",
"(",
")",
"if",
"key",
"is",
"None",
":",
"c",
".",
"execute",
"(",
"\"SELECT value... | 39.947368 | 18.263158 |
def perform_action(
self, action, machines, params, progress_title, success_title):
"""Perform the action on the set of machines."""
if len(machines) == 0:
return 0
with utils.Spinner() as context:
return self._async_perform_action(
context, ac... | [
"def",
"perform_action",
"(",
"self",
",",
"action",
",",
"machines",
",",
"params",
",",
"progress_title",
",",
"success_title",
")",
":",
"if",
"len",
"(",
"machines",
")",
"==",
"0",
":",
"return",
"0",
"with",
"utils",
".",
"Spinner",
"(",
")",
"as... | 43.111111 | 12.666667 |
def transform(self, X, lenscale=None):
"""
Apply the random basis to X.
Parameters
----------
X: ndarray
(N, d) array of observations where N is the number of samples, and
d is the dimensionality of X.
lenscale: scalar or ndarray, optional
... | [
"def",
"transform",
"(",
"self",
",",
"X",
",",
"lenscale",
"=",
"None",
")",
":",
"N",
",",
"D",
"=",
"X",
".",
"shape",
"lenscale",
"=",
"self",
".",
"_check_dim",
"(",
"D",
",",
"lenscale",
")",
"[",
":",
",",
"np",
".",
"newaxis",
"]",
"WX"... | 32.384615 | 21.230769 |
def imgAverage(images, copy=True):
'''
returns an image average
works on many, also unloaded images
minimises RAM usage
'''
i0 = images[0]
out = imread(i0, dtype='float')
if copy and id(i0) == id(out):
out = out.copy()
for i in images[1:]:
out += imread... | [
"def",
"imgAverage",
"(",
"images",
",",
"copy",
"=",
"True",
")",
":",
"i0",
"=",
"images",
"[",
"0",
"]",
"out",
"=",
"imread",
"(",
"i0",
",",
"dtype",
"=",
"'float'",
")",
"if",
"copy",
"and",
"id",
"(",
"i0",
")",
"==",
"id",
"(",
"out",
... | 22.6875 | 17.3125 |
def get_data_by_slug_or_404(model, slug, kind='', **kwargs):
"""Wrap get_data_by_slug, abort 404 if missing data."""
data = get_data_by_slug(model, slug, kind, **kwargs)
if not data:
abort(404)
return data | [
"def",
"get_data_by_slug_or_404",
"(",
"model",
",",
"slug",
",",
"kind",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"get_data_by_slug",
"(",
"model",
",",
"slug",
",",
"kind",
",",
"*",
"*",
"kwargs",
")",
"if",
"not",
"data",
":",
... | 28 | 23.375 |
def plot_figure(array, as_subplot, units, kpc_per_arcsec, figsize, aspect, cmap, norm, norm_min, norm_max,
linthresh, linscale, xticks_manual, yticks_manual):
"""Open a matplotlib figure and plot the array of data on it.
Parameters
-----------
array : data.array.scaled_array.ScaledArray... | [
"def",
"plot_figure",
"(",
"array",
",",
"as_subplot",
",",
"units",
",",
"kpc_per_arcsec",
",",
"figsize",
",",
"aspect",
",",
"cmap",
",",
"norm",
",",
"norm_min",
",",
"norm_max",
",",
"linthresh",
",",
"linscale",
",",
"xticks_manual",
",",
"yticks_manua... | 55.117647 | 36.019608 |
def import_cluster_template(self, api_cluster_template, add_repositories=False):
"""
Create a cluster according to the provided template
@param api_cluster_template: cluster template to import
@param add_repositories: if true the parcels repositories in the cluster template will be added.
@return: ... | [
"def",
"import_cluster_template",
"(",
"self",
",",
"api_cluster_template",
",",
"add_repositories",
"=",
"False",
")",
":",
"return",
"self",
".",
"_post",
"(",
"\"importClusterTemplate\"",
",",
"ApiCommand",
",",
"False",
",",
"api_cluster_template",
",",
"params"... | 52 | 30.8 |
def _FormatDateTime(self, event):
"""Formats the date to a datetime object without timezone information.
Note: timezone information must be removed due to lack of support
by xlsxwriter and Excel.
Args:
event (EventObject): event.
Returns:
datetime.datetime|str: date and time value or ... | [
"def",
"_FormatDateTime",
"(",
"self",
",",
"event",
")",
":",
"try",
":",
"datetime_object",
"=",
"datetime",
".",
"datetime",
"(",
"1970",
",",
"1",
",",
"1",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"tzinfo",
"=",
"pytz",
".",
"UTC",
")",
... | 35.111111 | 20.62963 |
def extract(self, name):
"""Get the contents of an entry.
NAME is an entry name.
Return the tuple (ispkg, contents).
For non-Python resoures, ispkg is meaningless (and 0).
Used by the import mechanism."""
if type(name) == type(''):
ndx = self.toc.... | [
"def",
"extract",
"(",
"self",
",",
"name",
")",
":",
"if",
"type",
"(",
"name",
")",
"==",
"type",
"(",
"''",
")",
":",
"ndx",
"=",
"self",
".",
"toc",
".",
"find",
"(",
"name",
")",
"if",
"ndx",
"==",
"-",
"1",
":",
"return",
"None",
"else"... | 34.592593 | 14.407407 |
def list_plugins(self):
"""Returns a sorted list of all plugins that are available in this
plugin source. This can be useful to automatically discover plugins
that are available and is usually used together with
:meth:`load_plugin`.
"""
rv = []
for _, modname, is... | [
"def",
"list_plugins",
"(",
"self",
")",
":",
"rv",
"=",
"[",
"]",
"for",
"_",
",",
"modname",
",",
"ispkg",
"in",
"pkgutil",
".",
"iter_modules",
"(",
"self",
".",
"mod",
".",
"__path__",
")",
":",
"rv",
".",
"append",
"(",
"modname",
")",
"return... | 41.5 | 16.8 |
def phylotree(self):
"""
Get the c++ PhyloTree object corresponding to this tree.
:return: PhyloTree instance
"""
if not self._phylotree or self._dirty:
try:
if ISPY3:
self._phylotree = PhyloTree(self.newick.encode(), self.rooted)
... | [
"def",
"phylotree",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_phylotree",
"or",
"self",
".",
"_dirty",
":",
"try",
":",
"if",
"ISPY3",
":",
"self",
".",
"_phylotree",
"=",
"PhyloTree",
"(",
"self",
".",
"newick",
".",
"encode",
"(",
")",
"... | 39.466667 | 18.266667 |
def _create_non_null_wrapper(name, t):
'creates type wrapper for non-null of given type'
def __new__(cls, json_data, selection_list=None):
if json_data is None:
raise ValueError(name + ' received null value')
return t(json_data, selection_list)
def __to_graphql_input__(value, in... | [
"def",
"_create_non_null_wrapper",
"(",
"name",
",",
"t",
")",
":",
"def",
"__new__",
"(",
"cls",
",",
"json_data",
",",
"selection_list",
"=",
"None",
")",
":",
"if",
"json_data",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"name",
"+",
"' received nul... | 37.733333 | 17.866667 |
def add_interface(self, interface):
"""Manually add or overwrite an interface definition from an Interface object.
:param interface: an Interface() object
"""
if not isinstance(interface, Interface):
raise TypeError
self._interfaces[interface.name] = interface | [
"def",
"add_interface",
"(",
"self",
",",
"interface",
")",
":",
"if",
"not",
"isinstance",
"(",
"interface",
",",
"Interface",
")",
":",
"raise",
"TypeError",
"self",
".",
"_interfaces",
"[",
"interface",
".",
"name",
"]",
"=",
"interface"
] | 30.6 | 16.5 |
def request_port_forward(self, address, port, handler=None):
"""
Ask the server to forward TCP connections from a listening port on
the server, across this SSH session.
If a handler is given, that handler is called from a different thread
whenever a forwarded connection arrives.... | [
"def",
"request_port_forward",
"(",
"self",
",",
"address",
",",
"port",
",",
"handler",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"active",
":",
"raise",
"SSHException",
"(",
"'SSH session not active'",
")",
"address",
"=",
"str",
"(",
"address",
"... | 41.590909 | 23.5 |
def atlasdb_get_random_peer( con=None, path=None ):
"""
Select a peer from the db at random
Return None if the table is empty
"""
ret = {}
with AtlasDBOpen(con=con, path=path) as dbcon:
num_peers = atlasdb_num_peers( con=con, path=path )
if num_peers is None or num_peers == 0:
... | [
"def",
"atlasdb_get_random_peer",
"(",
"con",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"}",
"with",
"AtlasDBOpen",
"(",
"con",
"=",
"con",
",",
"path",
"=",
"path",
")",
"as",
"dbcon",
":",
"num_peers",
"=",
"atlasdb_num_peers"... | 25.1 | 18.7 |
def get_state_paths(cls, impl, working_dir):
"""
Get the set of state paths that point to the current chain and state info.
Returns a list of paths.
"""
return [config.get_db_filename(impl, working_dir), config.get_snapshots_filename(impl, working_dir)] | [
"def",
"get_state_paths",
"(",
"cls",
",",
"impl",
",",
"working_dir",
")",
":",
"return",
"[",
"config",
".",
"get_db_filename",
"(",
"impl",
",",
"working_dir",
")",
",",
"config",
".",
"get_snapshots_filename",
"(",
"impl",
",",
"working_dir",
")",
"]"
] | 48 | 20.333333 |
def remover(self, id_tipo_acesso):
"""Removes access type by its identifier.
:param id_tipo_acesso: Access type identifier.
:return: None
:raise TipoAcessoError: Access type associated with equipment, cannot be removed.
:raise InvalidParameterError: Protocol value is invalid o... | [
"def",
"remover",
"(",
"self",
",",
"id_tipo_acesso",
")",
":",
"if",
"not",
"is_valid_int_param",
"(",
"id_tipo_acesso",
")",
":",
"raise",
"InvalidParameterError",
"(",
"u'Access type id is invalid or was not informed.'",
")",
"url",
"=",
"'tipoacesso/'",
"+",
"str"... | 38.272727 | 23.363636 |
def http_exception(channel, title):
"""
Creates an embed UI containing the 'too long' error message
Args:
channel (discord.Channel): The Discord channel to bind the embed to
title (str): The title of the embed
Returns:
ui (ui_embed.UI): The embed UI object
"""
# Create... | [
"def",
"http_exception",
"(",
"channel",
",",
"title",
")",
":",
"# Create embed UI object",
"gui",
"=",
"ui_embed",
".",
"UI",
"(",
"channel",
",",
"\"Too much help\"",
",",
"\"{} is too helpful! Try trimming some of the help messages.\"",
".",
"format",
"(",
"title",
... | 24.619048 | 22.619048 |
def set_key(key: str, value: str) -> dict:
"""Set or update a key in the conf.
For now only strings are supported.
We use to update the version number.
"""
if not _conf.path:
return {}
if "toml" in _conf.path:
with open(_conf.path, "r") as f:
parser = parse(f.read()... | [
"def",
"set_key",
"(",
"key",
":",
"str",
",",
"value",
":",
"str",
")",
"->",
"dict",
":",
"if",
"not",
"_conf",
".",
"path",
":",
"return",
"{",
"}",
"if",
"\"toml\"",
"in",
"_conf",
".",
"path",
":",
"with",
"open",
"(",
"_conf",
".",
"path",
... | 28.391304 | 11.521739 |
def long_press(self, on_element):
"""
Long press on an element.
:Args:
- on_element: The element to long press.
"""
self._actions.append(lambda: self._driver.execute(
Command.LONG_PRESS, {'element': on_element.id}))
return self | [
"def",
"long_press",
"(",
"self",
",",
"on_element",
")",
":",
"self",
".",
"_actions",
".",
"append",
"(",
"lambda",
":",
"self",
".",
"_driver",
".",
"execute",
"(",
"Command",
".",
"LONG_PRESS",
",",
"{",
"'element'",
":",
"on_element",
".",
"id",
"... | 28.8 | 14.8 |
def _to_epoch(self, ts):
"""
Adds a year to the syslog timestamp because syslog doesn't use years
:param ts: The timestamp to add a year to
:return: Date/time string that includes a year
"""
year = self.year
tmpts = "%s %s" % (ts, str(self.year))
new_tim... | [
"def",
"_to_epoch",
"(",
"self",
",",
"ts",
")",
":",
"year",
"=",
"self",
".",
"year",
"tmpts",
"=",
"\"%s %s\"",
"%",
"(",
"ts",
",",
"str",
"(",
"self",
".",
"year",
")",
")",
"new_time",
"=",
"int",
"(",
"calendar",
".",
"timegm",
"(",
"time"... | 35.473684 | 22.631579 |
def trunc_list(s: List) -> List:
"""Truncate lists to maximum length."""
if len(s) > max_list_size:
i = max_list_size // 2
j = i - 1
s = s[:i] + [ELLIPSIS] + s[-j:]
return s | [
"def",
"trunc_list",
"(",
"s",
":",
"List",
")",
"->",
"List",
":",
"if",
"len",
"(",
"s",
")",
">",
"max_list_size",
":",
"i",
"=",
"max_list_size",
"//",
"2",
"j",
"=",
"i",
"-",
"1",
"s",
"=",
"s",
"[",
":",
"i",
"]",
"+",
"[",
"ELLIPSIS",... | 29 | 11.428571 |
def xml_import(self,
filepath="",
xml_content=None,
markings=None,
identifier_ns_uri=None,
**kwargs):
"""
Import a STIX or CybOX xml from file <filepath> or a string passed as ``xml_content``
You c... | [
"def",
"xml_import",
"(",
"self",
",",
"filepath",
"=",
"\"\"",
",",
"xml_content",
"=",
"None",
",",
"markings",
"=",
"None",
",",
"identifier_ns_uri",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# Clear internal state such that same object can be reused for... | 45.679487 | 31.470085 |
def _analyze_all_function_features(self, all_funcs_completed=False):
"""
Iteratively analyze all changed functions, update their returning attribute, until a fix-point is reached (i.e.
no new returning/not-returning functions are found).
:return: None
"""
while True:
... | [
"def",
"_analyze_all_function_features",
"(",
"self",
",",
"all_funcs_completed",
"=",
"False",
")",
":",
"while",
"True",
":",
"new_changes",
"=",
"self",
".",
"_iteratively_analyze_function_features",
"(",
"all_funcs_completed",
"=",
"all_funcs_completed",
")",
"new_r... | 59.961538 | 39.307692 |
def decode_sequence(self,
source_encoded: mx.sym.Symbol,
source_encoded_lengths: mx.sym.Symbol,
source_encoded_max_length: int,
target_embed: mx.sym.Symbol,
target_embed_lengths: mx.sym.Symbol,
... | [
"def",
"decode_sequence",
"(",
"self",
",",
"source_encoded",
":",
"mx",
".",
"sym",
".",
"Symbol",
",",
"source_encoded_lengths",
":",
"mx",
".",
"sym",
".",
"Symbol",
",",
"source_encoded_max_length",
":",
"int",
",",
"target_embed",
":",
"mx",
".",
"sym",... | 60.15 | 31.35 |
def parse_args():
"""Parser/validator for the cmd line args."""
parser = get_parser()
if len(sys.argv) < 2:
parser.print_help()
warnings.warn('Too few arguments!', UserWarning)
parser.exit(1)
# parsing
try:
params = parser.parse_args()
except Exception as exc:
... | [
"def",
"parse_args",
"(",
")",
":",
"parser",
"=",
"get_parser",
"(",
")",
"if",
"len",
"(",
"sys",
".",
"argv",
")",
"<",
"2",
":",
"parser",
".",
"print_help",
"(",
")",
"warnings",
".",
"warn",
"(",
"'Too few arguments!'",
",",
"UserWarning",
")",
... | 33.962963 | 24.888889 |
def get_meta_content(self, metaName):
"""\
Extract a given meta content form document
"""
meta = self.parser.css_select(self.article.doc, metaName)
content = None
if meta is not None and len(meta) > 0:
content = self.parser.getAttribute(meta[0], 'content')
... | [
"def",
"get_meta_content",
"(",
"self",
",",
"metaName",
")",
":",
"meta",
"=",
"self",
".",
"parser",
".",
"css_select",
"(",
"self",
".",
"article",
".",
"doc",
",",
"metaName",
")",
"content",
"=",
"None",
"if",
"meta",
"is",
"not",
"None",
"and",
... | 27.071429 | 18.428571 |
def _generate_validation_scripts(self):
"""
Include the scripts used by solutions.
"""
id_script_list_validation_fields = (
AccessibleFormImplementation.ID_SCRIPT_LIST_VALIDATION_FIELDS
)
local = self.parser.find('head,body').first_result()
if local i... | [
"def",
"_generate_validation_scripts",
"(",
"self",
")",
":",
"id_script_list_validation_fields",
"=",
"(",
"AccessibleFormImplementation",
".",
"ID_SCRIPT_LIST_VALIDATION_FIELDS",
")",
"local",
"=",
"self",
".",
"parser",
".",
"find",
"(",
"'head,body'",
")",
".",
"f... | 39.317308 | 18.490385 |
def rescan_file(self, filename, sha256hash, apikey):
"""
just send the hash, check the date
"""
url = self.base_url + "file/rescan"
params = {
'apikey': apikey,
'resource': sha256hash
}
rate_limit_clear = self.rate_limit()
if rate_... | [
"def",
"rescan_file",
"(",
"self",
",",
"filename",
",",
"sha256hash",
",",
"apikey",
")",
":",
"url",
"=",
"self",
".",
"base_url",
"+",
"\"file/rescan\"",
"params",
"=",
"{",
"'apikey'",
":",
"apikey",
",",
"'resource'",
":",
"sha256hash",
"}",
"rate_lim... | 40.45 | 19.75 |
def _add_converted_units(self, dataframe, parameter, key='VALUE'):
"""Add an additional DATA_VALUE column with converted VALUEs"""
convert_unit = self.parameters.get_converter(parameter)
try:
log.debug("Adding unit converted DATA_VALUE to the data")
dataframe[key] = dataf... | [
"def",
"_add_converted_units",
"(",
"self",
",",
"dataframe",
",",
"parameter",
",",
"key",
"=",
"'VALUE'",
")",
":",
"convert_unit",
"=",
"self",
".",
"parameters",
".",
"get_converter",
"(",
"parameter",
")",
"try",
":",
"log",
".",
"debug",
"(",
"\"Addi... | 51.3 | 22.4 |
def _ratelimited_get(self, *args, **kwargs):
"""Perform get request, handling rate limiting."""
with self._ratelimiter:
resp = self.session.get(*args, **kwargs)
# It's possible that Space-Track will return HTTP status 500 with a
# query rate limit violation. This can happen ... | [
"def",
"_ratelimited_get",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"self",
".",
"_ratelimiter",
":",
"resp",
"=",
"self",
".",
"session",
".",
"get",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# It's possible t... | 43.518519 | 21.814815 |
def serializer_by_type_id(self, type_id):
"""
Find and return the serializer for the type-id
:param type_id: type-id the serializer
:return: the serializer
"""
if type_id <= 0:
indx = index_for_default_type(type_id)
serializer = self._constant_type... | [
"def",
"serializer_by_type_id",
"(",
"self",
",",
"type_id",
")",
":",
"if",
"type_id",
"<=",
"0",
":",
"indx",
"=",
"index_for_default_type",
"(",
"type_id",
")",
"serializer",
"=",
"self",
".",
"_constant_type_ids",
".",
"get",
"(",
"indx",
",",
"None",
... | 37.416667 | 7.916667 |
def crypto_sign_keypair(seed=None):
"""Return (verifying, secret) key from a given seed, or os.urandom(32)"""
if seed is None:
seed = os.urandom(PUBLICKEYBYTES)
else:
warnings.warn("ed25519ll should choose random seed.",
RuntimeWarning)
if len(seed) != 32:
r... | [
"def",
"crypto_sign_keypair",
"(",
"seed",
"=",
"None",
")",
":",
"if",
"seed",
"is",
"None",
":",
"seed",
"=",
"os",
".",
"urandom",
"(",
"PUBLICKEYBYTES",
")",
"else",
":",
"warnings",
".",
"warn",
"(",
"\"ed25519ll should choose random seed.\"",
",",
"Run... | 39 | 12.583333 |
def main():
"""Ideally we shouldn't lose the first second of events"""
with Input() as input_generator:
def extra_bytes_callback(string):
print('got extra bytes', repr(string))
print('type:', type(string))
input_generator.unget_bytes(string)
time.sleep(1)
... | [
"def",
"main",
"(",
")",
":",
"with",
"Input",
"(",
")",
"as",
"input_generator",
":",
"def",
"extra_bytes_callback",
"(",
"string",
")",
":",
"print",
"(",
"'got extra bytes'",
",",
"repr",
"(",
"string",
")",
")",
"print",
"(",
"'type:'",
",",
"type",
... | 41.583333 | 10.583333 |
def parameterSpace( self ):
"""Return the parameter space of the experiment as a list of dicts,
with each dict mapping each parameter name to a value.
:returns: the parameter space as a list of dicts"""
ps = self.parameters()
if len(ps) == 0:
return []
else:
... | [
"def",
"parameterSpace",
"(",
"self",
")",
":",
"ps",
"=",
"self",
".",
"parameters",
"(",
")",
"if",
"len",
"(",
"ps",
")",
"==",
"0",
":",
"return",
"[",
"]",
"else",
":",
"return",
"self",
".",
"_crossProduct",
"(",
"ps",
")"
] | 35.2 | 14.8 |
def add(self, name, definition):
""" Register a definition to the registry. Existing definitions are
replaced silently.
:param name: The name which can be used as reference in a validation
schema.
:type name: :class:`str`
:param definition: The definition.
... | [
"def",
"add",
"(",
"self",
",",
"name",
",",
"definition",
")",
":",
"self",
".",
"_storage",
"[",
"name",
"]",
"=",
"self",
".",
"_expand_definition",
"(",
"definition",
")"
] | 42.5 | 14.5 |
def get_supported_metrics_topic(self, name, topic_name):
'''
Retrieves the list of supported metrics for this namespace and topic
name:
Name of the service bus namespace.
topic_name:
Name of the service bus queue in this namespace.
'''
response = ... | [
"def",
"get_supported_metrics_topic",
"(",
"self",
",",
"name",
",",
"topic_name",
")",
":",
"response",
"=",
"self",
".",
"_perform_get",
"(",
"self",
".",
"_get_get_supported_metrics_topic_path",
"(",
"name",
",",
"topic_name",
")",
",",
"None",
")",
"return",... | 32.65 | 23.55 |
async def restore_storage_configuration(self):
"""
Restore machine's storage configuration to its initial state.
"""
self._data = await self._handler.restore_storage_configuration(
system_id=self.system_id) | [
"async",
"def",
"restore_storage_configuration",
"(",
"self",
")",
":",
"self",
".",
"_data",
"=",
"await",
"self",
".",
"_handler",
".",
"restore_storage_configuration",
"(",
"system_id",
"=",
"self",
".",
"system_id",
")"
] | 40.833333 | 11.5 |
def call_parallel(self, cdata, low):
'''
Call the state defined in the given cdata in parallel
'''
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name... | [
"def",
"call_parallel",
"(",
"self",
",",
"cdata",
",",
"low",
")",
":",
"# There are a number of possibilities to not have the cdata",
"# populated with what we might have expected, so just be smart",
"# enough to not raise another KeyError as the name is easily",
"# guessable and fallbac... | 40.565217 | 19.26087 |
def _prompt_placement(D, tt):
"""
Since automatic placement didn't work, find somewhere to place the model data manually with the help of the user.
:param dict D: Metadata
:param str tt: Table type
:return str _model_name: Chosen model name for placement
"""
_model_name = ""
# There was... | [
"def",
"_prompt_placement",
"(",
"D",
",",
"tt",
")",
":",
"_model_name",
"=",
"\"\"",
"# There wasn't a table name match, so we need prompts to fix it",
"_placement_options",
"=",
"_get_available_placements",
"(",
"D",
",",
"tt",
")",
"print",
"(",
"\"Please choose where... | 37.142857 | 18.928571 |
def execute(helper, config, args):
"""
Deletes an environment
"""
env_config = parse_env_config(config, args.environment)
environments_to_wait_for_term = []
environments = helper.get_environments()
for env in environments:
if env['EnvironmentName'] == args.environment:
... | [
"def",
"execute",
"(",
"helper",
",",
"config",
",",
"args",
")",
":",
"env_config",
"=",
"parse_env_config",
"(",
"config",
",",
"args",
".",
"environment",
")",
"environments_to_wait_for_term",
"=",
"[",
"]",
"environments",
"=",
"helper",
".",
"get_environm... | 36.222222 | 18.592593 |
def get(self, model_module, model_module_version, model_name, view_module, view_module_version, view_name):
"""Get a value"""
module_versions = self._registry[model_module]
# The python semver module doesn't work well, for example, it can't do match('3', '*')
# so we just take the first ... | [
"def",
"get",
"(",
"self",
",",
"model_module",
",",
"model_module_version",
",",
"model_name",
",",
"view_module",
",",
"view_module_version",
",",
"view_name",
")",
":",
"module_versions",
"=",
"self",
".",
"_registry",
"[",
"model_module",
"]",
"# The python se... | 60.75 | 23.3125 |
def _extract_tag_from_data(self, data, tag_name=b'packet'):
"""Gets data containing a (part of) tshark xml.
If the given tag is found in it, returns the tag data and the remaining data.
Otherwise returns None and the same data.
:param data: string of a partial tshark xml.
:retu... | [
"def",
"_extract_tag_from_data",
"(",
"self",
",",
"data",
",",
"tag_name",
"=",
"b'packet'",
")",
":",
"opening_tag",
"=",
"b'<'",
"+",
"tag_name",
"+",
"b'>'",
"closing_tag",
"=",
"opening_tag",
".",
"replace",
"(",
"b'<'",
",",
"b'</'",
")",
"tag_end",
... | 42.176471 | 16.058824 |
def default_value(self, type_name):
'''
Obtain the default value for some *type name*.
'''
uname = type_name.upper()
if uname == 'BOOLEAN':
return False
elif uname == 'INTEGER':
return 0
elif uname == 'REAL':
... | [
"def",
"default_value",
"(",
"self",
",",
"type_name",
")",
":",
"uname",
"=",
"type_name",
".",
"upper",
"(",
")",
"if",
"uname",
"==",
"'BOOLEAN'",
":",
"return",
"False",
"elif",
"uname",
"==",
"'INTEGER'",
":",
"return",
"0",
"elif",
"uname",
"==",
... | 27.083333 | 17.916667 |
def dumps(data, escape=False, **kwargs):
"""A wrapper around `json.dumps` that can handle objects that json
module is not aware.
This function is aware of a list of custom serializers that can be
registered by the API user, making it possible to convert any kind
of object to types that the json lib... | [
"def",
"dumps",
"(",
"data",
",",
"escape",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'sort_keys'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'sort_keys'",
"]",
"=",
"True",
"converted",
"=",
"json",
".",
"dumps",
"(",
"data",
",",
... | 43.363636 | 22.045455 |
def getResults(self, parFound = None):
'''
Function to obtain the Dictionarythat represents this object.
:param parFound: values to return.
:return: The output format will be like:
[{"type" : "i3visio.email", "value": "foo@bar.com", "attri... | [
"def",
"getResults",
"(",
"self",
",",
"parFound",
"=",
"None",
")",
":",
"# Defining a dictionary",
"results",
"=",
"[",
"]",
"# Defining a dictionary inside with a couple of fields: reg_exp for the regular expression and found_exp for the expressions found.",
"#results[self.name] =... | 46.681818 | 26.136364 |
def example_2_load_data(self):
"""
加载数据
"""
# 权重向量, w1代表神经网络的第一层,w2代表神经网络的第二层
self.w1 = Variable(random_normal([2, 3], stddev=1, seed=1))
self.w2 = Variable(random_normal([3, 1], stddev=1, seed=1))
# 特征向量, 区别是,这里不会在计算图中生成节点
#self.x = placeholder(float32, s... | [
"def",
"example_2_load_data",
"(",
"self",
")",
":",
"# 权重向量, w1代表神经网络的第一层,w2代表神经网络的第二层",
"self",
".",
"w1",
"=",
"Variable",
"(",
"random_normal",
"(",
"[",
"2",
",",
"3",
"]",
",",
"stddev",
"=",
"1",
",",
"seed",
"=",
"1",
")",
")",
"self",
".",
"w2... | 40.3 | 15.1 |
def list_domains():
'''
Return a list of virtual machine names on the minion
CLI Example:
.. code-block:: bash
salt '*' virt.list_domains
'''
data = __salt__['vmadm.list'](keyed=True)
vms = ["UUID TYPE RAM STATE ALIAS"]
for vm... | [
"def",
"list_domains",
"(",
")",
":",
"data",
"=",
"__salt__",
"[",
"'vmadm.list'",
"]",
"(",
"keyed",
"=",
"True",
")",
"vms",
"=",
"[",
"\"UUID TYPE RAM STATE ALIAS\"",
"]",
"for",
"vm",
"in",
"data",
":",
"vms"... | 29.380952 | 21.761905 |
def parse_input_file(text, variables=None):
""" Parser for a file with syntax somewhat similar to Drake."""
text = find_includes(text)
lines = text.splitlines()
tasks, linenumbers = find_tasks(lines)
preamble = [line for line in lines[:linenumbers[0]]]
logging.debug("Preamble:\n{}".format("\n".j... | [
"def",
"parse_input_file",
"(",
"text",
",",
"variables",
"=",
"None",
")",
":",
"text",
"=",
"find_includes",
"(",
"text",
")",
"lines",
"=",
"text",
".",
"splitlines",
"(",
")",
"tasks",
",",
"linenumbers",
"=",
"find_tasks",
"(",
"lines",
")",
"preamb... | 40.4 | 9.65 |
def movingSum(requestContext, seriesList, windowSize):
"""
Graphs the moving sum of a metric (or metrics) over a fixed number of
past points, or a time interval.
Takes one metric or a wildcard seriesList followed by a number N of
datapoints or a quoted string with a length of time like '1hour' or '... | [
"def",
"movingSum",
"(",
"requestContext",
",",
"seriesList",
",",
"windowSize",
")",
":",
"if",
"not",
"seriesList",
":",
"return",
"[",
"]",
"windowInterval",
"=",
"None",
"if",
"isinstance",
"(",
"windowSize",
",",
"six",
".",
"string_types",
")",
":",
... | 36.222222 | 21.68254 |
def get_token(self, token):
'''
Request a token from the master
'''
load = {}
load['token'] = token
load['cmd'] = 'get_token'
tdata = self._send_token_request(load)
return tdata | [
"def",
"get_token",
"(",
"self",
",",
"token",
")",
":",
"load",
"=",
"{",
"}",
"load",
"[",
"'token'",
"]",
"=",
"token",
"load",
"[",
"'cmd'",
"]",
"=",
"'get_token'",
"tdata",
"=",
"self",
".",
"_send_token_request",
"(",
"load",
")",
"return",
"t... | 25.888889 | 15.444444 |
def view(self, sort=None, purge=False, done=None, undone=None, **kwargs):
"""Handles the 'v' command.
:sort: Sort pattern.
:purge: Whether to purge items marked as 'done'.
:done: Done pattern.
:undone: Not done pattern.
:kwargs: Additional arguments to pass to the View o... | [
"def",
"view",
"(",
"self",
",",
"sort",
"=",
"None",
",",
"purge",
"=",
"False",
",",
"done",
"=",
"None",
",",
"undone",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"View",
"(",
"self",
".",
"model",
".",
"modify",
"(",
"sort",
"=",
"self... | 32.6 | 15.533333 |
def fit(self, X, y=None, groups=None):
"""Run fit with all sets of parameters.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Training vector, where n_samples is the number of samples and
n_features is the number of feature... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
",",
"groups",
"=",
"None",
")",
":",
"return",
"self",
".",
"_fit",
"(",
"X",
",",
"y",
",",
"groups",
",",
"ParameterGrid",
"(",
"self",
".",
"param_grid",
")",
")"
] | 40.263158 | 21.105263 |
def commit(self, offsets=None):
"""Commit offsets to kafka, blocking until success or error.
This commits offsets only to Kafka. The offsets committed using this API
will be used on the first fetch after every rebalance and also on
startup. As such, if you need to store offsets in anyth... | [
"def",
"commit",
"(",
"self",
",",
"offsets",
"=",
"None",
")",
":",
"assert",
"self",
".",
"config",
"[",
"'api_version'",
"]",
">=",
"(",
"0",
",",
"8",
",",
"1",
")",
",",
"'Requires >= Kafka 0.8.1'",
"assert",
"self",
".",
"config",
"[",
"'group_id... | 52.8 | 29.16 |
def correlate(self, signal):
"""
Correlate records against one or many one-dimensional arrays.
Parameters
----------
signal : array-like
One or more signals to correlate against.
"""
s = asarray(signal)
if s.ndim == 1:
if size(s) ... | [
"def",
"correlate",
"(",
"self",
",",
"signal",
")",
":",
"s",
"=",
"asarray",
"(",
"signal",
")",
"if",
"s",
".",
"ndim",
"==",
"1",
":",
"if",
"size",
"(",
"s",
")",
"!=",
"self",
".",
"shape",
"[",
"-",
"1",
"]",
":",
"raise",
"ValueError",
... | 37.222222 | 24.62963 |
def flatten(cls, stats):
"""Makes a flat statistics from the given statistics."""
flat_children = {}
for _stats in spread_stats(stats):
key = (_stats.name, _stats.filename, _stats.lineno, _stats.module)
try:
flat_stats = flat_children[key]
exce... | [
"def",
"flatten",
"(",
"cls",
",",
"stats",
")",
":",
"flat_children",
"=",
"{",
"}",
"for",
"_stats",
"in",
"spread_stats",
"(",
"stats",
")",
":",
"key",
"=",
"(",
"_stats",
".",
"name",
",",
"_stats",
".",
"filename",
",",
"_stats",
".",
"lineno",... | 48.470588 | 14.823529 |
def query(database, query, **client_args):
'''
Execute a query.
database
Name of the database to query on.
query
InfluxQL query string.
'''
client = _client(**client_args)
_result = client.query(query, database=database)
if isinstance(_result, collections.Sequence):
... | [
"def",
"query",
"(",
"database",
",",
"query",
",",
"*",
"*",
"client_args",
")",
":",
"client",
"=",
"_client",
"(",
"*",
"*",
"client_args",
")",
"_result",
"=",
"client",
".",
"query",
"(",
"query",
",",
"database",
"=",
"database",
")",
"if",
"is... | 28.8125 | 23.8125 |
def _assemble_translocation(stmt):
"""Assemble Translocation statements into text."""
agent_str = _assemble_agent_str(stmt.agent)
stmt_str = agent_str + ' translocates'
if stmt.from_location is not None:
stmt_str += ' from the ' + stmt.from_location
if stmt.to_location is not None:
s... | [
"def",
"_assemble_translocation",
"(",
"stmt",
")",
":",
"agent_str",
"=",
"_assemble_agent_str",
"(",
"stmt",
".",
"agent",
")",
"stmt_str",
"=",
"agent_str",
"+",
"' translocates'",
"if",
"stmt",
".",
"from_location",
"is",
"not",
"None",
":",
"stmt_str",
"+... | 43.111111 | 5.333333 |
def transitively_reduce(self):
"""
Performs a transitive reduction on the graph.
"""
removals = set()
for from_node, neighbors in self._edges.items():
childpairs = \
[(c1, c2) for c1 in neighbors for c2 in neighbors if c1 != c2]
for child... | [
"def",
"transitively_reduce",
"(",
"self",
")",
":",
"removals",
"=",
"set",
"(",
")",
"for",
"from_node",
",",
"neighbors",
"in",
"self",
".",
"_edges",
".",
"items",
"(",
")",
":",
"childpairs",
"=",
"[",
"(",
"c1",
",",
"c2",
")",
"for",
"c1",
"... | 33.647059 | 17.176471 |
def ppdict(dict_to_print, br='\n', html=False, key_align='l', sort_keys=True,
key_preffix='', key_suffix='', value_prefix='', value_suffix='', left_margin=3, indent=2):
"""Indent representation of a dict"""
if dict_to_print:
if sort_keys:
dic = dict_to_print.copy()
key... | [
"def",
"ppdict",
"(",
"dict_to_print",
",",
"br",
"=",
"'\\n'",
",",
"html",
"=",
"False",
",",
"key_align",
"=",
"'l'",
",",
"sort_keys",
"=",
"True",
",",
"key_preffix",
"=",
"''",
",",
"key_suffix",
"=",
"''",
",",
"value_prefix",
"=",
"''",
",",
... | 37.351351 | 24.891892 |
def deletesystemhook(self, hook_id):
"""
Delete a project hook
:param hook_id: hook id
:return: True if success
"""
data = {"id": hook_id}
request = requests.delete(
'{0}/{1}'.format(self.hook_url, hook_id), data=data,
headers=self.header... | [
"def",
"deletesystemhook",
"(",
"self",
",",
"hook_id",
")",
":",
"data",
"=",
"{",
"\"id\"",
":",
"hook_id",
"}",
"request",
"=",
"requests",
".",
"delete",
"(",
"'{0}/{1}'",
".",
"format",
"(",
"self",
".",
"hook_url",
",",
"hook_id",
")",
",",
"data... | 27.705882 | 18.176471 |
def _remove_processed_data(
self):
"""*remove processed data*
"""
self.log.info('starting the ``_remove_processed_data`` method')
archivePath = self.settings["atlas archive path"]
from fundamentals.mysql import readquery
sqlQuery = u"""
select mj... | [
"def",
"_remove_processed_data",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'starting the ``_remove_processed_data`` method'",
")",
"archivePath",
"=",
"self",
".",
"settings",
"[",
"\"atlas archive path\"",
"]",
"from",
"fundamentals",
".",
"mysq... | 28.84127 | 18.904762 |
def get_allowed(allow, disallow):
""" Normalize the given string attributes as a list of all allowed vClasses."""
if allow is None and disallow is None:
return SUMO_VEHICLE_CLASSES
elif disallow is None:
return allow.split()
else:
disallow = disallow.split()
return tuple(... | [
"def",
"get_allowed",
"(",
"allow",
",",
"disallow",
")",
":",
"if",
"allow",
"is",
"None",
"and",
"disallow",
"is",
"None",
":",
"return",
"SUMO_VEHICLE_CLASSES",
"elif",
"disallow",
"is",
"None",
":",
"return",
"allow",
".",
"split",
"(",
")",
"else",
... | 40.777778 | 12.444444 |
def dictionize(fields: Sequence, records: Sequence) -> Generator:
"""Create dictionaries mapping fields to record data."""
return (dict(zip(fields, rec)) for rec in records) | [
"def",
"dictionize",
"(",
"fields",
":",
"Sequence",
",",
"records",
":",
"Sequence",
")",
"->",
"Generator",
":",
"return",
"(",
"dict",
"(",
"zip",
"(",
"fields",
",",
"rec",
")",
")",
"for",
"rec",
"in",
"records",
")"
] | 44.75 | 19.75 |
async def from_href(self):
"""Get the full object from spotify with a `href` attribute."""
if not hasattr(self, 'href'):
raise TypeError('Spotify object has no `href` attribute, therefore cannot be retrived')
elif hasattr(self, 'http'):
return await self.http.request(('G... | [
"async",
"def",
"from_href",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'href'",
")",
":",
"raise",
"TypeError",
"(",
"'Spotify object has no `href` attribute, therefore cannot be retrived'",
")",
"elif",
"hasattr",
"(",
"self",
",",
"'http'... | 32.952381 | 24.238095 |
def nalu(x, depth, epsilon=1e-30, name=None, reuse=None):
"""NALU as in https://arxiv.org/abs/1808.00508."""
with tf.variable_scope(name, default_name="nalu", values=[x], reuse=reuse):
x_shape = shape_list(x)
x_flat = tf.reshape(x, [-1, x_shape[-1]])
gw = tf.get_variable("w", [x_shape[-1], depth])
g... | [
"def",
"nalu",
"(",
"x",
",",
"depth",
",",
"epsilon",
"=",
"1e-30",
",",
"name",
"=",
"None",
",",
"reuse",
"=",
"None",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",
"default_name",
"=",
"\"nalu\"",
",",
"values",
"=",
"[",
"x"... | 46.083333 | 8.25 |
def set_address(self, address):
"""
Set the address of the remote host the is contacted, without
changing hostname, username, password, protocol, and TCP port
number.
This is the actual address that is used to open the connection.
:type address: string
:param ad... | [
"def",
"set_address",
"(",
"self",
",",
"address",
")",
":",
"if",
"is_ip",
"(",
"address",
")",
":",
"self",
".",
"address",
"=",
"clean_ip",
"(",
"address",
")",
"else",
":",
"self",
".",
"address",
"=",
"address"
] | 33.5 | 16.357143 |
def frequency2fractional(frequency, mean_frequency=-1):
""" Convert frequency in Hz to fractional frequency
Parameters
----------
frequency: np.array
Data array of frequency in Hz
mean_frequency: float
(optional) The nominal mean frequency, in Hz
if omitted, defaults to mean... | [
"def",
"frequency2fractional",
"(",
"frequency",
",",
"mean_frequency",
"=",
"-",
"1",
")",
":",
"if",
"mean_frequency",
"==",
"-",
"1",
":",
"mu",
"=",
"np",
".",
"mean",
"(",
"frequency",
")",
"else",
":",
"mu",
"=",
"mean_frequency",
"y",
"=",
"[",
... | 25.545455 | 18.545455 |
def get_monomers(self, ligands=True, pseudo_group=False):
"""Retrieves all the `Monomers` from the `Assembly` object.
Parameters
----------
ligands : bool, optional
If `true`, will include ligand `Monomers`.
pseudo_group : bool, optional
If `True`, will i... | [
"def",
"get_monomers",
"(",
"self",
",",
"ligands",
"=",
"True",
",",
"pseudo_group",
"=",
"False",
")",
":",
"base_filters",
"=",
"dict",
"(",
"ligands",
"=",
"ligands",
",",
"pseudo_group",
"=",
"pseudo_group",
")",
"restricted_mol_types",
"=",
"[",
"x",
... | 43.3125 | 18.0625 |
def valid_body_waiting(self):
"""
Check if a valid body is waiting in buffer
"""
# 0f f8 be 04 00 08 00 00 2f 04
packet_size = velbus.MINIMUM_MESSAGE_SIZE + \
(self.buffer[3] & 0x0F)
if len(self.buffer) < packet_size:
self.logger.debug("Buffer does... | [
"def",
"valid_body_waiting",
"(",
"self",
")",
":",
"# 0f f8 be 04 00 08 00 00 2f 04",
"packet_size",
"=",
"velbus",
".",
"MINIMUM_MESSAGE_SIZE",
"+",
"(",
"self",
".",
"buffer",
"[",
"3",
"]",
"&",
"0x0F",
")",
"if",
"len",
"(",
"self",
".",
"buffer",
")",
... | 42.619048 | 16.809524 |
def setup(product_name):
"""Setup logging."""
if CONF.log_config:
_load_log_config(CONF.log_config)
else:
_setup_logging_from_conf()
sys.excepthook = _create_logging_excepthook(product_name) | [
"def",
"setup",
"(",
"product_name",
")",
":",
"if",
"CONF",
".",
"log_config",
":",
"_load_log_config",
"(",
"CONF",
".",
"log_config",
")",
"else",
":",
"_setup_logging_from_conf",
"(",
")",
"sys",
".",
"excepthook",
"=",
"_create_logging_excepthook",
"(",
"... | 30.857143 | 13.142857 |
def SystemShare():
"""
Register AntShare.
Returns:
RegisterTransaction:
"""
amount = Fixed8.FromDecimal(sum(Blockchain.GENERATION_AMOUNT) * Blockchain.DECREMENT_INTERVAL)
owner = ECDSA.secp256r1().Curve.Infinity
admin = Crypto.ToScriptHash(PUSHT)
... | [
"def",
"SystemShare",
"(",
")",
":",
"amount",
"=",
"Fixed8",
".",
"FromDecimal",
"(",
"sum",
"(",
"Blockchain",
".",
"GENERATION_AMOUNT",
")",
"*",
"Blockchain",
".",
"DECREMENT_INTERVAL",
")",
"owner",
"=",
"ECDSA",
".",
"secp256r1",
"(",
")",
".",
"Curv... | 42.307692 | 23.384615 |
def set_progress(self, progress):
"""Update the progress for this application.
For applications processing a fixed set of work it may be useful for
diagnostics to set the progress as the application processes.
Progress indicates job progression, and must be a float between 0 and
... | [
"def",
"set_progress",
"(",
"self",
",",
"progress",
")",
":",
"if",
"not",
"(",
"0",
"<=",
"progress",
"<=",
"1.0",
")",
":",
"raise",
"ValueError",
"(",
"\"progress must be between 0 and 1, got %.3f\"",
"%",
"progress",
")",
"self",
".",
"_call",
"(",
"'Se... | 43.45 | 23.2 |
def paintEvent(self, event):
""" Fills the panel background. """
super(EncodingPanel, self).paintEvent(event)
if self.isVisible():
# fill background
painter = QtGui.QPainter(self)
self._background_brush = QtGui.QBrush(self._color)
painter.fillRect(... | [
"def",
"paintEvent",
"(",
"self",
",",
"event",
")",
":",
"super",
"(",
"EncodingPanel",
",",
"self",
")",
".",
"paintEvent",
"(",
"event",
")",
"if",
"self",
".",
"isVisible",
"(",
")",
":",
"# fill background",
"painter",
"=",
"QtGui",
".",
"QPainter",... | 43.75 | 12.125 |
def write(self, x):
"""Write a string into the output stream."""
if self._new_lines:
if not self._first_write:
self.stream.write('\n' * self._new_lines)
self.code_lineno += self._new_lines
if self._write_debug_info is not None:
... | [
"def",
"write",
"(",
"self",
",",
"x",
")",
":",
"if",
"self",
".",
"_new_lines",
":",
"if",
"not",
"self",
".",
"_first_write",
":",
"self",
".",
"stream",
".",
"write",
"(",
"'\\n'",
"*",
"self",
".",
"_new_lines",
")",
"self",
".",
"code_lineno",
... | 44.857143 | 12.714286 |
def is_valid(cls, oid):
"""Checks if a `oid` string is valid or not.
:Parameters:
- `oid`: the object id to validate
.. versionadded:: 2.3
"""
if not oid:
return False
try:
ObjectId(oid)
return True
except (InvalidI... | [
"def",
"is_valid",
"(",
"cls",
",",
"oid",
")",
":",
"if",
"not",
"oid",
":",
"return",
"False",
"try",
":",
"ObjectId",
"(",
"oid",
")",
"return",
"True",
"except",
"(",
"InvalidId",
",",
"TypeError",
")",
":",
"return",
"False"
] | 21.5 | 17.9375 |
def execute_command(args, shell=False, cwd=None, env=None, stdin=None, stdout=None, stderr=None, cmd_encoding='utf-8'):
"""
Execute external command
:param args: command line arguments : [unicode]
:param shell: True when using shell : boolean
:param cwd: working directory : string
:param env: en... | [
"def",
"execute_command",
"(",
"args",
",",
"shell",
"=",
"False",
",",
"cwd",
"=",
"None",
",",
"env",
"=",
"None",
",",
"stdin",
"=",
"None",
",",
"stdout",
"=",
"None",
",",
"stderr",
"=",
"None",
",",
"cmd_encoding",
"=",
"'utf-8'",
")",
":",
"... | 44.75 | 16.625 |
def setLegendData(self, *args, **kwargs):
""" Set or genernate the legend data from this canteen.
Uses :py:func:`.buildLegend` for genernating """
self.legendData = buildLegend(*args, key=self.legendKeyFunc, **kwargs) | [
"def",
"setLegendData",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"legendData",
"=",
"buildLegend",
"(",
"*",
"args",
",",
"key",
"=",
"self",
".",
"legendKeyFunc",
",",
"*",
"*",
"kwargs",
")"
] | 60.5 | 9.75 |
def _getSegmentActiveSynapses(self, c, i, s, activeState, newSynapses=False):
"""
Return a segmentUpdate data structure containing a list of proposed
changes to segment s. Let activeSynapses be the list of active synapses
where the originating cells have their activeState output = 1 at time step
t. ... | [
"def",
"_getSegmentActiveSynapses",
"(",
"self",
",",
"c",
",",
"i",
",",
"s",
",",
"activeState",
",",
"newSynapses",
"=",
"False",
")",
":",
"activeSynapses",
"=",
"[",
"]",
"if",
"s",
"is",
"not",
"None",
":",
"# s can be None, if adding a new segment",
"... | 43.186047 | 24.767442 |
def chart(
symbols=("AAPL", "GLD", "GOOG", "$SPX", "XOM", "msft"),
start=datetime.datetime(2008, 1, 1),
end=datetime.datetime(2009, 12, 31), # data stops at 2013/1/1
normalize=True,
):
"""Display a graph of the price history for the list of ticker symbols provided
Arguments:
symbols... | [
"def",
"chart",
"(",
"symbols",
"=",
"(",
"\"AAPL\"",
",",
"\"GLD\"",
",",
"\"GOOG\"",
",",
"\"$SPX\"",
",",
"\"XOM\"",
",",
"\"msft\"",
")",
",",
"start",
"=",
"datetime",
".",
"datetime",
"(",
"2008",
",",
"1",
",",
"1",
")",
",",
"end",
"=",
"da... | 35.605263 | 21.026316 |
def initializenb():
""" Find input files and log initialization info """
logger.info('Working directory: {0}'.format(os.getcwd()))
logger.info('Run on {0}'.format(asctime()))
try:
fileroot = os.environ['fileroot']
logger.info('Setting fileroot to {0} from environment variable.\n'.format... | [
"def",
"initializenb",
"(",
")",
":",
"logger",
".",
"info",
"(",
"'Working directory: {0}'",
".",
"format",
"(",
"os",
".",
"getcwd",
"(",
")",
")",
")",
"logger",
".",
"info",
"(",
"'Run on {0}'",
".",
"format",
"(",
"asctime",
"(",
")",
")",
")",
... | 47.28 | 23.12 |
def frame_generator(frame_duration_ms, audio, sample_rate):
"""Generates audio frames from PCM audio data.
Takes the desired frame duration in milliseconds, the PCM data, and
the sample rate.
Yields Frames of the requested duration.
"""
n = int(sample_rate * (frame_duration_ms / 1000.0) * 2)
... | [
"def",
"frame_generator",
"(",
"frame_duration_ms",
",",
"audio",
",",
"sample_rate",
")",
":",
"n",
"=",
"int",
"(",
"sample_rate",
"*",
"(",
"frame_duration_ms",
"/",
"1000.0",
")",
"*",
"2",
")",
"offset",
"=",
"0",
"timestamp",
"=",
"0.0",
"duration",
... | 33.5 | 18.0625 |
def create_sobol_samples(order, dim, seed=1):
"""
Args:
order (int):
Number of unique samples to generate.
dim (int):
Number of spacial dimensions. Must satisfy ``0 < dim < 41``.
seed (int):
Starting seed. Non-positive values are treated as 1. If omitt... | [
"def",
"create_sobol_samples",
"(",
"order",
",",
"dim",
",",
"seed",
"=",
"1",
")",
":",
"assert",
"0",
"<",
"dim",
"<",
"DIM_MAX",
",",
"\"dim in [1, 40]\"",
"# global RANDOM_SEED # pylint: disable=global-statement",
"# if seed is None:",
"# seed = RANDOM_SEED",
... | 31.424658 | 18.328767 |
def find_font(face, bold, italic):
"""Find font"""
bold = FC_WEIGHT_BOLD if bold else FC_WEIGHT_REGULAR
italic = FC_SLANT_ITALIC if italic else FC_SLANT_ROMAN
face = face.encode('utf8')
fontconfig.FcInit()
pattern = fontconfig.FcPatternCreate()
fontconfig.FcPatternAddInteger(pattern, FC_WEIG... | [
"def",
"find_font",
"(",
"face",
",",
"bold",
",",
"italic",
")",
":",
"bold",
"=",
"FC_WEIGHT_BOLD",
"if",
"bold",
"else",
"FC_WEIGHT_REGULAR",
"italic",
"=",
"FC_SLANT_ITALIC",
"if",
"italic",
"else",
"FC_SLANT_ROMAN",
"face",
"=",
"face",
".",
"encode",
"... | 43.814815 | 16.148148 |
def getRecommendedRenderTargetSize(self):
"""Suggested size for the intermediate render target that the distortion pulls from."""
fn = self.function_table.getRecommendedRenderTargetSize
pnWidth = c_uint32()
pnHeight = c_uint32()
fn(byref(pnWidth), byref(pnHeight))
return... | [
"def",
"getRecommendedRenderTargetSize",
"(",
"self",
")",
":",
"fn",
"=",
"self",
".",
"function_table",
".",
"getRecommendedRenderTargetSize",
"pnWidth",
"=",
"c_uint32",
"(",
")",
"pnHeight",
"=",
"c_uint32",
"(",
")",
"fn",
"(",
"byref",
"(",
"pnWidth",
")... | 42.875 | 11.75 |
def vsearch_chimera_filter_de_novo(
fasta_filepath,
working_dir,
output_chimeras=True,
output_nonchimeras=True,
output_alns=False,
output_tabular=False,
log_name="vsearch_uchime_de_novo_chimera_filtering.log",
HALT_EXEC=False):
""" Detect chimeras present in the fasta-formatted filen... | [
"def",
"vsearch_chimera_filter_de_novo",
"(",
"fasta_filepath",
",",
"working_dir",
",",
"output_chimeras",
"=",
"True",
",",
"output_nonchimeras",
"=",
"True",
",",
"output_alns",
"=",
"False",
",",
"output_tabular",
"=",
"False",
",",
"log_name",
"=",
"\"vsearch_u... | 37.857143 | 18.263736 |
def insert(self, index, item):
"""Insert an item at the specified index.
Args:
index (int): Position to insert the item.
item: Item to be inserted. It must have the type specified in the
constructor.
Raises:
:exc:`~.exceptions.WrongListItemTy... | [
"def",
"insert",
"(",
"self",
",",
"index",
",",
"item",
")",
":",
"if",
"issubclass",
"(",
"item",
".",
"__class__",
",",
"self",
".",
"_pyof_class",
")",
":",
"list",
".",
"insert",
"(",
"self",
",",
"index",
",",
"item",
")",
"else",
":",
"raise... | 37.333333 | 23 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.