text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def fetch_data_table(api_key,
show_progress,
retries):
""" Fetch WIKI Prices data table from Quandl
"""
for _ in range(retries):
try:
if show_progress:
log.info('Downloading WIKI metadata.')
metadata = pd.read_csv(
... | [
"def",
"fetch_data_table",
"(",
"api_key",
",",
"show_progress",
",",
"retries",
")",
":",
"for",
"_",
"in",
"range",
"(",
"retries",
")",
":",
"try",
":",
"if",
"show_progress",
":",
"log",
".",
"info",
"(",
"'Downloading WIKI metadata.'",
")",
"metadata",
... | 31.621622 | 18.189189 |
def deprecated(since_or_msg, old=None, new=None, extra=None):
""" Issue a nicely formatted deprecation warning. """
if isinstance(since_or_msg, tuple):
if old is None or new is None:
raise ValueError("deprecated entity and a replacement are required")
if len(since_or_msg) != 3 or n... | [
"def",
"deprecated",
"(",
"since_or_msg",
",",
"old",
"=",
"None",
",",
"new",
"=",
"None",
",",
"extra",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"since_or_msg",
",",
"tuple",
")",
":",
"if",
"old",
"is",
"None",
"or",
"new",
"is",
"None",
... | 44.041667 | 26.5 |
def context_chain(self) -> List['Context']:
"""Return a list of contexts starting from this one, its parent and so on."""
contexts = []
ctx = self # type: Optional[Context]
while ctx is not None:
contexts.append(ctx)
ctx = ctx.parent
return contexts | [
"def",
"context_chain",
"(",
"self",
")",
"->",
"List",
"[",
"'Context'",
"]",
":",
"contexts",
"=",
"[",
"]",
"ctx",
"=",
"self",
"# type: Optional[Context]",
"while",
"ctx",
"is",
"not",
"None",
":",
"contexts",
".",
"append",
"(",
"ctx",
")",
"ctx",
... | 34.111111 | 12.666667 |
def get_file_contents(self, pointer=False):
'''
Gets any file contents you care about. Defaults to the main file
@param pointer: The the contents of the file pointer, not the pointed
at file
@return: A string of the contents
'''
if self.pointer:
if poi... | [
"def",
"get_file_contents",
"(",
"self",
",",
"pointer",
"=",
"False",
")",
":",
"if",
"self",
".",
"pointer",
":",
"if",
"pointer",
":",
"return",
"self",
".",
"old_pointed",
"else",
":",
"return",
"self",
".",
"old_data",
"else",
":",
"return",
"self",... | 32.428571 | 18 |
def _setup_py_run_from_dir(root_dir, py_interpreter):
"""run the extractmeta command via the setup.py in the given root_dir.
the output of extractmeta is json and is stored in a tempfile
which is then read in and returned as data"""
data = {}
with _enter_single_subdir(root_dir) as single_subdir:
... | [
"def",
"_setup_py_run_from_dir",
"(",
"root_dir",
",",
"py_interpreter",
")",
":",
"data",
"=",
"{",
"}",
"with",
"_enter_single_subdir",
"(",
"root_dir",
")",
"as",
"single_subdir",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"\"setup.py\"",
")... | 48.806452 | 18.387097 |
def default_logging(grab_log=None, # '/tmp/grab.log',
network_log=None, # '/tmp/grab.network.log',
level=logging.DEBUG, mode='a',
propagate_network_logger=False):
"""
Customize logging output to display all log messages
except grab network logs.
... | [
"def",
"default_logging",
"(",
"grab_log",
"=",
"None",
",",
"# '/tmp/grab.log',",
"network_log",
"=",
"None",
",",
"# '/tmp/grab.network.log',",
"level",
"=",
"logging",
".",
"DEBUG",
",",
"mode",
"=",
"'a'",
",",
"propagate_network_logger",
"=",
"False",
")",
... | 33.16 | 14.52 |
def process_task_topic_list(app, doctree, fromdocname):
"""Process the ``task_topic_list`` node to generate a rendered listing of
Task, Configurable, or Config topics (as determined by the types
key of the ``task_topic_list`` node).
This is called during the "doctree-resolved" phase so that the
``l... | [
"def",
"process_task_topic_list",
"(",
"app",
",",
"doctree",
",",
"fromdocname",
")",
":",
"logger",
"=",
"getLogger",
"(",
"__name__",
")",
"logger",
".",
"debug",
"(",
"'Started process_task_list'",
")",
"env",
"=",
"app",
".",
"builder",
".",
"env",
"for... | 39.54878 | 19.353659 |
def run_step(self):
"""
Defines what to do in one iteration. The default is:
``self.hooked_sess.run(self.train_op)``.
The behavior of each iteration can be changed by either setting ``trainer.train_op``,
or overriding this method.
"""
if not hasattr(self, 'train_... | [
"def",
"run_step",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'train_op'",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"Please either set `Trainer.train_op` or provide an implementation \"",
"\"of Trainer.run_step()!\"",
")",
"self",
".",
"ho... | 40.230769 | 15.307692 |
def __get_by_info(post_id, catalog_id):
'''
Geo the record by post and catalog.
'''
recs = TabPost2Tag.select().where(
(TabPost2Tag.post_id == post_id) &
(TabPost2Tag.tag_id == catalog_id)
)
if recs.count() == 1:
return recs.get()
... | [
"def",
"__get_by_info",
"(",
"post_id",
",",
"catalog_id",
")",
":",
"recs",
"=",
"TabPost2Tag",
".",
"select",
"(",
")",
".",
"where",
"(",
"(",
"TabPost2Tag",
".",
"post_id",
"==",
"post_id",
")",
"&",
"(",
"TabPost2Tag",
".",
"tag_id",
"==",
"catalog_... | 30.416667 | 14.25 |
def put_file(self, target, path, file_data=None, server_file=None, offset=None, truncate=False):
"""Put data into a file on the device
:param target: The device(s) to be targeted with this request
:type target: :class:`devicecloud.sci.TargetABC` or list of :class:`devicecloud.sci.TargetABC` ins... | [
"def",
"put_file",
"(",
"self",
",",
"target",
",",
"path",
",",
"file_data",
"=",
"None",
",",
"server_file",
"=",
"None",
",",
"offset",
"=",
"None",
",",
"truncate",
"=",
"False",
")",
":",
"command_block",
"=",
"FileSystemServiceCommandBlock",
"(",
")"... | 61.909091 | 38.090909 |
def export_data_dir(target_path):
"""
Exports the media files of the application and bundles a zip archive
:return: the target path of the zip archive
"""
from django_productline import utils
from django.conf import settings
utils.zipdir(settings.PRODUCT_CONTEXT.DATA_DIR, target_path, wrapd... | [
"def",
"export_data_dir",
"(",
"target_path",
")",
":",
"from",
"django_productline",
"import",
"utils",
"from",
"django",
".",
"conf",
"import",
"settings",
"utils",
".",
"zipdir",
"(",
"settings",
".",
"PRODUCT_CONTEXT",
".",
"DATA_DIR",
",",
"target_path",
",... | 37.818182 | 16.363636 |
def load_vocab(vocab_file):
"""Loads a vocabulary file into a dictionary."""
vocab = collections.OrderedDict()
index = 0
with io.open(vocab_file, 'r') as reader:
while True:
token = reader.readline()
if not token:
break
token = token.strip()
... | [
"def",
"load_vocab",
"(",
"vocab_file",
")",
":",
"vocab",
"=",
"collections",
".",
"OrderedDict",
"(",
")",
"index",
"=",
"0",
"with",
"io",
".",
"open",
"(",
"vocab_file",
",",
"'r'",
")",
"as",
"reader",
":",
"while",
"True",
":",
"token",
"=",
"r... | 29.076923 | 12.461538 |
def byte_to_unitcode(bytecode):
"""Return an X10 unitcode value from a byte value."""
return list(UC_LOOKUP.keys())[list(UC_LOOKUP.values()).index(bytecode)] | [
"def",
"byte_to_unitcode",
"(",
"bytecode",
")",
":",
"return",
"list",
"(",
"UC_LOOKUP",
".",
"keys",
"(",
")",
")",
"[",
"list",
"(",
"UC_LOOKUP",
".",
"values",
"(",
")",
")",
".",
"index",
"(",
"bytecode",
")",
"]"
] | 54.333333 | 14.666667 |
def resolved_ok(self):
"""
Shortcut to testing unresolved_symbols and count_braces separately.
Returns false if there are unresolved symbols or {{ or }} braces remaining, true otherwise
"""
left_braces, right_braces = self.count_braces()
return len(self.unresolved_symbols()) == left_braces == ri... | [
"def",
"resolved_ok",
"(",
"self",
")",
":",
"left_braces",
",",
"right_braces",
"=",
"self",
".",
"count_braces",
"(",
")",
"return",
"len",
"(",
"self",
".",
"unresolved_symbols",
"(",
")",
")",
"==",
"left_braces",
"==",
"right_braces",
"==",
"0"
] | 47 | 21.571429 |
def get_next_environment(env):
"""
Given an environment, return the next environment in the
promotion hierarchy
"""
config = _config_file()
juicer.utils.Log.log_debug("Finding next environment...")
if env not in config.sections():
raise JuicerConfigError("%s is not a server configu... | [
"def",
"get_next_environment",
"(",
"env",
")",
":",
"config",
"=",
"_config_file",
"(",
")",
"juicer",
".",
"utils",
".",
"Log",
".",
"log_debug",
"(",
"\"Finding next environment...\"",
")",
"if",
"env",
"not",
"in",
"config",
".",
"sections",
"(",
")",
... | 30.473684 | 21.105263 |
def getVariants(self, referenceName, startPosition, endPosition,
callSetIds=[]):
"""
Returns an iterator over the specified variants. The parameters
correspond to the attributes of a GASearchVariantsRequest object.
"""
if callSetIds is None:
callSe... | [
"def",
"getVariants",
"(",
"self",
",",
"referenceName",
",",
"startPosition",
",",
"endPosition",
",",
"callSetIds",
"=",
"[",
"]",
")",
":",
"if",
"callSetIds",
"is",
"None",
":",
"callSetIds",
"=",
"self",
".",
"_callSetIds",
"else",
":",
"for",
"callSe... | 44.9375 | 13.8125 |
def get_inchi(self):
'''Returns inchi'''
inchi = parsers.get_inchi(self.__chebi_id)
if inchi is None:
inchi = parsers.get_inchi(self.get_parent_id())
if inchi is None:
for parent_or_child_id in self.__get_all_ids():
inchi = parsers.get_inchi(pare... | [
"def",
"get_inchi",
"(",
"self",
")",
":",
"inchi",
"=",
"parsers",
".",
"get_inchi",
"(",
"self",
".",
"__chebi_id",
")",
"if",
"inchi",
"is",
"None",
":",
"inchi",
"=",
"parsers",
".",
"get_inchi",
"(",
"self",
".",
"get_parent_id",
"(",
")",
")",
... | 27.2 | 22 |
def replaceNode(oldNode, newNode):
# type: (_RuleConnectable, _RuleConnectable) -> _RuleConnectable
"""
Replace instance of Nonterminal or Terminal in the tree with another one.
:param oldNode: Old nonterminal or terminal already in the tree.
:param newNode: Instance of nontermin... | [
"def",
"replaceNode",
"(",
"oldNode",
",",
"newNode",
")",
":",
"# type: (_RuleConnectable, _RuleConnectable) -> _RuleConnectable",
"if",
"oldNode",
".",
"from_rule",
"is",
"not",
"None",
"and",
"len",
"(",
"oldNode",
".",
"from_rule",
".",
"to_symbols",
")",
">",
... | 56.235294 | 22.470588 |
def match_template(template, image, options=None):
"""
Multi channel template matching using simple correlation distance
:param template: Template image
:param image: Search image
:param options: Other options:
- distance: Distance measure to use. Default: 'correlation'
- normalize:... | [
"def",
"match_template",
"(",
"template",
",",
"image",
",",
"options",
"=",
"None",
")",
":",
"# If the input has max of 3 channels, use the faster OpenCV matching",
"if",
"len",
"(",
"image",
".",
"shape",
")",
"<=",
"3",
"and",
"image",
".",
"shape",
"[",
"2"... | 32.843137 | 20.686275 |
def vectors_between_pts(pts=[]):
'''Return vectors between points on N dimensions.
Last vector is the path between the first and last point, creating a loop.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pts = len(pts)
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
... | [
"def",
"vectors_between_pts",
"(",
"pts",
"=",
"[",
"]",
")",
":",
"assert",
"isinstance",
"(",
"pts",
",",
"list",
")",
"and",
"len",
"(",
"pts",
")",
">",
"0",
"l_pts",
"=",
"len",
"(",
"pts",
")",
"l_pt_prev",
"=",
"None",
"for",
"pt",
"in",
"... | 32.473684 | 17.315789 |
def version():
"""Wrapper for opj_version library routine."""
try:
OPENJP2.opj_version.restype = ctypes.c_char_p
except:
return "0.0.0"
v = OPENJP2.opj_version()
return v.decode('utf-8') if sys.hexversion >= 0x03000000 else v | [
"def",
"version",
"(",
")",
":",
"try",
":",
"OPENJP2",
".",
"opj_version",
".",
"restype",
"=",
"ctypes",
".",
"c_char_p",
"except",
":",
"return",
"\"0.0.0\"",
"v",
"=",
"OPENJP2",
".",
"opj_version",
"(",
")",
"return",
"v",
".",
"decode",
"(",
"'ut... | 28.222222 | 21.777778 |
def _generate_read_callable(name, display_name, arguments, regex, doc, supported):
"""
Returns a callable which conjures the URL for the resource and GETs a response
"""
def f(self, *args, **kwargs):
url = self._generate_url(regex, args)
if 'params' in kwargs:
url += "?" + ur... | [
"def",
"_generate_read_callable",
"(",
"name",
",",
"display_name",
",",
"arguments",
",",
"regex",
",",
"doc",
",",
"supported",
")",
":",
"def",
"f",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"self",
".",
"_gener... | 36.444444 | 14.666667 |
def plot_recurrence_models(
configs, area, slip, msr, rake,
shear_modulus=30.0, disp_length_ratio=1.25E-5, msr_sigma=0.,
figure_size=(8, 6), filename=None, filetype='png', dpi=300, ax=None):
"""
Plots a set of recurrence models
:param list configs:
List of configuration dict... | [
"def",
"plot_recurrence_models",
"(",
"configs",
",",
"area",
",",
"slip",
",",
"msr",
",",
"rake",
",",
"shear_modulus",
"=",
"30.0",
",",
"disp_length_ratio",
"=",
"1.25E-5",
",",
"msr_sigma",
"=",
"0.",
",",
"figure_size",
"=",
"(",
"8",
",",
"6",
")"... | 39.567568 | 17.459459 |
def repository_contributors(self, **kwargs):
"""Return a list of contributors for the project.
Args:
all (bool): If True, return all the items, without pagination
per_page (int): Number of items to retrieve per request
page (int): ID of the page to return (starts wit... | [
"def",
"repository_contributors",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"path",
"=",
"'/projects/%s/repository/contributors'",
"%",
"self",
".",
"get_id",
"(",
")",
"return",
"self",
".",
"manager",
".",
"gitlab",
".",
"http_list",
"(",
"path",
","... | 43.55 | 24.35 |
def validate(self, folder):
"""Validate files and folders contained in this folder
It validates all of the files and folders contained in this
folder if some observers are interested in them.
"""
for observer in list(self.observers):
observer.validate(folder) | [
"def",
"validate",
"(",
"self",
",",
"folder",
")",
":",
"for",
"observer",
"in",
"list",
"(",
"self",
".",
"observers",
")",
":",
"observer",
".",
"validate",
"(",
"folder",
")"
] | 33.888889 | 16 |
def run(create_app, config, description=None, args=None, namespace=None, options=None):
"""Parses commandline options, updates config, creates and runs the application.
Supports listing and selecting environment configurations if `Flask-Config`_ configuration class is used.
.. _Flask-Config: http://pypi.p... | [
"def",
"run",
"(",
"create_app",
",",
"config",
",",
"description",
"=",
"None",
",",
"args",
"=",
"None",
",",
"namespace",
"=",
"None",
",",
"options",
"=",
"None",
")",
":",
"import",
"argparse",
"class",
"HelpFormatter",
"(",
"# argparse.RawTextHelpForma... | 40.495146 | 24.019417 |
def get_response_attribute_filter(self, template_filter, template_model=None):
"""
Prestans-Response-Attribute-List can contain a client's requested
definition for attributes required in the response. This should match
the response_attribute_filter_template?
:param template_filt... | [
"def",
"get_response_attribute_filter",
"(",
"self",
",",
"template_filter",
",",
"template_model",
"=",
"None",
")",
":",
"if",
"template_filter",
"is",
"None",
":",
"return",
"None",
"if",
"'Prestans-Response-Attribute-List'",
"not",
"in",
"self",
".",
"headers",
... | 36.833333 | 22.666667 |
def pprofile(line, cell=None):
"""
Profile line execution.
"""
if cell is None:
# TODO: detect and use arguments (statistical profiling, ...) ?
return run(line)
return _main(
['%%pprofile', '-m', '-'] + shlex.split(line),
io.StringIO(cell),
) | [
"def",
"pprofile",
"(",
"line",
",",
"cell",
"=",
"None",
")",
":",
"if",
"cell",
"is",
"None",
":",
"# TODO: detect and use arguments (statistical profiling, ...) ?",
"return",
"run",
"(",
"line",
")",
"return",
"_main",
"(",
"[",
"'%%pprofile'",
",",
"'-m'",
... | 26.181818 | 16 |
def write_dir_tree(self, tree):
""" Recur through dir tree data structure and write it as a set of objects """
dirs = tree['dirs']; files = tree['files']
child_dirs = {name : self.write_dir_tree(contents) for name, contents in dirs.iteritems()}
return self.write_index_object('tree', {'... | [
"def",
"write_dir_tree",
"(",
"self",
",",
"tree",
")",
":",
"dirs",
"=",
"tree",
"[",
"'dirs'",
"]",
"files",
"=",
"tree",
"[",
"'files'",
"]",
"child_dirs",
"=",
"{",
"name",
":",
"self",
".",
"write_dir_tree",
"(",
"contents",
")",
"for",
"name",
... | 58.5 | 27.166667 |
def retrieve_tx(self, txid):
"""Returns rawtx for <txid>."""
txid = deserialize.txid(txid)
tx = self.service.get_tx(txid)
return serialize.tx(tx) | [
"def",
"retrieve_tx",
"(",
"self",
",",
"txid",
")",
":",
"txid",
"=",
"deserialize",
".",
"txid",
"(",
"txid",
")",
"tx",
"=",
"self",
".",
"service",
".",
"get_tx",
"(",
"txid",
")",
"return",
"serialize",
".",
"tx",
"(",
"tx",
")"
] | 34.6 | 5.2 |
def encryption_mode(self):
"""
Returns the name of the encryption mode to use.
:return:
A unicode string from one of the following: "cbc", "ecb", "ofb",
"cfb", "wrap", "gcm", "ccm", "wrap_pad"
"""
encryption_algo = self['algorithm'].native
if en... | [
"def",
"encryption_mode",
"(",
"self",
")",
":",
"encryption_algo",
"=",
"self",
"[",
"'algorithm'",
"]",
".",
"native",
"if",
"encryption_algo",
"[",
"0",
":",
"7",
"]",
"in",
"set",
"(",
"[",
"'aes128_'",
",",
"'aes192_'",
",",
"'aes256_'",
"]",
")",
... | 28.3125 | 22 |
def get_nonlocal_ip(host, subnet=None):
"""
Search result of getaddrinfo() for a non-localhost-net address
"""
try:
ailist = socket.getaddrinfo(host, None)
except socket.gaierror:
raise exc.UnableToResolveError(host)
for ai in ailist:
# an ai is a 5-tuple; the last elemen... | [
"def",
"get_nonlocal_ip",
"(",
"host",
",",
"subnet",
"=",
"None",
")",
":",
"try",
":",
"ailist",
"=",
"socket",
".",
"getaddrinfo",
"(",
"host",
",",
"None",
")",
"except",
"socket",
".",
"gaierror",
":",
"raise",
"exc",
".",
"UnableToResolveError",
"(... | 30.448276 | 18.448276 |
def _entry_must_exist(df, k1, k2):
"""Evaluate key-subkey existence.
Checks that the key-subkey combo exists in the
configuration options.
"""
count = df[(df['k1'] == k1) &
(df['k2'] == k2)].shape[0]
if count == 0:
raise NotRegisteredError(
"Option {0}.{1} not... | [
"def",
"_entry_must_exist",
"(",
"df",
",",
"k1",
",",
"k2",
")",
":",
"count",
"=",
"df",
"[",
"(",
"df",
"[",
"'k1'",
"]",
"==",
"k1",
")",
"&",
"(",
"df",
"[",
"'k2'",
"]",
"==",
"k2",
")",
"]",
".",
"shape",
"[",
"0",
"]",
"if",
"count"... | 30.727273 | 11.454545 |
def set_triggered_by_event(self, value):
"""
Setter for 'triggered_by_event' field.
:param value - a new value of 'triggered_by_event' field. Must be a boolean type. Does not accept None value.
"""
if value is None or not isinstance(value, bool):
raise TypeError("Trig... | [
"def",
"set_triggered_by_event",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
"or",
"not",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"raise",
"TypeError",
"(",
"\"TriggeredByEvent must be set to a bool\"",
")",
"else",
":",
"self"... | 45.333333 | 17.777778 |
def apply_gates_to_fd(stilde_dict, gates):
"""Applies the given dictionary of gates to the given dictionary of
strain in the frequency domain.
Gates are applied by IFFT-ing the strain data to the time domain, applying
the gate, then FFT-ing back to the frequency domain.
Parameters
----------
... | [
"def",
"apply_gates_to_fd",
"(",
"stilde_dict",
",",
"gates",
")",
":",
"# copy data to new dictionary",
"outdict",
"=",
"dict",
"(",
"stilde_dict",
".",
"items",
"(",
")",
")",
"# create a time-domin strain dictionary to apply the gates to",
"strain_dict",
"=",
"dict",
... | 37.931034 | 21.37931 |
def register_backend(mimetype, module, extensions=None):
"""Register a backend.
`mimetype`: a mimetype string (e.g. 'text/plain')
`module`: an import string (e.g. path.to.my.module)
`extensions`: a list of extensions (e.g. ['txt', 'text'])
"""
if mimetype in MIMETYPE_TO_BACKENDS:
warn("o... | [
"def",
"register_backend",
"(",
"mimetype",
",",
"module",
",",
"extensions",
"=",
"None",
")",
":",
"if",
"mimetype",
"in",
"MIMETYPE_TO_BACKENDS",
":",
"warn",
"(",
"\"overwriting %r mimetype which was already set\"",
"%",
"mimetype",
")",
"MIMETYPE_TO_BACKENDS",
"[... | 42.84 | 15.68 |
def fetchall(self):
"""Fetch all available rows from select result set.
:returns: list of row tuples
"""
result = r = self.fetchmany(size=self.FETCHALL_BLOCKSIZE)
while len(r) == self.FETCHALL_BLOCKSIZE or not self._received_last_resultset_part:
r = self.fetchmany(siz... | [
"def",
"fetchall",
"(",
"self",
")",
":",
"result",
"=",
"r",
"=",
"self",
".",
"fetchmany",
"(",
"size",
"=",
"self",
".",
"FETCHALL_BLOCKSIZE",
")",
"while",
"len",
"(",
"r",
")",
"==",
"self",
".",
"FETCHALL_BLOCKSIZE",
"or",
"not",
"self",
".",
"... | 43.222222 | 16.777778 |
def _filter_namespaces_by_route_whitelist(self):
"""
Given a parsed API in IR form, filter the user-defined datatypes
so that they include only the route datatypes and their direct dependencies.
"""
assert self._routes is not None, "Missing route whitelist"
assert 'route_... | [
"def",
"_filter_namespaces_by_route_whitelist",
"(",
"self",
")",
":",
"assert",
"self",
".",
"_routes",
"is",
"not",
"None",
",",
"\"Missing route whitelist\"",
"assert",
"'route_whitelist'",
"in",
"self",
".",
"_routes",
"assert",
"'datatype_whitelist'",
"in",
"self... | 52 | 25.80198 |
def make_gaussian_kernel(sigma, npix=501, cdelt=0.01, xpix=None, ypix=None):
"""Make kernel for a 2D gaussian.
Parameters
----------
sigma : float
Standard deviation in degrees.
"""
sigma /= cdelt
def fn(t, s): return 1. / (2 * np.pi * s ** 2) * np.exp(
-t ** 2 / (s ** 2 * ... | [
"def",
"make_gaussian_kernel",
"(",
"sigma",
",",
"npix",
"=",
"501",
",",
"cdelt",
"=",
"0.01",
",",
"xpix",
"=",
"None",
",",
"ypix",
"=",
"None",
")",
":",
"sigma",
"/=",
"cdelt",
"def",
"fn",
"(",
"t",
",",
"s",
")",
":",
"return",
"1.",
"/",... | 23.052632 | 22.210526 |
def from_short_lines_text(self, text: str):
"""
Example from Völsupá 28
>>> stanza = "Ein sat hon úti,\\nþá er inn aldni kom\\nyggjungr ása\\nok í augu leit.\\nHvers fregnið mik?\\nHví freistið mín?\\nAllt veit ek, Óðinn,\\nhvar þú auga falt,\\ní inum mæra\\nMímisbrunni.\\nDrekkr mjöð Mímir\\nmo... | [
"def",
"from_short_lines_text",
"(",
"self",
",",
"text",
":",
"str",
")",
":",
"Metre",
".",
"from_short_lines_text",
"(",
"self",
",",
"text",
")",
"self",
".",
"short_lines",
"=",
"[",
"ShortLine",
"(",
"line",
")",
"for",
"line",
"in",
"text",
".",
... | 64.1875 | 43.0625 |
def apply_grad_cartesian_tensor(grad_X, zmat_dist):
"""Apply the gradient for transformation to cartesian space onto zmat_dist.
Args:
grad_X (:class:`numpy.ndarray`): A ``(3, n, n, 3)`` array.
The mathematical details of the index layout is explained in
:meth:`~chemcoord.Cartesi... | [
"def",
"apply_grad_cartesian_tensor",
"(",
"grad_X",
",",
"zmat_dist",
")",
":",
"columns",
"=",
"[",
"'bond'",
",",
"'angle'",
",",
"'dihedral'",
"]",
"C_dist",
"=",
"zmat_dist",
".",
"loc",
"[",
":",
",",
"columns",
"]",
".",
"values",
".",
"T",
"try",... | 43.666667 | 18.083333 |
def stellar_luminosity2(self, steps=10000):
"""
DEPRECATED: ADW 2017-09-20
Compute the stellar luminosity (L_Sol; average per star).
Uses "sample" to generate mass sample and pdf. The range of
integration only covers the input isochrone data (no
extrapolation used), but... | [
"def",
"stellar_luminosity2",
"(",
"self",
",",
"steps",
"=",
"10000",
")",
":",
"msg",
"=",
"\"'%s.stellar_luminosity2': ADW 2017-09-20\"",
"%",
"self",
".",
"__class__",
".",
"__name__",
"DeprecationWarning",
"(",
"msg",
")",
"mass_init",
",",
"mass_pdf",
",",
... | 49.15 | 22.75 |
def sample_stats_prior_to_xarray(self):
"""Extract sample_stats_prior from prior."""
prior = self.prior
data = get_sample_stats(prior)
return dict_to_dataset(data, library=self.pystan, coords=self.coords, dims=self.dims) | [
"def",
"sample_stats_prior_to_xarray",
"(",
"self",
")",
":",
"prior",
"=",
"self",
".",
"prior",
"data",
"=",
"get_sample_stats",
"(",
"prior",
")",
"return",
"dict_to_dataset",
"(",
"data",
",",
"library",
"=",
"self",
".",
"pystan",
",",
"coords",
"=",
... | 50.4 | 13.4 |
def _has_flaky_attributes(cls, test):
"""
Returns True if the test callable in question is marked as flaky.
:param test:
The test that is being prepared to run
:type test:
:class:`nose.case.Test` or :class:`Function`
:return:
:rtype:
`... | [
"def",
"_has_flaky_attributes",
"(",
"cls",
",",
"test",
")",
":",
"current_runs",
"=",
"cls",
".",
"_get_flaky_attribute",
"(",
"test",
",",
"FlakyNames",
".",
"CURRENT_RUNS",
")",
"return",
"current_runs",
"is",
"not",
"None"
] | 31.642857 | 18.071429 |
def load():
"""Loads the libdmtx shared library.
"""
if 'Windows' == platform.system():
# Possible scenarios here
# 1. Run from source, DLLs are in pylibdmtx directory
# cdll.LoadLibrary() imports DLLs in repo root directory
# 2. Wheel install into CPython installat... | [
"def",
"load",
"(",
")",
":",
"if",
"'Windows'",
"==",
"platform",
".",
"system",
"(",
")",
":",
"# Possible scenarios here",
"# 1. Run from source, DLLs are in pylibdmtx directory",
"# cdll.LoadLibrary() imports DLLs in repo root directory",
"# 2. Wheel install into CPyt... | 35.896552 | 17.448276 |
def read(self, line, f, data):
"""See :meth:`PunchParser.read`"""
N = len(data["symbols"])
masses = np.zeros(N, float)
counter = 0
while counter < N:
words = f.readline().split()
for word in words:
masses[counter] = float(word)*amu
... | [
"def",
"read",
"(",
"self",
",",
"line",
",",
"f",
",",
"data",
")",
":",
"N",
"=",
"len",
"(",
"data",
"[",
"\"symbols\"",
"]",
")",
"masses",
"=",
"np",
".",
"zeros",
"(",
"N",
",",
"float",
")",
"counter",
"=",
"0",
"while",
"counter",
"<",
... | 32.909091 | 8.909091 |
def camera_status_send(self, time_usec, target_system, cam_idx, img_idx, event_id, p1, p2, p3, p4, force_mavlink1=False):
'''
Camera Event
time_usec : Image timestamp (microseconds since UNIX epoch, according to camera clock) (uint64_t)
ta... | [
"def",
"camera_status_send",
"(",
"self",
",",
"time_usec",
",",
"target_system",
",",
"cam_idx",
",",
"img_idx",
",",
"event_id",
",",
"p1",
",",
"p2",
",",
"p3",
",",
"p4",
",",
"force_mavlink1",
"=",
"False",
")",
":",
"return",
"self",
".",
"send",
... | 78.75 | 55.5 |
def hotspots(self):
'''
Get lines sampled accross all threads, in order
from most to least sampled.
'''
rooted_leaf_samples, _ = self.live_data_copy()
line_samples = {}
for _, counts in rooted_leaf_samples.items():
for key, count in counts.items():
... | [
"def",
"hotspots",
"(",
"self",
")",
":",
"rooted_leaf_samples",
",",
"_",
"=",
"self",
".",
"live_data_copy",
"(",
")",
"line_samples",
"=",
"{",
"}",
"for",
"_",
",",
"counts",
"in",
"rooted_leaf_samples",
".",
"items",
"(",
")",
":",
"for",
"key",
"... | 37.384615 | 15.384615 |
def get(self, service, path, **kwargs):
""" Make a get request (this returns a coroutine)"""
return self.make_request(Methods.GET, service, path, **kwargs) | [
"def",
"get",
"(",
"self",
",",
"service",
",",
"path",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"make_request",
"(",
"Methods",
".",
"GET",
",",
"service",
",",
"path",
",",
"*",
"*",
"kwargs",
")"
] | 56.333333 | 10.333333 |
def win32_refresh_window(cls):
"""
Call win32 API to refresh the whole Window.
This is sometimes necessary when the application paints background
for completion menus. When the menu disappears, it leaves traces due
to a bug in the Windows Console. Sending a repaint request solve... | [
"def",
"win32_refresh_window",
"(",
"cls",
")",
":",
"# Get console handle",
"handle",
"=",
"windll",
".",
"kernel32",
".",
"GetConsoleWindow",
"(",
")",
"RDW_INVALIDATE",
"=",
"0x0001",
"windll",
".",
"user32",
".",
"RedrawWindow",
"(",
"handle",
",",
"None",
... | 39.846154 | 21.384615 |
def score_for_task(properties, category, result):
"""
Return the possible score of task, depending on whether the result is correct or not.
"""
assert result is not None
if properties and Property.create_from_names(properties).is_svcomp:
return _svcomp_score(category, result)
return None | [
"def",
"score_for_task",
"(",
"properties",
",",
"category",
",",
"result",
")",
":",
"assert",
"result",
"is",
"not",
"None",
"if",
"properties",
"and",
"Property",
".",
"create_from_names",
"(",
"properties",
")",
".",
"is_svcomp",
":",
"return",
"_svcomp_sc... | 39.125 | 16.375 |
def DbDeleteDevice(self, argin):
""" Delete a devcie from database
:param argin: device name
:type: tango.DevString
:return:
:rtype: tango.DevVoid """
self._log.debug("In DbDeleteDevice()")
ret, dev_name, dfm = check_device_name(argin)
if not ret:
... | [
"def",
"DbDeleteDevice",
"(",
"self",
",",
"argin",
")",
":",
"self",
".",
"_log",
".",
"debug",
"(",
"\"In DbDeleteDevice()\"",
")",
"ret",
",",
"dev_name",
",",
"dfm",
"=",
"check_device_name",
"(",
"argin",
")",
"if",
"not",
"ret",
":",
"self",
".",
... | 37.25 | 16.5 |
def writeConfig(self):
"""
Persists the value of the :attr:`AbstractJobStore.config` attribute to the
job store, so that it can be retrieved later by other instances of this class.
"""
with self.writeSharedFileStream('config.pickle', isProtected=False) as fileHandle:
... | [
"def",
"writeConfig",
"(",
"self",
")",
":",
"with",
"self",
".",
"writeSharedFileStream",
"(",
"'config.pickle'",
",",
"isProtected",
"=",
"False",
")",
"as",
"fileHandle",
":",
"pickle",
".",
"dump",
"(",
"self",
".",
"__config",
",",
"fileHandle",
",",
... | 53.857143 | 27.285714 |
def wrap(scope, lines, format=BARE_FORMAT):
"""Wrap a stream of lines in armour.
Takes a stream of lines, for example, the following single line:
Line(1, "Lorem ipsum dolor.")
Or the following multiple lines:
Line(1, "Lorem ipsum")
Line(2, "dolor")
Line(3, "sit amet.")
Provides a gene... | [
"def",
"wrap",
"(",
"scope",
",",
"lines",
",",
"format",
"=",
"BARE_FORMAT",
")",
":",
"for",
"line",
"in",
"iterate",
"(",
"lines",
")",
":",
"prefix",
"=",
"suffix",
"=",
"''",
"if",
"line",
".",
"first",
"and",
"line",
".",
"last",
":",
"prefix... | 33.114286 | 26.514286 |
def graph_query(kind, source, target=None, neighbor_limit=1,
database_filter=None):
"""Perform a graph query on PathwayCommons.
For more information on these queries, see
http://www.pathwaycommons.org/pc2/#graph
Parameters
----------
kind : str
The kind of graph query t... | [
"def",
"graph_query",
"(",
"kind",
",",
"source",
",",
"target",
"=",
"None",
",",
"neighbor_limit",
"=",
"1",
",",
"database_filter",
"=",
"None",
")",
":",
"default_databases",
"=",
"[",
"'wp'",
",",
"'smpdb'",
",",
"'reconx'",
",",
"'reactome'",
",",
... | 35.86747 | 17.072289 |
def from_bytes(cls, bitstream, decode_payload=True):
r'''
Parse the given packet and update properties accordingly
>>> data_hex = ('c033d3c10000000745c0005835400000'
... 'ff06094a254d38204d45d1a30016f597'
... 'a1c3c7406718bf1b50180ff0793f0000'
...... | [
"def",
"from_bytes",
"(",
"cls",
",",
"bitstream",
",",
"decode_payload",
"=",
"True",
")",
":",
"packet",
"=",
"cls",
"(",
")",
"# Convert to ConstBitStream (if not already provided)",
"if",
"not",
"isinstance",
"(",
"bitstream",
",",
"ConstBitStream",
")",
":",
... | 34.078431 | 18 |
def gen_challenge(self, state):
"""returns the next challenge and increments the seed and index
in the state.
:param state: the state to use for generating the challenge. will
verify the integrity of the state object before using it to generate
a challenge. it will then modify... | [
"def",
"gen_challenge",
"(",
"self",
",",
"state",
")",
":",
"state",
".",
"checksig",
"(",
"self",
".",
"key",
")",
"if",
"(",
"state",
".",
"index",
">=",
"state",
".",
"n",
")",
":",
"raise",
"HeartbeatError",
"(",
"\"Out of challenges.\"",
")",
"st... | 42.166667 | 19.166667 |
def request_anime(aid: int) -> 'Anime':
"""Make an anime API request."""
anime_info = alib.request_anime(_CLIENT, aid)
return Anime._make(anime_info) | [
"def",
"request_anime",
"(",
"aid",
":",
"int",
")",
"->",
"'Anime'",
":",
"anime_info",
"=",
"alib",
".",
"request_anime",
"(",
"_CLIENT",
",",
"aid",
")",
"return",
"Anime",
".",
"_make",
"(",
"anime_info",
")"
] | 39.5 | 4 |
def connect_all(state):
'''
Connect to all the configured servers in parallel. Reads/writes state.inventory.
Args:
state (``pyinfra.api.State`` obj): the state containing an inventory to connect to
'''
hosts = [
host for host in state.inventory
if state.is_host_in_limit(hos... | [
"def",
"connect_all",
"(",
"state",
")",
":",
"hosts",
"=",
"[",
"host",
"for",
"host",
"in",
"state",
".",
"inventory",
"if",
"state",
".",
"is_host_in_limit",
"(",
"host",
")",
"]",
"greenlet_to_host",
"=",
"{",
"state",
".",
"pool",
".",
"spawn",
"(... | 27.648649 | 24.135135 |
def imatch(pattern, name):
# type: (Text, Text) -> bool
"""Test whether a name matches a wildcard pattern (case insensitive).
Arguments:
pattern (str): A wildcard pattern, e.g. ``"*.py"``.
name (bool): A filename.
Returns:
bool: `True` if the filename matches the pattern.
... | [
"def",
"imatch",
"(",
"pattern",
",",
"name",
")",
":",
"# type: (Text, Text) -> bool",
"try",
":",
"re_pat",
"=",
"_PATTERN_CACHE",
"[",
"(",
"pattern",
",",
"False",
")",
"]",
"except",
"KeyError",
":",
"res",
"=",
"\"(?ms)\"",
"+",
"_translate",
"(",
"p... | 32.5 | 20.944444 |
def _set_get_flexports(self, v, load=False):
"""
Setter method for get_flexports, mapped from YANG variable /brocade_hardware_rpc/get_flexports (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_get_flexports is considered as a private
method. Backends looking to ... | [
"def",
"_set_get_flexports",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"... | 73.727273 | 34.590909 |
def enrich_pull_requests(self, ocean_backend, enrich_backend, raw_issues_index="github_issues_raw"):
"""
The purpose of this Study is to add additional fields to the pull_requests only index.
Basically to calculate some of the metrics from Code Development under GMD metrics:
https://gith... | [
"def",
"enrich_pull_requests",
"(",
"self",
",",
"ocean_backend",
",",
"enrich_backend",
",",
"raw_issues_index",
"=",
"\"github_issues_raw\"",
")",
":",
"HEADER_JSON",
"=",
"{",
"\"Content-Type\"",
":",
"\"application/json\"",
"}",
"# issues raw index from which the data w... | 48.607595 | 28.056962 |
def check_inputs(self):
""" Check for the existence of input files """
self.inputs = self.expand_filenames(self.inputs)
result = False
if len(self.inputs) == 0 or self.files_exist(self.inputs):
result = True
else:
print("Not executing task. Input file(s) d... | [
"def",
"check_inputs",
"(",
"self",
")",
":",
"self",
".",
"inputs",
"=",
"self",
".",
"expand_filenames",
"(",
"self",
".",
"inputs",
")",
"result",
"=",
"False",
"if",
"len",
"(",
"self",
".",
"inputs",
")",
"==",
"0",
"or",
"self",
".",
"files_exi... | 38.666667 | 18.444444 |
def got_arbiter_module_type_defined(self, module_type):
"""Check if a module type is defined in one of the arbiters
Also check the module name
:param module_type: module type to search for
:type module_type: str
:return: True if mod_type is found else False
:rtype: bool
... | [
"def",
"got_arbiter_module_type_defined",
"(",
"self",
",",
"module_type",
")",
":",
"for",
"arbiter",
"in",
"self",
".",
"arbiters",
":",
"# Do like the linkify will do after....",
"for",
"module",
"in",
"getattr",
"(",
"arbiter",
",",
"'modules'",
",",
"[",
"]",... | 46.130435 | 14.913043 |
def parse_localnamespacepath(parser, event, node):
#pylint: disable=unused-argument
"""Parse LOCALNAMESPACEPATH for Namespace. Return assembled namespace
<!ELEMENT LOCALNAMESPACEPATH (NAMESPACE+)>
"""
(next_event, next_node) = six.next(parser)
namespaces = []
if not _is_start(next... | [
"def",
"parse_localnamespacepath",
"(",
"parser",
",",
"event",
",",
"node",
")",
":",
"#pylint: disable=unused-argument",
"(",
"next_event",
",",
"next_node",
")",
"=",
"six",
".",
"next",
"(",
"parser",
")",
"namespaces",
"=",
"[",
"]",
"if",
"not",
"_is_s... | 29.862069 | 22.689655 |
def verified_approved(pronac, dt):
"""
This metric compare budgetary items of SALIC projects in terms of
verified versus approved value
Items that have vlComprovacao > vlAprovacao * 1.5 are considered outliers
output:
is_outlier: True if any item is outlier
valor: Absolute nu... | [
"def",
"verified_approved",
"(",
"pronac",
",",
"dt",
")",
":",
"items_df",
"=",
"data",
".",
"approved_verified_items",
"items_df",
"=",
"items_df",
".",
"loc",
"[",
"items_df",
"[",
"'PRONAC'",
"]",
"==",
"pronac",
"]",
"items_df",
"[",
"[",
"APPROVED_COLU... | 40.368421 | 17.157895 |
def _getStrippedValue(value, strip):
"""Like the strip() string method, except the strip argument describes
different behavior:
If strip is None, whitespace is stripped.
If strip is a string, the characters in the string are stripped.
If strip is False, nothing is stripped."""
if strip is Non... | [
"def",
"_getStrippedValue",
"(",
"value",
",",
"strip",
")",
":",
"if",
"strip",
"is",
"None",
":",
"value",
"=",
"value",
".",
"strip",
"(",
")",
"# Call strip() with no arguments to strip whitespace.",
"elif",
"isinstance",
"(",
"strip",
",",
"str",
")",
":"... | 36.375 | 20.375 |
def encode (text):
"""Encode text with default encoding if its Unicode."""
if isinstance(text, unicode):
return text.encode(i18n.default_encoding, 'ignore')
return text | [
"def",
"encode",
"(",
"text",
")",
":",
"if",
"isinstance",
"(",
"text",
",",
"unicode",
")",
":",
"return",
"text",
".",
"encode",
"(",
"i18n",
".",
"default_encoding",
",",
"'ignore'",
")",
"return",
"text"
] | 36.8 | 14.6 |
def get_common_complete_suffix(document, completions):
"""
Return the common prefix for all completions.
"""
# Take only completions that don't change the text before the cursor.
def doesnt_change_before_cursor(completion):
end = completion.text[:-completion.start_position]
return do... | [
"def",
"get_common_complete_suffix",
"(",
"document",
",",
"completions",
")",
":",
"# Take only completions that don't change the text before the cursor.",
"def",
"doesnt_change_before_cursor",
"(",
"completion",
")",
":",
"end",
"=",
"completion",
".",
"text",
"[",
":",
... | 37.809524 | 20.095238 |
def order_assets(self, asset_ids, composition_id):
"""Reorders a set of assets in a composition.
arg: asset_ids (osid.id.Id[]): ``Ids`` for a set of
``Assets``
arg: composition_id (osid.id.Id): ``Id`` of the
``Composition``
raise: NotFound - ``comp... | [
"def",
"order_assets",
"(",
"self",
",",
"asset_ids",
",",
"composition_id",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"composition_id",
",",
"ABCId",
")",
"and",
"composition_id",
".",
"get_identifier_namespace",
"(",
")",
"!=",
"'repository.Composition'",
... | 51.090909 | 22.636364 |
def map_query(self, variables=None, evidence=None, elimination_order=None):
"""
Computes the MAP Query over the variables given the evidence.
Note: When multiple variables are passed, it returns the map_query for each
of them individually.
Parameters
----------
... | [
"def",
"map_query",
"(",
"self",
",",
"variables",
"=",
"None",
",",
"evidence",
"=",
"None",
",",
"elimination_order",
"=",
"None",
")",
":",
"# TODO:Check the note in docstring. Change that behavior to return the joint MAP",
"final_distribution",
"=",
"self",
".",
"_v... | 41.38 | 21.66 |
def save(self, description=None, raiseError=True, ntrials=3):
"""
Save repository '.pyreprepo' to disk and create (if missing) or
update (if description is not None) '.pyrepdirinfo'.
:Parameters:
#. description (None, str): Repository main directory information.
... | [
"def",
"save",
"(",
"self",
",",
"description",
"=",
"None",
",",
"raiseError",
"=",
"True",
",",
"ntrials",
"=",
"3",
")",
":",
"assert",
"isinstance",
"(",
"raiseError",
",",
"bool",
")",
",",
"\"raiseError must be boolean\"",
"assert",
"isinstance",
"(",
... | 51.594203 | 24.347826 |
def multivariate_ess(samples, batch_size_generator=None):
r"""Estimate the multivariate Effective Sample Size for the samples of every problem.
This essentially applies :func:`estimate_multivariate_ess` to every problem.
Args:
samples (ndarray, dict or generator): either a matrix of shape (d, p, n... | [
"def",
"multivariate_ess",
"(",
"samples",
",",
"batch_size_generator",
"=",
"None",
")",
":",
"samples_generator",
"=",
"_get_sample_generator",
"(",
"samples",
")",
"return",
"np",
".",
"array",
"(",
"multiprocess_mapping",
"(",
"_MultivariateESSMultiProcessing",
"(... | 55.882353 | 36 |
def discover_config_path(self, config_filename: str) -> str:
"""
Search for config file in a number of places.
If there is no config file found, will return None.
:param config_filename: Config file name or custom path to filename with config.
:return: Path to the discovered con... | [
"def",
"discover_config_path",
"(",
"self",
",",
"config_filename",
":",
"str",
")",
"->",
"str",
":",
"if",
"config_filename",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"config_filename",
")",
":",
"return",
"config_filename",
"for",
"place",
"in",
"_co... | 34.888889 | 20.555556 |
def add_cookies_to_web_driver(driver, cookies):
"""
Sets cookies in an existing WebDriver session.
"""
for cookie in cookies:
driver.add_cookie(convert_cookie_to_dict(cookie))
return driver | [
"def",
"add_cookies_to_web_driver",
"(",
"driver",
",",
"cookies",
")",
":",
"for",
"cookie",
"in",
"cookies",
":",
"driver",
".",
"add_cookie",
"(",
"convert_cookie_to_dict",
"(",
"cookie",
")",
")",
"return",
"driver"
] | 30.142857 | 10.142857 |
def get_card(self):
'''
Get card this checklist is on.
'''
card_id = self.get_checklist_information().get('idCard', None)
if card_id:
return self.client.get_card(card_id) | [
"def",
"get_card",
"(",
"self",
")",
":",
"card_id",
"=",
"self",
".",
"get_checklist_information",
"(",
")",
".",
"get",
"(",
"'idCard'",
",",
"None",
")",
"if",
"card_id",
":",
"return",
"self",
".",
"client",
".",
"get_card",
"(",
"card_id",
")"
] | 30.857143 | 20 |
def emit(self, record):
"""
Emit a record.
The record is formatted, and then sent to the syslog server. If
exception information is present, it is NOT sent to the server.
"""
try:
syslog_msg = self.build_msg(record)
self.transport.transmit(syslog_... | [
"def",
"emit",
"(",
"self",
",",
"record",
")",
":",
"try",
":",
"syslog_msg",
"=",
"self",
".",
"build_msg",
"(",
"record",
")",
"self",
".",
"transport",
".",
"transmit",
"(",
"syslog_msg",
")",
"except",
"Exception",
":",
"self",
".",
"handleError",
... | 31.333333 | 16.5 |
def _set_exp_dscp(self, v, load=False):
"""
Setter method for exp_dscp, mapped from YANG variable /qos_mpls/map/exp_dscp (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_exp_dscp is considered as a private
method. Backends looking to populate this variable shou... | [
"def",
"_set_exp_dscp",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base"... | 113.727273 | 54.318182 |
def GroupEncoder(field_number, is_repeated, is_packed):
"""Returns an encoder for a group field."""
start_tag = TagBytes(field_number, wire_format.WIRETYPE_START_GROUP)
end_tag = TagBytes(field_number, wire_format.WIRETYPE_END_GROUP)
assert not is_packed
if is_repeated:
def EncodeRepeatedField(write, val... | [
"def",
"GroupEncoder",
"(",
"field_number",
",",
"is_repeated",
",",
"is_packed",
")",
":",
"start_tag",
"=",
"TagBytes",
"(",
"field_number",
",",
"wire_format",
".",
"WIRETYPE_START_GROUP",
")",
"end_tag",
"=",
"TagBytes",
"(",
"field_number",
",",
"wire_format"... | 32.105263 | 15.947368 |
def _handle_subscribed(self, *args, chanId=None, channel=None, **kwargs):
"""
Handles responses to subscribe() commands - registers a channel id with
the client and assigns a data handler to it.
:param chanId: int, represent channel id as assigned by server
:param channel: str, ... | [
"def",
"_handle_subscribed",
"(",
"self",
",",
"*",
"args",
",",
"chanId",
"=",
"None",
",",
"channel",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"log",
".",
"debug",
"(",
"\"_handle_subscribed: %s - %s - %s\"",
",",
"chanId",
",",
"channel",
",",
... | 30.833333 | 21.404762 |
def _GetDataStreams(self):
"""Retrieves the data streams.
Returns:
list[DataStream]: data streams.
"""
if self._data_streams is None:
if self._directory is None:
self._directory = self._GetDirectory()
self._data_streams = []
# It is assumed that directory and link file... | [
"def",
"_GetDataStreams",
"(",
"self",
")",
":",
"if",
"self",
".",
"_data_streams",
"is",
"None",
":",
"if",
"self",
".",
"_directory",
"is",
"None",
":",
"self",
".",
"_directory",
"=",
"self",
".",
"_GetDirectory",
"(",
")",
"self",
".",
"_data_stream... | 27.105263 | 15.789474 |
def h2i(self, pkt, h):
"""human x.x.x.x/y to internal"""
ip,mask = re.split( '/', h)
return int(mask), ip | [
"def",
"h2i",
"(",
"self",
",",
"pkt",
",",
"h",
")",
":",
"ip",
",",
"mask",
"=",
"re",
".",
"split",
"(",
"'/'",
",",
"h",
")",
"return",
"int",
"(",
"mask",
")",
",",
"ip"
] | 27.25 | 11.5 |
def normal(target, seeds, scale, loc):
r"""
Produces values from a Weibull distribution given a set of random numbers.
Parameters
----------
target : OpenPNM Object
The object with which this function as associated. This argument
is required to (1) set number of values to generate ... | [
"def",
"normal",
"(",
"target",
",",
"seeds",
",",
"scale",
",",
"loc",
")",
":",
"seeds",
"=",
"target",
"[",
"seeds",
"]",
"value",
"=",
"spts",
".",
"norm",
".",
"ppf",
"(",
"q",
"=",
"seeds",
",",
"scale",
"=",
"scale",
",",
"loc",
"=",
"lo... | 33.135135 | 23.540541 |
def error_class_for_http_status(status):
"""Return the appropriate `ResponseError` subclass for the given
HTTP status code."""
try:
return error_classes[status]
except KeyError:
def new_status_error(xml_response):
if (status > 400 and status < 500):
return Une... | [
"def",
"error_class_for_http_status",
"(",
"status",
")",
":",
"try",
":",
"return",
"error_classes",
"[",
"status",
"]",
"except",
"KeyError",
":",
"def",
"new_status_error",
"(",
"xml_response",
")",
":",
"if",
"(",
"status",
">",
"400",
"and",
"status",
"... | 42.923077 | 12 |
def lookup(self, name, version=None):
"""If version is omitted, max version is used"""
versions = self.get(name)
if not versions:
return None
if version:
return versions[version]
return versions[max(versions)] | [
"def",
"lookup",
"(",
"self",
",",
"name",
",",
"version",
"=",
"None",
")",
":",
"versions",
"=",
"self",
".",
"get",
"(",
"name",
")",
"if",
"not",
"versions",
":",
"return",
"None",
"if",
"version",
":",
"return",
"versions",
"[",
"version",
"]",
... | 33.25 | 8.75 |
def proton_hydroxide_free_energy(temperature, pressure, pH):
"""Returns the Gibbs free energy of proton in bulk solution.
Parameters
----------
pH : pH of bulk solution
temperature : numeric
temperature in K
pressure : numeric
pressure in mbar
Returns
-------
G_H, G_... | [
"def",
"proton_hydroxide_free_energy",
"(",
"temperature",
",",
"pressure",
",",
"pH",
")",
":",
"H2",
"=",
"GasMolecule",
"(",
"'H2'",
")",
"H2O",
"=",
"GasMolecule",
"(",
"'H2O'",
")",
"G_H2",
"=",
"H2",
".",
"get_free_energy",
"(",
"temperature",
"=",
"... | 31.318182 | 20.181818 |
def newDocText(self, content):
"""Creation of a new text node within a document. """
ret = libxml2mod.xmlNewDocText(self._o, content)
if ret is None:raise treeError('xmlNewDocText() failed')
__tmp = xmlNode(_obj=ret)
return __tmp | [
"def",
"newDocText",
"(",
"self",
",",
"content",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlNewDocText",
"(",
"self",
".",
"_o",
",",
"content",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'xmlNewDocText() failed'",
")",
"__tmp",
... | 44 | 12.833333 |
def wb020(self, value=None):
""" Corresponds to IDD Field `wb020`
Wet-bulb temperature corresponding to 02.0% annual cumulative frequency of occurrence
Args:
value (float): value for IDD Field `wb020`
Unit: C
if `value` is None it will not be checked... | [
"def",
"wb020",
"(",
"self",
",",
"value",
"=",
"None",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"try",
":",
"value",
"=",
"float",
"(",
"value",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"'value {} need to be of type float '"... | 35.52381 | 21.714286 |
def parse_css(self):
"""
Take a .css file (classes only please) and parse it into a dictionary
of class/style pairs.
"""
# todo: save the prefs for use later
# orig_prefs = cssutils.ser.prefs
cssutils.ser.prefs.useMinified()
pairs = (
(r.selectorText, r.style.cssText)
for r in self.get_stylesheet(... | [
"def",
"parse_css",
"(",
"self",
")",
":",
"# todo: save the prefs for use later",
"# orig_prefs = cssutils.ser.prefs",
"cssutils",
".",
"ser",
".",
"prefs",
".",
"useMinified",
"(",
")",
"pairs",
"=",
"(",
"(",
"r",
".",
"selectorText",
",",
"r",
".",
"style",
... | 27.285714 | 13.285714 |
def run(itf):
"""
Run optimize functions.
"""
if not itf:
return 1
# access user input
options = SplitInput(itf)
# read input
inputpath = os.path.abspath(options.inputpath)
print(" Reading input file ...")
molecules = csv_interface.read_csv(inputpath, options)
if not mol... | [
"def",
"run",
"(",
"itf",
")",
":",
"if",
"not",
"itf",
":",
"return",
"1",
"# access user input",
"options",
"=",
"SplitInput",
"(",
"itf",
")",
"# read input",
"inputpath",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"options",
".",
"inputpath",
")",
... | 30.214286 | 20.714286 |
def relpath(self, path):
""" Return a relative filepath to path from Dir path. """
return os.path.relpath(path, start=self.path) | [
"def",
"relpath",
"(",
"self",
",",
"path",
")",
":",
"return",
"os",
".",
"path",
".",
"relpath",
"(",
"path",
",",
"start",
"=",
"self",
".",
"path",
")"
] | 47.333333 | 9.666667 |
def find(self, binding_id, instance):
"""find an instance
Create a new instance and populate it with data stored if it exists.
Args:
binding_id (string): UUID of the binding
instance (AtlasServiceInstance.Instance): instance
Returns:... | [
"def",
"find",
"(",
"self",
",",
"binding_id",
",",
"instance",
")",
":",
"binding",
"=",
"AtlasServiceBinding",
".",
"Binding",
"(",
"binding_id",
",",
"instance",
")",
"self",
".",
"backend",
".",
"storage",
".",
"populate",
"(",
"binding",
")",
"return"... | 33.266667 | 17.933333 |
def p_ConstValue_float(p):
"""ConstValue : FLOAT"""
p[0] = model.Value(type=model.Value.FLOAT, value=p[1]) | [
"def",
"p_ConstValue_float",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"model",
".",
"Value",
"(",
"type",
"=",
"model",
".",
"Value",
".",
"FLOAT",
",",
"value",
"=",
"p",
"[",
"1",
"]",
")"
] | 36 | 10 |
def u_grade_ipix(ipix, nside_in, nside_out, nest=False):
"""
Return the indices of sub-pixels (resolution nside_subpix) within
the super-pixel(s) (resolution nside_superpix).
Parameters:
-----------
ipix : index of the input superpixel(s)
nside_in : nside of the input superpixel
... | [
"def",
"u_grade_ipix",
"(",
"ipix",
",",
"nside_in",
",",
"nside_out",
",",
"nest",
"=",
"False",
")",
":",
"if",
"nside_in",
"==",
"nside_out",
":",
"return",
"ipix",
"if",
"not",
"(",
"nside_in",
"<",
"nside_out",
")",
":",
"raise",
"ValueError",
"(",
... | 30.870968 | 19.774194 |
def get_context_data(self, **kwargs):
"""
checks if there is SocialFrind model record for the user
if not attempt to create one
if all fail, redirects to the next page
"""
context = super(FriendListView, self).get_context_data(**kwargs)
friends = []
for f... | [
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"context",
"=",
"super",
"(",
"FriendListView",
",",
"self",
")",
".",
"get_context_data",
"(",
"*",
"*",
"kwargs",
")",
"friends",
"=",
"[",
"]",
"for",
"friend_list",
"in",
"s... | 31.73913 | 16.173913 |
def _copy_attachment(self, name, data, mimetype, mfg_event):
"""Copies an attachment to mfg_event."""
attachment = mfg_event.attachment.add()
attachment.name = name
if isinstance(data, unicode):
data = data.encode('utf8')
attachment.value_binary = data
if mimetype in test_runs_converter.MI... | [
"def",
"_copy_attachment",
"(",
"self",
",",
"name",
",",
"data",
",",
"mimetype",
",",
"mfg_event",
")",
":",
"attachment",
"=",
"mfg_event",
".",
"attachment",
".",
"add",
"(",
")",
"attachment",
".",
"name",
"=",
"name",
"if",
"isinstance",
"(",
"data... | 40.307692 | 11.384615 |
def exists(cls, excludes_, **filters):
""" Return `True` if objects matching the provided filters and excludes
exist if not return false.
Calls the `filter` method by default, but can be overridden for better and
quicker implementations that may be supported by a database.
... | [
"def",
"exists",
"(",
"cls",
",",
"excludes_",
",",
"*",
"*",
"filters",
")",
":",
"results",
"=",
"cls",
".",
"query",
".",
"filter",
"(",
"*",
"*",
"filters",
")",
".",
"exclude",
"(",
"*",
"*",
"excludes_",
")",
"return",
"bool",
"(",
"results",... | 43.5 | 20.166667 |
def relabel_variables(self, mapping, inplace=True):
"""Relabel variables of a binary polynomial as specified by mapping.
Args:
mapping (dict):
Dict mapping current variable labels to new ones. If an
incomplete mapping is provided, unmapped variables retain th... | [
"def",
"relabel_variables",
"(",
"self",
",",
"mapping",
",",
"inplace",
"=",
"True",
")",
":",
"if",
"not",
"inplace",
":",
"return",
"self",
".",
"copy",
"(",
")",
".",
"relabel_variables",
"(",
"mapping",
",",
"inplace",
"=",
"True",
")",
"try",
":"... | 37.816327 | 25.061224 |
def _parallel_tfa_worker(task):
'''
This is a parallel worker for the function below.
task[0] = lcfile
task[1] = timecol
task[2] = magcol
task[3] = errcol
task[4] = templateinfo
task[5] = lcformat
task[6] = lcformatdir
task[6] = interp
task[7] = sigclip
'''
(lcfile... | [
"def",
"_parallel_tfa_worker",
"(",
"task",
")",
":",
"(",
"lcfile",
",",
"timecol",
",",
"magcol",
",",
"errcol",
",",
"templateinfo",
",",
"lcformat",
",",
"lcformatdir",
",",
"interp",
",",
"sigclip",
",",
"mintemplatedist_arcmin",
")",
"=",
"task",
"try"... | 23.128205 | 20.512821 |
def Indicator(pos, size, dtype):
"""
Returns an array of length size and type dtype that is everywhere 0,
except in the index in pos.
:param pos: (int) specifies the position of the one entry that will be set.
:param size: (int) The total size of the array to be returned.
:param dtype: The element type (co... | [
"def",
"Indicator",
"(",
"pos",
",",
"size",
",",
"dtype",
")",
":",
"x",
"=",
"numpy",
".",
"zeros",
"(",
"size",
",",
"dtype",
"=",
"dtype",
")",
"x",
"[",
"pos",
"]",
"=",
"1",
"return",
"x"
] | 36.142857 | 18.857143 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.