text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def is_dirty(self):
""" .. todo:: docstring for is_dirty
"""
# Imports
from ..error import RepoError as RErr
# Get the return value from the dataset, complaining if repo not
# bound. Using 'require_dataset' since any repo w/o a defined
# 'dirty' value is just ... | [
"def",
"is_dirty",
"(",
"self",
")",
":",
"# Imports",
"from",
".",
".",
"error",
"import",
"RepoError",
"as",
"RErr",
"# Get the return value from the dataset, complaining if repo not",
"# bound. Using 'require_dataset' since any repo w/o a defined",
"# 'dirty' value is just goi... | 36.571429 | 0.007614 |
def area_pal(range=(1, 6)):
"""
Point area palette (continuous).
Parameters
----------
range : tuple
Numeric vector of length two, giving range of possible sizes.
Should be greater than 0.
Returns
-------
out : function
Palette function that takes a sequence of ... | [
"def",
"area_pal",
"(",
"range",
"=",
"(",
"1",
",",
"6",
")",
")",
":",
"def",
"area_palette",
"(",
"x",
")",
":",
"return",
"rescale",
"(",
"np",
".",
"sqrt",
"(",
"x",
")",
",",
"to",
"=",
"range",
",",
"_from",
"=",
"(",
"0",
",",
"1",
... | 24.9 | 0.001289 |
def show_print_dialog(self):
"""Open the print dialog"""
if not self.impact_function:
# Now try to read the keywords and show them in the dock
try:
active_layer = self.iface.activeLayer()
keywords = self.keyword_io.read_keywords(active_layer)
... | [
"def",
"show_print_dialog",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"impact_function",
":",
"# Now try to read the keywords and show them in the dock",
"try",
":",
"active_layer",
"=",
"self",
".",
"iface",
".",
"activeLayer",
"(",
")",
"keywords",
"=",
"... | 43.296296 | 0.000836 |
def to_file(self, path, precision='%.2g'):
"""
Create a CSV report of the trackables
:param path: path to file
:param precision: numeric string formatter
"""
table_info = self.get_table_info()
def dump_rows(rows):
if len(rows) > 1:
for... | [
"def",
"to_file",
"(",
"self",
",",
"path",
",",
"precision",
"=",
"'%.2g'",
")",
":",
"table_info",
"=",
"self",
".",
"get_table_info",
"(",
")",
"def",
"dump_rows",
"(",
"rows",
")",
":",
"if",
"len",
"(",
"rows",
")",
">",
"1",
":",
"for",
"row"... | 47.533333 | 0.005039 |
def _write_plist(self, root):
"""Write plist file based on our generated tree."""
# prettify the XML
indent_xml(root)
tree = ElementTree.ElementTree(root)
with open(self.preferences_file, "w") as prefs_file:
prefs_file.write(
"<?xml version=\"1.0\" en... | [
"def",
"_write_plist",
"(",
"self",
",",
"root",
")",
":",
"# prettify the XML",
"indent_xml",
"(",
"root",
")",
"tree",
"=",
"ElementTree",
".",
"ElementTree",
"(",
"root",
")",
"with",
"open",
"(",
"self",
".",
"preferences_file",
",",
"\"w\"",
")",
"as"... | 45.428571 | 0.003082 |
def run(self):
""" Runs the given OPF task against the given Model instance """
self._logger.debug("Starting Dummy Model: modelID=%s;" % (self._modelID))
# =========================================================================
# Initialize periodic activities (e.g., for model result updates)
# ... | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"Starting Dummy Model: modelID=%s;\"",
"%",
"(",
"self",
".",
"_modelID",
")",
")",
"# =========================================================================",
"# Initialize periodic activi... | 37 | 0.012694 |
def align(args):
"""
%prog align database.fasta read1.fq [read2.fq]
Wrapper for three modes of BWA - mem (default), aln, bwasw (long reads).
"""
valid_modes = ("bwasw", "aln", "mem")
p = OptionParser(align.__doc__)
p.add_option("--mode", default="mem", choices=valid_modes, help="BWA mode")
... | [
"def",
"align",
"(",
"args",
")",
":",
"valid_modes",
"=",
"(",
"\"bwasw\"",
",",
"\"aln\"",
",",
"\"mem\"",
")",
"p",
"=",
"OptionParser",
"(",
"align",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--mode\"",
",",
"default",
"=",
"\"mem\"",
",... | 24.176471 | 0.000779 |
def tf_smooth_eig_vec(self):
"""Function that returns smoothed version of min eigen vector."""
_, matrix_m = self.dual_object.get_full_psd_matrix()
# Easier to think in terms of max so negating the matrix
[eig_vals, eig_vectors] = tf.self_adjoint_eig(-matrix_m)
exp_eig_vals = tf.exp(tf.divide(eig_va... | [
"def",
"tf_smooth_eig_vec",
"(",
"self",
")",
":",
"_",
",",
"matrix_m",
"=",
"self",
".",
"dual_object",
".",
"get_full_psd_matrix",
"(",
")",
"# Easier to think in terms of max so negating the matrix",
"[",
"eig_vals",
",",
"eig_vectors",
"]",
"=",
"tf",
".",
"s... | 51.2 | 0.001279 |
def is_open_chunk(self, chk):
"""Check the chunk is free or not"""
cs = self.get_chunk_status(chk)
if cs & 0x4 != 0:
return True
return False | [
"def",
"is_open_chunk",
"(",
"self",
",",
"chk",
")",
":",
"cs",
"=",
"self",
".",
"get_chunk_status",
"(",
"chk",
")",
"if",
"cs",
"&",
"0x4",
"!=",
"0",
":",
"return",
"True",
"return",
"False"
] | 30.833333 | 0.010526 |
def run(self):
"""Main entrypoint method.
Returns
-------
new_nodes : `list`
Nodes to add to the doctree.
"""
self._env = self.state.document.settings.env
nodes = []
if 'toctree' in self.options:
# Insert a hidden toctree
... | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"_env",
"=",
"self",
".",
"state",
".",
"document",
".",
"settings",
".",
"env",
"nodes",
"=",
"[",
"]",
"if",
"'toctree'",
"in",
"self",
".",
"options",
":",
"# Insert a hidden toctree",
"toctree_node",
... | 26.416667 | 0.003044 |
def is_link(url, processed, files):
"""
Determine whether or not a link should be crawled
A url should not be crawled if it
- Is a file
- Has already been crawled
Args:
url: str Url to be processed
processed: list[str] List of urls that have already been crawled
Ret... | [
"def",
"is_link",
"(",
"url",
",",
"processed",
",",
"files",
")",
":",
"if",
"url",
"not",
"in",
"processed",
":",
"is_file",
"=",
"url",
".",
"endswith",
"(",
"BAD_TYPES",
")",
"if",
"is_file",
":",
"files",
".",
"add",
"(",
"url",
")",
"return",
... | 25.380952 | 0.001808 |
def prepare(self, inputstring, strip=False, nl_at_eof_check=False, **kwargs):
"""Prepare a string for processing."""
if self.strict and nl_at_eof_check and inputstring and not inputstring.endswith("\n"):
end_index = len(inputstring) - 1 if inputstring else 0
raise self.make_err(C... | [
"def",
"prepare",
"(",
"self",
",",
"inputstring",
",",
"strip",
"=",
"False",
",",
"nl_at_eof_check",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"strict",
"and",
"nl_at_eof_check",
"and",
"inputstring",
"and",
"not",
"inputstring"... | 54.25 | 0.006042 |
def workflow(ctx, client):
"""List or manage workflows with subcommands."""
if ctx.invoked_subcommand is None:
from renku.models.refs import LinkReference
names = defaultdict(list)
for ref in LinkReference.iter_items(client, common_path='workflows'):
names[ref.reference.name... | [
"def",
"workflow",
"(",
"ctx",
",",
"client",
")",
":",
"if",
"ctx",
".",
"invoked_subcommand",
"is",
"None",
":",
"from",
"renku",
".",
"models",
".",
"refs",
"import",
"LinkReference",
"names",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"ref",
"in",
... | 36.105263 | 0.00142 |
def get_file(self, sharename, fileid):
"""
Get a specific file. Does not require authentication.
Input:
* A sharename
* A fileid - must be an integer
Output:
* A :py:mod:`pygett.files.GettFile` object
Example::
file = client.get... | [
"def",
"get_file",
"(",
"self",
",",
"sharename",
",",
"fileid",
")",
":",
"if",
"not",
"isinstance",
"(",
"fileid",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"\"'fileid' must be an integer\"",
")",
"response",
"=",
"GettRequest",
"(",
")",
".",
"ge... | 26.304348 | 0.00319 |
def temp_connect(self, hardware: hc.API):
""" Connect temporarily to the specified hardware controller.
This should be used as a context manager:
.. code-block :: python
with ctx.temp_connect(hw):
# do some tasks
ctx.home()
# after the w... | [
"def",
"temp_connect",
"(",
"self",
",",
"hardware",
":",
"hc",
".",
"API",
")",
":",
"old_hw",
"=",
"self",
".",
"_hw_manager",
".",
"hardware",
"try",
":",
"self",
".",
"_hw_manager",
".",
"set_hw",
"(",
"hardware",
")",
"yield",
"self",
"finally",
"... | 32.47619 | 0.002849 |
def cancel(self, msg='', exc_type=CancelledError):
"""Cancels all inprogress transfers
This cancels the inprogress transfers by calling cancel() on all
tracked transfer coordinators.
:param msg: The message to pass on to each transfer coordinator that
gets cancelled.
... | [
"def",
"cancel",
"(",
"self",
",",
"msg",
"=",
"''",
",",
"exc_type",
"=",
"CancelledError",
")",
":",
"for",
"transfer_coordinator",
"in",
"self",
".",
"tracked_transfer_coordinators",
":",
"transfer_coordinator",
".",
"cancel",
"(",
"msg",
",",
"exc_type",
"... | 39.692308 | 0.003788 |
def format_authors(self, format='html5', deparagraph=True, mathjax=False,
smart=True, extra_args=None):
"""Get the document authors in the specified markup format.
Parameters
----------
format : `str`, optional
Output format (such as ``'html5'`` or ``'... | [
"def",
"format_authors",
"(",
"self",
",",
"format",
"=",
"'html5'",
",",
"deparagraph",
"=",
"True",
",",
"mathjax",
"=",
"False",
",",
"smart",
"=",
"True",
",",
"extra_args",
"=",
"None",
")",
":",
"formatted_authors",
"=",
"[",
"]",
"for",
"latex_aut... | 40.228571 | 0.00208 |
async def xclaim(self, name: str, group: str, consumer: str, min_idle_time: int, *stream_ids):
"""
[NOTICE] Not officially released yet
Gets ownership of one or multiple messages in the Pending Entries List of a given stream consumer group.
:param name: name of the stream
:para... | [
"async",
"def",
"xclaim",
"(",
"self",
",",
"name",
":",
"str",
",",
"group",
":",
"str",
",",
"consumer",
":",
"str",
",",
"min_idle_time",
":",
"int",
",",
"*",
"stream_ids",
")",
":",
"return",
"await",
"self",
".",
"execute_command",
"(",
"'XCLAIM'... | 51.235294 | 0.007892 |
def create(cli, command, docker_id):
"""Creates waybill shims from a given command name and docker image"""
content = waybill_template.format(command=command,
docker_id=docker_id)
waybill_dir = cli.get_waybill_dir()
waybill_filename = os.path.joi... | [
"def",
"create",
"(",
"cli",
",",
"command",
",",
"docker_id",
")",
":",
"content",
"=",
"waybill_template",
".",
"format",
"(",
"command",
"=",
"command",
",",
"docker_id",
"=",
"docker_id",
")",
"waybill_dir",
"=",
"cli",
".",
"get_waybill_dir",
"(",
")"... | 56.888889 | 0.003846 |
def partition(thelist, n):
"""
Break a list into ``n`` pieces. The last list may be larger than the rest if
the list doesn't break cleanly. That is::
>>> l = range(10)
>>> partition(l, 2)
[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]
>>> partition(l, 3)
[[0, 1, 2], [3, 4, ... | [
"def",
"partition",
"(",
"thelist",
",",
"n",
")",
":",
"try",
":",
"n",
"=",
"int",
"(",
"n",
")",
"thelist",
"=",
"list",
"(",
"thelist",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"return",
"[",
"thelist",
"]",
"p",
"=",
"le... | 25.962963 | 0.011004 |
def get_collections(self):
""" Get names of collections from request matchdict.
:return: Names of collections
:rtype: list of str
"""
collections = self.request.matchdict['collections'].split('/')[0]
collections = [coll.strip() for coll in collections.split(',')]
... | [
"def",
"get_collections",
"(",
"self",
")",
":",
"collections",
"=",
"self",
".",
"request",
".",
"matchdict",
"[",
"'collections'",
"]",
".",
"split",
"(",
"'/'",
")",
"[",
"0",
"]",
"collections",
"=",
"[",
"coll",
".",
"strip",
"(",
")",
"for",
"c... | 37.333333 | 0.005814 |
def build_arch(self, arch):
'''Build any cython components, then install the Python module by
calling setup.py install with the target Python dir.
'''
Recipe.build_arch(self, arch)
self.build_compiled_components(arch)
self.install_python_package(arch) | [
"def",
"build_arch",
"(",
"self",
",",
"arch",
")",
":",
"Recipe",
".",
"build_arch",
"(",
"self",
",",
"arch",
")",
"self",
".",
"build_compiled_components",
"(",
"arch",
")",
"self",
".",
"install_python_package",
"(",
"arch",
")"
] | 41.857143 | 0.006689 |
def log(self, n=None, **kwargs):
"""
Run the repository log command
Returns:
str: output of log command (``hg log -l <n> <--kwarg=value>``)
"""
cmd = ['hg', 'log']
if n:
cmd.extend('-l%d' % n)
cmd.extend(
(('--%s=%s' % (k, v)) ... | [
"def",
"log",
"(",
"self",
",",
"n",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"cmd",
"=",
"[",
"'hg'",
",",
"'log'",
"]",
"if",
"n",
":",
"cmd",
".",
"extend",
"(",
"'-l%d'",
"%",
"n",
")",
"cmd",
".",
"extend",
"(",
"(",
"(",
"'--%s... | 27 | 0.004773 |
def cmdline_params(self, structure_file_name, surface_sample_file_name):
"""Synthesize command line parameters
e.g. [ ['struct.cssr'], ['struct.vsa'], [2.4]]
"""
parameters = []
parameters += [structure_file_name]
parameters += [surface_sample_file_name]
pm_dic... | [
"def",
"cmdline_params",
"(",
"self",
",",
"structure_file_name",
",",
"surface_sample_file_name",
")",
":",
"parameters",
"=",
"[",
"]",
"parameters",
"+=",
"[",
"structure_file_name",
"]",
"parameters",
"+=",
"[",
"surface_sample_file_name",
"]",
"pm_dict",
"=",
... | 29.142857 | 0.002372 |
async def set_slave_neighbors(self):
'''Set neighbor environments for all the slave environments. Assumes
that :attr:`neighbors` are set for this multi-environment.
'''
for i, elem in enumerate(self._slave_origins):
o, addr = elem
r_slave = await self.env.connect(... | [
"async",
"def",
"set_slave_neighbors",
"(",
"self",
")",
":",
"for",
"i",
",",
"elem",
"in",
"enumerate",
"(",
"self",
".",
"_slave_origins",
")",
":",
"o",
",",
"addr",
"=",
"elem",
"r_slave",
"=",
"await",
"self",
".",
"env",
".",
"connect",
"(",
"... | 50.5 | 0.001022 |
def open(self, url, *args, **kwargs):
"""Open the URL and store the Browser's state in this object.
All arguments are forwarded to :func:`Browser.get`.
:return: Forwarded from :func:`Browser.get`.
"""
if self.__verbose == 1:
sys.stdout.write('.')
sys.stdo... | [
"def",
"open",
"(",
"self",
",",
"url",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"__verbose",
"==",
"1",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"'.'",
")",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"e... | 35.3125 | 0.003448 |
def execute(self, timeSeries):
"""Creates a new TimeSeries containing the smoothed values.
:return: TimeSeries object containing the smoothed TimeSeries,
including the forecasted values.
:rtype: TimeSeries
:note: The first normalized value is chosen as the starting p... | [
"def",
"execute",
"(",
"self",
",",
"timeSeries",
")",
":",
"# determine the number of values to forecast, if necessary",
"self",
".",
"_calculate_values_to_forecast",
"(",
"timeSeries",
")",
"# extract the required parameters, performance improvement",
"alpha",
"=",
"self",
".... | 35.890411 | 0.005572 |
def cluster_del_slots(self, slot, *slots):
"""Set hash slots as unbound in receiving node."""
slots = (slot,) + slots
if not all(isinstance(s, int) for s in slots):
raise TypeError("All parameters must be of type int")
fut = self.execute(b'CLUSTER', b'DELSLOTS', *slots)
... | [
"def",
"cluster_del_slots",
"(",
"self",
",",
"slot",
",",
"*",
"slots",
")",
":",
"slots",
"=",
"(",
"slot",
",",
")",
"+",
"slots",
"if",
"not",
"all",
"(",
"isinstance",
"(",
"s",
",",
"int",
")",
"for",
"s",
"in",
"slots",
")",
":",
"raise",
... | 48 | 0.005848 |
def get_config():
"""Read the configfile and return config dict.
Returns
-------
dict
Dictionary with the content of the configpath file.
"""
configpath = get_configpath()
if not configpath.exists():
raise IOError("Config file {} not found.".format(str(configpath)))
else... | [
"def",
"get_config",
"(",
")",
":",
"configpath",
"=",
"get_configpath",
"(",
")",
"if",
"not",
"configpath",
".",
"exists",
"(",
")",
":",
"raise",
"IOError",
"(",
"\"Config file {} not found.\"",
".",
"format",
"(",
"str",
"(",
"configpath",
")",
")",
")... | 27.4 | 0.002353 |
def title(self):
"""Extract title from a release."""
if self.event:
if self.release['name']:
return u'{0}: {1}'.format(
self.repository['full_name'], self.release['name']
)
return u'{0} {1}'.format(self.repo_model.name, self.model.t... | [
"def",
"title",
"(",
"self",
")",
":",
"if",
"self",
".",
"event",
":",
"if",
"self",
".",
"release",
"[",
"'name'",
"]",
":",
"return",
"u'{0}: {1}'",
".",
"format",
"(",
"self",
".",
"repository",
"[",
"'full_name'",
"]",
",",
"self",
".",
"release... | 39.5 | 0.006192 |
def headinside(self):
"""The head inside the well
Returns
-------
array (length number of screens)
Head inside the well for each screen
"""
h = self.model.head(self.xw + self.rw, self.yw, layers=self.layers)
return h - se... | [
"def",
"headinside",
"(",
"self",
")",
":",
"h",
"=",
"self",
".",
"model",
".",
"head",
"(",
"self",
".",
"xw",
"+",
"self",
".",
"rw",
",",
"self",
".",
"yw",
",",
"layers",
"=",
"self",
".",
"layers",
")",
"return",
"h",
"-",
"self",
".",
... | 28.5 | 0.014164 |
def _gather_group_members(group, groups, users):
'''
Gather group members
'''
_group = __salt__['group.info'](group)
if not _group:
log.warning('Group %s does not exist, ignoring.', group)
return
for member in _group['members']:
if member not in users:
users... | [
"def",
"_gather_group_members",
"(",
"group",
",",
"groups",
",",
"users",
")",
":",
"_group",
"=",
"__salt__",
"[",
"'group.info'",
"]",
"(",
"group",
")",
"if",
"not",
"_group",
":",
"log",
".",
"warning",
"(",
"'Group %s does not exist, ignoring.'",
",",
... | 25.538462 | 0.002907 |
def get_cuda_devices():
"""
Imports pycuda at runtime and reads GPU information.
:return: A list of available cuda GPUs.
"""
devices = []
try:
import pycuda.autoinit
import pycuda.driver as cuda
for device_id in range(cuda.Device.count()):
vram = cuda.Devic... | [
"def",
"get_cuda_devices",
"(",
")",
":",
"devices",
"=",
"[",
"]",
"try",
":",
"import",
"pycuda",
".",
"autoinit",
"import",
"pycuda",
".",
"driver",
"as",
"cuda",
"for",
"device_id",
"in",
"range",
"(",
"cuda",
".",
"Device",
".",
"count",
"(",
")",... | 26.85 | 0.003597 |
def make_posts(generator, metadata, url):
"""
Make posts on reddit if it's not a draft, on whatever subs are specified
"""
reddit = generator.get_reddit()
title = lxml.html.fromstring(metadata['title']).text_content()
if reddit is None:
log.info("Reddit plugin not enabled")
retu... | [
"def",
"make_posts",
"(",
"generator",
",",
"metadata",
",",
"url",
")",
":",
"reddit",
"=",
"generator",
".",
"get_reddit",
"(",
")",
"title",
"=",
"lxml",
".",
"html",
".",
"fromstring",
"(",
"metadata",
"[",
"'title'",
"]",
")",
".",
"text_content",
... | 40.296296 | 0.003591 |
def draw_material(material, face=GL_FRONT_AND_BACK):
"""Draw a single material"""
if material.gl_floats is None:
material.gl_floats = (GLfloat * len(material.vertices))(*material.vertices)
material.triangle_count = len(material.vertices) / material.vertex_size
vertex_format = VERTEX_FORMATS... | [
"def",
"draw_material",
"(",
"material",
",",
"face",
"=",
"GL_FRONT_AND_BACK",
")",
":",
"if",
"material",
".",
"gl_floats",
"is",
"None",
":",
"material",
".",
"gl_floats",
"=",
"(",
"GLfloat",
"*",
"len",
"(",
"material",
".",
"vertices",
")",
")",
"(... | 37.051282 | 0.002023 |
def OpenEnumerateInstances(self, ClassName, namespace=None, LocalOnly=None,
DeepInheritance=None, IncludeQualifiers=None,
IncludeClassOrigin=None, PropertyList=None,
FilterQueryLanguage=None, FilterQuery=None,
... | [
"def",
"OpenEnumerateInstances",
"(",
"self",
",",
"ClassName",
",",
"namespace",
"=",
"None",
",",
"LocalOnly",
"=",
"None",
",",
"DeepInheritance",
"=",
"None",
",",
"IncludeQualifiers",
"=",
"None",
",",
"IncludeClassOrigin",
"=",
"None",
",",
"PropertyList",... | 46.235484 | 0.000546 |
def flags(name,
use=None,
accept_keywords=None,
env=None,
license=None,
properties=None,
unmask=False,
mask=False):
'''
Enforce the given flags on the given package or ``DEPEND`` atom.
.. warning::
In most cases, the affected pa... | [
"def",
"flags",
"(",
"name",
",",
"use",
"=",
"None",
",",
"accept_keywords",
"=",
"None",
",",
"env",
"=",
"None",
",",
"license",
"=",
"None",
",",
"properties",
"=",
"None",
",",
"unmask",
"=",
"False",
",",
"mask",
"=",
"False",
")",
":",
"ret"... | 30.283019 | 0.001207 |
def printStatus(self):
"""Dumps different debug info about cluster to default logger"""
status = self.getStatus()
for k, v in iteritems(status):
logging.info('%s: %s' % (str(k), str(v))) | [
"def",
"printStatus",
"(",
"self",
")",
":",
"status",
"=",
"self",
".",
"getStatus",
"(",
")",
"for",
"k",
",",
"v",
"in",
"iteritems",
"(",
"status",
")",
":",
"logging",
".",
"info",
"(",
"'%s: %s'",
"%",
"(",
"str",
"(",
"k",
")",
",",
"str",... | 43.6 | 0.009009 |
def _gen_hash(self, password, salt):
""" Generate password hash.
"""
# generate hash
h = hashlib.sha1()
h.update(salt)
h.update(password)
return h.hexdigest() | [
"def",
"_gen_hash",
"(",
"self",
",",
"password",
",",
"salt",
")",
":",
"# generate hash",
"h",
"=",
"hashlib",
".",
"sha1",
"(",
")",
"h",
".",
"update",
"(",
"salt",
")",
"h",
".",
"update",
"(",
"password",
")",
"return",
"h",
".",
"hexdigest",
... | 23 | 0.009302 |
def video_search(self, entitiy_type, query, **kwargs):
"""
Search the TV schedule database
Where ``entitiy_type`` is a comma separated list of:
``movie``
Movie
``tvseries``
TV series
``episode``
Episode titles
``onetimeonly... | [
"def",
"video_search",
"(",
"self",
",",
"entitiy_type",
",",
"query",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"make_request",
"(",
"'video'",
",",
"entitiy_type",
",",
"query",
",",
"kwargs",
")"
] | 21.409091 | 0.004065 |
def get_items_batch(self, item_request_data, project=None):
"""GetItemsBatch.
Post for retrieving a set of items given a list of paths or a long path. Allows for specifying the recursionLevel and version descriptors for each path.
:param :class:`<TfvcItemRequestData> <azure.devops.v5_0.tfvc.mode... | [
"def",
"get_items_batch",
"(",
"self",
",",
"item_request_data",
",",
"project",
"=",
"None",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"project",
"is",
"not",
"None",
":",
"route_values",
"[",
"'project'",
"]",
"=",
"self",
".",
"_serialize",
".",
... | 60.705882 | 0.007634 |
def scanl(f: Callable[[T, U], T], x: T, xs: Iterable[U]) -> Iterator[T]:
""" Make an iterator that returns accumulated results of a binary function
applied to elements of an iterable.
.. math::
scanl(f, x_0, [x_1, x_2, ...]) = [x_0, f(x_0, x_1), f(f(x_0, x_1), x_2), ...]
Parameters
-------... | [
"def",
"scanl",
"(",
"f",
":",
"Callable",
"[",
"[",
"T",
",",
"U",
"]",
",",
"T",
"]",
",",
"x",
":",
"T",
",",
"xs",
":",
"Iterable",
"[",
"U",
"]",
")",
"->",
"Iterator",
"[",
"T",
"]",
":",
"return",
"accumulate",
"(",
"prepend",
"(",
"... | 23.83871 | 0.003901 |
def addrs2managers(addrs):
'''Map agent addresses to their assumed managers.
.. seealso::
:func:`creamas.util.get_manager`
'''
mgrs = {}
for addr in addrs:
mgr_addr = get_manager(addr)
if mgr_addr not in mgrs:
mgrs[mgr_addr] = []
mgrs[mgr_addr].append(ad... | [
"def",
"addrs2managers",
"(",
"addrs",
")",
":",
"mgrs",
"=",
"{",
"}",
"for",
"addr",
"in",
"addrs",
":",
"mgr_addr",
"=",
"get_manager",
"(",
"addr",
")",
"if",
"mgr_addr",
"not",
"in",
"mgrs",
":",
"mgrs",
"[",
"mgr_addr",
"]",
"=",
"[",
"]",
"m... | 23.285714 | 0.00295 |
def dynamic_import(import_string):
"""
Dynamically import a module or object.
"""
# Use rfind rather than rsplit for Python 2.3 compatibility.
lastdot = import_string.rfind('.')
if lastdot == -1:
return __import__(import_string, {}, {}, [])
module_name, attr = import_string[:lastdot]... | [
"def",
"dynamic_import",
"(",
"import_string",
")",
":",
"# Use rfind rather than rsplit for Python 2.3 compatibility.",
"lastdot",
"=",
"import_string",
".",
"rfind",
"(",
"'.'",
")",
"if",
"lastdot",
"==",
"-",
"1",
":",
"return",
"__import__",
"(",
"import_string",... | 39.909091 | 0.002227 |
def get_nas_credentials(self, identifier, **kwargs):
"""Returns a list of IDs of VLANs which match the given VLAN name.
:param integer instance_id: the instance ID
:returns: A dictionary containing a large amount of information about
the specified instance.
"""
... | [
"def",
"get_nas_credentials",
"(",
"self",
",",
"identifier",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"self",
".",
"network_storage",
".",
"getObject",
"(",
"id",
"=",
"identifier",
",",
"*",
"*",
"kwargs",
")",
"return",
"result"
] | 44.333333 | 0.004914 |
def get_docs_sources_from_ES(self):
"""Get document sources using MGET elasticsearch API"""
docs = [doc for doc, _, _, get_from_ES in self.doc_to_update if get_from_ES]
if docs:
documents = self.docman.elastic.mget(body={"docs": docs}, realtime=True)
return iter(documents... | [
"def",
"get_docs_sources_from_ES",
"(",
"self",
")",
":",
"docs",
"=",
"[",
"doc",
"for",
"doc",
",",
"_",
",",
"_",
",",
"get_from_ES",
"in",
"self",
".",
"doc_to_update",
"if",
"get_from_ES",
"]",
"if",
"docs",
":",
"documents",
"=",
"self",
".",
"do... | 45.5 | 0.010782 |
def generate_nodeselector_dict(self, nodeselector_str):
"""
helper method for generating nodeselector dict
:param nodeselector_str:
:return: dict
"""
nodeselector = {}
if nodeselector_str and nodeselector_str != 'none':
constraints = [x.strip() for x i... | [
"def",
"generate_nodeselector_dict",
"(",
"self",
",",
"nodeselector_str",
")",
":",
"nodeselector",
"=",
"{",
"}",
"if",
"nodeselector_str",
"and",
"nodeselector_str",
"!=",
"'none'",
":",
"constraints",
"=",
"[",
"x",
".",
"strip",
"(",
")",
"for",
"x",
"i... | 42.769231 | 0.007042 |
def args_length(min_len, max_len, *args):
"""
检查参数长度
"""
not_null(*args)
if not all(map(lambda v: min_len <= len(v) <= max_len, args)):
raise ValueError("Argument length must be between {0} and {1}!".format(min_len, max_len)) | [
"def",
"args_length",
"(",
"min_len",
",",
"max_len",
",",
"*",
"args",
")",
":",
"not_null",
"(",
"*",
"args",
")",
"if",
"not",
"all",
"(",
"map",
"(",
"lambda",
"v",
":",
"min_len",
"<=",
"len",
"(",
"v",
")",
"<=",
"max_len",
",",
"args",
")"... | 32.25 | 0.007547 |
def _hash_token(application, token):
"""Creates a hashable object for given token then we could use it as a
dictionary key.
"""
if isinstance(token, dict):
hashed_token = tuple(sorted(token.items()))
elif isinstance(token, tuple):
hashed_token = token
else:
raise TypeErro... | [
"def",
"_hash_token",
"(",
"application",
",",
"token",
")",
":",
"if",
"isinstance",
"(",
"token",
",",
"dict",
")",
":",
"hashed_token",
"=",
"tuple",
"(",
"sorted",
"(",
"token",
".",
"items",
"(",
")",
")",
")",
"elif",
"isinstance",
"(",
"token",
... | 35.5 | 0.002288 |
def mea_approximation(model, max_order, closure='scalar', *closure_args, **closure_kwargs):
r"""
A wrapper around :class:`~means.approximation.mea.moment_expansion_approximation.MomentExpansionApproximation`.
It performs moment expansion approximation (MEA) up to a given order of moment.
See :class:... | [
"def",
"mea_approximation",
"(",
"model",
",",
"max_order",
",",
"closure",
"=",
"'scalar'",
",",
"*",
"closure_args",
",",
"*",
"*",
"closure_kwargs",
")",
":",
"mea",
"=",
"MomentExpansionApproximation",
"(",
"model",
",",
"max_order",
",",
"closure",
"=",
... | 54.692308 | 0.009682 |
def compare(self, value, expectation, regex_expr=False):
"""
Compares two values with regular expression matching support.
Arguments:
value (mixed): value to compare.
expectation (mixed): value to match.
regex_expr (bool, optional): enables string based regex... | [
"def",
"compare",
"(",
"self",
",",
"value",
",",
"expectation",
",",
"regex_expr",
"=",
"False",
")",
":",
"return",
"compare",
"(",
"value",
",",
"expectation",
",",
"regex_expr",
"=",
"regex_expr",
")"
] | 33.153846 | 0.004515 |
def _transstat(status, grouppath, dictpath, line):
"""Executes processing steps when reading a line"""
if status == 0:
raise MTLParseError(
"Status should not be '%s' after reading line:\n%s"
% (STATUSCODE[status], line))
elif status == 1:
currentdict = dictpath[-1]
... | [
"def",
"_transstat",
"(",
"status",
",",
"grouppath",
",",
"dictpath",
",",
"line",
")",
":",
"if",
"status",
"==",
"0",
":",
"raise",
"MTLParseError",
"(",
"\"Status should not be '%s' after reading line:\\n%s\"",
"%",
"(",
"STATUSCODE",
"[",
"status",
"]",
","... | 37.439024 | 0.000635 |
def _highest_degree_variable_chooser(problem, variables, domains):
'''
Choose the variable that is involved on more constraints.
'''
# the variable involved in more constraints
return sorted(variables, key=lambda v: problem.var_degrees[v], reverse=True)[0] | [
"def",
"_highest_degree_variable_chooser",
"(",
"problem",
",",
"variables",
",",
"domains",
")",
":",
"# the variable involved in more constraints",
"return",
"sorted",
"(",
"variables",
",",
"key",
"=",
"lambda",
"v",
":",
"problem",
".",
"var_degrees",
"[",
"v",
... | 45.166667 | 0.007246 |
def _combine_individual_stats(self, operator_count, cv_score, individual_stats):
"""Combine the stats with operator count and cv score and preprare to be written to _evaluated_individuals
Parameters
----------
operator_count: int
number of components in the pipeline
... | [
"def",
"_combine_individual_stats",
"(",
"self",
",",
"operator_count",
",",
"cv_score",
",",
"individual_stats",
")",
":",
"stats",
"=",
"deepcopy",
"(",
"individual_stats",
")",
"# Deepcopy, since the string reference to predecessor should be cloned",
"stats",
"[",
"'oper... | 50.357143 | 0.005567 |
def _parse_content(self, snv_entries):
"""
Parses SNV entries to SNVItems, objects
representing the content for every entry, that
can be used for further processing.
"""
if len(snv_entries) == 1:
return
for line in snv_entries[1:]:
info_dic... | [
"def",
"_parse_content",
"(",
"self",
",",
"snv_entries",
")",
":",
"if",
"len",
"(",
"snv_entries",
")",
"==",
"1",
":",
"return",
"for",
"line",
"in",
"snv_entries",
"[",
"1",
":",
"]",
":",
"info_dict",
"=",
"self",
".",
"_map_info_to_col",
"(",
"li... | 36.090909 | 0.004914 |
def _sort(self, short_list, sorts):
"""
TAKE SHORTLIST, RETURN IT SORTED
:param short_list:
:param sorts: LIST OF SORTS TO PERFORM
:return:
"""
sort_values = self._index_columns(sorts)
# RECURSIVE SORTING
output = []
def _sort_more(short_... | [
"def",
"_sort",
"(",
"self",
",",
"short_list",
",",
"sorts",
")",
":",
"sort_values",
"=",
"self",
".",
"_index_columns",
"(",
"sorts",
")",
"# RECURSIVE SORTING",
"output",
"=",
"[",
"]",
"def",
"_sort_more",
"(",
"short_list",
",",
"i",
",",
"sorts",
... | 28.032258 | 0.003337 |
def _compute_site_class_dummy_variables(cls, vs30):
"""
Extend
:meth:`AtkinsonBoore2003SInter._compute_site_class_dummy_variables`
and includes dummy variable for B/C site conditions (vs30 > 760.)
"""
Sbc = np.zeros_like(vs30)
Sc = np.zeros_like(vs30)
Sd =... | [
"def",
"_compute_site_class_dummy_variables",
"(",
"cls",
",",
"vs30",
")",
":",
"Sbc",
"=",
"np",
".",
"zeros_like",
"(",
"vs30",
")",
"Sc",
"=",
"np",
".",
"zeros_like",
"(",
"vs30",
")",
"Sd",
"=",
"np",
".",
"zeros_like",
"(",
"vs30",
")",
"Se",
... | 31.588235 | 0.003617 |
def addfield(self, pkt, s, val):
"""Add an internal value to a string"""
tmp_len = self.length_of(pkt)
if tmp_len == 0:
return s
internal = self.i2m(pkt, val)[-tmp_len:]
return s + struct.pack("!%ds" % tmp_len, internal) | [
"def",
"addfield",
"(",
"self",
",",
"pkt",
",",
"s",
",",
"val",
")",
":",
"tmp_len",
"=",
"self",
".",
"length_of",
"(",
"pkt",
")",
"if",
"tmp_len",
"==",
"0",
":",
"return",
"s",
"internal",
"=",
"self",
".",
"i2m",
"(",
"pkt",
",",
"val",
... | 38.142857 | 0.007326 |
def execute_download_request(request):
""" Executes download request.
:param request: DownloadRequest to be executed
:type request: DownloadRequest
:return: downloaded data or None
:rtype: numpy array, other possible data type or None
:raises: DownloadFailedException
"""
if request.save... | [
"def",
"execute_download_request",
"(",
"request",
")",
":",
"if",
"request",
".",
"save_response",
"and",
"request",
".",
"data_folder",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Data folder is not specified. '",
"'Please give a data folder name in the initializatio... | 46.622642 | 0.003171 |
def gene_forms(self):
"""
:return: List of strings for all available gene forms
:rtype: list[str]
"""
q = self.session.query(distinct(models.ChemGeneIxnGeneForm.gene_form))
return [x[0] for x in q.all()] | [
"def",
"gene_forms",
"(",
"self",
")",
":",
"q",
"=",
"self",
".",
"session",
".",
"query",
"(",
"distinct",
"(",
"models",
".",
"ChemGeneIxnGeneForm",
".",
"gene_form",
")",
")",
"return",
"[",
"x",
"[",
"0",
"]",
"for",
"x",
"in",
"q",
".",
"all"... | 35 | 0.007968 |
def close(self):
"""Close the listening sockets and all accepted connections."""
for handle in self._handles:
if not handle.closed:
handle.close()
del self._handles[:]
for transport, _ in self.connections:
transport.close()
self._all_closed... | [
"def",
"close",
"(",
"self",
")",
":",
"for",
"handle",
"in",
"self",
".",
"_handles",
":",
"if",
"not",
"handle",
".",
"closed",
":",
"handle",
".",
"close",
"(",
")",
"del",
"self",
".",
"_handles",
"[",
":",
"]",
"for",
"transport",
",",
"_",
... | 35.444444 | 0.006116 |
def gen_experiment_id(n=10):
"""Generate a random string with n characters.
Parameters
----------
n : int
The length of the string to be generated.
Returns
-------
:obj:`str`
A string with only alphabetic characters.
"""
chrs = 'abcdefghijklmnopqrstuvwxyz'
inds... | [
"def",
"gen_experiment_id",
"(",
"n",
"=",
"10",
")",
":",
"chrs",
"=",
"'abcdefghijklmnopqrstuvwxyz'",
"inds",
"=",
"np",
".",
"random",
".",
"randint",
"(",
"0",
",",
"len",
"(",
"chrs",
")",
",",
"size",
"=",
"n",
")",
"return",
"''",
".",
"join",... | 24.375 | 0.007407 |
def compute_allele_frequencies(self, using=None):
"Computes the allele frequencies across all samples in this cohort."
if using is None:
using = router.db_for_write(self.__class__)
cursor = connections[using].cursor()
with transition(self, 'Recomputed Allele Frequencies'):
... | [
"def",
"compute_allele_frequencies",
"(",
"self",
",",
"using",
"=",
"None",
")",
":",
"if",
"using",
"is",
"None",
":",
"using",
"=",
"router",
".",
"db_for_write",
"(",
"self",
".",
"__class__",
")",
"cursor",
"=",
"connections",
"[",
"using",
"]",
"."... | 46.725 | 0.001048 |
def find_files(args):
'''
Return list of spec files. `args` may be filenames which are passed right
through, or directories in which case they are searched recursively for
*._spec.py
'''
files_or_dirs = args or ['.']
filenames = []
for f in files_or_dirs:
if path.isdir(f):
... | [
"def",
"find_files",
"(",
"args",
")",
":",
"files_or_dirs",
"=",
"args",
"or",
"[",
"'.'",
"]",
"filenames",
"=",
"[",
"]",
"for",
"f",
"in",
"files_or_dirs",
":",
"if",
"path",
".",
"isdir",
"(",
"f",
")",
":",
"filenames",
".",
"extend",
"(",
"g... | 35.0625 | 0.003472 |
def startswith(self, prefix, start=None, end=None):
"""Return whether the current bitstring starts with prefix.
prefix -- The bitstring to search for.
start -- The bit position to start from. Defaults to 0.
end -- The bit position to end at. Defaults to self.len.
"""
pr... | [
"def",
"startswith",
"(",
"self",
",",
"prefix",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
")",
":",
"prefix",
"=",
"Bits",
"(",
"prefix",
")",
"start",
",",
"end",
"=",
"self",
".",
"_validate_slice",
"(",
"start",
",",
"end",
")",
"if",... | 37.428571 | 0.003724 |
def get(object_ids):
"""Get a single or a collection of remote objects from the object store.
This method is identical to `ray.get` except it adds support for tuples,
ndarrays and dictionaries.
Args:
object_ids: Object ID of the object to get, a list, tuple, ndarray of
object IDs t... | [
"def",
"get",
"(",
"object_ids",
")",
":",
"if",
"isinstance",
"(",
"object_ids",
",",
"(",
"tuple",
",",
"np",
".",
"ndarray",
")",
")",
":",
"return",
"ray",
".",
"get",
"(",
"list",
"(",
"object_ids",
")",
")",
"elif",
"isinstance",
"(",
"object_i... | 33.4 | 0.00097 |
def flatten(nested_list: list) -> list:
"""Flattens a list, ignore all the lambdas."""
return list(sorted(filter(lambda y: y is not None,
list(map(lambda x: (nested_list.extend(x) # noqa: T484
if isinstance(x, list) else x),
... | [
"def",
"flatten",
"(",
"nested_list",
":",
"list",
")",
"->",
"list",
":",
"return",
"list",
"(",
"sorted",
"(",
"filter",
"(",
"lambda",
"y",
":",
"y",
"is",
"not",
"None",
",",
"list",
"(",
"map",
"(",
"lambda",
"x",
":",
"(",
"nested_list",
".",... | 60.666667 | 0.00542 |
def form(self, usr=None, **kwargs):
""" Returns an HTTPForm that matches the given criteria
Searches for an HTML form in the page's content matching the criteria
specified in kwargs. If a form is found, returns an HTTPForm instance
that represents the form.
P... | [
"def",
"form",
"(",
"self",
",",
"usr",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"usr",
":",
"usr",
"=",
"self",
".",
"usr",
"if",
"self",
".",
"find",
"(",
"\"form\"",
",",
"kwargs",
")",
":",
"return",
"HTTPForm",
"(... | 42.235294 | 0.010899 |
def _parse_json(self, resources, exactly_one=True):
"""
Parse type, words, latitude, and longitude and language from a
JSON response.
"""
code = resources['status'].get('code')
if code:
# https://docs.what3words.com/api/v2/#errors
exc_msg = "Erro... | [
"def",
"_parse_json",
"(",
"self",
",",
"resources",
",",
"exactly_one",
"=",
"True",
")",
":",
"code",
"=",
"resources",
"[",
"'status'",
"]",
".",
"get",
"(",
"'code'",
")",
"if",
"code",
":",
"# https://docs.what3words.com/api/v2/#errors",
"exc_msg",
"=",
... | 32.342105 | 0.00237 |
def fetchmany(self, size=None):
"""Fetch many"""
self._check_executed()
if size is None:
size = self.arraysize
rows = []
for i in range_type(size):
row = self.read_next()
if row is None:
break
rows.append(row)
... | [
"def",
"fetchmany",
"(",
"self",
",",
"size",
"=",
"None",
")",
":",
"self",
".",
"_check_executed",
"(",
")",
"if",
"size",
"is",
"None",
":",
"size",
"=",
"self",
".",
"arraysize",
"rows",
"=",
"[",
"]",
"for",
"i",
"in",
"range_type",
"(",
"size... | 25.214286 | 0.005464 |
def notify_start(self, data):
"""Call this to trigger startup actions.
This logs the process startup and sets the state to 'running'. It is
a pass-through so it can be used as a callback.
"""
self.log.debug('Process %r started: %r', self.args[0], data)
self.start_data ... | [
"def",
"notify_start",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'Process %r started: %r'",
",",
"self",
".",
"args",
"[",
"0",
"]",
",",
"data",
")",
"self",
".",
"start_data",
"=",
"data",
"self",
".",
"state",
"="... | 33.363636 | 0.005305 |
def _images(self, sys_output):
''' a helper method for parsing docker image output '''
import re
gap_pattern = re.compile('\t|\s{2,}')
image_list = []
output_lines = sys_output.split('\n')
column_headers = gap_pattern.split(output_lines[0])
for i in... | [
"def",
"_images",
"(",
"self",
",",
"sys_output",
")",
":",
"import",
"re",
"gap_pattern",
"=",
"re",
".",
"compile",
"(",
"'\\t|\\s{2,}'",
")",
"image_list",
"=",
"[",
"]",
"output_lines",
"=",
"sys_output",
".",
"split",
"(",
"'\\n'",
")",
"column_header... | 37.277778 | 0.007267 |
def extract_data(self):
"""Extracts data from archive.
Returns:
PackageData object containing the extracted data.
"""
data = PackageData(
local_file=self.local_file,
name=self.name,
pkg_name=self.rpm_name or self.name_convertor.rpm_name(
... | [
"def",
"extract_data",
"(",
"self",
")",
":",
"data",
"=",
"PackageData",
"(",
"local_file",
"=",
"self",
".",
"local_file",
",",
"name",
"=",
"self",
".",
"name",
",",
"pkg_name",
"=",
"self",
".",
"rpm_name",
"or",
"self",
".",
"name_convertor",
".",
... | 36.217391 | 0.002339 |
def _parse_sot_segment(self, fptr):
"""Parse the SOT segment.
Parameters
----------
fptr : file
Open file object.
Returns
-------
SOTSegment
The current SOT segment.
"""
offset = fptr.tell() - 2
read_buffer = fptr... | [
"def",
"_parse_sot_segment",
"(",
"self",
",",
"fptr",
")",
":",
"offset",
"=",
"fptr",
".",
"tell",
"(",
")",
"-",
"2",
"read_buffer",
"=",
"fptr",
".",
"read",
"(",
"10",
")",
"data",
"=",
"struct",
".",
"unpack",
"(",
"'>HHIBB'",
",",
"read_buffer... | 26 | 0.001951 |
def learn(self, msg, learnas):
"""Learn message as spam/ham or forget"""
if not isinstance(learnas, types.StringTypes):
raise SpamCError('The learnas option is invalid')
if learnas.lower() == 'forget':
resp = self.tell(msg, 'forget')
else:
resp = self.... | [
"def",
"learn",
"(",
"self",
",",
"msg",
",",
"learnas",
")",
":",
"if",
"not",
"isinstance",
"(",
"learnas",
",",
"types",
".",
"StringTypes",
")",
":",
"raise",
"SpamCError",
"(",
"'The learnas option is invalid'",
")",
"if",
"learnas",
".",
"lower",
"("... | 39.888889 | 0.00545 |
def _ParseCommentRecord(self, structure):
"""Parse a comment and store appropriate attributes.
Args:
structure (pyparsing.ParseResults): parsed log line.
"""
comment = structure[1]
if comment.startswith('Version'):
_, _, self._version = comment.partition(':')
elif comment.startswith... | [
"def",
"_ParseCommentRecord",
"(",
"self",
",",
"structure",
")",
":",
"comment",
"=",
"structure",
"[",
"1",
"]",
"if",
"comment",
".",
"startswith",
"(",
"'Version'",
")",
":",
"_",
",",
"_",
",",
"self",
".",
"_version",
"=",
"comment",
".",
"partit... | 35.866667 | 0.009058 |
def split_ext(path, basename=True):
"""Wrap them to make life easier."""
if basename:
path = os.path.basename(path)
return os.path.splitext(path) | [
"def",
"split_ext",
"(",
"path",
",",
"basename",
"=",
"True",
")",
":",
"if",
"basename",
":",
"path",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"path",
")",
"return",
"os",
".",
"path",
".",
"splitext",
"(",
"path",
")"
] | 32.2 | 0.006061 |
def parse_args(self, args=None, namespace=None, defaults=None):
"""Parse args, returns a tuple of a parser and ParsedArgs object
Args:
args -- sequence of strings representing the arguments to parse
namespace -- object to use for holding arguments
defaults -- la... | [
"def",
"parse_args",
"(",
"self",
",",
"args",
"=",
"None",
",",
"namespace",
"=",
"None",
",",
"defaults",
"=",
"None",
")",
":",
"epilog",
"=",
"self",
".",
"subparsers_summary",
"(",
")",
"epilog",
"+=",
"self",
".",
"epilog",
"return",
"self",
"(",... | 54.428571 | 0.007742 |
def cache_last_modified(request, *argz, **kwz):
'''Last modification date for a cached page.
Intended for usage in conditional views (@condition decorator).'''
response, site, cachekey = kwz.get('_view_data') or initview(request)
if not response: return None
return response[1] | [
"def",
"cache_last_modified",
"(",
"request",
",",
"*",
"argz",
",",
"*",
"*",
"kwz",
")",
":",
"response",
",",
"site",
",",
"cachekey",
"=",
"kwz",
".",
"get",
"(",
"'_view_data'",
")",
"or",
"initview",
"(",
"request",
")",
"if",
"not",
"response",
... | 46.333333 | 0.024735 |
def build(self):
"""
Build vocabulary.
"""
token_freq = self._token_count.most_common(self._max_size)
idx = len(self.vocab)
for token, _ in token_freq:
self._token2id[token] = idx
self._id2token.append(token)
idx += 1
if self._u... | [
"def",
"build",
"(",
"self",
")",
":",
"token_freq",
"=",
"self",
".",
"_token_count",
".",
"most_common",
"(",
"self",
".",
"_max_size",
")",
"idx",
"=",
"len",
"(",
"self",
".",
"vocab",
")",
"for",
"token",
",",
"_",
"in",
"token_freq",
":",
"self... | 29.5 | 0.004695 |
def agent_color(self, val):
"""
gets a colour for agent 0 - 9
"""
if val == '0':
colour = 'blue'
elif val == '1':
colour = 'navy'
elif val == '2':
colour = 'firebrick'
elif val == '3':
colour = 'blue'
elif v... | [
"def",
"agent_color",
"(",
"self",
",",
"val",
")",
":",
"if",
"val",
"==",
"'0'",
":",
"colour",
"=",
"'blue'",
"elif",
"val",
"==",
"'1'",
":",
"colour",
"=",
"'navy'",
"elif",
"val",
"==",
"'2'",
":",
"colour",
"=",
"'firebrick'",
"elif",
"val",
... | 22.821429 | 0.009009 |
def get_folder(self, *, folder_id=None, folder_name=None):
""" Get a folder by it's id or name
:param str folder_id: the folder_id to be retrieved.
Can be any folder Id (child or not)
:param str folder_name: the folder name to be retrieved.
Must be a child of this folder.
... | [
"def",
"get_folder",
"(",
"self",
",",
"*",
",",
"folder_id",
"=",
"None",
",",
"folder_name",
"=",
"None",
")",
":",
"if",
"folder_id",
"and",
"folder_name",
":",
"raise",
"RuntimeError",
"(",
"'Provide only one of the options'",
")",
"if",
"not",
"folder_id"... | 40.88 | 0.001433 |
def authenticated_userid(request):
"""Helper function that can be used in ``db_key`` to support `self`
as a collection key.
"""
user = getattr(request, 'user', None)
key = user.pk_field()
return getattr(user, key) | [
"def",
"authenticated_userid",
"(",
"request",
")",
":",
"user",
"=",
"getattr",
"(",
"request",
",",
"'user'",
",",
"None",
")",
"key",
"=",
"user",
".",
"pk_field",
"(",
")",
"return",
"getattr",
"(",
"user",
",",
"key",
")"
] | 33 | 0.004219 |
def path_exists(value,
allow_empty = False,
**kwargs):
"""Validate that ``value`` is a path-like object that exists on the local
filesystem.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is emp... | [
"def",
"path_exists",
"(",
"value",
",",
"allow_empty",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"value",
"and",
"not",
"allow_empty",
":",
"raise",
"errors",
".",
"EmptyValueError",
"(",
"'value (%s) was empty'",
"%",
"value",
")",
"e... | 35.441176 | 0.004847 |
def random_patt_uniform(nrows, ncols, patt_type=scalar):
"""Returns a ScalarPatternUniform object or a VectorPatternUniform object
where each of the elements is set to a normal random variable with zero
mean and unit standard deviation. *nrows* is the number of rows in
the pattern, which correspon... | [
"def",
"random_patt_uniform",
"(",
"nrows",
",",
"ncols",
",",
"patt_type",
"=",
"scalar",
")",
":",
"if",
"np",
".",
"mod",
"(",
"ncols",
",",
"2",
")",
"==",
"1",
":",
"raise",
"ValueError",
"(",
"err_msg",
"[",
"'ncols_even'",
"]",
")",
"if",
"(",... | 41 | 0.005955 |
def _fastfood_build(args):
"""Run on `fastfood build`."""
written_files, cookbook = food.build_cookbook(
args.config_file, args.template_pack,
args.cookbooks, args.force)
if len(written_files) > 0:
print("%s: %s files written" % (cookbook,
len... | [
"def",
"_fastfood_build",
"(",
"args",
")",
":",
"written_files",
",",
"cookbook",
"=",
"food",
".",
"build_cookbook",
"(",
"args",
".",
"config_file",
",",
"args",
".",
"template_pack",
",",
"args",
".",
"cookbooks",
",",
"args",
".",
"force",
")",
"if",
... | 31.769231 | 0.002353 |
def lcs_logs():
"""
Pull Retrosheet LCS Game Logs
"""
file_name = 'GLLC.TXT'
z = get_zip_file(lcs_url)
data = pd.read_csv(z.open(file_name), header=None, sep=',', quotechar='"')
data.columns = gamelog_columns
return data | [
"def",
"lcs_logs",
"(",
")",
":",
"file_name",
"=",
"'GLLC.TXT'",
"z",
"=",
"get_zip_file",
"(",
"lcs_url",
")",
"data",
"=",
"pd",
".",
"read_csv",
"(",
"z",
".",
"open",
"(",
"file_name",
")",
",",
"header",
"=",
"None",
",",
"sep",
"=",
"','",
"... | 27.111111 | 0.003968 |
def following_qs(self, user, *models, **kwargs):
"""
Returns a queryset of actors that the given user is following (eg who im following).
Items in the list can be of any model unless a list of restricted models are passed.
Eg following(user, User) will only return users following the giv... | [
"def",
"following_qs",
"(",
"self",
",",
"user",
",",
"*",
"models",
",",
"*",
"*",
"kwargs",
")",
":",
"qs",
"=",
"self",
".",
"filter",
"(",
"user",
"=",
"user",
")",
"ctype_filters",
"=",
"Q",
"(",
")",
"for",
"model",
"in",
"models",
":",
"ch... | 39.888889 | 0.008163 |
def _make_regs_symbolic(input_state, reg_list, project):
"""
converts an input state into a state with symbolic registers
:return: the symbolic state
"""
state = input_state.copy()
# overwrite all registers
for reg in reg_list:
state.registers.store(re... | [
"def",
"_make_regs_symbolic",
"(",
"input_state",
",",
"reg_list",
",",
"project",
")",
":",
"state",
"=",
"input_state",
".",
"copy",
"(",
")",
"# overwrite all registers",
"for",
"reg",
"in",
"reg_list",
":",
"state",
".",
"registers",
".",
"store",
"(",
"... | 38.428571 | 0.005445 |
def search_in_rubric(self, **kwargs):
"""Firms search in rubric
http://api.2gis.ru/doc/firms/searches/searchinrubric/
"""
point = kwargs.pop('point', False)
if point:
kwargs['point'] = '%s,%s' % point
bound = kwargs.pop('bound', False)
if bound:
... | [
"def",
"search_in_rubric",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"point",
"=",
"kwargs",
".",
"pop",
"(",
"'point'",
",",
"False",
")",
"if",
"point",
":",
"kwargs",
"[",
"'point'",
"]",
"=",
"'%s,%s'",
"%",
"point",
"bound",
"=",
"kwargs",... | 28.285714 | 0.003257 |
def set_environment(self, environment):
"""Set the environment for all nodes."""
todo = deque([self])
while todo:
node = todo.popleft()
node.environment = environment
todo.extend(node.iter_child_nodes())
return self | [
"def",
"set_environment",
"(",
"self",
",",
"environment",
")",
":",
"todo",
"=",
"deque",
"(",
"[",
"self",
"]",
")",
"while",
"todo",
":",
"node",
"=",
"todo",
".",
"popleft",
"(",
")",
"node",
".",
"environment",
"=",
"environment",
"todo",
".",
"... | 34.5 | 0.007067 |
def _key_index_iter(self) -> Iterator[Tuple[str, Any]]:
""" Allows for iteration over the ``KeyIndex`` values.
This function is intended to be assigned to a newly created KeyIndex class. It enables iteration
over the ``KeyIndex`` names and values. We don't use a mixin to avoid issues with YAML.
Note:
... | [
"def",
"_key_index_iter",
"(",
"self",
")",
"->",
"Iterator",
"[",
"Tuple",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"for",
"k",
",",
"v",
"in",
"vars",
"(",
"self",
")",
".",
"items",
"(",
")",
":",
"yield",
"k",
",",
"v"
] | 45.166667 | 0.007233 |
def visit_FunctionCall(self, node):
"""Visitor for `FunctionCall` AST node."""
call = self.memory[node.identifier.name]._node
args = [self.visit(parameter) for parameter in node.parameters]
if isinstance(call, AST):
current_scope = self.memory.stack.current.current
... | [
"def",
"visit_FunctionCall",
"(",
"self",
",",
"node",
")",
":",
"call",
"=",
"self",
".",
"memory",
"[",
"node",
".",
"identifier",
".",
"name",
"]",
".",
"_node",
"args",
"=",
"[",
"self",
".",
"visit",
"(",
"parameter",
")",
"for",
"parameter",
"i... | 33.961538 | 0.002203 |
def get_gene_pathways(self, gene_name=None, gene_symbol=None, gene_id=None, pathway_id=None,
pathway_name=None, limit=None, as_df=False):
"""Get gene pathway link
:param bool as_df: if set to True result returns as `pandas.DataFrame`
:param str gene_name: gene ... | [
"def",
"get_gene_pathways",
"(",
"self",
",",
"gene_name",
"=",
"None",
",",
"gene_symbol",
"=",
"None",
",",
"gene_id",
"=",
"None",
",",
"pathway_id",
"=",
"None",
",",
"pathway_name",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"as_df",
"=",
"False",... | 42.884615 | 0.009649 |
def remove_redundant_accidentals(note):
"""Remove redundant sharps and flats from the given note.
Examples:
>>> remove_redundant_accidentals('C##b')
'C#'
>>> remove_redundant_accidentals('Eb##b')
'E'
"""
val = 0
for token in note[1:]:
if token == 'b':
val -= 1
... | [
"def",
"remove_redundant_accidentals",
"(",
"note",
")",
":",
"val",
"=",
"0",
"for",
"token",
"in",
"note",
"[",
"1",
":",
"]",
":",
"if",
"token",
"==",
"'b'",
":",
"val",
"-=",
"1",
"elif",
"token",
"==",
"'#'",
":",
"val",
"+=",
"1",
"result",
... | 22.652174 | 0.001842 |
def _ipc_send(self, sock, message_type, payload):
'''
Send and receive a message from the ipc.
NOTE: this is not thread safe
'''
sock.sendall(self._pack(message_type, payload))
data, msg_type = self._ipc_recv(sock)
return data | [
"def",
"_ipc_send",
"(",
"self",
",",
"sock",
",",
"message_type",
",",
"payload",
")",
":",
"sock",
".",
"sendall",
"(",
"self",
".",
"_pack",
"(",
"message_type",
",",
"payload",
")",
")",
"data",
",",
"msg_type",
"=",
"self",
".",
"_ipc_recv",
"(",
... | 34.375 | 0.007092 |
def restore(name):
"""Restores the database from a snapshot"""
app = get_app()
if not name:
snapshot = app.get_latest_snapshot()
if not snapshot:
click.echo(
"Couldn't find any snapshots for project %s" %
load_config()['project_name']
... | [
"def",
"restore",
"(",
"name",
")",
":",
"app",
"=",
"get_app",
"(",
")",
"if",
"not",
"name",
":",
"snapshot",
"=",
"app",
".",
"get_latest_snapshot",
"(",
")",
"if",
"not",
"snapshot",
":",
"click",
".",
"echo",
"(",
"\"Couldn't find any snapshots for pr... | 31.121951 | 0.00076 |
def _update_project(config, task_presenter, results,
long_description, tutorial):
"""Update a project."""
try:
# Get project
project = find_project_by_short_name(config.project['short_name'],
config.pbclient,
... | [
"def",
"_update_project",
"(",
"config",
",",
"task_presenter",
",",
"results",
",",
"long_description",
",",
"tutorial",
")",
":",
"try",
":",
"# Get project",
"project",
"=",
"find_project_by_short_name",
"(",
"config",
".",
"project",
"[",
"'short_name'",
"]",
... | 44 | 0.002471 |
def _p_iteration(self, P, Bp_solver, Vm, Va, pvpq):
""" Performs a P iteration, updates Va.
"""
dVa = -Bp_solver.solve(P)
# Update voltage.
Va[pvpq] = Va[pvpq] + dVa
V = Vm * exp(1j * Va)
return V, Vm, Va | [
"def",
"_p_iteration",
"(",
"self",
",",
"P",
",",
"Bp_solver",
",",
"Vm",
",",
"Va",
",",
"pvpq",
")",
":",
"dVa",
"=",
"-",
"Bp_solver",
".",
"solve",
"(",
"P",
")",
"# Update voltage.",
"Va",
"[",
"pvpq",
"]",
"=",
"Va",
"[",
"pvpq",
"]",
"+",... | 25.3 | 0.007634 |
def get_checked(self):
"""Return the list of checked items that do not have any child."""
checked = []
def get_checked_children(item):
if not self.tag_has("unchecked", item):
ch = self.get_children(item)
if not ch and self.tag_has("checked", item):
... | [
"def",
"get_checked",
"(",
"self",
")",
":",
"checked",
"=",
"[",
"]",
"def",
"get_checked_children",
"(",
"item",
")",
":",
"if",
"not",
"self",
".",
"tag_has",
"(",
"\"unchecked\"",
",",
"item",
")",
":",
"ch",
"=",
"self",
".",
"get_children",
"(",
... | 33 | 0.003466 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.