text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def _create(self, **kwargs):
'''Allow creation of draft policy and ability to publish a draft
Draft policies only exist in 12.1.0 and greater versions of TMOS.
But there must be a method to create a draft, then publish it.
:raises: MissingRequiredCreationParameter
'''
... | [
"def",
"_create",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"tmos_ver",
"=",
"self",
".",
"_meta_data",
"[",
"'bigip'",
"]",
".",
"_meta_data",
"[",
"'tmos_version'",
"]",
"legacy",
"=",
"kwargs",
".",
"pop",
"(",
"'legacy'",
",",
"False",
")",
... | 44.178571 | 0.001582 |
def clear_i2b2_tables(tables: I2B2Tables, uploadid: int) -> None:
"""
Remove all entries in the i2b2 tables for uploadid.
:param tables:
:param uploadid:
:return:
"""
# This is a static function to support the removefacts operation
print("Deleted {} patient_dimension records"
.... | [
"def",
"clear_i2b2_tables",
"(",
"tables",
":",
"I2B2Tables",
",",
"uploadid",
":",
"int",
")",
"->",
"None",
":",
"# This is a static function to support the removefacts operation",
"print",
"(",
"\"Deleted {} patient_dimension records\"",
".",
"format",
"(",
"PatientDimen... | 46.5 | 0.001171 |
def convert_html_to_text(value, preserve_urls=False):
r"""
>>> convert_html_to_text(
... '''
... <html><body>
... Look & click
... <a href="https://example.com">here</a>
... </body></html>''', preserve_urls=True)
'Look & click here (https://example.com)'
... | [
"def",
"convert_html_to_text",
"(",
"value",
",",
"preserve_urls",
"=",
"False",
")",
":",
"s",
"=",
"MLStripper",
"(",
"preserve_urls",
"=",
"preserve_urls",
")",
"s",
".",
"feed",
"(",
"value",
")",
"s",
".",
"close",
"(",
")",
"return",
"s",
".",
"g... | 33.945946 | 0.000387 |
def vstack_tables(filelist, hdus):
"""vstack a set of HDUs from a set of files
Parameters
----------
filelist : list
List of the files to get data from.
hdus : list
Names of the HDU containing the table with the input data.
Returns
-------
out_tables : list
A... | [
"def",
"vstack_tables",
"(",
"filelist",
",",
"hdus",
")",
":",
"nfiles",
"=",
"len",
"(",
"filelist",
")",
"out_tables",
"=",
"[",
"]",
"out_names",
"=",
"[",
"]",
"for",
"hdu",
"in",
"hdus",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"'Working o... | 24.930233 | 0.000898 |
def _compute_bounds(self, axis, view):
"""Get the bounds
Parameters
----------
mode : str
Describes the type of boundary requested. Can be "visual", "data",
or "mouse".
axis : 0, 1, 2
The axis along which to measure the bounding values, in
... | [
"def",
"_compute_bounds",
"(",
"self",
",",
"axis",
",",
"view",
")",
":",
"# Can and should we calculate bounds?",
"if",
"(",
"self",
".",
"_bounds",
"is",
"None",
")",
"and",
"self",
".",
"_pos",
"is",
"not",
"None",
":",
"pos",
"=",
"self",
".",
"_pos... | 32.44 | 0.002395 |
def mrc_header_from_params(shape, dtype, kind, **kwargs):
"""Create a minimal MRC2014 header from the given parameters.
Parameters
----------
shape : 3-sequence of ints
3D shape of the stored data. The values are used as
``'nx', 'ny', 'nz'`` header entries, in this order. Note that
... | [
"def",
"mrc_header_from_params",
"(",
"shape",
",",
"dtype",
",",
"kind",
",",
"*",
"*",
"kwargs",
")",
":",
"# Positional args",
"shape",
"=",
"[",
"int",
"(",
"n",
")",
"for",
"n",
"in",
"shape",
"]",
"kind",
",",
"kind_in",
"=",
"str",
"(",
"kind"... | 43.678832 | 0.000163 |
def batch_slice(dist, params_event_ndims, params_overrides, slices):
"""Slices `dist` along its batch dimensions. Helper for tfd.Distribution.
Args:
dist: A `tfd.Distribution` instance.
params_event_ndims: A `dict` of `str->int` indicating the number of
dimensions of a given parameter required to par... | [
"def",
"batch_slice",
"(",
"dist",
",",
"params_event_ndims",
",",
"params_overrides",
",",
"slices",
")",
":",
"if",
"not",
"isinstance",
"(",
"slices",
",",
"collections",
".",
"Sequence",
")",
":",
"slices",
"=",
"(",
"slices",
",",
")",
"# We track the h... | 48.222222 | 0.009036 |
def parse_blast_tab(filename, fraglengths, identity, coverage, mode="ANIb"):
"""Returns (alignment length, similarity errors, mean_pid) tuple
from .blast_tab
- filename - path to .blast_tab file
Calculate the alignment length and total number of similarity errors (as
we would with ANIm), as well a... | [
"def",
"parse_blast_tab",
"(",
"filename",
",",
"fraglengths",
",",
"identity",
",",
"coverage",
",",
"mode",
"=",
"\"ANIb\"",
")",
":",
"# Assuming that the filename format holds org1_vs_org2.blast_tab:",
"qname",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"os",... | 41.547368 | 0.000742 |
def group_delays(stream_list):
"""
Group template waveforms according to their arrival times (delays).
:type stream_list: list
:param stream_list:
List of :class:`obspy.core.stream.Stream` waveforms you want to group.
:returns:
list of List of :class:`obspy.core.stream.Stream` wher... | [
"def",
"group_delays",
"(",
"stream_list",
")",
":",
"groups",
"=",
"[",
"]",
"group_delays",
"=",
"[",
"]",
"group_chans",
"=",
"[",
"]",
"# Sort templates by number of channels",
"stream_list",
"=",
"[",
"(",
"st",
",",
"len",
"(",
"st",
")",
")",
"for",... | 41.763158 | 0.000308 |
def find_config(config_path: str) -> str:
"""
Derive configuration file path from the given path and check its existence.
The given path is expected to be either
1. path to the file
2. path to a dir, in such case the path is joined with ``CXF_CONFIG_FILE``
:param config_path: path to the conf... | [
"def",
"find_config",
"(",
"config_path",
":",
"str",
")",
"->",
"str",
":",
"if",
"path",
".",
"isdir",
"(",
"config_path",
")",
":",
"# dir specified instead of config file",
"config_path",
"=",
"path",
".",
"join",
"(",
"config_path",
",",
"CXF_CONFIG_FILE",
... | 39.625 | 0.001541 |
def head_account(self, headers=None, query=None, cdn=False):
"""
HEADs the account and returns the results. Useful headers
returned are:
=========================== =================================
x-account-bytes-used Object storage used for the
... | [
"def",
"head_account",
"(",
"self",
",",
"headers",
"=",
"None",
",",
"query",
"=",
"None",
",",
"cdn",
"=",
"False",
")",
":",
"return",
"self",
".",
"request",
"(",
"'HEAD'",
",",
"''",
",",
"''",
",",
"headers",
",",
"query",
"=",
"query",
",",
... | 43.657143 | 0.00128 |
def get_class_attributes(cls):
"""Return a generator for class attributes' names and value.
This method strict relies on the PEP 520 (Preserving Class Attribute
Definition Order), implemented on Python 3.6. So, if this behaviour
changes this whole lib can loose its functionality (since ... | [
"def",
"get_class_attributes",
"(",
"cls",
")",
":",
"#: see this method docstring for a important notice about the use of",
"#: cls.__dict__",
"for",
"name",
",",
"value",
"in",
"cls",
".",
"__dict__",
".",
"items",
"(",
")",
":",
"# gets only our (kytos) attributes. this ... | 43.538462 | 0.001729 |
async def close(self):
'''Close any of open connections'''
if self._ws is not None:
await self._ws.close()
if self.polygon is not None:
await self.polygon.close() | [
"async",
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_ws",
"is",
"not",
"None",
":",
"await",
"self",
".",
"_ws",
".",
"close",
"(",
")",
"if",
"self",
".",
"polygon",
"is",
"not",
"None",
":",
"await",
"self",
".",
"polygon",
".",... | 34.166667 | 0.009524 |
def _connect_control_flow_node(control_flow_node, next_node):
"""Connect a ControlFlowNode properly to the next_node."""
for last in control_flow_node.last_nodes:
if isinstance(next_node, ControlFlowNode):
last.connect(next_node.test) # connect to next if test case
elif isinstance(n... | [
"def",
"_connect_control_flow_node",
"(",
"control_flow_node",
",",
"next_node",
")",
":",
"for",
"last",
"in",
"control_flow_node",
".",
"last_nodes",
":",
"if",
"isinstance",
"(",
"next_node",
",",
"ControlFlowNode",
")",
":",
"last",
".",
"connect",
"(",
"nex... | 50.636364 | 0.001764 |
def random_size_crop(src, size, min_area=0.25, ratio=(3.0/4.0, 4.0/3.0)):
"""Randomly crop src with size. Randomize area and aspect ratio"""
h, w, _ = src.shape
area = w*h
for _ in range(10):
new_area = random.uniform(min_area, 1.0) * area
new_ratio = random.uniform(*ratio)
new_w... | [
"def",
"random_size_crop",
"(",
"src",
",",
"size",
",",
"min_area",
"=",
"0.25",
",",
"ratio",
"=",
"(",
"3.0",
"/",
"4.0",
",",
"4.0",
"/",
"3.0",
")",
")",
":",
"h",
",",
"w",
",",
"_",
"=",
"src",
".",
"shape",
"area",
"=",
"w",
"*",
"h",... | 31.521739 | 0.001339 |
def num_signups(self):
"""How many people have signed up?"""
return EighthSignup.objects.filter(scheduled_activity__block=self, user__in=User.objects.get_students()).count() | [
"def",
"num_signups",
"(",
"self",
")",
":",
"return",
"EighthSignup",
".",
"objects",
".",
"filter",
"(",
"scheduled_activity__block",
"=",
"self",
",",
"user__in",
"=",
"User",
".",
"objects",
".",
"get_students",
"(",
")",
")",
".",
"count",
"(",
")"
] | 62.333333 | 0.015873 |
def metadataURL(self, value):
"""gets/sets the public metadata url"""
if value != self._metadataURL:
self._metadataURL = value
self._metaFS = None | [
"def",
"metadataURL",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"!=",
"self",
".",
"_metadataURL",
":",
"self",
".",
"_metadataURL",
"=",
"value",
"self",
".",
"_metaFS",
"=",
"None"
] | 36.4 | 0.010753 |
def create_search_index(self, index, schema=None, n_val=None,
timeout=None):
"""
Create a Solr search index for Yokozuna.
:param index: a name of a yz index
:type index: string
:param schema: XML of Solr schema
:type schema: string
:pa... | [
"def",
"create_search_index",
"(",
"self",
",",
"index",
",",
"schema",
"=",
"None",
",",
"n_val",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"yz_wm_index",
":",
"raise",
"NotImplementedError",
"(",
"\"Search 2.0 administra... | 32.594595 | 0.002415 |
def extract(self, file_obj, extractOnly=True, handler='update/extract', **kwargs):
"""
POSTs a file to the Solr ExtractingRequestHandler so rich content can
be processed using Apache Tika. See the Solr wiki for details:
http://wiki.apache.org/solr/ExtractingRequestHandler
T... | [
"def",
"extract",
"(",
"self",
",",
"file_obj",
",",
"extractOnly",
"=",
"True",
",",
"handler",
"=",
"'update/extract'",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"hasattr",
"(",
"file_obj",
",",
"\"name\"",
")",
":",
"raise",
"ValueError",
"(",
... | 40.5 | 0.001555 |
def bind(self, lan):
"""bind to a LAN."""
if _debug: Node._debug("bind %r", lan)
lan.add_node(self) | [
"def",
"bind",
"(",
"self",
",",
"lan",
")",
":",
"if",
"_debug",
":",
"Node",
".",
"_debug",
"(",
"\"bind %r\"",
",",
"lan",
")",
"lan",
".",
"add_node",
"(",
"self",
")"
] | 24 | 0.024194 |
def get(key, default=None):
"""
Searches os.environ. If a key is found try evaluating its type else;
return the string.
returns: k->value (type as defined by ast.literal_eval)
"""
try:
# Attempt to evaluate into python literal
return ast.literal_eval(os.environ.get(k... | [
"def",
"get",
"(",
"key",
",",
"default",
"=",
"None",
")",
":",
"try",
":",
"# Attempt to evaluate into python literal",
"return",
"ast",
".",
"literal_eval",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"key",
".",
"upper",
"(",
")",
",",
"default",
")"... | 35 | 0.00232 |
def make_step(
net,
step_size = 1.5,
end = "inception_4c/output",
jitter = 32,
clip = True,
objective = objective_L2
):
'''
basic gradient ascent step
'''
src = net.blobs["data"]
dst = net.blobs[end]
ox, oy = np.random.randint(- jitter, jitter + 1, 2)... | [
"def",
"make_step",
"(",
"net",
",",
"step_size",
"=",
"1.5",
",",
"end",
"=",
"\"inception_4c/output\"",
",",
"jitter",
"=",
"32",
",",
"clip",
"=",
"True",
",",
"objective",
"=",
"objective_L2",
")",
":",
"src",
"=",
"net",
".",
"blobs",
"[",
"\"data... | 26.40625 | 0.023973 |
def ReadPathInfoHistory(self, client_id, path_type, components):
"""Reads a collection of hash and stat entry for given path.
Args:
client_id: An identifier string for a client.
path_type: A type of a path to retrieve path history for.
components: A tuple of path components corresponding to p... | [
"def",
"ReadPathInfoHistory",
"(",
"self",
",",
"client_id",
",",
"path_type",
",",
"components",
")",
":",
"histories",
"=",
"self",
".",
"ReadPathInfosHistories",
"(",
"client_id",
",",
"path_type",
",",
"[",
"components",
"]",
")",
"return",
"histories",
"[... | 40.142857 | 0.001739 |
def is_valid_export_dir(self):
"""
export_dir={export_dir} must refer to a directory,
and the user must have the permission to write on it.
"""
if self.export_dir and not os.path.isabs(self.export_dir):
self.export_dir = os.path.normpath(
os.path.join(... | [
"def",
"is_valid_export_dir",
"(",
"self",
")",
":",
"if",
"self",
".",
"export_dir",
"and",
"not",
"os",
".",
"path",
".",
"isabs",
"(",
"self",
".",
"export_dir",
")",
":",
"self",
".",
"export_dir",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"o... | 42.095238 | 0.002212 |
def newDocNodeEatName(self, doc, name, content):
"""Creation of a new node element within a document. @ns and
@content are optional (None). NOTE: @content is supposed to
be a piece of XML CDATA, so it allow entities references,
but XML special chars need to be escaped first by usin... | [
"def",
"newDocNodeEatName",
"(",
"self",
",",
"doc",
",",
"name",
",",
"content",
")",
":",
"if",
"doc",
"is",
"None",
":",
"doc__o",
"=",
"None",
"else",
":",
"doc__o",
"=",
"doc",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"xmlNewDocNodeEatName",
"(",... | 53.538462 | 0.008475 |
def color_code(self, fore=None, back=None, style=None):
""" Return the codes for this style/colors. """
# Map from style type to raw code formatter function.
colorcodes = []
resetcodes = []
userstyles = {'style': style, 'back': back, 'fore': fore}
for stype in userstyles:... | [
"def",
"color_code",
"(",
"self",
",",
"fore",
"=",
"None",
",",
"back",
"=",
"None",
",",
"style",
"=",
"None",
")",
":",
"# Map from style type to raw code formatter function.",
"colorcodes",
"=",
"[",
"]",
"resetcodes",
"=",
"[",
"]",
"userstyles",
"=",
"... | 44.909091 | 0.001982 |
def _sample(self, maxIter=1000, c1=1.193, c2=1.193, lookback = 0.25, standard_dev = None):
"""
Launches the PSO. Yields the complete swarm per iteration
:param maxIter: maximum iterations
:param c1: cognitive weight
:param c2: social weight
:param lookback: percentange o... | [
"def",
"_sample",
"(",
"self",
",",
"maxIter",
"=",
"1000",
",",
"c1",
"=",
"1.193",
",",
"c2",
"=",
"1.193",
",",
"lookback",
"=",
"0.25",
",",
"standard_dev",
"=",
"None",
")",
":",
"self",
".",
"_get_fitness",
"(",
"self",
".",
"swarm",
")",
"i"... | 36.056604 | 0.008151 |
def id_pools_vmac_ranges(self):
"""
Gets the IdPoolsRanges API Client for VMAC Ranges.
Returns:
IdPoolsRanges:
"""
if not self.__id_pools_vmac_ranges:
self.__id_pools_vmac_ranges = IdPoolsRanges('vmac', self.__connection)
return self.__id_pools_vm... | [
"def",
"id_pools_vmac_ranges",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"__id_pools_vmac_ranges",
":",
"self",
".",
"__id_pools_vmac_ranges",
"=",
"IdPoolsRanges",
"(",
"'vmac'",
",",
"self",
".",
"__connection",
")",
"return",
"self",
".",
"__id_pools_v... | 32 | 0.009119 |
def _get_sleep(self, poller, timeout, block, rsock, wsock, cookie):
"""
When a result is not immediately available, sleep waiting for
:meth:`put` to write a byte to our socket pair.
"""
_vv and IOLOG.debug(
'%r._get_sleep(timeout=%r, block=%r, rfd=%d, wfd=%d)',
... | [
"def",
"_get_sleep",
"(",
"self",
",",
"poller",
",",
"timeout",
",",
"block",
",",
"rsock",
",",
"wsock",
",",
"cookie",
")",
":",
"_vv",
"and",
"IOLOG",
".",
"debug",
"(",
"'%r._get_sleep(timeout=%r, block=%r, rfd=%d, wfd=%d)'",
",",
"self",
",",
"timeout",
... | 33.52381 | 0.00207 |
def radio_calibration_send(self, aileron, elevator, rudder, gyro, pitch, throttle, force_mavlink1=False):
'''
Complete set of calibration parameters for the radio
aileron : Aileron setpoints: left, center, right (uint16_t)
elevator ... | [
"def",
"radio_calibration_send",
"(",
"self",
",",
"aileron",
",",
"elevator",
",",
"rudder",
",",
"gyro",
",",
"pitch",
",",
"throttle",
",",
"force_mavlink1",
"=",
"False",
")",
":",
"return",
"self",
".",
"send",
"(",
"self",
".",
"radio_calibration_encod... | 72.230769 | 0.010515 |
def add_search_index_criteria(prepend=False):
"""
Add the search criteria used when calling :meth:`register() <cqparts.search.register>`
on a :class:`Component <cqparts.Component>` as a table to the *docstring*.
This is only intended to be used with *sphinx autodoc*.
In your *sphinx* ``config.py``... | [
"def",
"add_search_index_criteria",
"(",
"prepend",
"=",
"False",
")",
":",
"from",
".",
".",
"search",
"import",
"class_criteria",
"from",
".",
".",
"import",
"Component",
"COLUMN_INFO",
"=",
"[",
"# (<title>, <width>, <method>),",
"(",
"'Key'",
",",
"50",
",",... | 33.634146 | 0.002113 |
def argunique(items, key=None):
"""
Returns indices corresponding to the first instance of each unique item.
Args:
items (Sequence): indexable collection of items
key (Callable, optional): custom normalization function.
If specified returns items where `key(item)` is unique.
... | [
"def",
"argunique",
"(",
"items",
",",
"key",
"=",
"None",
")",
":",
"# yield from unique(range(len(items)), key=lambda i: items[i])",
"if",
"key",
"is",
"None",
":",
"return",
"unique",
"(",
"range",
"(",
"len",
"(",
"items",
")",
")",
",",
"key",
"=",
"lam... | 33.84 | 0.001149 |
def close(self):
"""Shutdown and free all resources."""
for controller in self._controllers:
controller.quit()
self._controllers = []
for process in self._processes:
process.close()
self._processes = []
portspicker.return_ports(self._lan_ports)
self._lan_ports = [] | [
"def",
"close",
"(",
"self",
")",
":",
"for",
"controller",
"in",
"self",
".",
"_controllers",
":",
"controller",
".",
"quit",
"(",
")",
"self",
".",
"_controllers",
"=",
"[",
"]",
"for",
"process",
"in",
"self",
".",
"_processes",
":",
"process",
".",... | 24.666667 | 0.009772 |
def reload(self, client=None):
"""Reload properties from Cloud Storage.
If :attr:`user_project` is set, bills the API request to that project.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: the client to use. If not pass... | [
"def",
"reload",
"(",
"self",
",",
"client",
"=",
"None",
")",
":",
"client",
"=",
"self",
".",
"_require_client",
"(",
"client",
")",
"query_params",
"=",
"self",
".",
"_query_params",
"# Pass only '?projection=noAcl' here because 'acl' and related",
"# are handled v... | 40.217391 | 0.002112 |
def make_job(
name: str = '',
run_name: str = '',
num_tasks: int = 1,
install_script: str = '',
instance_type: str = '',
image_name: str = '',
create_resources=True,
**kwargs) -> Job:
"""
Args:
create_resources: if True, will create resources if ne... | [
"def",
"make_job",
"(",
"name",
":",
"str",
"=",
"''",
",",
"run_name",
":",
"str",
"=",
"''",
",",
"num_tasks",
":",
"int",
"=",
"1",
",",
"install_script",
":",
"str",
"=",
"''",
",",
"instance_type",
":",
"str",
"=",
"''",
",",
"image_name",
":"... | 34.225 | 0.012425 |
def copy(self):
""" Return a new instance of this gene with the same DNA. """
return type(self)(self.dna, suppressed=self.suppressed, name=self.name) | [
"def",
"copy",
"(",
"self",
")",
":",
"return",
"type",
"(",
"self",
")",
"(",
"self",
".",
"dna",
",",
"suppressed",
"=",
"self",
".",
"suppressed",
",",
"name",
"=",
"self",
".",
"name",
")"
] | 54.333333 | 0.012121 |
def simxSetBooleanParameter(clientID, paramIdentifier, paramValue, operationMode):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
return c_SetBooleanParameter(clientID, paramIdentifier, paramValue, operationMode) | [
"def",
"simxSetBooleanParameter",
"(",
"clientID",
",",
"paramIdentifier",
",",
"paramValue",
",",
"operationMode",
")",
":",
"return",
"c_SetBooleanParameter",
"(",
"clientID",
",",
"paramIdentifier",
",",
"paramValue",
",",
"operationMode",
")"
] | 45.166667 | 0.014493 |
def p_if_statement_woelse(self, p):
'if_statement : IF LPAREN cond RPAREN true_statement'
p[0] = IfStatement(p[3], p[5], None, lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | [
"def",
"p_if_statement_woelse",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"IfStatement",
"(",
"p",
"[",
"3",
"]",
",",
"p",
"[",
"5",
"]",
",",
"None",
",",
"lineno",
"=",
"p",
".",
"lineno",
"(",
"1",
")",
")",
"p",
".",
"s... | 49 | 0.01005 |
def streaming_bulk(self, actions, chunk_size=500, max_chunk_bytes=100 * 1024 * 1024,
raise_on_error=True, expand_action_callback=ActionParser.expand_action,
raise_on_exception=True, **kwargs):
"""
Streaming bulk consumes actions from the iterable passed in a... | [
"def",
"streaming_bulk",
"(",
"self",
",",
"actions",
",",
"chunk_size",
"=",
"500",
",",
"max_chunk_bytes",
"=",
"100",
"*",
"1024",
"*",
"1024",
",",
"raise_on_error",
"=",
"True",
",",
"expand_action_callback",
"=",
"ActionParser",
".",
"expand_action",
","... | 69 | 0.008701 |
def _init_client(self, from_archive=False):
"""Init client"""
return DockerHubClient(archive=self.archive, from_archive=from_archive) | [
"def",
"_init_client",
"(",
"self",
",",
"from_archive",
"=",
"False",
")",
":",
"return",
"DockerHubClient",
"(",
"archive",
"=",
"self",
".",
"archive",
",",
"from_archive",
"=",
"from_archive",
")"
] | 36.75 | 0.013333 |
def parity(num: int) -> int:
"""Return the parity of a non-negative integer.
For example, here are the parities of the first ten integers:
>>> [parity(n) for n in range(10)]
[0, 1, 1, 0, 1, 0, 0, 1, 1, 0]
This function is undefined for negative integers:
>>> parity(-1)
Traceback (most re... | [
"def",
"parity",
"(",
"num",
":",
"int",
")",
"->",
"int",
":",
"if",
"num",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"expected num >= 0\"",
")",
"par",
"=",
"0",
"while",
"num",
":",
"par",
"^=",
"(",
"num",
"&",
"1",
")",
"num",
">>=",
"1",... | 23.454545 | 0.001862 |
def round(self, decimals=0, *args, **kwargs):
"""
Round each value in a Series to the given number of decimals.
Parameters
----------
decimals : int
Number of decimal places to round to (default: 0).
If decimals is negative, it specifies the number of
... | [
"def",
"round",
"(",
"self",
",",
"decimals",
"=",
"0",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"nv",
".",
"validate_round",
"(",
"args",
",",
"kwargs",
")",
"result",
"=",
"com",
".",
"values_from_object",
"(",
"self",
")",
".",
"roun... | 27.457143 | 0.00201 |
def fetch_by_uuid(uuid):
"""
Serve publications by UUID.
"""
# fetch all - private and public - publications
all_pubs = [
pub
for pub in search_publications(DBPublication(uuid=uuid))
]
if not all_pubs:
abort(404, "Dokument s UUID '%s' není dostupný." % (uuid))
p... | [
"def",
"fetch_by_uuid",
"(",
"uuid",
")",
":",
"# fetch all - private and public - publications",
"all_pubs",
"=",
"[",
"pub",
"for",
"pub",
"in",
"search_publications",
"(",
"DBPublication",
"(",
"uuid",
"=",
"uuid",
")",
")",
"]",
"if",
"not",
"all_pubs",
":",... | 27.982759 | 0.000595 |
def up(self):
"""
Move this object up one position.
"""
self.swap(self.get_ordering_queryset().filter(order__lt=self.order).order_by('-order')) | [
"def",
"up",
"(",
"self",
")",
":",
"self",
".",
"swap",
"(",
"self",
".",
"get_ordering_queryset",
"(",
")",
".",
"filter",
"(",
"order__lt",
"=",
"self",
".",
"order",
")",
".",
"order_by",
"(",
"'-order'",
")",
")"
] | 34.2 | 0.017143 |
def _put_or_post_json(self, method, url, data):
"""
urlencodes the data and PUTs it to the url
the response is parsed as JSON and the resulting data type is returned
"""
if self.parsed_endpoint.scheme == 'https':
conn = httplib.HTTPSConnection(self.parsed_endpoint.net... | [
"def",
"_put_or_post_json",
"(",
"self",
",",
"method",
",",
"url",
",",
"data",
")",
":",
"if",
"self",
".",
"parsed_endpoint",
".",
"scheme",
"==",
"'https'",
":",
"conn",
"=",
"httplib",
".",
"HTTPSConnection",
"(",
"self",
".",
"parsed_endpoint",
".",
... | 42.47619 | 0.002193 |
def list_set_bits(r, expected_length):
"""Return list of positions of bits set to one in given data.
This method is used to read e.g. violated zones. They are marked by ones
on respective bit positions - as per Satel manual.
"""
set_bit_numbers = []
bit_index = 0x1
assert (len(r) == expecte... | [
"def",
"list_set_bits",
"(",
"r",
",",
"expected_length",
")",
":",
"set_bit_numbers",
"=",
"[",
"]",
"bit_index",
"=",
"0x1",
"assert",
"(",
"len",
"(",
"r",
")",
"==",
"expected_length",
"+",
"1",
")",
"for",
"b",
"in",
"r",
"[",
"1",
":",
"]",
"... | 29.764706 | 0.001916 |
def escape_markdown(text, *, as_needed=False, ignore_links=True):
r"""A helper function that escapes Discord's markdown.
Parameters
-----------
text: :class:`str`
The text to escape markdown from.
as_needed: :class:`bool`
Whether to escape the markdown characters as needed. This
... | [
"def",
"escape_markdown",
"(",
"text",
",",
"*",
",",
"as_needed",
"=",
"False",
",",
"ignore_links",
"=",
"True",
")",
":",
"if",
"not",
"as_needed",
":",
"url_regex",
"=",
"r'(?P<url>(?:https?|steam)://(?:-\\.)?(?:[^\\s/?\\.#-]+\\.?)+(?:/[^\\s]*)?)'",
"def",
"replac... | 38.536585 | 0.001852 |
def sign(pkey, data, digest):
"""
Sign a data string using the given key and message digest.
:param pkey: PKey to sign with
:param data: data to be signed
:param digest: message digest to use
:return: signature
.. versionadded:: 0.11
"""
data = _text_to_bytes_and_warn("data", data)... | [
"def",
"sign",
"(",
"pkey",
",",
"data",
",",
"digest",
")",
":",
"data",
"=",
"_text_to_bytes_and_warn",
"(",
"\"data\"",
",",
"data",
")",
"digest_obj",
"=",
"_lib",
".",
"EVP_get_digestbyname",
"(",
"_byte_string",
"(",
"digest",
")",
")",
"if",
"digest... | 32.375 | 0.000937 |
def init_config(self, **kw):
""" Get a configuration object for this type of YubiKey. """
return YubiKeyConfigUSBHID(ykver=self.version_num(), \
capabilities = self.capabilities, \
**kw) | [
"def",
"init_config",
"(",
"self",
",",
"*",
"*",
"kw",
")",
":",
"return",
"YubiKeyConfigUSBHID",
"(",
"ykver",
"=",
"self",
".",
"version_num",
"(",
")",
",",
"capabilities",
"=",
"self",
".",
"capabilities",
",",
"*",
"*",
"kw",
")"
] | 55.2 | 0.028571 |
def render(self, total=False, transpose=False, style=False):
"""Render the HTMTL table of the chart.
`total` can be specified to include data sums
`transpose` make labels becomes columns
`style` include scoped style for the table
"""
self.chart.setup()
ln = self... | [
"def",
"render",
"(",
"self",
",",
"total",
"=",
"False",
",",
"transpose",
"=",
"False",
",",
"style",
"=",
"False",
")",
":",
"self",
".",
"chart",
".",
"setup",
"(",
")",
"ln",
"=",
"self",
".",
"chart",
".",
"_len",
"html",
"=",
"HTML",
"(",
... | 29.448276 | 0.00068 |
def HandleFilterMaxComponentLimit(handle, lfilter):
"""
Method checks the filter count and if the filter count exceeds the maxComponents(number of filters), then the given filter
objects get distributed among small groups and then again binded together in complex filters(like and , or) so that the
count of filt... | [
"def",
"HandleFilterMaxComponentLimit",
"(",
"handle",
",",
"lfilter",
")",
":",
"from",
"Ucs",
"import",
"AndFilter",
",",
"OrFilter",
",",
"AbstractFilter",
"maxComponents",
"=",
"10",
"if",
"(",
"(",
"lfilter",
"==",
"None",
")",
"or",
"(",
"lfilter",
"."... | 37.538462 | 0.029294 |
def is_already_running(self):
"""Return True if lock exists and has not timed out."""
date_done = (self.restore_group(self.task_identifier) or dict()).get('date_done')
if not date_done:
return False
difference = datetime.utcnow() - date_done
return difference < timede... | [
"def",
"is_already_running",
"(",
"self",
")",
":",
"date_done",
"=",
"(",
"self",
".",
"restore_group",
"(",
"self",
".",
"task_identifier",
")",
"or",
"dict",
"(",
")",
")",
".",
"get",
"(",
"'date_done'",
")",
"if",
"not",
"date_done",
":",
"return",
... | 48.428571 | 0.008696 |
def p_param_substitution(self, p):
'param_substitution : ID EQUALS rvalue'
p[0] = (p[1], p[3])
p.set_lineno(0, p.lineno(1)) | [
"def",
"p_param_substitution",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"(",
"p",
"[",
"1",
"]",
",",
"p",
"[",
"3",
"]",
")",
"p",
".",
"set_lineno",
"(",
"0",
",",
"p",
".",
"lineno",
"(",
"1",
")",
")"
] | 36 | 0.013605 |
def huffman(freq):
"""Huffman code
:param freq: dictionary with frequencies for each item
:returns: dictionary with binary code string for each item
:complexity: O(n log n)
"""
h = []
for a in freq:
heappush(h, (freq[a], a))
while len(h) > 1:
(fl, l) = heappop(h)
... | [
"def",
"huffman",
"(",
"freq",
")",
":",
"h",
"=",
"[",
"]",
"for",
"a",
"in",
"freq",
":",
"heappush",
"(",
"h",
",",
"(",
"freq",
"[",
"a",
"]",
",",
"a",
")",
")",
"while",
"len",
"(",
"h",
")",
">",
"1",
":",
"(",
"fl",
",",
"l",
")... | 24.764706 | 0.002288 |
def get_package_data():
"""Include all files from all sub-directories"""
package_data = dict()
package_data['PyQt5'] = list()
for subdir in ("doc/", "examples/", "include/",
"mkspecs/", "plugins/", "qml/",
"qsci/", "sip/", "translations/", "uic/"):
abspath ... | [
"def",
"get_package_data",
"(",
")",
":",
"package_data",
"=",
"dict",
"(",
")",
"package_data",
"[",
"'PyQt5'",
"]",
"=",
"list",
"(",
")",
"for",
"subdir",
"in",
"(",
"\"doc/\"",
",",
"\"examples/\"",
",",
"\"include/\"",
",",
"\"mkspecs/\"",
",",
"\"plu... | 39.958333 | 0.001018 |
def encipher_shift(plaintext, plain_vocab, shift):
"""Encrypt plain text with a single shift layer.
Args:
plaintext (list of list of Strings): a list of plain text to encrypt.
plain_vocab (list of Integer): unique vocabularies being used.
shift (Integer): number of shift, shift to the right if shift is... | [
"def",
"encipher_shift",
"(",
"plaintext",
",",
"plain_vocab",
",",
"shift",
")",
":",
"ciphertext",
"=",
"[",
"]",
"cipher",
"=",
"ShiftEncryptionLayer",
"(",
"plain_vocab",
",",
"shift",
")",
"for",
"_",
",",
"sentence",
"in",
"enumerate",
"(",
"plaintext"... | 34.809524 | 0.010652 |
def delete_object(cache, template, indexes):
"""Delete an object in Redis using a pipeline.
Deletes all fields defined by the template.
Arguments:
template: a dictionary containg the keys for the object and
template strings for the corresponding redis keys. The template
str... | [
"def",
"delete_object",
"(",
"cache",
",",
"template",
",",
"indexes",
")",
":",
"with",
"cache",
"as",
"redis_connection",
":",
"pipe",
"=",
"redis_connection",
".",
"pipeline",
"(",
")",
"for",
"key",
"in",
"set",
"(",
"template",
".",
"keys",
"(",
")"... | 29.4 | 0.001098 |
def strip_cdata(text):
"""Removes all CDATA blocks from `text` if it contains them.
Note:
If the function contains escaped XML characters outside of a
CDATA block, they will be unescaped.
Args:
A string containing one or more CDATA blocks.
Returns:
An XML unescaped str... | [
"def",
"strip_cdata",
"(",
"text",
")",
":",
"if",
"not",
"is_cdata",
"(",
"text",
")",
":",
"return",
"text",
"xml",
"=",
"\"<e>{0}</e>\"",
".",
"format",
"(",
"text",
")",
"node",
"=",
"etree",
".",
"fromstring",
"(",
"xml",
")",
"return",
"node",
... | 24.4 | 0.001972 |
def get_shiftfile_row(self):
""" Return the information for a shiftfile for this image to provide
compatability with the IRAF-based MultiDrizzle.
"""
if self.fit is not None:
rowstr = '%s %0.6f %0.6f %0.6f %0.6f %0.6f %0.6f\n'%(
self.name... | [
"def",
"get_shiftfile_row",
"(",
"self",
")",
":",
"if",
"self",
".",
"fit",
"is",
"not",
"None",
":",
"rowstr",
"=",
"'%s %0.6f %0.6f %0.6f %0.6f %0.6f %0.6f\\n'",
"%",
"(",
"self",
".",
"name",
",",
"self",
".",
"fit",
"[",
"'offset'",
"]",
"... | 44.416667 | 0.012868 |
def MakeDeployableBinary(self, template_path, output_path):
"""This will add the config to the client template."""
context = self.context + ["Client Context"]
utils.EnsureDirExists(os.path.dirname(output_path))
client_config_data = self.GetClientConfig(context)
shutil.copyfile(template_path, output... | [
"def",
"MakeDeployableBinary",
"(",
"self",
",",
"template_path",
",",
"output_path",
")",
":",
"context",
"=",
"self",
".",
"context",
"+",
"[",
"\"Client Context\"",
"]",
"utils",
".",
"EnsureDirExists",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"output... | 43.333333 | 0.001883 |
def get_line(thing):
"""
Get the line number for something.
Parameters
----------
thing : function, class, module
Returns
-------
int
Line number in the source file
"""
try:
return inspect.getsourcelines(thing)[1]
except TypeError:
# Might be a proper... | [
"def",
"get_line",
"(",
"thing",
")",
":",
"try",
":",
"return",
"inspect",
".",
"getsourcelines",
"(",
"thing",
")",
"[",
"1",
"]",
"except",
"TypeError",
":",
"# Might be a property",
"return",
"inspect",
".",
"getsourcelines",
"(",
"thing",
".",
"fget",
... | 21.1 | 0.002268 |
def model_data(self):
"""str: The model location in S3. Only set if Estimator has been ``fit()``."""
if self.latest_training_job is not None:
model_uri = self.sagemaker_session.sagemaker_client.describe_training_job(
TrainingJobName=self.latest_training_job.name)['ModelArtifa... | [
"def",
"model_data",
"(",
"self",
")",
":",
"if",
"self",
".",
"latest_training_job",
"is",
"not",
"None",
":",
"model_uri",
"=",
"self",
".",
"sagemaker_session",
".",
"sagemaker_client",
".",
"describe_training_job",
"(",
"TrainingJobName",
"=",
"self",
".",
... | 61.636364 | 0.011628 |
def extendable(network, args, line_max):
"""
Function that sets selected components extendable
'network' for all lines, links and transformers
'german_network' for all lines, links and transformers located in Germany
'foreign_network' for all foreign lines, links and transformers
'transformers... | [
"def",
"extendable",
"(",
"network",
",",
"args",
",",
"line_max",
")",
":",
"if",
"'network'",
"in",
"args",
"[",
"'extendable'",
"]",
":",
"network",
".",
"lines",
".",
"s_nom_extendable",
"=",
"True",
"network",
".",
"lines",
".",
"s_nom_min",
"=",
"n... | 43.841584 | 0.008244 |
def init(device_id=None, random_seed=None):
"""Initialize Hebel.
This function creates a CUDA context, CUBLAS context and
initializes and seeds the pseudo-random number generator.
**Parameters:**
device_id : integer, optional
The ID of the GPU device to use. If this is omitted, PyCUDA... | [
"def",
"init",
"(",
"device_id",
"=",
"None",
",",
"random_seed",
"=",
"None",
")",
":",
"if",
"device_id",
"is",
"None",
":",
"random_seed",
"=",
"_os",
".",
"environ",
".",
"get",
"(",
"'CUDA_DEVICE'",
")",
"if",
"random_seed",
"is",
"None",
":",
"ra... | 30.583333 | 0.00198 |
def transitivity_bu(A):
'''
Transitivity is the ratio of 'triangles to triplets' in the network.
(A classical version of the clustering coefficient).
Parameters
----------
A : NxN np.ndarray
binary undirected connection matrix
Returns
-------
T : float
transitivity ... | [
"def",
"transitivity_bu",
"(",
"A",
")",
":",
"tri3",
"=",
"np",
".",
"trace",
"(",
"np",
".",
"dot",
"(",
"A",
",",
"np",
".",
"dot",
"(",
"A",
",",
"A",
")",
")",
")",
"tri2",
"=",
"np",
".",
"sum",
"(",
"np",
".",
"dot",
"(",
"A",
",",... | 24.555556 | 0.002179 |
def output_redirect(stdout, stderr):
"""
thread safe redirect of stdout and stderr
:param stdout:
:param stderr:
:return:
"""
import sys
import threading
if not redirect:
originals = (sys.stdout.write, sys.stderr.write)
class Logger:
def __init__(self, fun):
self.buffer = ""
... | [
"def",
"output_redirect",
"(",
"stdout",
",",
"stderr",
")",
":",
"import",
"sys",
"import",
"threading",
"if",
"not",
"redirect",
":",
"originals",
"=",
"(",
"sys",
".",
"stdout",
".",
"write",
",",
"sys",
".",
"stderr",
".",
"write",
")",
"class",
"L... | 26.552239 | 0.013008 |
def clip_eta(eta, ord, eps):
"""
PyTorch implementation of the clip_eta in utils_tf.
:param eta: Tensor
:param ord: np.inf, 1, or 2
:param eps: float
"""
if ord not in [np.inf, 1, 2]:
raise ValueError('ord must be np.inf, 1, or 2.')
avoid_zero_div = torch.tensor(1e-12, dtype=eta.dtype, device=eta.... | [
"def",
"clip_eta",
"(",
"eta",
",",
"ord",
",",
"eps",
")",
":",
"if",
"ord",
"not",
"in",
"[",
"np",
".",
"inf",
",",
"1",
",",
"2",
"]",
":",
"raise",
"ValueError",
"(",
"'ord must be np.inf, 1, or 2.'",
")",
"avoid_zero_div",
"=",
"torch",
".",
"t... | 27 | 0.012618 |
def get_table(table, table_file, path=None, target=None, key=None, key_items=None,
filters=None, template_args=None):
'''
Retrieve data from a Junos device using Tables/Views
table (required)
Name of PyEZ Table
table_file (required)
YAML file that has the table specified ... | [
"def",
"get_table",
"(",
"table",
",",
"table_file",
",",
"path",
"=",
"None",
",",
"target",
"=",
"None",
",",
"key",
"=",
"None",
",",
"key_items",
"=",
"None",
",",
"filters",
"=",
"None",
",",
"template_args",
"=",
"None",
")",
":",
"conn",
"=",
... | 35.723214 | 0.001459 |
def main():
"""The entrypoint for the hairball command installed via setup.py."""
description = ('PATH can be either the path to a scratch file, or a '
'directory containing scratch files. Multiple PATH '
'arguments can be provided.')
parser = OptionParser(usage='%prog ... | [
"def",
"main",
"(",
")",
":",
"description",
"=",
"(",
"'PATH can be either the path to a scratch file, or a '",
"'directory containing scratch files. Multiple PATH '",
"'arguments can be provided.'",
")",
"parser",
"=",
"OptionParser",
"(",
"usage",
"=",
"'%prog -p PLUGIN_NAME [... | 51.954545 | 0.000429 |
def save_thumbnail(image_path_template, src_file, file_conf, gallery_conf):
"""Generate and Save the thumbnail image
Parameters
----------
image_path_template : str
holds the template where to save and how to name the image
src_file : str
path to source python file
gallery_conf ... | [
"def",
"save_thumbnail",
"(",
"image_path_template",
",",
"src_file",
",",
"file_conf",
",",
"gallery_conf",
")",
":",
"# read specification of the figure to display as thumbnail from main text",
"thumbnail_number",
"=",
"file_conf",
".",
"get",
"(",
"'thumbnail_number'",
","... | 39.883721 | 0.000569 |
def setdict(self, D=None, B=None):
"""Set dictionary array."""
if D is not None:
self.D = np.asarray(D, dtype=self.dtype)
if B is not None:
self.B = np.asarray(B, dtype=self.dtype)
if B is not None or not hasattr(self, 'Gamma'):
self.Gamma, self.Q = ... | [
"def",
"setdict",
"(",
"self",
",",
"D",
"=",
"None",
",",
"B",
"=",
"None",
")",
":",
"if",
"D",
"is",
"not",
"None",
":",
"self",
".",
"D",
"=",
"np",
".",
"asarray",
"(",
"D",
",",
"dtype",
"=",
"self",
".",
"dtype",
")",
"if",
"B",
"is"... | 36.428571 | 0.00191 |
def _unquote(string):
"""remove optional quotes (simple or double) from the string
:type string: str or unicode
:param string: an optionally quoted string
:rtype: str or unicode
:return: the unquoted string (or the input string if it wasn't quoted)
"""
if not string:
return string
... | [
"def",
"_unquote",
"(",
"string",
")",
":",
"if",
"not",
"string",
":",
"return",
"string",
"if",
"string",
"[",
"0",
"]",
"in",
"\"\\\"'\"",
":",
"string",
"=",
"string",
"[",
"1",
":",
"]",
"if",
"string",
"[",
"-",
"1",
"]",
"in",
"\"\\\"'\"",
... | 27.125 | 0.002227 |
async def _set_annotations(entity_tag, annotations, connection):
"""Set annotations on the specified entity.
:param annotations map[string]string: the annotations as key/value
pairs.
"""
# TODO: ensure annotations is dict with only string keys
# and values.
log.debug('Updating annotatio... | [
"async",
"def",
"_set_annotations",
"(",
"entity_tag",
",",
"annotations",
",",
"connection",
")",
":",
"# TODO: ensure annotations is dict with only string keys",
"# and values.",
"log",
".",
"debug",
"(",
"'Updating annotations on %s'",
",",
"entity_tag",
")",
"facade",
... | 35.533333 | 0.001828 |
def get_dashboard_tags(self, id, **kwargs): # noqa: E501
"""Get all tags associated with a specific dashboard # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.... | [
"def",
"get_dashboard_tags",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"get_dashb... | 42.571429 | 0.002188 |
def start_transaction(self, sort, address, price=None, data=None, caller=None, value=0, gas=2300):
"""
Initiate a transaction
:param sort: the type of transaction. CREATE or CALL or DELEGATECALL
:param address: the address of the account which owns the code that is executing.
:pa... | [
"def",
"start_transaction",
"(",
"self",
",",
"sort",
",",
"address",
",",
"price",
"=",
"None",
",",
"data",
"=",
"None",
",",
"caller",
"=",
"None",
",",
"value",
"=",
"0",
",",
"gas",
"=",
"2300",
")",
":",
"assert",
"self",
".",
"_pending_transac... | 76.142857 | 0.008341 |
def uncomment_or_update_or_append_line(filename, prefix, new_line, comment='#',
keep_backup=True):
'''Remove the comment of an commented out line and make the line "active".
If such an commented out line not exists it would be appended.
'''
return uua_local(filena... | [
"def",
"uncomment_or_update_or_append_line",
"(",
"filename",
",",
"prefix",
",",
"new_line",
",",
"comment",
"=",
"'#'",
",",
"keep_backup",
"=",
"True",
")",
":",
"return",
"uua_local",
"(",
"filename",
",",
"prefix",
",",
"new_line",
",",
"comment",
",",
... | 52.75 | 0.002331 |
def later(periods=10.0, precision=2.0, offset=0.0, check_interval=0.1, only_run_once=True):
"""
**注意:会阻塞程序运行, 如果后台运行, 请放置于线程中**
这个会阻塞程序运行, 如果不是这个目的, 请确保待装饰程序以线程方式运行
* periods 是正常提供的参数, 如 10s, 则函数每10s 运行一次
* precision 精度,
* 如3s, 则 0~3s 内都可以触发运行
* 如果是0s, 则函数可在 ```sleep check_interva... | [
"def",
"later",
"(",
"periods",
"=",
"10.0",
",",
"precision",
"=",
"2.0",
",",
"offset",
"=",
"0.0",
",",
"check_interval",
"=",
"0.1",
",",
"only_run_once",
"=",
"True",
")",
":",
"def",
"dec_fn",
"(",
"fn",
")",
":",
"@",
"wraps",
"(",
"fn",
")"... | 30.605634 | 0.000892 |
def _get_arguments_for_execution(self, function_name, serialized_args):
"""Retrieve the arguments for the remote function.
This retrieves the values for the arguments to the remote function that
were passed in as object IDs. Arguments that were passed by value are
not changed. This is c... | [
"def",
"_get_arguments_for_execution",
"(",
"self",
",",
"function_name",
",",
"serialized_args",
")",
":",
"arguments",
"=",
"[",
"]",
"for",
"(",
"i",
",",
"arg",
")",
"in",
"enumerate",
"(",
"serialized_args",
")",
":",
"if",
"isinstance",
"(",
"arg",
"... | 39.694444 | 0.001366 |
def from_linearized(first, second, intersections):
"""Determine curve-curve intersection from pair of linearizations.
.. note::
This assumes that at least one of ``first`` and ``second`` is
not a line. The line-line case should be handled "early"
by :func:`check_lines`.
.. note::
... | [
"def",
"from_linearized",
"(",
"first",
",",
"second",
",",
"intersections",
")",
":",
"# NOTE: There is no corresponding \"enable\", but the disable only applies",
"# in this lexical scope.",
"# pylint: disable=too-many-return-statements",
"s",
",",
"t",
",",
"success",
"=... | 36.75 | 0.000368 |
def beta(self):
"""
The result :math:`\\beta` of the linear least squares
"""
if self._beta is None:
# This is the linear least squares matrix formalism
self._beta = _np.dot(_np.linalg.pinv(self.X) , self.y)
return self._beta | [
"def",
"beta",
"(",
"self",
")",
":",
"if",
"self",
".",
"_beta",
"is",
"None",
":",
"# This is the linear least squares matrix formalism",
"self",
".",
"_beta",
"=",
"_np",
".",
"dot",
"(",
"_np",
".",
"linalg",
".",
"pinv",
"(",
"self",
".",
"X",
")",
... | 35.25 | 0.010381 |
def main():
"""The main function.
These are the steps performed for the data clean up:
1. Prints the version number.
2. Reads the configuration file (:py:func:`read_config_file`).
3. Creates a new directory with ``data_clean_up`` as prefix and the date
and time as suffix.
4. Check the i... | [
"def",
"main",
"(",
")",
":",
"# Getting and checking the options",
"args",
"=",
"parse_args",
"(",
")",
"check_args",
"(",
"args",
")",
"# The directory name",
"dirname",
"=",
"\"data_clean_up.\"",
"dirname",
"+=",
"datetime",
".",
"datetime",
".",
"today",
"(",
... | 36.80203 | 0.000134 |
def assignee(self):
"""
| Comment: The id of the assignee if the field is visible to end users
"""
if self.api and self.assignee_id:
return self.api._get_user(self.assignee_id) | [
"def",
"assignee",
"(",
"self",
")",
":",
"if",
"self",
".",
"api",
"and",
"self",
".",
"assignee_id",
":",
"return",
"self",
".",
"api",
".",
"_get_user",
"(",
"self",
".",
"assignee_id",
")"
] | 36 | 0.00905 |
def get(cls, label='default', path=None):
"""Read a server configuration from a configuration file.
This method extends :meth:`nailgun.config.BaseServerConfig.get`. Please
read up on that method before trying to understand this one.
The entity classes rely on the requests library to be... | [
"def",
"get",
"(",
"cls",
",",
"label",
"=",
"'default'",
",",
"path",
"=",
"None",
")",
":",
"config",
"=",
"super",
"(",
"ServerConfig",
",",
"cls",
")",
".",
"get",
"(",
"label",
",",
"path",
")",
"if",
"hasattr",
"(",
"config",
",",
"'auth'",
... | 47.346154 | 0.001592 |
def write(self,f):
""" write control data section to a file
Parameters
----------
f: file handle or string filename
"""
if isinstance(f,str):
f = open(f,'w')
f.write("pcf\n")
f.write("* control data\n")
for line in CON... | [
"def",
"write",
"(",
"self",
",",
"f",
")",
":",
"if",
"isinstance",
"(",
"f",
",",
"str",
")",
":",
"f",
"=",
"open",
"(",
"f",
",",
"'w'",
")",
"f",
".",
"write",
"(",
"\"pcf\\n\"",
")",
"f",
".",
"write",
"(",
"\"* control data\\n\"",
")",
"... | 30.666667 | 0.018987 |
def _maybe_apply_time_shift(da, time_offset=None, **DataAttrs):
"""Correct off-by-one error in GFDL instantaneous model data.
Instantaneous data that is outputted by GFDL models is generally off by
one timestep. For example, a netCDF file that is supposed to
correspond to 6 hourly data... | [
"def",
"_maybe_apply_time_shift",
"(",
"da",
",",
"time_offset",
"=",
"None",
",",
"*",
"*",
"DataAttrs",
")",
":",
"if",
"time_offset",
"is",
"not",
"None",
":",
"time",
"=",
"times",
".",
"apply_time_offset",
"(",
"da",
"[",
"TIME_STR",
"]",
",",
"*",
... | 45.15 | 0.002169 |
def convert_strain_to_deformation(strain, shape="upper"):
"""
This function converts a strain to a deformation gradient that will
produce that strain. Supports three methods:
Args:
strain (3x3 array-like): strain matrix
shape: (string): method for determining deformation, supports
... | [
"def",
"convert_strain_to_deformation",
"(",
"strain",
",",
"shape",
"=",
"\"upper\"",
")",
":",
"strain",
"=",
"SquareTensor",
"(",
"strain",
")",
"ftdotf",
"=",
"2",
"*",
"strain",
"+",
"np",
".",
"eye",
"(",
"3",
")",
"if",
"shape",
"==",
"\"upper\"",... | 37.380952 | 0.001242 |
def _drag_row(self, event):
"""Continue dragging a row"""
y = self._dy + event.y # get dragged row new upper y coordinate
self._visual_drag.place_configure(y=y) # update row preview position
if y > self._dragged_row_y:
# moving downward
item = self.identify_row... | [
"def",
"_drag_row",
"(",
"self",
",",
"event",
")",
":",
"y",
"=",
"self",
".",
"_dy",
"+",
"event",
".",
"y",
"# get dragged row new upper y coordinate",
"self",
".",
"_visual_drag",
".",
"place_configure",
"(",
"y",
"=",
"y",
")",
"# update row preview posit... | 47.947368 | 0.002152 |
def _build_credentials_tuple(mech, source, user, passwd, extra, database):
"""Build and return a mechanism specific credentials tuple.
"""
if mech != 'MONGODB-X509' and user is None:
raise ConfigurationError("%s requires a username." % (mech,))
if mech == 'GSSAPI':
if source is not None ... | [
"def",
"_build_credentials_tuple",
"(",
"mech",
",",
"source",
",",
"user",
",",
"passwd",
",",
"extra",
",",
"database",
")",
":",
"if",
"mech",
"!=",
"'MONGODB-X509'",
"and",
"user",
"is",
"None",
":",
"raise",
"ConfigurationError",
"(",
"\"%s requires a use... | 50.162162 | 0.000529 |
def main(argv=None):
"""
Entrypoint.
"""
if argv is None:
argv = sys.argv
psr = option_parser()
args = psr.parse_args(argv[1:])
if not args.template:
if args.list_engines:
ecs = anytemplate.api.list_engines()
print(", ".join("%s (%s)" % (e.name(), e.... | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"if",
"argv",
"is",
"None",
":",
"argv",
"=",
"sys",
".",
"argv",
"psr",
"=",
"option_parser",
"(",
")",
"args",
"=",
"psr",
".",
"parse_args",
"(",
"argv",
"[",
"1",
":",
"]",
")",
"if",
"not"... | 29.966667 | 0.001078 |
def transaction_id(self, transaction_id):
"""
Sets the transaction_id of this AdditionalRecipientReceivable.
The ID of the transaction that the additional recipient receivable was applied to.
:param transaction_id: The transaction_id of this AdditionalRecipientReceivable.
:type:... | [
"def",
"transaction_id",
"(",
"self",
",",
"transaction_id",
")",
":",
"if",
"transaction_id",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Invalid value for `transaction_id`, must not be `None`\"",
")",
"if",
"len",
"(",
"transaction_id",
")",
"<",
"1",
":",
... | 42.666667 | 0.009174 |
def idfstr(self):
"""String representation of the IDF.
Returns
-------
str
"""
if self.outputtype == 'standard':
astr = ''
else:
astr = self.model.__repr__()
if self.outputtype == 'standard':
astr = ''
dtl... | [
"def",
"idfstr",
"(",
"self",
")",
":",
"if",
"self",
".",
"outputtype",
"==",
"'standard'",
":",
"astr",
"=",
"''",
"else",
":",
"astr",
"=",
"self",
".",
"model",
".",
"__repr__",
"(",
")",
"if",
"self",
".",
"outputtype",
"==",
"'standard'",
":",
... | 32.27027 | 0.001626 |
def assign_asset_to_repository(self, asset_id, repository_id):
"""Adds an existing ``Asset`` to a ``Repository``.
arg: asset_id (osid.id.Id): the ``Id`` of the ``Asset``
arg: repository_id (osid.id.Id): the ``Id`` of the
``Repository``
raise: AlreadyExists - ``ass... | [
"def",
"assign_asset_to_repository",
"(",
"self",
",",
"asset_id",
",",
"repository_id",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceBinAssignmentSession.assign_resource_to_bin",
"mgr",
"=",
"self",
".",
"_get_provider_manager",
"(",
"'REPOSITORY'",
",... | 51 | 0.00175 |
def ksl(A, y0, tau, verb=1, scheme='symm', space=8, rmax=2000, use_normest=1):
""" Dynamical tensor-train approximation based on projector splitting
This function performs one step of dynamical tensor-train approximation
for the equation
.. math ::
\\frac{dy}{dt} = A y, \\quad y... | [
"def",
"ksl",
"(",
"A",
",",
"y0",
",",
"tau",
",",
"verb",
"=",
"1",
",",
"scheme",
"=",
"'symm'",
",",
"space",
"=",
"8",
",",
"rmax",
"=",
"2000",
",",
"use_normest",
"=",
"1",
")",
":",
"y0",
"=",
"y0",
".",
"round",
"(",
"1e-14",
")",
... | 28.940171 | 0.002284 |
def put(self, withdraw_account_id, deposit_account_id, amount):
"""
:param withdraw_account_id: int of the account_id to withdraw the money from
:param deposit_account_id: int of the account_id to deposit the money to
:param amount: float of the amount to transfer
:re... | [
"def",
"put",
"(",
"self",
",",
"withdraw_account_id",
",",
"deposit_account_id",
",",
"amount",
")",
":",
"return",
"self",
".",
"connection",
".",
"put",
"(",
"'account/transfer'",
",",
"data",
"=",
"dict",
"(",
"withdraw_account_id",
"=",
"withdraw_account_id... | 58.636364 | 0.00916 |
def spawn_managed_host(config_file, manager, connect_on_start=True):
"""
Spawns a managed host, if it is not already running
"""
data = manager.request_host_status(config_file)
is_running = data['started']
# Managed hosts run as persistent processes, so it may already be running
if is_run... | [
"def",
"spawn_managed_host",
"(",
"config_file",
",",
"manager",
",",
"connect_on_start",
"=",
"True",
")",
":",
"data",
"=",
"manager",
".",
"request_host_status",
"(",
"config_file",
")",
"is_running",
"=",
"data",
"[",
"'started'",
"]",
"# Managed hosts run as ... | 26.90625 | 0.001121 |
def _set_mongodb_host_val(key, default, mongodb_host, mongodb_defaults):
"""
Set a value in a 'cascade' fashion for mongodb_host[key]
Within 'mongodb', as a last resort, its hardcoded default value is going to
be picked.
:param key: key name
:param default: default last resort value
:param... | [
"def",
"_set_mongodb_host_val",
"(",
"key",
",",
"default",
",",
"mongodb_host",
",",
"mongodb_defaults",
")",
":",
"# If mongodb_host[key] is not already set, its value is going to be picked",
"# from mongodb_defaults[key]",
"if",
"key",
"not",
"in",
"mongodb_host",
":",
"if... | 41.666667 | 0.000978 |
def send_game(self, *args, **kwargs):
"""See :func:`send_game`"""
return send_game(*args, **self._merge_overrides(**kwargs)).run() | [
"def",
"send_game",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"send_game",
"(",
"*",
"args",
",",
"*",
"*",
"self",
".",
"_merge_overrides",
"(",
"*",
"*",
"kwargs",
")",
")",
".",
"run",
"(",
")"
] | 48 | 0.013699 |
def __make_another_index(self, list_of_entries, url=False, hs_admin=False):
'''
Find an index not yet used in the handle record and not reserved for
any (other) special type.
:param: list_of_entries: List of all entries to find which indices are
used already.
:pa... | [
"def",
"__make_another_index",
"(",
"self",
",",
"list_of_entries",
",",
"url",
"=",
"False",
",",
"hs_admin",
"=",
"False",
")",
":",
"start",
"=",
"2",
"# reserved indices:",
"reserved_for_url",
"=",
"set",
"(",
"[",
"1",
"]",
")",
"reserved_for_admin",
"=... | 36.4 | 0.001338 |
def createContactItem(self, person, email):
"""
Create a new L{EmailAddress} associated with the given person based on
the given email address.
@type person: L{Person}
@param person: The person with whom to associate the new
L{EmailAddress}.
@type email: C{u... | [
"def",
"createContactItem",
"(",
"self",
",",
"person",
",",
"email",
")",
":",
"if",
"email",
":",
"address",
"=",
"self",
".",
"_existing",
"(",
"email",
")",
"if",
"address",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"'There is already a per... | 38.125 | 0.002132 |
def p_const_ref(self, p):
'''const_ref : IDENTIFIER'''
p[0] = ast.ConstReference(p[1], lineno=p.lineno(1)) | [
"def",
"p_const_ref",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"ast",
".",
"ConstReference",
"(",
"p",
"[",
"1",
"]",
",",
"lineno",
"=",
"p",
".",
"lineno",
"(",
"1",
")",
")"
] | 40 | 0.016393 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.