text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def _get_parser(description):
"""Build an ArgumentParser with common arguments for both operations."""
parser = argparse.ArgumentParser(description=description)
parser.add_argument('key', help="Camellia key.")
parser.add_argument('input_file', nargs='*',
help="File(s) to read as ... | [
"def",
"_get_parser",
"(",
"description",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"description",
")",
"parser",
".",
"add_argument",
"(",
"'key'",
",",
"help",
"=",
"\"Camellia key.\"",
")",
"parser",
".",
"add_argu... | 55.375 | 22.375 |
def touch(self, mode=0o666, exist_ok=True):
"""
Create this file with the given access mode, if it doesn't exist.
"""
if self._closed:
self._raise_closed()
if exist_ok:
# First try to bump modification time
# Implementation note: GNU touch uses... | [
"def",
"touch",
"(",
"self",
",",
"mode",
"=",
"0o666",
",",
"exist_ok",
"=",
"True",
")",
":",
"if",
"self",
".",
"_closed",
":",
"self",
".",
"_raise_closed",
"(",
")",
"if",
"exist_ok",
":",
"# First try to bump modification time",
"# Implementation note: G... | 33.409091 | 13.136364 |
def confd_state_rest_listen_tcp_ip(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring")
rest = ET.SubElement(confd_state, "rest")
listen = ET.SubElemen... | [
"def",
"confd_state_rest_listen_tcp_ip",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"confd_state",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"confd-state\"",
",",
"xmlns",
"=",
"\"... | 40.923077 | 13.307692 |
def _from_timeseries(ts1, ts2, stride, fftlength=None, overlap=None,
window=None, **kwargs):
"""Generate a time-frequency coherence
:class:`~gwpy.spectrogram.Spectrogram` from a pair of
:class:`~gwpy.timeseries.TimeSeries`.
For each `stride`, a PSD :class:`~gwpy.frequencyseries.Fre... | [
"def",
"_from_timeseries",
"(",
"ts1",
",",
"ts2",
",",
"stride",
",",
"fftlength",
"=",
"None",
",",
"overlap",
"=",
"None",
",",
"window",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# check sampling rates",
"if",
"ts1",
".",
"sample_rate",
".",
... | 34.423077 | 18.711538 |
def list_installed_genomes(genome_dir=None):
"""
List all available genomes.
Parameters
----------
genome_dir : str
Directory with installed genomes.
Returns
-------
list with genome names
"""
if not genome_dir:
genome_dir = config.get("genome_dir", None)
if... | [
"def",
"list_installed_genomes",
"(",
"genome_dir",
"=",
"None",
")",
":",
"if",
"not",
"genome_dir",
":",
"genome_dir",
"=",
"config",
".",
"get",
"(",
"\"genome_dir\"",
",",
"None",
")",
"if",
"not",
"genome_dir",
":",
"raise",
"norns",
".",
"exceptions",
... | 25.25 | 19.45 |
def get_libs_dir(self, arch):
'''The libs dir for a given arch.'''
ensure_dir(join(self.libs_dir, arch))
return join(self.libs_dir, arch) | [
"def",
"get_libs_dir",
"(",
"self",
",",
"arch",
")",
":",
"ensure_dir",
"(",
"join",
"(",
"self",
".",
"libs_dir",
",",
"arch",
")",
")",
"return",
"join",
"(",
"self",
".",
"libs_dir",
",",
"arch",
")"
] | 39.5 | 5 |
def entry_links(self):
""" Given a parsed feed, return the links to its entries, including ones
which disappeared (as a quick-and-dirty way to support deletions)
"""
return {entry['link'] for entry in self.feed.entries if entry and entry.get('link')} | [
"def",
"entry_links",
"(",
"self",
")",
":",
"return",
"{",
"entry",
"[",
"'link'",
"]",
"for",
"entry",
"in",
"self",
".",
"feed",
".",
"entries",
"if",
"entry",
"and",
"entry",
".",
"get",
"(",
"'link'",
")",
"}"
] | 55.6 | 20.6 |
def set_chat_title(
self,
chat_id: Union[int, str],
title: str
) -> bool:
"""Use this method to change the title of a chat.
Titles can't be changed for private chats.
You must be an administrator in the chat for this to work and must have the appropriate admin rights.... | [
"def",
"set_chat_title",
"(",
"self",
",",
"chat_id",
":",
"Union",
"[",
"int",
",",
"str",
"]",
",",
"title",
":",
"str",
")",
"->",
"bool",
":",
"peer",
"=",
"self",
".",
"resolve_peer",
"(",
"chat_id",
")",
"if",
"isinstance",
"(",
"peer",
",",
... | 31.255319 | 22.659574 |
def add_license(self, contents):
"""Adds the given ``contents`` as a new custom license to the J-Link.
Args:
self (JLink): the ``JLink`` instance
contents: the string contents of the new custom license
Returns:
``True`` if license was added, ``False`` if license a... | [
"def",
"add_license",
"(",
"self",
",",
"contents",
")",
":",
"buf_size",
"=",
"len",
"(",
"contents",
")",
"buf",
"=",
"(",
"ctypes",
".",
"c_char",
"*",
"(",
"buf_size",
"+",
"1",
")",
")",
"(",
"*",
"contents",
".",
"encode",
"(",
")",
")",
"r... | 32.533333 | 23.4 |
def standardize_polygons_str(data_str):
"""Given a POLYGON string, standardize the coordinates to a 1x1 grid.
Input : data_str (taken from above)
Output: tuple of polygon objects
"""
# find all of the polygons in the letter (for instance an A
# needs to be constructed from 2 polygons)
path_s... | [
"def",
"standardize_polygons_str",
"(",
"data_str",
")",
":",
"# find all of the polygons in the letter (for instance an A",
"# needs to be constructed from 2 polygons)",
"path_strs",
"=",
"re",
".",
"findall",
"(",
"\"\\(\\(([^\\)]+?)\\)\\)\"",
",",
"data_str",
".",
"strip",
"... | 36.758621 | 17.103448 |
def parse_rest_doc(doc):
""" Extract the headers, delimiters, and text from reST-formatted docstrings.
Parameters
----------
doc: Union[str, None]
Returns
-------
Dict[str, Section] """
class Section(object):
def __init__(self, header=None, body=None):
... | [
"def",
"parse_rest_doc",
"(",
"doc",
")",
":",
"class",
"Section",
"(",
"object",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"header",
"=",
"None",
",",
"body",
"=",
"None",
")",
":",
"self",
".",
"header",
"=",
"header",
"# str",
"self",
".",
... | 29.37037 | 19.907407 |
def getQCAnalyses(self, qctype=None, review_state=None):
"""return the QC analyses performed in the worksheet in which, at
least, one sample of this AR is present.
Depending on qctype value, returns the analyses of:
- 'b': all Blank Reference Samples used in related worksheet/s
... | [
"def",
"getQCAnalyses",
"(",
"self",
",",
"qctype",
"=",
"None",
",",
"review_state",
"=",
"None",
")",
":",
"qcanalyses",
"=",
"[",
"]",
"suids",
"=",
"[",
"]",
"ans",
"=",
"self",
".",
"getAnalyses",
"(",
")",
"wf",
"=",
"getToolByName",
"(",
"self... | 37.283019 | 17.509434 |
def create_directory(self, filename):
"""Create a subdirectory in the temporary directory."""
path = os.path.join(self.path, filename)
makedirs(path)
return path | [
"def",
"create_directory",
"(",
"self",
",",
"filename",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"path",
",",
"filename",
")",
"makedirs",
"(",
"path",
")",
"return",
"path"
] | 37.8 | 10 |
def _add_ts2q(self, pore, queue):
"""
Helper method to add throats to the cluster queue
"""
net = self.project.network
elem_type = 'throat'
# Find throats connected to newly invaded pore
Ts = net.find_neighbor_throats(pores=pore)
# Remove already invaded t... | [
"def",
"_add_ts2q",
"(",
"self",
",",
"pore",
",",
"queue",
")",
":",
"net",
"=",
"self",
".",
"project",
".",
"network",
"elem_type",
"=",
"'throat'",
"# Find throats connected to newly invaded pore",
"Ts",
"=",
"net",
".",
"find_neighbor_throats",
"(",
"pores"... | 38.206897 | 9.793103 |
def chroma(sr, n_fft, n_chroma=12, A440=440.0, ctroct=5.0,
octwidth=2, norm=2, base_c=True, dtype=np.float32):
"""Create a Filterbank matrix to convert STFT to chroma
Parameters
----------
sr : number > 0 [scalar]
audio sampling rate
n_fft : int > 0 [scalar]
... | [
"def",
"chroma",
"(",
"sr",
",",
"n_fft",
",",
"n_chroma",
"=",
"12",
",",
"A440",
"=",
"440.0",
",",
"ctroct",
"=",
"5.0",
",",
"octwidth",
"=",
"2",
",",
"norm",
"=",
"2",
",",
"base_c",
"=",
"True",
",",
"dtype",
"=",
"np",
".",
"float32",
"... | 31.709924 | 23.89313 |
def get_random_xy_color(self):
"""Returns the approximate CIE 1931 x,y coordinates represented by the
supplied hexColor parameter, or of a random color if the parameter
is not passed."""
r = self.color.random_rgb_value()
g = self.color.random_rgb_value()
b = self.color.ra... | [
"def",
"get_random_xy_color",
"(",
"self",
")",
":",
"r",
"=",
"self",
".",
"color",
".",
"random_rgb_value",
"(",
")",
"g",
"=",
"self",
".",
"color",
".",
"random_rgb_value",
"(",
")",
"b",
"=",
"self",
".",
"color",
".",
"random_rgb_value",
"(",
")"... | 46 | 6.125 |
def open_upload_stream(self, filename, chunk_size_bytes=None,
metadata=None):
"""Opens a Stream that the application can write the contents of the
file to.
The user must specify the filename, and can choose to add any
additional information in the metadata fie... | [
"def",
"open_upload_stream",
"(",
"self",
",",
"filename",
",",
"chunk_size_bytes",
"=",
"None",
",",
"metadata",
"=",
"None",
")",
":",
"validate_string",
"(",
"\"filename\"",
",",
"filename",
")",
"opts",
"=",
"{",
"\"filename\"",
":",
"filename",
",",
"\"... | 41.95122 | 20.804878 |
def execute(self, request, session=None, method='post'):
'''
pyTOP.API -- TOPRequest instance
'''
params = {
'app_key' : self.API_KEY,
'v' : self.API_VERSION,
'format' : self.FORMAT,
#'sign_method' : self.SIGN_METHOD,
'... | [
"def",
"execute",
"(",
"self",
",",
"request",
",",
"session",
"=",
"None",
",",
"method",
"=",
"'post'",
")",
":",
"params",
"=",
"{",
"'app_key'",
":",
"self",
".",
"API_KEY",
",",
"'v'",
":",
"self",
".",
"API_VERSION",
",",
"'format'",
":",
"self... | 39.315789 | 13.789474 |
def _prune_penalty_box(self):
"""Restores clients that have reconnected.
This function should be called first for every public method.
"""
added = False
for client in self.penalty_box.get():
log.info("Client %r is back up.", client)
self.active_clients.ap... | [
"def",
"_prune_penalty_box",
"(",
"self",
")",
":",
"added",
"=",
"False",
"for",
"client",
"in",
"self",
".",
"penalty_box",
".",
"get",
"(",
")",
":",
"log",
".",
"info",
"(",
"\"Client %r is back up.\"",
",",
"client",
")",
"self",
".",
"active_clients"... | 33.083333 | 14.166667 |
def slice_before(predicate, iterable):
"""Returns groups of elements from iterable,
slicing just before predicate(elem) is True
"""
if isinstance(predicate, string_type):
predicate = re.compile(predicate)
if hasattr(predicate, 'match'):
predicate = predicate.match
record = []
... | [
"def",
"slice_before",
"(",
"predicate",
",",
"iterable",
")",
":",
"if",
"isinstance",
"(",
"predicate",
",",
"string_type",
")",
":",
"predicate",
"=",
"re",
".",
"compile",
"(",
"predicate",
")",
"if",
"hasattr",
"(",
"predicate",
",",
"'match'",
")",
... | 23.28 | 16.52 |
def read_sql(sql, con, filePath, index_col=None, coerce_float=True,
params=None, parse_dates=None, columns=None, chunksize=None):
"""
Read SQL query or database table into a DataFrameModel.
Provide a filePath argument in addition to the *args/**kwargs from
pandas.read_sql and get a DataFram... | [
"def",
"read_sql",
"(",
"sql",
",",
"con",
",",
"filePath",
",",
"index_col",
"=",
"None",
",",
"coerce_float",
"=",
"True",
",",
"params",
"=",
"None",
",",
"parse_dates",
"=",
"None",
",",
"columns",
"=",
"None",
",",
"chunksize",
"=",
"None",
")",
... | 39.521739 | 26.652174 |
def default_diff(latest_config, current_config):
"""Determine if two revisions have actually changed."""
# Pop off the fields we don't care about:
pop_no_diff_fields(latest_config, current_config)
diff = DeepDiff(
latest_config,
current_config,
ignore_order=True
)
return... | [
"def",
"default_diff",
"(",
"latest_config",
",",
"current_config",
")",
":",
"# Pop off the fields we don't care about:",
"pop_no_diff_fields",
"(",
"latest_config",
",",
"current_config",
")",
"diff",
"=",
"DeepDiff",
"(",
"latest_config",
",",
"current_config",
",",
... | 28.636364 | 17.818182 |
def publish(self, msg):
'''
Send message to all connected sockets
'''
if not self.streams:
return
pack = salt.transport.frame.frame_msg_ipc(msg, raw_body=True)
for stream in self.streams:
self.io_loop.spawn_callback(self._write, stream, pack) | [
"def",
"publish",
"(",
"self",
",",
"msg",
")",
":",
"if",
"not",
"self",
".",
"streams",
":",
"return",
"pack",
"=",
"salt",
".",
"transport",
".",
"frame",
".",
"frame_msg_ipc",
"(",
"msg",
",",
"raw_body",
"=",
"True",
")",
"for",
"stream",
"in",
... | 27.818182 | 23.090909 |
def get_categories(self, languages=None):
"""GetCategories.
[Preview API]
:param str languages:
:rtype: [str]
"""
query_parameters = {}
if languages is not None:
query_parameters['languages'] = self._serialize.query('languages', languages, 'str')
... | [
"def",
"get_categories",
"(",
"self",
",",
"languages",
"=",
"None",
")",
":",
"query_parameters",
"=",
"{",
"}",
"if",
"languages",
"is",
"not",
"None",
":",
"query_parameters",
"[",
"'languages'",
"]",
"=",
"self",
".",
"_serialize",
".",
"query",
"(",
... | 44.928571 | 17.642857 |
def bbox_transform(ex_rois, gt_rois, box_stds):
"""
compute bounding box regression targets from ex_rois to gt_rois
:param ex_rois: [N, 4]
:param gt_rois: [N, 4]
:return: [N, 4]
"""
assert ex_rois.shape[0] == gt_rois.shape[0], 'inconsistent rois number'
ex_widths = ex_rois[:, 2] - ex_ro... | [
"def",
"bbox_transform",
"(",
"ex_rois",
",",
"gt_rois",
",",
"box_stds",
")",
":",
"assert",
"ex_rois",
".",
"shape",
"[",
"0",
"]",
"==",
"gt_rois",
".",
"shape",
"[",
"0",
"]",
",",
"'inconsistent rois number'",
"ex_widths",
"=",
"ex_rois",
"[",
":",
... | 41.230769 | 21.538462 |
def calcELStaeckel(R,vR,vT,z,vz,pot,vc=1.,ro=1.):
"""
NAME:
calcELStaeckel
PURPOSE:
calculate the energy and angular momentum
INPUT:
R - Galactocentric radius (/ro)
vR - radial part of the velocity (/vc)
vT - azimuthal part of the velocity (/vc)
vc - circular ve... | [
"def",
"calcELStaeckel",
"(",
"R",
",",
"vR",
",",
"vT",
",",
"z",
",",
"vz",
",",
"pot",
",",
"vc",
"=",
"1.",
",",
"ro",
"=",
"1.",
")",
":",
"return",
"(",
"_evaluatePotentials",
"(",
"pot",
",",
"R",
",",
"z",
")",
"+",
"vR",
"**",
"2.",
... | 29.388889 | 15.777778 |
def side_effect(self):
"""
Executes ``ansible-playbook`` against the side_effect playbook and
returns None.
:return: None
"""
pb = self._get_ansible_playbook(self.playbooks.side_effect)
pb.execute() | [
"def",
"side_effect",
"(",
"self",
")",
":",
"pb",
"=",
"self",
".",
"_get_ansible_playbook",
"(",
"self",
".",
"playbooks",
".",
"side_effect",
")",
"pb",
".",
"execute",
"(",
")"
] | 27.444444 | 19.666667 |
def clean(self):
"""
Make sure that the scope is less or equal to the previous scope!
"""
data = self.cleaned_data
want_scope = data.get('scope') or 0
refresh_token = data.get('refresh_token')
access_token = getattr(refresh_token, 'access_token', None) if \
... | [
"def",
"clean",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"cleaned_data",
"want_scope",
"=",
"data",
".",
"get",
"(",
"'scope'",
")",
"or",
"0",
"refresh_token",
"=",
"data",
".",
"get",
"(",
"'refresh_token'",
")",
"access_token",
"=",
"getattr",... | 37.888889 | 19.444444 |
def _get_subparser_cell_args(self, subparser_prog):
""" Get cell args of a specified subparser by its prog."""
subparsers = self._get_subparsers()
for subparser in subparsers:
if subparser_prog == subparser.prog:
return subparser._cell_args
return None | [
"def",
"_get_subparser_cell_args",
"(",
"self",
",",
"subparser_prog",
")",
":",
"subparsers",
"=",
"self",
".",
"_get_subparsers",
"(",
")",
"for",
"subparser",
"in",
"subparsers",
":",
"if",
"subparser_prog",
"==",
"subparser",
".",
"prog",
":",
"return",
"s... | 30.666667 | 14.666667 |
def wr_tsv(fout_tsv, tsv_data, **kws):
"""Write a file of tab-separated table data"""
items_str = "items" if "items" not in kws else kws["items"]
if tsv_data:
ifstrm = sys.stdout if fout_tsv is None else open(fout_tsv, 'w')
num_items = prt_tsv(ifstrm, tsv_data, **kws)
if fout_tsv is ... | [
"def",
"wr_tsv",
"(",
"fout_tsv",
",",
"tsv_data",
",",
"*",
"*",
"kws",
")",
":",
"items_str",
"=",
"\"items\"",
"if",
"\"items\"",
"not",
"in",
"kws",
"else",
"kws",
"[",
"\"items\"",
"]",
"if",
"tsv_data",
":",
"ifstrm",
"=",
"sys",
".",
"stdout",
... | 46.615385 | 18 |
def load_flickr25k_dataset(tag='sky', path="data", n_threads=50, printable=False):
"""Load Flickr25K dataset.
Returns a list of images by a given tag from Flick25k dataset,
it will download Flickr25k from `the official website <http://press.liacs.nl/mirflickr/mirdownload.html>`__
at the first time you ... | [
"def",
"load_flickr25k_dataset",
"(",
"tag",
"=",
"'sky'",
",",
"path",
"=",
"\"data\"",
",",
"n_threads",
"=",
"50",
",",
"printable",
"=",
"False",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'flickr25k'",
")",
"filename... | 36.397059 | 26 |
def pick(rest):
"Pick between a few options"
question = rest.strip()
choices = util.splitem(question)
if len(choices) == 1:
return "I can't pick if you give me only one choice!"
else:
pick = random.choice(choices)
certainty = random.sample(phrases.certainty_opts, 1)[0]
return "%s... %s %s" % (pick, certain... | [
"def",
"pick",
"(",
"rest",
")",
":",
"question",
"=",
"rest",
".",
"strip",
"(",
")",
"choices",
"=",
"util",
".",
"splitem",
"(",
"question",
")",
"if",
"len",
"(",
"choices",
")",
"==",
"1",
":",
"return",
"\"I can't pick if you give me only one choice!... | 32 | 16 |
def read_all(filename):
"""
Reads the serialized objects from disk. Caller must wrap objects in appropriate Python wrapper classes.
:param filename: the file with the serialized objects
:type filename: str
:return: the list of JB_OBjects
:rtype: list
"""
array = javabridge.static_call(
... | [
"def",
"read_all",
"(",
"filename",
")",
":",
"array",
"=",
"javabridge",
".",
"static_call",
"(",
"\"Lweka/core/SerializationHelper;\"",
",",
"\"readAll\"",
",",
"\"(Ljava/lang/String;)[Ljava/lang/Object;\"",
",",
"filename",
")",
"if",
"array",
"is",
"None",
":",
... | 32.176471 | 19.823529 |
def set_attribute(attribute, attribute_value, instance_name=None, instance_id=None, region=None, key=None, keyid=None,
profile=None, filters=None):
'''
Set an EC2 instance attribute.
Returns whether the operation succeeded or not.
CLI Example:
.. code-block:: bash
salt m... | [
"def",
"set_attribute",
"(",
"attribute",
",",
"attribute_value",
",",
"instance_name",
"=",
"None",
",",
"instance_id",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"filte... | 41.711538 | 27.942308 |
def pretty_print_config_to_json(self, configs):
"""JSON string description of a protorpc.remote.Service in a discovery doc.
Args:
configs: Either a single dict or a list of dicts containing the service
configurations to list.
Returns:
string, The directory list document as a JSON strin... | [
"def",
"pretty_print_config_to_json",
"(",
"self",
",",
"configs",
")",
":",
"descriptor",
"=",
"self",
".",
"get_directory_list_doc",
"(",
"configs",
")",
"return",
"json",
".",
"dumps",
"(",
"descriptor",
",",
"sort_keys",
"=",
"True",
",",
"indent",
"=",
... | 36.769231 | 19.076923 |
def create(parallel, dirs, config):
"""Create a cluster based on the provided parallel arguments.
Returns an IPython view on the cluster, enabling processing on jobs.
Adds a mincores specification if he have machines with a larger
number of cores to allow jobs to be batched together for shared
mem... | [
"def",
"create",
"(",
"parallel",
",",
"dirs",
",",
"config",
")",
":",
"profile_dir",
"=",
"utils",
".",
"safe_makedir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dirs",
"[",
"\"work\"",
"]",
",",
"get_log_dir",
"(",
"config",
")",
",",
"\"ipython\""... | 62.242424 | 31.818182 |
def summoner_names_to_id(summoners):
"""
Gets a list of summoners names and return a dictionary mapping the player name to his/her summoner id
:param summoners: a list of player names
:return: a dictionary name -> id
"""
ids = {}
for start, end in _slice(0, len(summoners), 40):
resul... | [
"def",
"summoner_names_to_id",
"(",
"summoners",
")",
":",
"ids",
"=",
"{",
"}",
"for",
"start",
",",
"end",
"in",
"_slice",
"(",
"0",
",",
"len",
"(",
"summoners",
")",
",",
"40",
")",
":",
"result",
"=",
"get_summoners_by_name",
"(",
"summoners",
"["... | 37.75 | 14.416667 |
def height_water_critical(FlowRate, Width):
"""Return the critical local water depth."""
#Checking input validity
ut.check_range([FlowRate, ">0", "Flow rate"], [Width, ">0", "Width"])
return (FlowRate / (Width * np.sqrt(gravity.magnitude))) ** (2/3) | [
"def",
"height_water_critical",
"(",
"FlowRate",
",",
"Width",
")",
":",
"#Checking input validity",
"ut",
".",
"check_range",
"(",
"[",
"FlowRate",
",",
"\">0\"",
",",
"\"Flow rate\"",
"]",
",",
"[",
"Width",
",",
"\">0\"",
",",
"\"Width\"",
"]",
")",
"retu... | 52.2 | 15.4 |
def handle_aliases_in_init_files(name, import_alias_mapping):
"""Returns either None or the handled alias.
Used in add_module.
"""
for key, val in import_alias_mapping.items():
# e.g. Foo == Foo
# e.g. Foo.Bar startswith Foo.
if name == val or \
name.startswith(va... | [
"def",
"handle_aliases_in_init_files",
"(",
"name",
",",
"import_alias_mapping",
")",
":",
"for",
"key",
",",
"val",
"in",
"import_alias_mapping",
".",
"items",
"(",
")",
":",
"# e.g. Foo == Foo",
"# e.g. Foo.Bar startswith Foo.",
"if",
"name",
"==",
"val",
"or",
... | 36.733333 | 13.333333 |
def tofile(self, path='filters'):
r"""Save filter values to ascii-files.
Store the filter base and the filter coefficients in separate files
in the directory `path`; `path` can be a relative or absolute path.
Examples
--------
>>> import empymod
>>> # Load a fil... | [
"def",
"tofile",
"(",
"self",
",",
"path",
"=",
"'filters'",
")",
":",
"# Get name of filter",
"name",
"=",
"self",
".",
"savename",
"# Get absolute path, create if it doesn't exist",
"path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")",
"os",
".",... | 33.526316 | 16.921053 |
def reciprocal_space(space, axes=None, halfcomplex=False, shift=True,
**kwargs):
"""Return the range of the Fourier transform on ``space``.
Parameters
----------
space : `DiscreteLp`
Real space whose reciprocal is calculated. It must be
uniformly discretized.
ax... | [
"def",
"reciprocal_space",
"(",
"space",
",",
"axes",
"=",
"None",
",",
"halfcomplex",
"=",
"False",
",",
"shift",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"space",
",",
"DiscreteLp",
")",
":",
"raise",
"TypeError... | 40.13 | 20.7 |
def remove_commented_topic(self, topic_id):
"""
删除回复的话题(删除所有自己发布的评论)
:param topic_id: 话题ID
:return: None
"""
return [self.remove_comment(topic_id, item['id']) for item in self.list_user_comments(topic_id)] | [
"def",
"remove_commented_topic",
"(",
"self",
",",
"topic_id",
")",
":",
"return",
"[",
"self",
".",
"remove_comment",
"(",
"topic_id",
",",
"item",
"[",
"'id'",
"]",
")",
"for",
"item",
"in",
"self",
".",
"list_user_comments",
"(",
"topic_id",
")",
"]"
] | 31.875 | 17.625 |
def refresh(self) -> None:
"""Prepare the actual |anntools.SeasonalANN| object for calculations.
Dispite all automated refreshings explained in the general
documentation on class |anntools.SeasonalANN|, it is still possible
to destroy the inner consistency of a |anntools.SeasonalANN| in... | [
"def",
"refresh",
"(",
"self",
")",
"->",
"None",
":",
"# pylint: disable=unsupported-assignment-operation",
"if",
"self",
".",
"_do_refresh",
":",
"if",
"self",
".",
"anns",
":",
"self",
".",
"__sann",
"=",
"annutils",
".",
"SeasonalANN",
"(",
"self",
".",
... | 43.416667 | 19.416667 |
def meta_model_fit(X_train, y_train, svm_hardness, fit_intercept, number_of_threads, regressor_type="LinearSVR"):
"""
Trains meta-labeler for predicting number of labels for each user.
Based on: Tang, L., Rajan, S., & Narayanan, V. K. (2009, April).
Large scale multi-label classification via ... | [
"def",
"meta_model_fit",
"(",
"X_train",
",",
"y_train",
",",
"svm_hardness",
",",
"fit_intercept",
",",
"number_of_threads",
",",
"regressor_type",
"=",
"\"LinearSVR\"",
")",
":",
"if",
"regressor_type",
"==",
"\"LinearSVR\"",
":",
"if",
"X_train",
".",
"shape",
... | 38.086957 | 22.869565 |
def put(self, vpn_id: int) -> Vpn:
"""
Updates the Vpn Resource with the
name.
"""
vpn = self._get_or_abort(vpn_id)
self.update(vpn)
session.commit()
return vpn | [
"def",
"put",
"(",
"self",
",",
"vpn_id",
":",
"int",
")",
"->",
"Vpn",
":",
"vpn",
"=",
"self",
".",
"_get_or_abort",
"(",
"vpn_id",
")",
"self",
".",
"update",
"(",
"vpn",
")",
"session",
".",
"commit",
"(",
")",
"return",
"vpn"
] | 24 | 9.777778 |
def start(self, execution_history, backward_execution=False, generate_run_id=True):
""" Starts the execution of the state in a new thread.
:return:
"""
self.execution_history = execution_history
if generate_run_id:
self._run_id = run_id_generator()
self.backw... | [
"def",
"start",
"(",
"self",
",",
"execution_history",
",",
"backward_execution",
"=",
"False",
",",
"generate_run_id",
"=",
"True",
")",
":",
"self",
".",
"execution_history",
"=",
"execution_history",
"if",
"generate_run_id",
":",
"self",
".",
"_run_id",
"=",
... | 39.909091 | 16.909091 |
def _parse(self):
"""Get axes and shape from file names."""
if not self.pattern:
raise TiffSequence.ParseError('invalid pattern')
pattern = re.compile(self.pattern, re.IGNORECASE | re.VERBOSE)
matches = pattern.findall(os.path.split(self.files[0])[-1])
if not matches:... | [
"def",
"_parse",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"pattern",
":",
"raise",
"TiffSequence",
".",
"ParseError",
"(",
"'invalid pattern'",
")",
"pattern",
"=",
"re",
".",
"compile",
"(",
"self",
".",
"pattern",
",",
"re",
".",
"IGNORECASE",
... | 43.588235 | 18.205882 |
def connect(self):
"""
Starts the mongodb connection. Must be called before anything else
will work.
"""
self.client = MongoClient(self.mongo_uri)
self.db = self.client[self.db_name] | [
"def",
"connect",
"(",
"self",
")",
":",
"self",
".",
"client",
"=",
"MongoClient",
"(",
"self",
".",
"mongo_uri",
")",
"self",
".",
"db",
"=",
"self",
".",
"client",
"[",
"self",
".",
"db_name",
"]"
] | 32 | 12.857143 |
def filter_code(source, additional_imports=None,
expand_star_imports=False,
remove_all_unused_imports=False,
remove_duplicate_keys=False,
remove_unused_variables=False,
ignore_init_module_imports=False,
):
"""Yield code ... | [
"def",
"filter_code",
"(",
"source",
",",
"additional_imports",
"=",
"None",
",",
"expand_star_imports",
"=",
"False",
",",
"remove_all_unused_imports",
"=",
"False",
",",
"remove_duplicate_keys",
"=",
"False",
",",
"remove_unused_variables",
"=",
"False",
",",
"ign... | 38.109756 | 17.073171 |
def OSPFNeighborState_OSPFNeighborIpAddress(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
OSPFNeighborState = ET.SubElement(config, "OSPFNeighborState", xmlns="http://brocade.com/ns/brocade-notification-stream")
OSPFNeighborIpAddress = ET.SubElement(OS... | [
"def",
"OSPFNeighborState_OSPFNeighborIpAddress",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"OSPFNeighborState",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"OSPFNeighborState\"",
",",
... | 51.6 | 25.9 |
def run(self, callback=None, limit=0):
"""
Start pcap's loop over the interface, calling the given callback for each packet
:param callback: a function receiving (win_pcap, param, header, pkt_data) for each packet intercepted
:param limit: how many packets to capture (A value of -1 or 0 ... | [
"def",
"run",
"(",
"self",
",",
"callback",
"=",
"None",
",",
"limit",
"=",
"0",
")",
":",
"if",
"self",
".",
"_handle",
"is",
"None",
":",
"raise",
"self",
".",
"DeviceIsNotOpen",
"(",
")",
"# Set new callback",
"self",
".",
"_callback",
"=",
"callbac... | 49.916667 | 19.916667 |
def get_timedelta(self, now=None):
"""
Returns number of seconds that passed since ``self.started``, as float.
None is returned if ``self.started`` was not set yet.
"""
def datetime_to_time(timestamp):
atime = time.mktime(timestamp.timetuple())
atime += ti... | [
"def",
"get_timedelta",
"(",
"self",
",",
"now",
"=",
"None",
")",
":",
"def",
"datetime_to_time",
"(",
"timestamp",
")",
":",
"atime",
"=",
"time",
".",
"mktime",
"(",
"timestamp",
".",
"timetuple",
"(",
")",
")",
"atime",
"+=",
"timestamp",
".",
"mic... | 40.8 | 10.933333 |
def table(self):
"""
The |Table| object contained in this graphic frame. Raises
|ValueError| if this graphic frame does not contain a table.
"""
if not self.has_table:
raise ValueError('shape does not contain a table')
tbl = self._element.graphic.graphicData.t... | [
"def",
"table",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"has_table",
":",
"raise",
"ValueError",
"(",
"'shape does not contain a table'",
")",
"tbl",
"=",
"self",
".",
"_element",
".",
"graphic",
".",
"graphicData",
".",
"tbl",
"return",
"Table",
... | 38.444444 | 14.444444 |
def print_paired_paths(nb_file, fmt):
"""Display the paired paths for this notebook"""
notebook = readf(nb_file, fmt)
formats = notebook.metadata.get('jupytext', {}).get('formats')
if formats:
for path, _ in paired_paths(nb_file, fmt, formats):
if path != nb_file:
sys... | [
"def",
"print_paired_paths",
"(",
"nb_file",
",",
"fmt",
")",
":",
"notebook",
"=",
"readf",
"(",
"nb_file",
",",
"fmt",
")",
"formats",
"=",
"notebook",
".",
"metadata",
".",
"get",
"(",
"'jupytext'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'formats'",
... | 42.375 | 11.625 |
def GetEntries(self, parser_mediator, data=None, **unused_kwargs):
"""Extract data from Transmission's resume folder files.
This is the main parsing engine for the parser. It determines if
the selected file is the proper file to parse and extracts current
running torrents.
Transmission stores an i... | [
"def",
"GetEntries",
"(",
"self",
",",
"parser_mediator",
",",
"data",
"=",
"None",
",",
"*",
"*",
"unused_kwargs",
")",
":",
"seeding_time",
"=",
"data",
".",
"get",
"(",
"'seeding-time-seconds'",
",",
"None",
")",
"event_data",
"=",
"TransmissionEventData",
... | 43.139535 | 22.325581 |
def check_node_position(
self, parent_id, position, on_same_branch, db_session=None, *args, **kwargs
):
"""
Checks if node position for given parent is valid, raises exception if
this is not the case
:param parent_id:
:param position:
:param on_same_branch: i... | [
"def",
"check_node_position",
"(",
"self",
",",
"parent_id",
",",
"position",
",",
"on_same_branch",
",",
"db_session",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"service",
".",
"check_node_position",
"(",
"pa... | 30.380952 | 18.666667 |
def walk(self, *types):
'''
Iterator which visits all suites and suite files,
yielding test cases and keywords
'''
requested = types if len(types) > 0 else [SuiteFile, ResourceFile, SuiteFolder, Testcase, Keyword]
for thing in self.robot_files:
if thing.__cla... | [
"def",
"walk",
"(",
"self",
",",
"*",
"types",
")",
":",
"requested",
"=",
"types",
"if",
"len",
"(",
"types",
")",
">",
"0",
"else",
"[",
"SuiteFile",
",",
"ResourceFile",
",",
"SuiteFolder",
",",
"Testcase",
",",
"Keyword",
"]",
"for",
"thing",
"in... | 36.941176 | 16.588235 |
def disks(self):
"""Instance depends on the API version:
* 2016-04-30-preview: :class:`DisksOperations<azure.mgmt.compute.v2016_04_30_preview.operations.DisksOperations>`
* 2017-03-30: :class:`DisksOperations<azure.mgmt.compute.v2017_03_30.operations.DisksOperations>`
* 2018-04... | [
"def",
"disks",
"(",
"self",
")",
":",
"api_version",
"=",
"self",
".",
"_get_api_version",
"(",
"'disks'",
")",
"if",
"api_version",
"==",
"'2016-04-30-preview'",
":",
"from",
".",
"v2016_04_30_preview",
".",
"operations",
"import",
"DisksOperations",
"as",
"Op... | 67.652174 | 36.521739 |
def absent(name, tags=None, region=None, key=None, keyid=None, profile=None):
'''
Ensure VPC with passed properties is absent.
name
Name of the VPC.
tags
A list of tags. All tags must match.
region
Region to connect to.
key
Secret key to be used.
keyid
... | [
"def",
"absent",
"(",
"name",
",",
"tags",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
... | 28.438596 | 24.684211 |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'field') and self.field is not None:
_dict['field'] = self.field
if hasattr(self, 'count') and self.count is not None:
_dict['count'] = self.count
retur... | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'field'",
")",
"and",
"self",
".",
"field",
"is",
"not",
"None",
":",
"_dict",
"[",
"'field'",
"]",
"=",
"self",
".",
"field",
"if",
"hasattr",
... | 40 | 13.375 |
def fts_match(self, features, segment):
"""Answer question "are `ft_mask`'s features a subset of ft_seg?"
This is like `FeatureTable.match` except that it checks whether a
segment is valid and returns None if it is not.
Args:
features (set): pattern defined as set of (value... | [
"def",
"fts_match",
"(",
"self",
",",
"features",
",",
"segment",
")",
":",
"features",
"=",
"set",
"(",
"features",
")",
"if",
"self",
".",
"seg_known",
"(",
"segment",
")",
":",
"return",
"features",
"<=",
"self",
".",
"fts",
"(",
"segment",
")",
"... | 37.157895 | 21.052632 |
def init_parser():
"""Initialize option parser."""
usage = "Usage: %(prog)s <option(s)> <file(s)>"
description = " Display information from object <file(s)>.\n"
description += " At least one of the following switches must be given:"
#
# Create an argument parser and an exclusive group.
#
... | [
"def",
"init_parser",
"(",
")",
":",
"usage",
"=",
"\"Usage: %(prog)s <option(s)> <file(s)>\"",
"description",
"=",
"\" Display information from object <file(s)>.\\n\"",
"description",
"+=",
"\" At least one of the following switches must be given:\"",
"#",
"# Create an argument parser... | 43.795455 | 29.011364 |
def condensed_coords_between(pop1, pop2, n):
"""Return indices into a condensed distance matrix for all pairwise
comparisons between two populations.
Parameters
----------
pop1 : array_like, int
Indices of samples or haplotypes within the first population.
pop2 : array_like, int
... | [
"def",
"condensed_coords_between",
"(",
"pop1",
",",
"pop2",
",",
"n",
")",
":",
"return",
"[",
"condensed_coords",
"(",
"i",
",",
"j",
",",
"n",
")",
"for",
"i",
",",
"j",
"in",
"itertools",
".",
"product",
"(",
"sorted",
"(",
"pop1",
")",
",",
"s... | 29.47619 | 22.333333 |
def transform(self, data, allow_timestamps=False):
"""
Transform H2OFrame using a MOJO Pipeline.
:param data: Frame to be transformed.
:param allow_timestamps: Allows datetime columns to be used directly with MOJO pipelines. It is recommended
to parse your datetime columns as St... | [
"def",
"transform",
"(",
"self",
",",
"data",
",",
"allow_timestamps",
"=",
"False",
")",
":",
"assert_is_type",
"(",
"data",
",",
"H2OFrame",
")",
"assert_is_type",
"(",
"allow_timestamps",
",",
"bool",
")",
"return",
"H2OFrame",
".",
"_expr",
"(",
"ExprNod... | 54.733333 | 30.466667 |
def convert_fillstyle(inputstyle, mode, inputmode=None):
"""
Convert *inputstyle* to ROOT or matplotlib format.
Output format is determined by *mode* ('root' or 'mpl'). The *inputstyle*
may be a ROOT fill style, a matplotlib hatch style, None, 'none', 'hollow',
or 'solid'.
"""
mode = mode.... | [
"def",
"convert_fillstyle",
"(",
"inputstyle",
",",
"mode",
",",
"inputmode",
"=",
"None",
")",
":",
"mode",
"=",
"mode",
".",
"lower",
"(",
")",
"if",
"mode",
"not",
"in",
"(",
"'mpl'",
",",
"'root'",
")",
":",
"raise",
"ValueError",
"(",
"\"`{0}` is ... | 38.772727 | 15.545455 |
def set_target(self, target, ctx=None):
"""Set target.
:param target: new target to use.
:param target ctx: target ctx if target is an class/instance attribute.
"""
if target is not None:
# check if target is already intercepted
if is_intercepted(target)... | [
"def",
"set_target",
"(",
"self",
",",
"target",
",",
"ctx",
"=",
"None",
")",
":",
"if",
"target",
"is",
"not",
"None",
":",
"# check if target is already intercepted",
"if",
"is_intercepted",
"(",
"target",
")",
":",
"# set self interception last target reference"... | 38.411765 | 15.529412 |
def translate_state(self, s):
"""Translate the given state string
"""
if not isinstance(s, basestring):
return s
s = s.capitalize().replace("_", " ")
return t(_(s)) | [
"def",
"translate_state",
"(",
"self",
",",
"s",
")",
":",
"if",
"not",
"isinstance",
"(",
"s",
",",
"basestring",
")",
":",
"return",
"s",
"s",
"=",
"s",
".",
"capitalize",
"(",
")",
".",
"replace",
"(",
"\"_\"",
",",
"\" \"",
")",
"return",
"t",
... | 30 | 7.714286 |
def _modify(self, **patch):
"""Override modify to check kwargs before request sent to device."""
if 'state' in patch:
if patch['state'] != 'user-up' and patch['state'] != 'user-down':
msg = "The members resource does not support a modify with " \
"the va... | [
"def",
"_modify",
"(",
"self",
",",
"*",
"*",
"patch",
")",
":",
"if",
"'state'",
"in",
"patch",
":",
"if",
"patch",
"[",
"'state'",
"]",
"!=",
"'user-up'",
"and",
"patch",
"[",
"'state'",
"]",
"!=",
"'user-down'",
":",
"msg",
"=",
"\"The members resou... | 57.722222 | 20.055556 |
def _dev_by_id(self, device_type):
"""! Get a dict, USBID -> device, for a device class
@param device_type The type of devices to search. For exmaple, "serial"
looks for all serial devices connected to this computer
@return A dict: Device USBID -> device file in /dev
"""
... | [
"def",
"_dev_by_id",
"(",
"self",
",",
"device_type",
")",
":",
"dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"\"/dev\"",
",",
"device_type",
",",
"\"by-id\"",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"dir",
")",
":",
"to_ret",
"=",
"dic... | 41.217391 | 18.043478 |
def replace(s, replace):
"""Replace multiple values in a string"""
for r in replace:
s = s.replace(*r)
return s | [
"def",
"replace",
"(",
"s",
",",
"replace",
")",
":",
"for",
"r",
"in",
"replace",
":",
"s",
"=",
"s",
".",
"replace",
"(",
"*",
"r",
")",
"return",
"s"
] | 25.4 | 15.6 |
def _make_builder_configs():
"""Make built-in Librispeech BuilderConfigs.
Uses 4 text encodings (plain text, bytes, subwords with 8k vocab, subwords
with 32k vocab) crossed with the data subsets (clean100, clean360, all).
Returns:
`list<tfds.audio.LibrispeechConfig>`
"""
text_encoder_configs = [
... | [
"def",
"_make_builder_configs",
"(",
")",
":",
"text_encoder_configs",
"=",
"[",
"None",
",",
"tfds",
".",
"features",
".",
"text",
".",
"TextEncoderConfig",
"(",
"name",
"=",
"\"bytes\"",
",",
"encoder",
"=",
"tfds",
".",
"features",
".",
"text",
".",
"By... | 33.966667 | 18.2 |
def stop_workers_async(self):
"""Signal that all workers should stop without waiting."""
self._started = False
for worker in self._workers:
worker.signal_stop() | [
"def",
"stop_workers_async",
"(",
"self",
")",
":",
"self",
".",
"_started",
"=",
"False",
"for",
"worker",
"in",
"self",
".",
"_workers",
":",
"worker",
".",
"signal_stop",
"(",
")"
] | 32 | 12.333333 |
def on_modified(self, event):
"""Handle a file modified event."""
path = event.src_path
if path not in self.saw:
self.saw.add(path)
self.recompile(path) | [
"def",
"on_modified",
"(",
"self",
",",
"event",
")",
":",
"path",
"=",
"event",
".",
"src_path",
"if",
"path",
"not",
"in",
"self",
".",
"saw",
":",
"self",
".",
"saw",
".",
"add",
"(",
"path",
")",
"self",
".",
"recompile",
"(",
"path",
")"
] | 32.5 | 8 |
def open(self, path, binary=False):
"""Open file and return a stream."""
if binary:
return open(path, "rb")
return open(path, encoding="utf-8") | [
"def",
"open",
"(",
"self",
",",
"path",
",",
"binary",
"=",
"False",
")",
":",
"if",
"binary",
":",
"return",
"open",
"(",
"path",
",",
"\"rb\"",
")",
"return",
"open",
"(",
"path",
",",
"encoding",
"=",
"\"utf-8\"",
")"
] | 35 | 7 |
def check_connection (self):
"""
In case of proxy, delegate to HttpUrl. Else check in this
order: login, changing directory, list the file.
"""
# proxy support (we support only http)
self.set_proxy(self.aggregate.config["proxy"].get(self.scheme))
if self.proxy:
... | [
"def",
"check_connection",
"(",
"self",
")",
":",
"# proxy support (we support only http)",
"self",
".",
"set_proxy",
"(",
"self",
".",
"aggregate",
".",
"config",
"[",
"\"proxy\"",
"]",
".",
"get",
"(",
"self",
".",
"scheme",
")",
")",
"if",
"self",
".",
... | 34.6 | 10.52 |
def get_service_info(service_instance):
'''
Returns information of the vCenter or ESXi host
service_instance
The Service Instance from which to obtain managed object references.
'''
try:
return service_instance.content.about
except vim.fault.NoPermission as exc:
log.exce... | [
"def",
"get_service_info",
"(",
"service_instance",
")",
":",
"try",
":",
"return",
"service_instance",
".",
"content",
".",
"about",
"except",
"vim",
".",
"fault",
".",
"NoPermission",
"as",
"exc",
":",
"log",
".",
"exception",
"(",
"exc",
")",
"raise",
"... | 35.05 | 15.75 |
def create_pool(batch_service_client, pool_id,
resource_files, publisher, offer, sku,
task_file, vm_size, node_count):
"""Creates a pool of compute nodes with the specified OS settings.
:param batch_service_client: A Batch service client.
:type batch_service_client: `azure.b... | [
"def",
"create_pool",
"(",
"batch_service_client",
",",
"pool_id",
",",
"resource_files",
",",
"publisher",
",",
"offer",
",",
"sku",
",",
"task_file",
",",
"vm_size",
",",
"node_count",
")",
":",
"_log",
".",
"info",
"(",
"'Creating pool [{}]...'",
".",
"form... | 47.805556 | 21.125 |
def _remove_mapper_from_plotter(plotter, actor, reset_camera):
"""removes this actor's mapper from the given plotter's _scalar_bar_mappers"""
try:
mapper = actor.GetMapper()
except AttributeError:
return
for name in list(plotter._scalar_bar_mappers.keys()):
try:
plott... | [
"def",
"_remove_mapper_from_plotter",
"(",
"plotter",
",",
"actor",
",",
"reset_camera",
")",
":",
"try",
":",
"mapper",
"=",
"actor",
".",
"GetMapper",
"(",
")",
"except",
"AttributeError",
":",
"return",
"for",
"name",
"in",
"list",
"(",
"plotter",
".",
... | 42.333333 | 19.333333 |
def merge(left, right):
"""
deep merge dictionary on the left with the one
on the right.
Fill in left dictionary with right one where
the value of the key from the right one in
the left one is missing or None.
"""
if isinstance(left, dict) and isinstance(right, dict):
for key, v... | [
"def",
"merge",
"(",
"left",
",",
"right",
")",
":",
"if",
"isinstance",
"(",
"left",
",",
"dict",
")",
"and",
"isinstance",
"(",
"right",
",",
"dict",
")",
":",
"for",
"key",
",",
"value",
"in",
"right",
".",
"items",
"(",
")",
":",
"if",
"key",... | 30.388889 | 11.833333 |
def clean(all=False, docs=False, dist=False, extra=None):
"""Clean up build files"""
run('find . -type f -name "*.py[co]" -delete')
run('find . -type d -name "__pycache__" -delete')
patterns = ['build', '*.egg-info/']
if all or docs:
patterns.append('doc/build/*')
if all or dist:
... | [
"def",
"clean",
"(",
"all",
"=",
"False",
",",
"docs",
"=",
"False",
",",
"dist",
"=",
"False",
",",
"extra",
"=",
"None",
")",
":",
"run",
"(",
"'find . -type f -name \"*.py[co]\" -delete'",
")",
"run",
"(",
"'find . -type d -name \"__pycache__\" -delete'",
")"... | 29.8 | 14.866667 |
def toindices(self, mask):
r"""
Convert a boolean mask to a list of pore or throat indices
Parameters
----------
mask : array_like booleans
A boolean array with True at locations where indices are desired.
The appropriate indices are returned based an the... | [
"def",
"toindices",
"(",
"self",
",",
"mask",
")",
":",
"if",
"sp",
".",
"amax",
"(",
"mask",
")",
">",
"1",
":",
"raise",
"Exception",
"(",
"'Received mask is invalid, with values above 1'",
")",
"mask",
"=",
"sp",
".",
"array",
"(",
"mask",
",",
"dtype... | 32.125 | 23.65625 |
def result_relpath(self, package_index):
"""Returns the relative path of the result
This method returns the path to the result relative to the
top dir of the working area. This method simply constructs the
path based on the convention and doesn't check if the result
actually exi... | [
"def",
"result_relpath",
"(",
"self",
",",
"package_index",
")",
":",
"dirname",
"=",
"'task_{:05d}'",
".",
"format",
"(",
"package_index",
")",
"# e.g., 'task_00009'",
"ret",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'results'",
",",
"dirname",
",",
"'resu... | 26.185185 | 22.666667 |
def check_arguments(c: typing.Callable,
hints: typing.Mapping[str, typing.Optional[type]],
*args, **kwargs) -> None:
"""Check arguments type, raise :class:`TypeError` if argument type is not
expected type.
:param c: callable object want to check types
:param hint... | [
"def",
"check_arguments",
"(",
"c",
":",
"typing",
".",
"Callable",
",",
"hints",
":",
"typing",
".",
"Mapping",
"[",
"str",
",",
"typing",
".",
"Optional",
"[",
"type",
"]",
"]",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"->",
"None",
":",
... | 36.32 | 16.16 |
def get_summary_data(self, group_name):
""" Get the summary data for an analysis group.
:param group_name: The name of the analysis group to pull summary
data for.
:returns: A dictionary whose keys are analysis steps, and whose
values are dictionaries of key/valu... | [
"def",
"get_summary_data",
"(",
"self",
",",
"group_name",
")",
":",
"self",
".",
"assert_open",
"(",
")",
"group",
"=",
"'Analyses/{}/Summary'",
".",
"format",
"(",
"group_name",
")",
"summary",
"=",
"None",
"if",
"group",
"in",
"self",
".",
"handle",
":"... | 39.066667 | 17.066667 |
def getCentreAndSpreadOffsets(spaceShape,
spreadShape,
stepSize=1):
"""
Generates centre offsets and spread offsets for block-mode based training
regimes - star, cross, block.
Parameters:
-----------------------------------------------
space... | [
"def",
"getCentreAndSpreadOffsets",
"(",
"spaceShape",
",",
"spreadShape",
",",
"stepSize",
"=",
"1",
")",
":",
"from",
"nupic",
".",
"math",
".",
"cross",
"import",
"cross",
"# =====================================================================",
"# Init data structures"... | 34.686567 | 20.179104 |
def Sum(a, axis, keep_dims):
"""
Sum reduction op.
"""
return np.sum(a, axis=axis if not isinstance(axis, np.ndarray) else tuple(axis),
keepdims=keep_dims), | [
"def",
"Sum",
"(",
"a",
",",
"axis",
",",
"keep_dims",
")",
":",
"return",
"np",
".",
"sum",
"(",
"a",
",",
"axis",
"=",
"axis",
"if",
"not",
"isinstance",
"(",
"axis",
",",
"np",
".",
"ndarray",
")",
"else",
"tuple",
"(",
"axis",
")",
",",
"ke... | 30.833333 | 12.833333 |
def emulate_mouse(self, key_code, x_val, y_val, data):
"""Emulate the ev codes using the data Windows has given us.
Note that by default in Windows, to recognise a double click,
you just notice two clicks in a row within a reasonablely
short time period.
However, if the applica... | [
"def",
"emulate_mouse",
"(",
"self",
",",
"key_code",
",",
"x_val",
",",
"y_val",
",",
"data",
")",
":",
"# Once again ignore Windows' relative time (since system",
"# startup) and use the absolute time (since epoch i.e. 1st Jan",
"# 1970).",
"self",
".",
"update_timeval",
"(... | 36.671429 | 18.628571 |
def status_job(self, fn=None, name=None, timeout=3):
"""Decorator that invokes `add_status_job`.
::
@app.status_job
def postgresql():
# query/ping postgres
@app.status_job(name="Active Directory")
def active_directory():
... | [
"def",
"status_job",
"(",
"self",
",",
"fn",
"=",
"None",
",",
"name",
"=",
"None",
",",
"timeout",
"=",
"3",
")",
":",
"if",
"fn",
"is",
"None",
":",
"def",
"decorator",
"(",
"fn",
")",
":",
"self",
".",
"add_status_job",
"(",
"fn",
",",
"name",... | 27.458333 | 17.041667 |
def split_sentences(text):
"""
Utility function to return a list of sentences.
@param text The text that must be split in to sentences.
"""
sentence_delimiters = re.compile(u'[\\[\\]\n.!?,;:\t\\-\\"\\(\\)\\\'\u2019\u2013]')
sentences = sentence_delimiters.split(text)
return sentences | [
"def",
"split_sentences",
"(",
"text",
")",
":",
"sentence_delimiters",
"=",
"re",
".",
"compile",
"(",
"u'[\\\\[\\\\]\\n.!?,;:\\t\\\\-\\\\\"\\\\(\\\\)\\\\\\'\\u2019\\u2013]'",
")",
"sentences",
"=",
"sentence_delimiters",
".",
"split",
"(",
"text",
")",
"return",
"sent... | 38.125 | 14.875 |
def execute_notebook_with_engine(self, engine_name, nb, kernel_name, **kwargs):
"""Fetch a named engine and execute the nb object against it."""
return self.get_engine(engine_name).execute_notebook(nb, kernel_name, **kwargs) | [
"def",
"execute_notebook_with_engine",
"(",
"self",
",",
"engine_name",
",",
"nb",
",",
"kernel_name",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"get_engine",
"(",
"engine_name",
")",
".",
"execute_notebook",
"(",
"nb",
",",
"kernel_name",
",... | 79.333333 | 28.666667 |
def post_execute(self):
"""Cache the modification times of any modules imported in this execution
"""
newly_loaded_modules = set(sys.modules) - self.loaded_modules
for modname in newly_loaded_modules:
_, pymtime = self._reloader.filename_and_mtime(sys.modules[modname])
... | [
"def",
"post_execute",
"(",
"self",
")",
":",
"newly_loaded_modules",
"=",
"set",
"(",
"sys",
".",
"modules",
")",
"-",
"self",
".",
"loaded_modules",
"for",
"modname",
"in",
"newly_loaded_modules",
":",
"_",
",",
"pymtime",
"=",
"self",
".",
"_reloader",
... | 46.3 | 17.5 |
def load_data(filename):
"""
:rtype : numpy matrix
"""
data = pandas.read_csv(filename, header=None, delimiter='\t', skiprows=9)
return data.as_matrix() | [
"def",
"load_data",
"(",
"filename",
")",
":",
"data",
"=",
"pandas",
".",
"read_csv",
"(",
"filename",
",",
"header",
"=",
"None",
",",
"delimiter",
"=",
"'\\t'",
",",
"skiprows",
"=",
"9",
")",
"return",
"data",
".",
"as_matrix",
"(",
")"
] | 27.833333 | 13.5 |
def _read_as_tiledir(
self,
out_tile=None,
td_crs=None,
tiles_paths=None,
profile=None,
validity_check=False,
indexes=None,
resampling=None,
dst_nodata=None,
gdal_opts=None,
**kwargs
):
"""
Read reprojected & res... | [
"def",
"_read_as_tiledir",
"(",
"self",
",",
"out_tile",
"=",
"None",
",",
"td_crs",
"=",
"None",
",",
"tiles_paths",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"validity_check",
"=",
"False",
",",
"indexes",
"=",
"None",
",",
"resampling",
"=",
"Non... | 29.893617 | 18.106383 |
def _process_container_metric(self, type, metric_name, metric, scraper_config):
"""
Takes a simple metric about a container, reports it as a rate or gauge.
If several series are found for a given container, values are summed before submission.
"""
if metric.type not in METRIC_TYP... | [
"def",
"_process_container_metric",
"(",
"self",
",",
"type",
",",
"metric_name",
",",
"metric",
",",
"scraper_config",
")",
":",
"if",
"metric",
".",
"type",
"not",
"in",
"METRIC_TYPES",
":",
"self",
".",
"log",
".",
"error",
"(",
"\"Metric type %s unsupporte... | 48.5625 | 26.4375 |
def _get_tns_search_results(
self):
"""
*query the tns and result the response*
"""
self.log.info('starting the ``_get_tns_search_results`` method')
try:
response = requests.get(
url="http://wis-tns.weizmann.ac.il/search",
... | [
"def",
"_get_tns_search_results",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'starting the ``_get_tns_search_results`` method'",
")",
"try",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
"=",
"\"http://wis-tns.weizmann.ac.il/search\"",
... | 38.875 | 13.525 |
def throttle(self, key, amount=1, rate=None, capacity=None,
exc_class=Throttled, **kwargs):
"""Consume an amount for a given key, or raise a Throttled exception."""
if not self.consume(key, amount, rate, capacity, **kwargs):
raise exc_class("Request of %d unit for %s exceeds cap... | [
"def",
"throttle",
"(",
"self",
",",
"key",
",",
"amount",
"=",
"1",
",",
"rate",
"=",
"None",
",",
"capacity",
"=",
"None",
",",
"exc_class",
"=",
"Throttled",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"consume",
"(",
"key",
"... | 51.142857 | 18 |
def update_config(file_name, yaml_contents):
'''
Update master config with
``yaml_contents``.
Writes ``yaml_contents`` to a file named
``file_name.conf`` under the folder
specified by ``default_include``.
This folder is named ``master.d`` by
default. Please look at
:conf_master:`inc... | [
"def",
"update_config",
"(",
"file_name",
",",
"yaml_contents",
")",
":",
"file_name",
"=",
"'{0}{1}'",
".",
"format",
"(",
"file_name",
",",
"'.conf'",
")",
"dir_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"__opts__",
"[",
"'config_dir'",
"]",
",",
... | 31 | 18 |
def unlock(name,
zk_hosts=None, # in case you need to unlock without having run lock (failed execution for example)
identifier=None,
max_concurrency=1,
ephemeral_lease=False,
profile=None,
scheme=None,
username=None,
password=None,... | [
"def",
"unlock",
"(",
"name",
",",
"zk_hosts",
"=",
"None",
",",
"# in case you need to unlock without having run lock (failed execution for example)",
"identifier",
"=",
"None",
",",
"max_concurrency",
"=",
"1",
",",
"ephemeral_lease",
"=",
"False",
",",
"profile",
"="... | 33.609756 | 23.95122 |
def get_evernote_notes(self, evernote_filter):
"""
get the notes related to the filter
:param evernote_filter: filtering
:return: notes
"""
data = []
note_store = self.client.get_note_store()
our_note_list = note_store.findNotesMetadata(self.t... | [
"def",
"get_evernote_notes",
"(",
"self",
",",
"evernote_filter",
")",
":",
"data",
"=",
"[",
"]",
"note_store",
"=",
"self",
".",
"client",
".",
"get_note_store",
"(",
")",
"our_note_list",
"=",
"note_store",
".",
"findNotesMetadata",
"(",
"self",
".",
"tok... | 42.526316 | 24.315789 |
def from_form(self, param_name, field):
"""
A decorator that converts a request form into a function parameter based on the specified field.
:param str param_name: The parameter which receives the argument.
:param Field field: The field class or instance used to deserialize the request ... | [
"def",
"from_form",
"(",
"self",
",",
"param_name",
",",
"field",
")",
":",
"return",
"self",
".",
"__from_source",
"(",
"param_name",
",",
"field",
",",
"lambda",
":",
"request",
".",
"form",
",",
"'form'",
")"
] | 51 | 29.444444 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.