text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def _write_export(export, file_obj=None):
"""
Write a string to a file.
If file_obj isn't specified, return the string
Parameters
---------
export: a string of the export data
file_obj: a file-like object or a filename
"""
if file_obj is None:
return export
if hasattr(... | [
"def",
"_write_export",
"(",
"export",
",",
"file_obj",
"=",
"None",
")",
":",
"if",
"file_obj",
"is",
"None",
":",
"return",
"export",
"if",
"hasattr",
"(",
"file_obj",
",",
"'write'",
")",
":",
"out_file",
"=",
"file_obj",
"else",
":",
"out_file",
"=",... | 20.846154 | 0.001764 |
def save_images(self, directory=None, axis='z', channel=None, global_norm=True, image_format='PNG'):
"""See cloudvolume.lib.save_images for more information."""
if directory is None:
directory = os.path.join('./saved_images', self.dataset_name, self.layer, str(self.mip), self.bounds.to_filename())
re... | [
"def",
"save_images",
"(",
"self",
",",
"directory",
"=",
"None",
",",
"axis",
"=",
"'z'",
",",
"channel",
"=",
"None",
",",
"global_norm",
"=",
"True",
",",
"image_format",
"=",
"'PNG'",
")",
":",
"if",
"directory",
"is",
"None",
":",
"directory",
"="... | 65 | 0.012658 |
def request(self, method, url, body=None, headers={}):
"""Send a complete request to the server."""
self._send_request(method, url, body, headers) | [
"def",
"request",
"(",
"self",
",",
"method",
",",
"url",
",",
"body",
"=",
"None",
",",
"headers",
"=",
"{",
"}",
")",
":",
"self",
".",
"_send_request",
"(",
"method",
",",
"url",
",",
"body",
",",
"headers",
")"
] | 53.333333 | 0.012346 |
def _replay_info(replay_path):
"""Query a replay for information."""
if not replay_path.lower().endswith("sc2replay"):
print("Must be a replay.")
return
run_config = run_configs.get()
with run_config.start(want_rgb=False) as controller:
info = controller.replay_info(run_config.replay_data(replay_pa... | [
"def",
"_replay_info",
"(",
"replay_path",
")",
":",
"if",
"not",
"replay_path",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"\"sc2replay\"",
")",
":",
"print",
"(",
"\"Must be a replay.\"",
")",
"return",
"run_config",
"=",
"run_configs",
".",
"get",
"(",... | 31.454545 | 0.019663 |
def file_md5(fname):
""" get the (md5 hexdigest, md5 digest) of a file """
from dvc.progress import progress
from dvc.istextfile import istextfile
if os.path.exists(fname):
hash_md5 = hashlib.md5()
binary = not istextfile(fname)
size = os.path.getsize(fname)
bar = False
... | [
"def",
"file_md5",
"(",
"fname",
")",
":",
"from",
"dvc",
".",
"progress",
"import",
"progress",
"from",
"dvc",
".",
"istextfile",
"import",
"istextfile",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"fname",
")",
":",
"hash_md5",
"=",
"hashlib",
".",
... | 28.975 | 0.000835 |
def count_top_centrality(graph: BELGraph, number: Optional[int] = 30) -> Mapping[BaseEntity, int]:
"""Get top centrality dictionary."""
dd = nx.betweenness_centrality(graph)
dc = Counter(dd)
return dict(dc.most_common(number)) | [
"def",
"count_top_centrality",
"(",
"graph",
":",
"BELGraph",
",",
"number",
":",
"Optional",
"[",
"int",
"]",
"=",
"30",
")",
"->",
"Mapping",
"[",
"BaseEntity",
",",
"int",
"]",
":",
"dd",
"=",
"nx",
".",
"betweenness_centrality",
"(",
"graph",
")",
... | 47.6 | 0.008264 |
def filereplacer(filepath):
"""
This context manager yields two file pointers:
origlines:
a generator that yields lines from the original file
tmp:
a file descriptor as if you had used open(tempfile.mkstemp(), 'w')
NL:
one of "\n", "\r\n" or "\r" depending on what is encount... | [
"def",
"filereplacer",
"(",
"filepath",
")",
":",
"# create the tmp dir if it doesn't exist yet",
"tmpdir",
"=",
"join",
"(",
"ROOT",
",",
"'tmp'",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"tmpdir",
")",
":",
"os",
".",
"makedirs",
"(",
"tm... | 37.789474 | 0.001357 |
def _process_request(self, request):
"""Adds data necessary for Horizon to function to the request."""
request.horizon = {'dashboard': None,
'panel': None,
'async_messages': []}
if not hasattr(request, "user") or not request.user.is_authenti... | [
"def",
"_process_request",
"(",
"self",
",",
"request",
")",
":",
"request",
".",
"horizon",
"=",
"{",
"'dashboard'",
":",
"None",
",",
"'panel'",
":",
"None",
",",
"'async_messages'",
":",
"[",
"]",
"}",
"if",
"not",
"hasattr",
"(",
"request",
",",
"\... | 47.828125 | 0.00064 |
def _value_data(self, value):
"""Parses binary and unidentified values."""
return codecs.decode(
codecs.encode(self.value_value(value)[1], 'base64'), 'utf8') | [
"def",
"_value_data",
"(",
"self",
",",
"value",
")",
":",
"return",
"codecs",
".",
"decode",
"(",
"codecs",
".",
"encode",
"(",
"self",
".",
"value_value",
"(",
"value",
")",
"[",
"1",
"]",
",",
"'base64'",
")",
",",
"'utf8'",
")"
] | 45.5 | 0.010811 |
def write_json_to_file(json_data, filename="metadata"):
"""
Write all JSON in python dictionary to a new json file.
:param any json_data: JSON data
:param str filename: Target filename (defaults to 'metadata.jsonld')
:return None:
"""
# Use demjson to maintain unicode characters in output
... | [
"def",
"write_json_to_file",
"(",
"json_data",
",",
"filename",
"=",
"\"metadata\"",
")",
":",
"# Use demjson to maintain unicode characters in output",
"json_bin",
"=",
"demjson",
".",
"encode",
"(",
"json_data",
",",
"encoding",
"=",
"'utf-8'",
",",
"compactly",
"="... | 39.2 | 0.001661 |
def print_kernel_code(self, output_file=sys.stdout):
"""Print source code of kernel."""
print(self.kernel_code, file=output_file) | [
"def",
"print_kernel_code",
"(",
"self",
",",
"output_file",
"=",
"sys",
".",
"stdout",
")",
":",
"print",
"(",
"self",
".",
"kernel_code",
",",
"file",
"=",
"output_file",
")"
] | 47.666667 | 0.013793 |
def parse_function_params(params):
""" parse function params to args and kwargs.
Args:
params (str): function param in string
Returns:
dict: function meta dict
{
"args": [],
"kwargs": {}
}
Examples:
>>> parse_function_pa... | [
"def",
"parse_function_params",
"(",
"params",
")",
":",
"function_meta",
"=",
"{",
"\"args\"",
":",
"[",
"]",
",",
"\"kwargs\"",
":",
"{",
"}",
"}",
"params_str",
"=",
"params",
".",
"strip",
"(",
")",
"if",
"params_str",
"==",
"\"\"",
":",
"return",
... | 23.64 | 0.001625 |
def CopyFromString(cls, time_string):
"""Copies a timestamp from a string containing a date and time value.
Args:
time_string: A string containing a date and time value formatted as:
YYYY-MM-DD hh:mm:ss.######[+-]##:##
Where # are numeric digits ranging from 0 to 9 a... | [
"def",
"CopyFromString",
"(",
"cls",
",",
"time_string",
")",
":",
"if",
"not",
"time_string",
":",
"raise",
"ValueError",
"(",
"'Invalid time string.'",
")",
"time_string_length",
"=",
"len",
"(",
"time_string",
")",
"# The time string should at least contain 'YYYY-MM-... | 32.401361 | 0.008963 |
def pattern_filter(items, whitelist=None, blacklist=None, key=None):
"""This filters `items` by a regular expression `whitelist` and/or
`blacklist`, with the `blacklist` taking precedence. An optional `key`
function can be provided that will be passed each item.
"""
key = key or __return_self
if... | [
"def",
"pattern_filter",
"(",
"items",
",",
"whitelist",
"=",
"None",
",",
"blacklist",
"=",
"None",
",",
"key",
"=",
"None",
")",
":",
"key",
"=",
"key",
"or",
"__return_self",
"if",
"whitelist",
":",
"whitelisted",
"=",
"_filter",
"(",
"items",
",",
... | 37.045455 | 0.001196 |
def delete(self, symbol, date_range=None):
"""
Delete all chunks for a symbol.
Which are, for the moment, fully contained in the passed in
date_range.
Parameters
----------
symbol : `str`
symbol name for the item
date_range : `date.DateRange`... | [
"def",
"delete",
"(",
"self",
",",
"symbol",
",",
"date_range",
"=",
"None",
")",
":",
"query",
"=",
"{",
"SYMBOL",
":",
"symbol",
"}",
"date_range",
"=",
"to_pandas_closed_closed",
"(",
"date_range",
")",
"if",
"date_range",
"is",
"not",
"None",
":",
"a... | 33.583333 | 0.002413 |
def leave(self, node):
"""walk on the tree from <node>, getting callbacks from handler"""
method = self.get_callbacks(node)[1]
if method is not None:
method(node) | [
"def",
"leave",
"(",
"self",
",",
"node",
")",
":",
"method",
"=",
"self",
".",
"get_callbacks",
"(",
"node",
")",
"[",
"1",
"]",
"if",
"method",
"is",
"not",
"None",
":",
"method",
"(",
"node",
")"
] | 38.8 | 0.010101 |
def check_memory_usage(buffered_geo_extent, cell_size):
"""Helper to check if analysis is feasible when extents change.
For simplicity, we will do all our calculations in geocrs.
:param buffered_geo_extent: An extent in the for [xmin, ymin, xmax, ymax]
:type buffered_geo_extent: list
:param cell_... | [
"def",
"check_memory_usage",
"(",
"buffered_geo_extent",
",",
"cell_size",
")",
":",
"message",
"=",
"m",
".",
"Message",
"(",
")",
"check_heading",
"=",
"m",
".",
"Heading",
"(",
"tr",
"(",
"'Checking available memory'",
")",
",",
"*",
"*",
"PROGRESS_UPDATE_S... | 41.208696 | 0.000206 |
def to_unit(self, values, unit, from_unit):
"""Return values converted to the unit given the input from_unit."""
return self._to_unit_base('degC-days', values, unit, from_unit) | [
"def",
"to_unit",
"(",
"self",
",",
"values",
",",
"unit",
",",
"from_unit",
")",
":",
"return",
"self",
".",
"_to_unit_base",
"(",
"'degC-days'",
",",
"values",
",",
"unit",
",",
"from_unit",
")"
] | 63.333333 | 0.010417 |
def url_as_file(url, ext=None):
"""
Context manager that GETs a given `url` and provides it as a local file.
The file is in a closed state upon entering the context,
and removed when leaving it, if still there.
To give the file name a specific extension, use `ext`;
the exte... | [
"def",
"url_as_file",
"(",
"url",
",",
"ext",
"=",
"None",
")",
":",
"if",
"ext",
":",
"ext",
"=",
"'.'",
"+",
"ext",
".",
"strip",
"(",
"'.'",
")",
"# normalize extension",
"url_hint",
"=",
"'www-{}-'",
".",
"format",
"(",
"urlparse",
"(",
"url",
")... | 34.395833 | 0.002356 |
def message(self):
"""Return RTSP method based on sequence number from session."""
message = self.message_methods[self.session.method]()
_LOGGER.debug(message)
return message | [
"def",
"message",
"(",
"self",
")",
":",
"message",
"=",
"self",
".",
"message_methods",
"[",
"self",
".",
"session",
".",
"method",
"]",
"(",
")",
"_LOGGER",
".",
"debug",
"(",
"message",
")",
"return",
"message"
] | 40.4 | 0.009709 |
def gmres_prolongation_smoothing(A, T, B, BtBinv, Sparsity_Pattern, maxiter,
tol, weighting='local', Cpt_params=None):
"""Use GMRES to smooth T by solving A T = 0, subject to nullspace and sparsity constraints.
Parameters
----------
A : csr_matrix, bsr_matrix
SP... | [
"def",
"gmres_prolongation_smoothing",
"(",
"A",
",",
"T",
",",
"B",
",",
"BtBinv",
",",
"Sparsity_Pattern",
",",
"maxiter",
",",
"tol",
",",
"weighting",
"=",
"'local'",
",",
"Cpt_params",
"=",
"None",
")",
":",
"# For non-SPD system, apply GMRES with Diagonal Pr... | 38.462555 | 0.000223 |
def copy(self, space=None, name=None):
"""Make a copy of itself and return it."""
return Cells(space=space, name=name, formula=self.formula) | [
"def",
"copy",
"(",
"self",
",",
"space",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"return",
"Cells",
"(",
"space",
"=",
"space",
",",
"name",
"=",
"name",
",",
"formula",
"=",
"self",
".",
"formula",
")"
] | 51.333333 | 0.012821 |
def helper(path):
"""
link helper files to given path
"""
if sys.platform.startswith("win"):
# link batch files
src_path = os.path.join(PHLB_BASE_DIR, "helper_cmd")
elif sys.platform.startswith("linux"):
# link shell scripts
src_path = os.path.join(PHLB_BASE_DIR, "hel... | [
"def",
"helper",
"(",
"path",
")",
":",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"\"win\"",
")",
":",
"# link batch files",
"src_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"PHLB_BASE_DIR",
",",
"\"helper_cmd\"",
")",
"elif",
"sys",
"."... | 29.918919 | 0.00175 |
def colinear_pairs(segments,
radius=.01,
angle=.01,
length=None):
"""
Find pairs of segments which are colinear.
Parameters
-------------
segments : (n, 2, (2, 3)) float
Two or three dimensional line segments
radius : float
Ma... | [
"def",
"colinear_pairs",
"(",
"segments",
",",
"radius",
"=",
".01",
",",
"angle",
"=",
".01",
",",
"length",
"=",
"None",
")",
":",
"from",
"scipy",
"import",
"spatial",
"# convert segments to parameterized origins",
"# which are the closest point on the line to",
"#... | 31.507692 | 0.000473 |
def list_renderers(*args):
'''
List the renderers loaded on the minion
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' sys.list_renderers
Render names can be specified as globs.
.. code-block:: bash
salt '*' sys.list_renderers 'yaml*'
'''
... | [
"def",
"list_renderers",
"(",
"*",
"args",
")",
":",
"renderers_",
"=",
"salt",
".",
"loader",
".",
"render",
"(",
"__opts__",
",",
"[",
"]",
")",
"renderers",
"=",
"set",
"(",
")",
"if",
"not",
"args",
":",
"for",
"rend",
"in",
"six",
".",
"iterke... | 20.290323 | 0.001517 |
def _convert_flux(wavelengths, fluxes, out_flux_unit, area=None,
vegaspec=None):
"""Flux conversion for PHOTLAM <-> X."""
flux_unit_names = (fluxes.unit.to_string(), out_flux_unit.to_string())
if PHOTLAM.to_string() not in flux_unit_names:
raise exceptions.SynphotError(
... | [
"def",
"_convert_flux",
"(",
"wavelengths",
",",
"fluxes",
",",
"out_flux_unit",
",",
"area",
"=",
"None",
",",
"vegaspec",
"=",
"None",
")",
":",
"flux_unit_names",
"=",
"(",
"fluxes",
".",
"unit",
".",
"to_string",
"(",
")",
",",
"out_flux_unit",
".",
... | 34.243902 | 0.000693 |
def sanitize_word(s):
"""Remove non-alphanumerical characters from metric word.
And trim excessive underscores.
"""
s = re.sub('[^\w-]+', '_', s)
s = re.sub('__+', '_', s)
return s.strip('_') | [
"def",
"sanitize_word",
"(",
"s",
")",
":",
"s",
"=",
"re",
".",
"sub",
"(",
"'[^\\w-]+'",
",",
"'_'",
",",
"s",
")",
"s",
"=",
"re",
".",
"sub",
"(",
"'__+'",
",",
"'_'",
",",
"s",
")",
"return",
"s",
".",
"strip",
"(",
"'_'",
")"
] | 29.857143 | 0.009302 |
def partial_fit(self, X, y=None, classes=None, **fit_params):
"""Fit the module.
If the module is initialized, it is not re-initialized, which
means that this method should be used if you want to continue
training a model (warm start).
Parameters
----------
X : ... | [
"def",
"partial_fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
",",
"classes",
"=",
"None",
",",
"*",
"*",
"fit_params",
")",
":",
"if",
"not",
"self",
".",
"initialized_",
":",
"self",
".",
"initialize",
"(",
")",
"self",
".",
"notify",
"(",
... | 33.282609 | 0.001269 |
def Show(self, waitTime: float = OPERATION_WAIT_TIME) -> bool:
"""
Call native `ShowWindow(SW.Show)`.
Return bool, True if succeed otherwise False.
"""
return self.ShowWindow(SW.Show, waitTime) | [
"def",
"Show",
"(",
"self",
",",
"waitTime",
":",
"float",
"=",
"OPERATION_WAIT_TIME",
")",
"->",
"bool",
":",
"return",
"self",
".",
"ShowWindow",
"(",
"SW",
".",
"Show",
",",
"waitTime",
")"
] | 38 | 0.008584 |
def close_cursor(self, cursor_id, address=None):
"""DEPRECATED - Send a kill cursors message soon with the given id.
Raises :class:`TypeError` if `cursor_id` is not an instance of
``(int, long)``. What closing the cursor actually means
depends on this client's cursor manager.
T... | [
"def",
"close_cursor",
"(",
"self",
",",
"cursor_id",
",",
"address",
"=",
"None",
")",
":",
"warnings",
".",
"warn",
"(",
"\"close_cursor is deprecated.\"",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"2",
")",
"if",
"not",
"isinstance",
"(",
"cursor_i... | 39.46875 | 0.001546 |
def parse_config_section(config_section, section_schema):
"""Parse a config file section (INI file) by using its schema/description.
.. sourcecode::
import configparser # -- NOTE: Use backport for Python2
import click
from click_configfile import SectionSchema, Param, parse_config_... | [
"def",
"parse_config_section",
"(",
"config_section",
",",
"section_schema",
")",
":",
"storage",
"=",
"{",
"}",
"for",
"name",
",",
"param",
"in",
"select_params_from_section_schema",
"(",
"section_schema",
")",
":",
"value",
"=",
"config_section",
".",
"get",
... | 35.72 | 0.000545 |
def log_likelihood_css_arma(self, diffedy):
"""
log likelihood based on conditional sum of squares. In contrast to logLikelihoodCSS the array
provided should correspond to an already differenced array, so that the function below
corresponds to the log likelihood for the ARMA rather than ... | [
"def",
"log_likelihood_css_arma",
"(",
"self",
",",
"diffedy",
")",
":",
"# need to copy diffedy to a double[] for Java",
"likelihood",
"=",
"self",
".",
"_jmodel",
".",
"logLikelihoodCSSARMA",
"(",
"_py2java_double_array",
"(",
"self",
".",
"_ctx",
",",
"diffedy",
")... | 44.0625 | 0.0125 |
def tokens(self):
""" Return a list of (type, value) tokens. """
if not self._tokens:
self._tokens = list(self.tokenise(self.route))
return self._tokens | [
"def",
"tokens",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_tokens",
":",
"self",
".",
"_tokens",
"=",
"list",
"(",
"self",
".",
"tokenise",
"(",
"self",
".",
"route",
")",
")",
"return",
"self",
".",
"_tokens"
] | 36.8 | 0.010638 |
def _serialize_zebra_family_prefix(prefix):
"""
Serializes family and prefix in Zebra format.
"""
if ip.valid_ipv4(prefix):
family = socket.AF_INET # fixup
prefix_addr, prefix_num = prefix.split('/')
return family, struct.pack(
_ZEBRA_FAMILY_IPV4_PREFIX_FMT,
... | [
"def",
"_serialize_zebra_family_prefix",
"(",
"prefix",
")",
":",
"if",
"ip",
".",
"valid_ipv4",
"(",
"prefix",
")",
":",
"family",
"=",
"socket",
".",
"AF_INET",
"# fixup",
"prefix_addr",
",",
"prefix_num",
"=",
"prefix",
".",
"split",
"(",
"'/'",
")",
"r... | 34.090909 | 0.001297 |
def _markdownify(tag, _listType=None, _blockQuote=False, _listIndex=1):
"""recursively converts a tag into markdown"""
children = tag.find_all(recursive=False)
if tag.name == '[document]':
for child in children:
_markdownify(child)
return
if tag.name not in _supportedTags or not _supportedAttrs(tag):
if ... | [
"def",
"_markdownify",
"(",
"tag",
",",
"_listType",
"=",
"None",
",",
"_blockQuote",
"=",
"False",
",",
"_listIndex",
"=",
"1",
")",
":",
"children",
"=",
"tag",
".",
"find_all",
"(",
"recursive",
"=",
"False",
")",
"if",
"tag",
".",
"name",
"==",
"... | 25.035714 | 0.039104 |
def delete_subtask(client, subtask_id, revision):
''' Deletes the subtask with the given ID provided the given revision equals the revision the server has '''
params = {
'revision' : int(revision),
}
endpoint = '/'.join([client.api.Endpoints.SUBTASKS, str(subtask_id)])
client.aut... | [
"def",
"delete_subtask",
"(",
"client",
",",
"subtask_id",
",",
"revision",
")",
":",
"params",
"=",
"{",
"'revision'",
":",
"int",
"(",
"revision",
")",
",",
"}",
"endpoint",
"=",
"'/'",
".",
"join",
"(",
"[",
"client",
".",
"api",
".",
"Endpoints",
... | 52.428571 | 0.008043 |
def find(cls, where='.', exclude=(), include=('*',)):
"""Return a list all Python packages found within directory 'where'
'where' should be supplied as a "cross-platform" (i.e. URL-style)
path; it will be converted to the appropriate local path syntax.
'exclude' is a sequence of package... | [
"def",
"find",
"(",
"cls",
",",
"where",
"=",
"'.'",
",",
"exclude",
"=",
"(",
")",
",",
"include",
"=",
"(",
"'*'",
",",
")",
")",
":",
"out",
"=",
"cls",
".",
"_find_packages_iter",
"(",
"convert_path",
"(",
"where",
")",
")",
"out",
"=",
"cls"... | 50 | 0.001635 |
def show_type(self, edge_type, **kwargs):
"""Draws the network, highlighting queues of a certain type.
The colored vertices represent self loops of type ``edge_type``.
Dark edges represent queues of type ``edge_type``.
Parameters
----------
edge_type : int
T... | [
"def",
"show_type",
"(",
"self",
",",
"edge_type",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"v",
"in",
"self",
".",
"g",
".",
"nodes",
"(",
")",
":",
"e",
"=",
"(",
"v",
",",
"v",
")",
"if",
"self",
".",
"g",
".",
"is_edge",
"(",
"e",
")",... | 39.90566 | 0.002307 |
def create_new_cookbook(cookbook_name, cookbooks_home):
"""Create a new cookbook.
:param cookbook_name: Name of the new cookbook.
:param cookbooks_home: Target dir for new cookbook.
"""
cookbooks_home = utils.normalize_path(cookbooks_home)
if not os.path.exists(cookbooks_home):
raise V... | [
"def",
"create_new_cookbook",
"(",
"cookbook_name",
",",
"cookbooks_home",
")",
":",
"cookbooks_home",
"=",
"utils",
".",
"normalize_path",
"(",
"cookbooks_home",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"cookbooks_home",
")",
":",
"raise",
"Va... | 32.692308 | 0.001143 |
def bulk_call(self, call_params):
"""REST BulkCalls Helper
"""
path = '/' + self.api_version + '/BulkCall/'
method = 'POST'
return self.request(path, method, call_params) | [
"def",
"bulk_call",
"(",
"self",
",",
"call_params",
")",
":",
"path",
"=",
"'/'",
"+",
"self",
".",
"api_version",
"+",
"'/BulkCall/'",
"method",
"=",
"'POST'",
"return",
"self",
".",
"request",
"(",
"path",
",",
"method",
",",
"call_params",
")"
] | 34.166667 | 0.009524 |
def quat2mat(quaternion):
"""
Converts given quaternion (x, y, z, w) to matrix.
Args:
quaternion: vec4 float angles
Returns:
3x3 rotation matrix
"""
q = np.array(quaternion, dtype=np.float32, copy=True)[[3, 0, 1, 2]]
n = np.dot(q, q)
if n < EPS:
return np.identi... | [
"def",
"quat2mat",
"(",
"quaternion",
")",
":",
"q",
"=",
"np",
".",
"array",
"(",
"quaternion",
",",
"dtype",
"=",
"np",
".",
"float32",
",",
"copy",
"=",
"True",
")",
"[",
"[",
"3",
",",
"0",
",",
"1",
",",
"2",
"]",
"]",
"n",
"=",
"np",
... | 27.478261 | 0.001529 |
def create_extension(namespace, nicira_header, nx_action, nx_stats_request, nx_stats_reply,
msg_subtype, action_subtype, stats_subtype):
'''
/* This command enables or disables an Open vSwitch extension that allows a
* controller to specify the OpenFlow table to which a flow should be ... | [
"def",
"create_extension",
"(",
"namespace",
",",
"nicira_header",
",",
"nx_action",
",",
"nx_stats_request",
",",
"nx_stats_reply",
",",
"msg_subtype",
",",
"action_subtype",
",",
"stats_subtype",
")",
":",
"with",
"_warnings",
".",
"catch_warnings",
"(",
")",
":... | 52.216632 | 0.014277 |
def pan_cb(self, setting, value):
"""Handle callback related to changes in pan."""
pan_x, pan_y = value[:2]
self.logger.debug("pan set to %.2f,%.2f" % (pan_x, pan_y))
self.redraw(whence=0) | [
"def",
"pan_cb",
"(",
"self",
",",
"setting",
",",
"value",
")",
":",
"pan_x",
",",
"pan_y",
"=",
"value",
"[",
":",
"2",
"]",
"self",
".",
"logger",
".",
"debug",
"(",
"\"pan set to %.2f,%.2f\"",
"%",
"(",
"pan_x",
",",
"pan_y",
")",
")",
"self",
... | 36 | 0.00905 |
def read_stat():
"""
Returns the system stat information.
:returns: The system stat information.
:rtype: list
"""
data = []
with open("/proc/stat", "rb") as stat_file:
for line in stat_file:
cpu_stat = line.split()
if cpu_stat[0][:3] != b"cpu":
... | [
"def",
"read_stat",
"(",
")",
":",
"data",
"=",
"[",
"]",
"with",
"open",
"(",
"\"/proc/stat\"",
",",
"\"rb\"",
")",
"as",
"stat_file",
":",
"for",
"line",
"in",
"stat_file",
":",
"cpu_stat",
"=",
"line",
".",
"split",
"(",
")",
"if",
"cpu_stat",
"["... | 29.535714 | 0.001171 |
def _download_images(data, img_cols):
"""Download images given image columns."""
images = collections.defaultdict(list)
for d in data:
for img_col in img_cols:
if d.get(img_col, None):
if isinstance(d[img_col], Image.Image):
# If it is already an Image, just copy and continue.
... | [
"def",
"_download_images",
"(",
"data",
",",
"img_cols",
")",
":",
"images",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"for",
"d",
"in",
"data",
":",
"for",
"img_col",
"in",
"img_cols",
":",
"if",
"d",
".",
"get",
"(",
"img_col",
",",
... | 31.368421 | 0.019544 |
def scf_compute_coeffs(dens, N, L, a=1., radial_order=None, costheta_order=None, phi_order=None):
"""
NAME:
scf_compute_coeffs
PURPOSE:
Numerically compute the expansion coefficients for a given triaxial density
INPUT:
dens - A density functi... | [
"def",
"scf_compute_coeffs",
"(",
"dens",
",",
"N",
",",
"L",
",",
"a",
"=",
"1.",
",",
"radial_order",
"=",
"None",
",",
"costheta_order",
"=",
"None",
",",
"phi_order",
"=",
"None",
")",
":",
"def",
"integrand",
"(",
"xi",
",",
"costheta",
",",
"ph... | 37.45 | 0.026016 |
def create_parser():
"""Creates the Namespace object to be used by the rest of the tool"""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('-d', '--dictionary',
nargs='?',
default='dictionaries/all_en_US.dict',
... | [
"def",
"create_parser",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"__doc__",
")",
"parser",
".",
"add_argument",
"(",
"'-d'",
",",
"'--dictionary'",
",",
"nargs",
"=",
"'?'",
",",
"default",
"=",
"'dictionaries... | 46.4375 | 0.000659 |
def resolve_spec_identifier(self, obj_name):
"""Find reference name based on spec identifier
Spec identifiers are used in parameter and return type definitions, but
should be a user-friendly version instead. Use docfx ``references``
lookup mapping for resolution.
If the spec id... | [
"def",
"resolve_spec_identifier",
"(",
"self",
",",
"obj_name",
")",
":",
"ref",
"=",
"self",
".",
"references",
".",
"get",
"(",
"obj_name",
")",
"if",
"ref",
"is",
"None",
":",
"return",
"obj_name",
"resolved",
"=",
"ref",
".",
"get",
"(",
"\"fullName\... | 38.275 | 0.001911 |
def connect(self, event, func=None):
"""
Connect a callback to a `Cursor` event; return the callback.
Two events can be connected to:
- callbacks connected to the ``"add"`` event are called when a
`Selection` is added, with that selection as only argument;
- callbacks... | [
"def",
"connect",
"(",
"self",
",",
"event",
",",
"func",
"=",
"None",
")",
":",
"if",
"event",
"not",
"in",
"self",
".",
"_callbacks",
":",
"raise",
"ValueError",
"(",
"\"{!r} is not a valid cursor event\"",
".",
"format",
"(",
"event",
")",
")",
"if",
... | 35.212121 | 0.001675 |
def _maybe_create_resources(logging_task: Task = None):
"""Use heuristics to decide to possibly create resources"""
def log(*args):
if logging_task:
logging_task.log(*args)
else:
util.log(*args)
def should_create_resources():
"""Check if gateway, keypair, vpc exist."""
prefix = u.get... | [
"def",
"_maybe_create_resources",
"(",
"logging_task",
":",
"Task",
"=",
"None",
")",
":",
"def",
"log",
"(",
"*",
"args",
")",
":",
"if",
"logging_task",
":",
"logging_task",
".",
"log",
"(",
"*",
"args",
")",
"else",
":",
"util",
".",
"log",
"(",
"... | 31.827586 | 0.015765 |
def check_files(filelist,
file_stage_manager=None,
return_found=True,
return_missing=True):
"""Check that all files in a list exist
Parameters
----------
filelist : list
The list of files we are checking for.
file_stage_manager : `fermipy.jo... | [
"def",
"check_files",
"(",
"filelist",
",",
"file_stage_manager",
"=",
"None",
",",
"return_found",
"=",
"True",
",",
"return_missing",
"=",
"True",
")",
":",
"found",
"=",
"[",
"]",
"missing",
"=",
"[",
"]",
"none_count",
"=",
"0",
"for",
"fname",
"in",... | 26.067797 | 0.000627 |
def constant_tuples(self):
"""
Returns
-------
constants: [(String, Constant)]
"""
return [constant_tuple for tuple_prior in self.tuple_prior_tuples for constant_tuple in
tuple_prior[1].constant_tuples] + self.direct_constant_tuples | [
"def",
"constant_tuples",
"(",
"self",
")",
":",
"return",
"[",
"constant_tuple",
"for",
"tuple_prior",
"in",
"self",
".",
"tuple_prior_tuples",
"for",
"constant_tuple",
"in",
"tuple_prior",
"[",
"1",
"]",
".",
"constant_tuples",
"]",
"+",
"self",
".",
"direct... | 36.125 | 0.010135 |
def trigger_update(self, trigger_parent=True):
"""
Update the model from the current state.
Make sure that updates are on, otherwise this
method will do nothing
:param bool trigger_parent: Whether to trigger the parent, after self has updated
"""
if not self.upda... | [
"def",
"trigger_update",
"(",
"self",
",",
"trigger_parent",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"update_model",
"(",
")",
"or",
"(",
"hasattr",
"(",
"self",
",",
"\"_in_init_\"",
")",
"and",
"self",
".",
"_in_init_",
")",
":",
"#print \"War... | 43.75 | 0.011194 |
def spam(self, msg, *args, **kw):
"""Log a message with level :data:`SPAM`. The arguments are interpreted as for :func:`logging.debug()`."""
if self.isEnabledFor(SPAM):
self._log(SPAM, msg, args, **kw) | [
"def",
"spam",
"(",
"self",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"if",
"self",
".",
"isEnabledFor",
"(",
"SPAM",
")",
":",
"self",
".",
"_log",
"(",
"SPAM",
",",
"msg",
",",
"args",
",",
"*",
"*",
"kw",
")"
] | 56.5 | 0.0131 |
def groupby(cls, dataset, dims, container_type=HoloMap, group_type=None, **kwargs):
"""
Groups the data by one or more dimensions returning a container
indexed by the grouped dimensions containing slices of the
cube wrapped in the group_type. This makes it very easy to
break up a... | [
"def",
"groupby",
"(",
"cls",
",",
"dataset",
",",
"dims",
",",
"container_type",
"=",
"HoloMap",
",",
"group_type",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"iris",
"if",
"not",
"isinstance",
"(",
"dims",
",",
"list",
")",
":",
"dim... | 45.175 | 0.002167 |
def K2onSilicon(infile, fieldnum, do_nearSiliconCheck=False):
"""Checks whether targets are on silicon during a given campaign.
This function will write a csv table called targets_siliconFlag.csv,
which details the silicon status for each target listed in `infile`
(0 = not on silicon, 2 = on silion).
... | [
"def",
"K2onSilicon",
"(",
"infile",
",",
"fieldnum",
",",
"do_nearSiliconCheck",
"=",
"False",
")",
":",
"ra_sources_deg",
",",
"dec_sources_deg",
",",
"mag",
"=",
"parse_file",
"(",
"infile",
")",
"n_sources",
"=",
"np",
".",
"shape",
"(",
"ra_sources_deg",
... | 35.978723 | 0.000288 |
def reduce(vector):
"""
Can be a vector or matrix. If data are bool, sum Trues.
"""
if type(vector) is list: # matrix
return array(list(map(add.reduce, vector)))
else:
return sum(vector) | [
"def",
"reduce",
"(",
"vector",
")",
":",
"if",
"type",
"(",
"vector",
")",
"is",
"list",
":",
"# matrix",
"return",
"array",
"(",
"list",
"(",
"map",
"(",
"add",
".",
"reduce",
",",
"vector",
")",
")",
")",
"else",
":",
"return",
"sum",
"(",
"ve... | 30.375 | 0.012 |
def select_template(template_name_list, using=None):
"""
Loads and returns a template for one of the given names.
Tries names in order and returns the first template found.
Raises TemplateDoesNotExist if no such template exists.
"""
if isinstance(template_name_list, six.string_types):
ra... | [
"def",
"select_template",
"(",
"template_name_list",
",",
"using",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"template_name_list",
",",
"six",
".",
"string_types",
")",
":",
"raise",
"TypeError",
"(",
"'select_template() takes an iterable of template names but got... | 37.96 | 0.001028 |
def create_deepcopied_groupby_dict(orig_df, obs_id_col):
"""
Will create a dictionary where each key corresponds to a unique value in
`orig_df[obs_id_col]` and each value corresponds to all of the rows of
`orig_df` where `orig_df[obs_id_col] == key`.
Parameters
----------
orig_df : pandas D... | [
"def",
"create_deepcopied_groupby_dict",
"(",
"orig_df",
",",
"obs_id_col",
")",
":",
"# Get the observation id values",
"obs_id_vals",
"=",
"orig_df",
"[",
"obs_id_col",
"]",
".",
"values",
"# Get the unique observation ids",
"unique_obs_ids",
"=",
"np",
".",
"unique",
... | 38.638889 | 0.000701 |
def apply_overwrites_to_context(context, overwrite_context):
"""Modify the given context in place based on the overwrite_context."""
for variable, overwrite in overwrite_context.items():
if variable not in context:
# Do not include variables which are not used in the template
con... | [
"def",
"apply_overwrites_to_context",
"(",
"context",
",",
"overwrite_context",
")",
":",
"for",
"variable",
",",
"overwrite",
"in",
"overwrite_context",
".",
"items",
"(",
")",
":",
"if",
"variable",
"not",
"in",
"context",
":",
"# Do not include variables which ar... | 46.2 | 0.00106 |
def subs(self, path):
"""
Search the strings in a config file for a substitutable value, e.g.
"morphologies_dir": "$COMPONENT_DIR/morphologies",
"""
#print_v('Checking for: \n %s, \n %s \n in %s'%(self.substitutes,self.init_substitutes,path))
if type(path) == ... | [
"def",
"subs",
"(",
"self",
",",
"path",
")",
":",
"#print_v('Checking for: \\n %s, \\n %s \\n in %s'%(self.substitutes,self.init_substitutes,path))",
"if",
"type",
"(",
"path",
")",
"==",
"int",
"or",
"type",
"(",
"path",
")",
"==",
"float",
":",
"return",
"path... | 42.117647 | 0.012295 |
def totp(key, format='dec6', period=30, t=None, hash=hashlib.sha1):
'''
Compute a TOTP value as prescribed by OATH specifications.
:param key:
the TOTP key given as an hexadecimal string
:param format:
the output format, can be:
- hex, for a variable length ... | [
"def",
"totp",
"(",
"key",
",",
"format",
"=",
"'dec6'",
",",
"period",
"=",
"30",
",",
"t",
"=",
"None",
",",
"hash",
"=",
"hashlib",
".",
"sha1",
")",
":",
"if",
"t",
"is",
"None",
":",
"t",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
... | 36.230769 | 0.002068 |
def list_templates(call=None):
'''
Lists all templates available to the user and the user's groups.
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt-cloud -f list_templates opennebula
'''
if call == 'action':
raise SaltCloudSystemExit(
'The li... | [
"def",
"list_templates",
"(",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_templates function must be called with -f or --function.'",
")",
"server",
",",
"user",
",",
"password",
"=",
"_get_xml_rp... | 26 | 0.001427 |
def interval_host(host, time, f, *args, **kwargs):
'''
Creates an Event attached to the *host* for management that will
execute the *f* function every *time* seconds.
See example in :ref:`sample_inter`
:param Proxy host: proxy of the host. Can be obtained from inside a
class with ``self.ho... | [
"def",
"interval_host",
"(",
"host",
",",
"time",
",",
"f",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"wrap",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"thread",
"=",
"getcurrent",
"(",
")",
"args",
"=",
"list",
"("... | 32.0625 | 0.000946 |
def parse_text_block(text: str) -> Tuple[str, str]:
"""
This will take a text block and return a tuple with body and footer,
where footer is defined as the last paragraph.
:param text: The text string to be divided.
:return: A tuple with body and footer,
where footer is defined as the last para... | [
"def",
"parse_text_block",
"(",
"text",
":",
"str",
")",
"->",
"Tuple",
"[",
"str",
",",
"str",
"]",
":",
"body",
",",
"footer",
"=",
"''",
",",
"''",
"if",
"text",
":",
"body",
"=",
"text",
".",
"split",
"(",
"'\\n\\n'",
")",
"[",
"0",
"]",
"i... | 33.875 | 0.001795 |
def get_remote_task_list(
self, peer_id, list_type=ListType.downloading, pos=0, number=10):
'''
list 返回列表
{
"recycleNum": 0,
"serverFailNum": 0,
"rtn": 0,
"completeNum": 34,
"sync": 0,
"tasks": [{
... | [
"def",
"get_remote_task_list",
"(",
"self",
",",
"peer_id",
",",
"list_type",
"=",
"ListType",
".",
"downloading",
",",
"pos",
"=",
"0",
",",
"number",
"=",
"10",
")",
":",
"params",
"=",
"{",
"'pid'",
":",
"peer_id",
",",
"'type'",
":",
"list_type",
"... | 28.542373 | 0.001148 |
def check(text):
"""Suggest the preferred forms."""
err = "strunk_white.composition"
msg = "Try '{}' instead of '{}'."
bad_forms = [
# Put statements in positive form
["dishonest", ["not honest"]],
["trifling", ["not important"]],
["forgot", ... | [
"def",
"check",
"(",
"text",
")",
":",
"err",
"=",
"\"strunk_white.composition\"",
"msg",
"=",
"\"Try '{}' instead of '{}'.\"",
"bad_forms",
"=",
"[",
"# Put statements in positive form",
"[",
"\"dishonest\"",
",",
"[",
"\"not honest\"",
"]",
"]",
",",
"[",
"\"trifl... | 47.454545 | 0.000626 |
def script_string_to_notebook_with_links(str, pth, cr=None):
"""
Convert a python script represented as string `str` to a notebook
with filename `pth` and replace sphinx cross-references with links
to online docs. Parameter `cr` is a CrossReferenceLookup object.
"""
if cr is None:
scrip... | [
"def",
"script_string_to_notebook_with_links",
"(",
"str",
",",
"pth",
",",
"cr",
"=",
"None",
")",
":",
"if",
"cr",
"is",
"None",
":",
"script_string_to_notebook",
"(",
"str",
",",
"pth",
")",
"else",
":",
"ntbk",
"=",
"script_string_to_notebook_object",
"(",... | 37.285714 | 0.001869 |
def _spline(t, p0, p1, p2, p3):
"""
Catmull-Rom cubic spline to interpolate 4 given points.
:param t: Time index through the spline (must be 0-1).
:param p0: The previous point in the curve (for continuity).
:param p1: The first point to interpolate.
:param p2: The second point to interpolate.
... | [
"def",
"_spline",
"(",
"t",
",",
"p0",
",",
"p1",
",",
"p2",
",",
"p3",
")",
":",
"return",
"(",
"t",
"*",
"(",
"(",
"2",
"-",
"t",
")",
"*",
"t",
"-",
"1",
")",
"*",
"p0",
"+",
"(",
"t",
"*",
"t",
"*",
"(",
"3",
"*",
"t",
"-",
"5",... | 35 | 0.001855 |
def is_enabled(iface):
'''
Returns ``True`` if interface is enabled, otherwise ``False``
CLI Example:
.. code-block:: bash
salt -G 'os_family:Windows' ip.is_enabled 'Local Area Connection #2'
'''
cmd = ['netsh', 'interface', 'show', 'interface', 'name={0}'.format(iface)]
iface_fou... | [
"def",
"is_enabled",
"(",
"iface",
")",
":",
"cmd",
"=",
"[",
"'netsh'",
",",
"'interface'",
",",
"'show'",
",",
"'interface'",
",",
"'name={0}'",
".",
"format",
"(",
"iface",
")",
"]",
"iface_found",
"=",
"False",
"for",
"line",
"in",
"__salt__",
"[",
... | 30.857143 | 0.001497 |
def remove(self, flag, extra):
"""Remove Slackware binary packages
"""
self.flag = flag
self.extra = extra
self.dep_path = self.meta.log_path + "dep/"
dependencies, rmv_list = [], []
self.removed = self._view_removed()
if not self.removed:
prin... | [
"def",
"remove",
"(",
"self",
",",
"flag",
",",
"extra",
")",
":",
"self",
".",
"flag",
"=",
"flag",
"self",
".",
"extra",
"=",
"extra",
"self",
".",
"dep_path",
"=",
"self",
".",
"meta",
".",
"log_path",
"+",
"\"dep/\"",
"dependencies",
",",
"rmv_li... | 46.386364 | 0.001919 |
def trim_empty_columns(self):
"""Removes all trailing empty columns."""
if self.nrows != 0 and self.ncols != 0:
last_col = -1
for row in self.rows:
for i in range(last_col + 1, len(row)):
if not self.is_cell_empty(row[i]):
last_col = i
ncols = last_col + 1
s... | [
"def",
"trim_empty_columns",
"(",
"self",
")",
":",
"if",
"self",
".",
"nrows",
"!=",
"0",
"and",
"self",
".",
"ncols",
"!=",
"0",
":",
"last_col",
"=",
"-",
"1",
"for",
"row",
"in",
"self",
".",
"rows",
":",
"for",
"i",
"in",
"range",
"(",
"last... | 32.916667 | 0.017241 |
def _requirement_element(self, parent_element, req_data):
"""Adds requirement XML element."""
req_data = self._transform_result(req_data)
if not req_data:
return
title = req_data.get("title")
if not title:
logger.warning("Skipping requirement, title is mi... | [
"def",
"_requirement_element",
"(",
"self",
",",
"parent_element",
",",
"req_data",
")",
":",
"req_data",
"=",
"self",
".",
"_transform_result",
"(",
"req_data",
")",
"if",
"not",
"req_data",
":",
"return",
"title",
"=",
"req_data",
".",
"get",
"(",
"\"title... | 36.054054 | 0.00219 |
def find_entity_view(self, view_type, begin_entity=None, filter={},
properties=None):
"""Find a ManagedEntity of the requested type.
Traverses the MOB looking for an entity matching the filter.
:param view_type: The type of ManagedEntity to find.
:type view_typ... | [
"def",
"find_entity_view",
"(",
"self",
",",
"view_type",
",",
"begin_entity",
"=",
"None",
",",
"filter",
"=",
"{",
"}",
",",
"properties",
"=",
"None",
")",
":",
"if",
"properties",
"is",
"None",
":",
"properties",
"=",
"[",
"]",
"kls",
"=",
"classma... | 40.602273 | 0.002186 |
def pause(ctx):
"""
Pause work on the current issue.
This command puts the issue in the configured paused status and stops the
current Harvest timer.
"""
lancet = ctx.obj
paused_status = lancet.config.get("tracker", "paused_status")
# Get the issue
issue = get_issue(lancet)
# ... | [
"def",
"pause",
"(",
"ctx",
")",
":",
"lancet",
"=",
"ctx",
".",
"obj",
"paused_status",
"=",
"lancet",
".",
"config",
".",
"get",
"(",
"\"tracker\"",
",",
"\"paused_status\"",
")",
"# Get the issue",
"issue",
"=",
"get_issue",
"(",
"lancet",
")",
"# Make ... | 28.136364 | 0.001563 |
def check_sign(api_secret, msg):
"""
>>> check_sign("123456",dict(code=1,s='2',msg=u'中文',sign='33C9065427EECA3490C5642C99165145'))
True
"""
if "sign" not in msg:
return False
sign = msg['sign']
params = [utils.safestr(msg[k]) for k in msg if k != 'sign' and msg[k] is not Non... | [
"def",
"check_sign",
"(",
"api_secret",
",",
"msg",
")",
":",
"if",
"\"sign\"",
"not",
"in",
"msg",
":",
"return",
"False",
"sign",
"=",
"msg",
"[",
"'sign'",
"]",
"params",
"=",
"[",
"utils",
".",
"safestr",
"(",
"msg",
"[",
"k",
"]",
")",
"for",
... | 34.266667 | 0.011364 |
def pip_install(package, fatal=False, upgrade=False, venv=None,
constraints=None, **options):
"""Install a python package"""
if venv:
venv_python = os.path.join(venv, 'bin/pip')
command = [venv_python, "install"]
else:
command = ["install"]
available_options = ('... | [
"def",
"pip_install",
"(",
"package",
",",
"fatal",
"=",
"False",
",",
"upgrade",
"=",
"False",
",",
"venv",
"=",
"None",
",",
"constraints",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"if",
"venv",
":",
"venv_python",
"=",
"os",
".",
"path",
... | 28.966667 | 0.001114 |
def mid_lvl_cmds_send(self, target, hCommand, uCommand, rCommand, force_mavlink1=False):
'''
Mid Level commands sent from the GS to the autopilot. These are only
sent when being operated in mid-level commands mode
from the ground.
target ... | [
"def",
"mid_lvl_cmds_send",
"(",
"self",
",",
"target",
",",
"hCommand",
",",
"uCommand",
",",
"rCommand",
",",
"force_mavlink1",
"=",
"False",
")",
":",
"return",
"self",
".",
"send",
"(",
"self",
".",
"mid_lvl_cmds_encode",
"(",
"target",
",",
"hCommand",
... | 58.230769 | 0.009103 |
def normalize(self,asOf=None,multiplier=100):
"""
Returns a normalized series or DataFrame
Example:
Series.normalize()
Returns: series of DataFrame
Parameters:
-----------
asOf : string
Date format
'2015-02-29'
multiplier : int
Factor by which the results will be adjusted
"""
if not asOf:
... | [
"def",
"normalize",
"(",
"self",
",",
"asOf",
"=",
"None",
",",
"multiplier",
"=",
"100",
")",
":",
"if",
"not",
"asOf",
":",
"x0",
"=",
"self",
".",
"ix",
"[",
"0",
"]",
"else",
":",
"x0",
"=",
"self",
".",
"ix",
"[",
"asOf",
"]",
"return",
... | 16.590909 | 0.069948 |
def prepare_fds (self):
"""Create needed file descriptors (pipes, mostly) before forking."""
if '_in' in self.options:
i= self.options['_in']
logger.debug ('_in: %r', i)
# this condition is complex, but basically handles any type of input
# that is not go... | [
"def",
"prepare_fds",
"(",
"self",
")",
":",
"if",
"'_in'",
"in",
"self",
".",
"options",
":",
"i",
"=",
"self",
".",
"options",
"[",
"'_in'",
"]",
"logger",
".",
"debug",
"(",
"'_in: %r'",
",",
"i",
")",
"# this condition is complex, but basically handles a... | 51.853333 | 0.017663 |
def translate_item_ids(self, item_ids, language, is_nested=None):
"""
Translate a list of item ids to JSON objects which reference them.
Args:
item_ids (list[int]): item ids
language (str): language used for further filtering (some objects
for different l... | [
"def",
"translate_item_ids",
"(",
"self",
",",
"item_ids",
",",
"language",
",",
"is_nested",
"=",
"None",
")",
":",
"if",
"is_nested",
"is",
"None",
":",
"def",
"is_nested_fun",
"(",
"x",
")",
":",
"return",
"True",
"elif",
"isinstance",
"(",
"is_nested",... | 47.214286 | 0.00247 |
def track(image_list, initial_points, remove_bad=True):
"""Track points in image list
Parameters
----------------
image_list : list
List of images to track in
initial_points : ndarray
Initial points to use (in first image in image_list)
remove_bad : bool
... | [
"def",
"track",
"(",
"image_list",
",",
"initial_points",
",",
"remove_bad",
"=",
"True",
")",
":",
"# Precreate track array",
"tracks",
"=",
"np",
".",
"zeros",
"(",
"(",
"initial_points",
".",
"shape",
"[",
"0",
"]",
",",
"len",
"(",
"image_list",
")",
... | 40.195652 | 0.0132 |
def register_extension(self, module, extension):
"""
Function registers into self.commands from module extension.
All extension subcommands are registered using the name convention
'extension:command'
Example:
If you have a redis extension namely 'gredis', the extens... | [
"def",
"register_extension",
"(",
"self",
",",
"module",
",",
"extension",
")",
":",
"if",
"module",
"is",
"not",
"None",
":",
"cmds",
"=",
"self",
".",
"retrieve_commands",
"(",
"module",
")",
"commands",
"=",
"[",
"]",
"for",
"c",
"in",
"cmds",
":",
... | 33.115385 | 0.002257 |
def cli(env):
"""Virtual server order options."""
vsi = SoftLayer.VSManager(env.client)
result = vsi.get_create_options()
table = formatting.KeyValueTable(['name', 'value'])
table.align['name'] = 'r'
table.align['value'] = 'l'
# Datacenters
datacenters = [dc['template']['datacenter'][... | [
"def",
"cli",
"(",
"env",
")",
":",
"vsi",
"=",
"SoftLayer",
".",
"VSManager",
"(",
"env",
".",
"client",
")",
"result",
"=",
"vsi",
".",
"get_create_options",
"(",
")",
"table",
"=",
"formatting",
".",
"KeyValueTable",
"(",
"[",
"'name'",
",",
"'value... | 38.30719 | 0.00133 |
def add_becs_from_scf_task(self, scf_task, ddk_tolerance, ph_tolerance):
"""
Build tasks for the computation of Born effective charges and add them to the work.
Args:
scf_task: ScfTask object.
ddk_tolerance: dict {"varname": value} with the tolerance used in the DDK run.... | [
"def",
"add_becs_from_scf_task",
"(",
"self",
",",
"scf_task",
",",
"ddk_tolerance",
",",
"ph_tolerance",
")",
":",
"if",
"not",
"isinstance",
"(",
"scf_task",
",",
"ScfTask",
")",
":",
"raise",
"TypeError",
"(",
"\"task `%s` does not inherit from ScfTask\"",
"%",
... | 40.648649 | 0.011688 |
def accept_subgame(self, visitor: "BaseVisitor[ResultT]") -> ResultT:
"""
Traverses headers and game nodes in PGN order, as if the game was
starting after this node. Returns the *visitor* result.
"""
if visitor.begin_game() is not SKIP:
game = self.root()
... | [
"def",
"accept_subgame",
"(",
"self",
",",
"visitor",
":",
"\"BaseVisitor[ResultT]\"",
")",
"->",
"ResultT",
":",
"if",
"visitor",
".",
"begin_game",
"(",
")",
"is",
"not",
"SKIP",
":",
"game",
"=",
"self",
".",
"root",
"(",
")",
"board",
"=",
"self",
... | 35.633333 | 0.001821 |
def _load(self, metrix):
"""
Load time series.
:param timeseries: a TimeSeries, a dictionary or a path to a csv file(str).
:return TimeSeries: a TimeSeries object.
"""
if isinstance(metrix, TimeSeries):
return metrix
if isinstance(metrix, dict):
return TimeSeries(metrix)
retu... | [
"def",
"_load",
"(",
"self",
",",
"metrix",
")",
":",
"if",
"isinstance",
"(",
"metrix",
",",
"TimeSeries",
")",
":",
"return",
"metrix",
"if",
"isinstance",
"(",
"metrix",
",",
"dict",
")",
":",
"return",
"TimeSeries",
"(",
"metrix",
")",
"return",
"T... | 31.545455 | 0.008403 |
def init_session(self, get_token=True):
"""
init a new oauth2 session that is required to access the cloud
:param bool get_token: if True, a token will be obtained, after
the session has been created
"""
if (self._client_id is None) or (self._clien... | [
"def",
"init_session",
"(",
"self",
",",
"get_token",
"=",
"True",
")",
":",
"if",
"(",
"self",
".",
"_client_id",
"is",
"None",
")",
"or",
"(",
"self",
".",
"_client_secret",
"is",
"None",
")",
":",
"sys",
".",
"exit",
"(",
"\"Please make sure to set th... | 37.227273 | 0.002381 |
def record_udp_port(self, port):
"""
Associate a reserved UDP port number with this project.
:param port: UDP port number
"""
if port not in self._used_udp_ports:
self._used_udp_ports.add(port) | [
"def",
"record_udp_port",
"(",
"self",
",",
"port",
")",
":",
"if",
"port",
"not",
"in",
"self",
".",
"_used_udp_ports",
":",
"self",
".",
"_used_udp_ports",
".",
"add",
"(",
"port",
")"
] | 26.555556 | 0.008097 |
def saveSV(self, fname, comments=None, metadata=None, printmetadict=None,
dialect = None, delimiter=None, doublequote=True,
lineterminator='\n', escapechar = None, quoting=csv.QUOTE_MINIMAL,
quotechar='"', skipinitialspace=False,
... | [
"def",
"saveSV",
"(",
"self",
",",
"fname",
",",
"comments",
"=",
"None",
",",
"metadata",
"=",
"None",
",",
"printmetadict",
"=",
"None",
",",
"dialect",
"=",
"None",
",",
"delimiter",
"=",
"None",
",",
"doublequote",
"=",
"True",
",",
"lineterminator",... | 52.764706 | 0.029573 |
def who(self, *args):
"""Display a table of connected users and clients"""
if len(self._users) == 0:
self.log('No users connected')
if len(self._clients) == 0:
self.log('No clients connected')
return
Row = namedtuple("Row", ['User', 'Clien... | [
"def",
"who",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"len",
"(",
"self",
".",
"_users",
")",
"==",
"0",
":",
"self",
".",
"log",
"(",
"'No users connected'",
")",
"if",
"len",
"(",
"self",
".",
"_clients",
")",
"==",
"0",
":",
"self",
"... | 34.347826 | 0.002463 |
def create(context, name, country, active, parent_id):
"""create(context, name, country, active, parent_id)
Create a team.
>>> dcictl team-create [OPTIONS]
:param string name: Name of the team [required]
:param string country: Country code where the team is based
:param boolean active: Set th... | [
"def",
"create",
"(",
"context",
",",
"name",
",",
"country",
",",
"active",
",",
"parent_id",
")",
":",
"state",
"=",
"utils",
".",
"active_string",
"(",
"active",
")",
"result",
"=",
"team",
".",
"create",
"(",
"context",
",",
"name",
"=",
"name",
... | 36.529412 | 0.00157 |
def submit_status_external_cmd(cmd_file, status_file):
''' Submits the status lines in the status_file to Nagios' external cmd file.
'''
try:
with open(cmd_file, 'a') as cmd_file:
cmd_file.write(status_file.read())
except IOError:
exit("Fatal error: Unable to write to Nagios external command file ... | [
"def",
"submit_status_external_cmd",
"(",
"cmd_file",
",",
"status_file",
")",
":",
"try",
":",
"with",
"open",
"(",
"cmd_file",
",",
"'a'",
")",
"as",
"cmd_file",
":",
"cmd_file",
".",
"write",
"(",
"status_file",
".",
"read",
"(",
")",
")",
"except",
"... | 43.777778 | 0.012438 |
def start(self, n):
"""Start n copies of the process using the Win HPC job scheduler."""
self.write_job_file(n)
args = [
'submit',
'/jobfile:%s' % self.job_file,
'/scheduler:%s' % self.scheduler
]
self.log.debug("Starting Win HPC Job: %s" % (se... | [
"def",
"start",
"(",
"self",
",",
"n",
")",
":",
"self",
".",
"write_job_file",
"(",
"n",
")",
"args",
"=",
"[",
"'submit'",
",",
"'/jobfile:%s'",
"%",
"self",
".",
"job_file",
",",
"'/scheduler:%s'",
"%",
"self",
".",
"scheduler",
"]",
"self",
".",
... | 32.5 | 0.011628 |
def parse_generator_doubling(config):
""" Returns generators that double with each value returned
Config includes optional start value """
start = 1
if 'start' in config:
start = int(config['start'])
# We cannot simply use start as the variable, because of scoping
# limitations
... | [
"def",
"parse_generator_doubling",
"(",
"config",
")",
":",
"start",
"=",
"1",
"if",
"'start'",
"in",
"config",
":",
"start",
"=",
"int",
"(",
"config",
"[",
"'start'",
"]",
")",
"# We cannot simply use start as the variable, because of scoping",
"# limitations",
"d... | 28.933333 | 0.002232 |
def map_set_properties(
m: tcod.map.Map, x: int, y: int, isTrans: bool, isWalk: bool
) -> None:
"""Set the properties of a single cell.
.. note::
This function is slow.
.. deprecated:: 4.5
Use :any:`tcod.map.Map.transparent` and :any:`tcod.map.Map.walkable`
arrays to set these p... | [
"def",
"map_set_properties",
"(",
"m",
":",
"tcod",
".",
"map",
".",
"Map",
",",
"x",
":",
"int",
",",
"y",
":",
"int",
",",
"isTrans",
":",
"bool",
",",
"isWalk",
":",
"bool",
")",
"->",
"None",
":",
"lib",
".",
"TCOD_map_set_properties",
"(",
"m"... | 32.583333 | 0.002488 |
def _pip_exists(self):
"""Returns True if pip exists inside the virtual environment. Can be
used as a naive way to verify that the environment is installed."""
return os.path.isfile(os.path.join(self.path, 'bin', 'pip')) | [
"def",
"_pip_exists",
"(",
"self",
")",
":",
"return",
"os",
".",
"path",
".",
"isfile",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"path",
",",
"'bin'",
",",
"'pip'",
")",
")"
] | 60.25 | 0.008197 |
def setup(self, services):
"""Service setup."""
super(SchedulerService, self).setup(services)
# Register filesystem event handlers on an FSEventService instance.
self._fs_event_service.register_all_files_handler(self._enqueue_fs_event)
# N.B. We compute the invalidating fileset eagerly at launch wi... | [
"def",
"setup",
"(",
"self",
",",
"services",
")",
":",
"super",
"(",
"SchedulerService",
",",
"self",
")",
".",
"setup",
"(",
"services",
")",
"# Register filesystem event handlers on an FSEventService instance.",
"self",
".",
"_fs_event_service",
".",
"register_all_... | 52.933333 | 0.011139 |
def delete(self, filepath):
"""
Stop and delete the specified filewatcher.
"""
Filewatcher.remove_directory_to_watch(filepath)
self.write({'msg':'Watcher deleted for {}'.format(filepath)}) | [
"def",
"delete",
"(",
"self",
",",
"filepath",
")",
":",
"Filewatcher",
".",
"remove_directory_to_watch",
"(",
"filepath",
")",
"self",
".",
"write",
"(",
"{",
"'msg'",
":",
"'Watcher deleted for {}'",
".",
"format",
"(",
"filepath",
")",
"}",
")"
] | 37.166667 | 0.013158 |
def default_route_options():
"""
Default callback for OPTIONS request
:rtype: Response
"""
response_obj = OrderedDict()
response_obj["status"] = True
response_obj["data"] = "Ok"
return Response(response_obj, content_type="application/json", charset="utf-... | [
"def",
"default_route_options",
"(",
")",
":",
"response_obj",
"=",
"OrderedDict",
"(",
")",
"response_obj",
"[",
"\"status\"",
"]",
"=",
"True",
"response_obj",
"[",
"\"data\"",
"]",
"=",
"\"Ok\"",
"return",
"Response",
"(",
"response_obj",
",",
"content_type",... | 28.454545 | 0.009288 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.