text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def get_subject_identifier(self, subject_type, user_id, sector_identifier=None):
# type: (str, str, str) -> str
"""
Returns a subject identifier for the local user identifier.
:param subject_type: 'pairwise' or 'public', see
<a href="http://openid.net/specs/openid-connect-cor... | [
"def",
"get_subject_identifier",
"(",
"self",
",",
"subject_type",
",",
"user_id",
",",
"sector_identifier",
"=",
"None",
")",
":",
"# type: (str, str, str) -> str",
"if",
"user_id",
"not",
"in",
"self",
".",
"subject_identifiers",
":",
"self",
".",
"subject_identif... | 50.902439 | 23.926829 |
def main():
"""
Main function, parses the URL from command line arguments
"""
signal.signal(signal.SIGINT, signal_handler)
global offset
global arguments
# Parse argument
arguments = docopt(__doc__, version=__version__)
if arguments['--debug']:
logger.level = logging.DEBUG
... | [
"def",
"main",
"(",
")",
":",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGINT",
",",
"signal_handler",
")",
"global",
"offset",
"global",
"arguments",
"# Parse argument",
"arguments",
"=",
"docopt",
"(",
"__doc__",
",",
"version",
"=",
"__version__",
")... | 29.882353 | 18.705882 |
def get_option(self, name):
"""
Returns the value for the specified generic configuration option.
:returns: configuration option value or `None`, if the option was not
set.
"""
self.__validate_option_name(name)
return self.__options.get(name, None) | [
"def",
"get_option",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"__validate_option_name",
"(",
"name",
")",
"return",
"self",
".",
"__options",
".",
"get",
"(",
"name",
",",
"None",
")"
] | 33.222222 | 17.222222 |
def hashitem(item):
'''
Generate a uniq hash for the JSON compatible primitive data structure.
'''
norm = normitem(item)
byts = s_msgpack.en(norm)
return hashlib.md5(byts).hexdigest() | [
"def",
"hashitem",
"(",
"item",
")",
":",
"norm",
"=",
"normitem",
"(",
"item",
")",
"byts",
"=",
"s_msgpack",
".",
"en",
"(",
"norm",
")",
"return",
"hashlib",
".",
"md5",
"(",
"byts",
")",
".",
"hexdigest",
"(",
")"
] | 28.714286 | 21 |
def list(self, ids, market=values.UNSET):
"""
List albums
:param List[str] ids: List of albums ids
:param str market: Market locale
:return: Page of Albums
:rtype: AlbumPage
"""
params = values.of({
'ids': ','.join(ids),
'market': ... | [
"def",
"list",
"(",
"self",
",",
"ids",
",",
"market",
"=",
"values",
".",
"UNSET",
")",
":",
"params",
"=",
"values",
".",
"of",
"(",
"{",
"'ids'",
":",
"','",
".",
"join",
"(",
"ids",
")",
",",
"'market'",
":",
"market",
"}",
")",
"response",
... | 30.8 | 14.133333 |
def bend_rounded_Miller(Di, angle, Re, rc=None, bend_diameters=None,
roughness=0.0, L_unimpeded=None):
r'''Calculates the loss coefficient for a rounded pipe bend according to
Miller [1]_. This is a sophisticated model which uses corrections for
pipe roughness, the length of the pi... | [
"def",
"bend_rounded_Miller",
"(",
"Di",
",",
"angle",
",",
"Re",
",",
"rc",
"=",
"None",
",",
"bend_diameters",
"=",
"None",
",",
"roughness",
"=",
"0.0",
",",
"L_unimpeded",
"=",
"None",
")",
":",
"if",
"not",
"rc",
":",
"if",
"bend_diameters",
"is",... | 37.395161 | 23.120968 |
def SGg(self):
r'''Specific gravity of a hypothetical gas phase of the mixture, .
[dimensionless]. The reference condition is air at 15.6 °C (60 °F) and
1 atm (rho=1.223 kg/m^3). The definition for gases uses the
compressibility factor of the reference gas and the mixture both at the
... | [
"def",
"SGg",
"(",
"self",
")",
":",
"Vmg",
"=",
"self",
".",
"VolumeGasMixture",
"(",
"T",
"=",
"288.70555555555552",
",",
"P",
"=",
"101325",
",",
"zs",
"=",
"self",
".",
"zs",
",",
"ws",
"=",
"self",
".",
"ws",
")",
"if",
"Vmg",
":",
"rho",
... | 43.411765 | 26.823529 |
def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):
'''
Search and return a setting in a known order:
1. In the virtual machine's configuration
2. In the virtual machine's profile configuration
3. In the virtual machine's provider configuration
4. In t... | [
"def",
"get_cloud_config_value",
"(",
"name",
",",
"vm_",
",",
"opts",
",",
"default",
"=",
"None",
",",
"search_global",
"=",
"True",
")",
":",
"# As a last resort, return the default",
"value",
"=",
"default",
"if",
"search_global",
"is",
"True",
"and",
"opts"... | 43.92 | 21.093333 |
def _update_with_rollback(self, on_dup, *args, **kw):
"""Update, rolling back on failure."""
writelog = []
appendlog = writelog.append
dedup_item = self._dedup_item
write_item = self._write_item
for (key, val) in _iteritems_args_kw(*args, **kw):
try:
... | [
"def",
"_update_with_rollback",
"(",
"self",
",",
"on_dup",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"writelog",
"=",
"[",
"]",
"appendlog",
"=",
"writelog",
".",
"append",
"dedup_item",
"=",
"self",
".",
"_dedup_item",
"write_item",
"=",
"self",... | 44.235294 | 12.941176 |
def pull_full_properties(self):
"""
Retrieve the full set of resource properties and cache them in this
object.
Authorization requirements:
* Object-access permission to this resource.
Raises:
:exc:`~zhmcclient.HTTPError`
:exc:`~zhmcclient.ParseErr... | [
"def",
"pull_full_properties",
"(",
"self",
")",
":",
"full_properties",
"=",
"self",
".",
"manager",
".",
"session",
".",
"get",
"(",
"self",
".",
"_uri",
")",
"self",
".",
"_properties",
"=",
"dict",
"(",
"full_properties",
")",
"self",
".",
"_properties... | 30.1 | 16.3 |
def smallest_prime_factor(Q):
"""Find the smallest number factorable by the small primes 2, 3, 4, and 7
that is larger than the argument Q"""
A = Q;
while(A != 1):
if(np.mod(A, 2) == 0):
A = A / 2
elif(np.mod(A, 3) == 0):
A = A / 3
elif(np.mod(... | [
"def",
"smallest_prime_factor",
"(",
"Q",
")",
":",
"A",
"=",
"Q",
"while",
"(",
"A",
"!=",
"1",
")",
":",
"if",
"(",
"np",
".",
"mod",
"(",
"A",
",",
"2",
")",
"==",
"0",
")",
":",
"A",
"=",
"A",
"/",
"2",
"elif",
"(",
"np",
".",
"mod",
... | 24.736842 | 17.421053 |
def OnPrint(self, event):
"""Print event handler"""
print_area = self._get_print_area()
print_data = self.main_window.print_data
self.main_window.actions.printout(print_area, print_data) | [
"def",
"OnPrint",
"(",
"self",
",",
"event",
")",
":",
"print_area",
"=",
"self",
".",
"_get_print_area",
"(",
")",
"print_data",
"=",
"self",
".",
"main_window",
".",
"print_data",
"self",
".",
"main_window",
".",
"actions",
".",
"printout",
"(",
"print_a... | 30.571429 | 18.714286 |
def setnonce(self, text=None):
"""
Set I{nonce} which is arbitraty set of bytes to prevent
reply attacks.
@param text: The nonce text value.
Generated when I{None}.
@type text: str
"""
if text is None:
s = []
s.append(self.usern... | [
"def",
"setnonce",
"(",
"self",
",",
"text",
"=",
"None",
")",
":",
"if",
"text",
"is",
"None",
":",
"s",
"=",
"[",
"]",
"s",
".",
"append",
"(",
"self",
".",
"username",
")",
"s",
".",
"append",
"(",
"self",
".",
"password",
")",
"s",
".",
"... | 29.777778 | 10.777778 |
def register_editor(self, editor, parent, ensure_uniqueness=False):
"""
Registers given :class:`umbra.components.factory.script_editor.editor.Editor` class editor in the Model.
:param editor: Editor to register.
:type editor: Editor
:param parent: EditorNode parent.
:typ... | [
"def",
"register_editor",
"(",
"self",
",",
"editor",
",",
"parent",
",",
"ensure_uniqueness",
"=",
"False",
")",
":",
"if",
"ensure_uniqueness",
":",
"if",
"self",
".",
"get_editor_nodes",
"(",
"editor",
")",
":",
"raise",
"foundations",
".",
"exceptions",
... | 36.9 | 20.5 |
def get_parser(prog='pycodestyle', version=__version__):
"""Create the parser for the program."""
parser = OptionParser(prog=prog, version=version,
usage="%prog [options] input ...")
parser.config_options = [
'exclude', 'filename', 'select', 'ignore', 'max-line-length',
... | [
"def",
"get_parser",
"(",
"prog",
"=",
"'pycodestyle'",
",",
"version",
"=",
"__version__",
")",
":",
"parser",
"=",
"OptionParser",
"(",
"prog",
"=",
"prog",
",",
"version",
"=",
"version",
",",
"usage",
"=",
"\"%prog [options] input ...\"",
")",
"parser",
... | 60.8 | 21.933333 |
def resolve_hooks(self):
"""Add in the decorated processors
By doing this after constructing the class, we let standard inheritance
do all the hard work.
"""
mro = inspect.getmro(self)
hooks = defaultdict(list)
for attr_name in dir(self):
# Need to ... | [
"def",
"resolve_hooks",
"(",
"self",
")",
":",
"mro",
"=",
"inspect",
".",
"getmro",
"(",
"self",
")",
"hooks",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"attr_name",
"in",
"dir",
"(",
"self",
")",
":",
"# Need to look up the actual descriptor, not whatever... | 35.447368 | 20.947368 |
def inc_convert(self, value):
"""Default converter for the inc:// protocol."""
if not os.path.isabs(value):
value = os.path.join(self.base, value)
with codecs.open(value, 'r', encoding='utf-8') as f:
result = json.load(f)
return result | [
"def",
"inc_convert",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isabs",
"(",
"value",
")",
":",
"value",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"base",
",",
"value",
")",
"with",
"codecs",
".",
"... | 40.714286 | 10.142857 |
def data_file(file_fmt, info=None, **kwargs):
"""
Data file name for given infomation
Args:
file_fmt: file format in terms of f-strings
info: dict, to be hashed and then pass to f-string using 'hash_key'
these info will also be passed to f-strings
**kwargs: arguments f... | [
"def",
"data_file",
"(",
"file_fmt",
",",
"info",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"info",
",",
"dict",
")",
":",
"kwargs",
"[",
"'hash_key'",
"]",
"=",
"hashlib",
".",
"sha256",
"(",
"json",
".",
"dumps",
"(... | 31.166667 | 18.833333 |
def as_dict(self) -> Dict[str, Any]:
"""Converts to a dict of attributes for easier serialization."""
def _on_filter(obj: Any, name: str) -> bool:
# Filter out any callbacks
if isinstance(obj, BaseUnit):
if name.startswith('on_'):
return False
... | [
"def",
"as_dict",
"(",
"self",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"def",
"_on_filter",
"(",
"obj",
":",
"Any",
",",
"name",
":",
"str",
")",
"->",
"bool",
":",
"# Filter out any callbacks",
"if",
"isinstance",
"(",
"obj",
",",
"Base... | 39.1 | 10.1 |
def parse_mmtf_header(infile):
"""Parse an MMTF file and return basic header-like information.
Args:
infile (str): Path to MMTF file
Returns:
dict: Dictionary of parsed header
Todo:
- Can this be sped up by not parsing the 3D coordinate info somehow?
- OR just store th... | [
"def",
"parse_mmtf_header",
"(",
"infile",
")",
":",
"infodict",
"=",
"{",
"}",
"mmtf_decoder",
"=",
"mmtf",
".",
"parse",
"(",
"infile",
")",
"infodict",
"[",
"'date'",
"]",
"=",
"mmtf_decoder",
".",
"deposition_date",
"infodict",
"[",
"'release_date'",
"]"... | 41.419355 | 30.322581 |
def import_process_template_status(self, id):
"""ImportProcessTemplateStatus.
[Preview API] Tells whether promote has completed for the specified promote job ID.
:param str id: The ID of the promote job operation
:rtype: :class:`<ProcessPromoteStatus> <azure.devops.v5_0.work_item_trackin... | [
"def",
"import_process_template_status",
"(",
"self",
",",
"id",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"id",
"is",
"not",
"None",
":",
"route_values",
"[",
"'id'",
"]",
"=",
"self",
".",
"_serialize",
".",
"url",
"(",
"'id'",
",",
"id",
",",
... | 56.066667 | 21.933333 |
def compress_css(self, paths, output_filename, variant=None, **kwargs):
"""Concatenate and compress CSS files"""
css = self.concatenate_and_rewrite(paths, output_filename, variant)
compressor = self.css_compressor
if compressor:
css = getattr(compressor(verbose=self.verbose),... | [
"def",
"compress_css",
"(",
"self",
",",
"paths",
",",
"output_filename",
",",
"variant",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"css",
"=",
"self",
".",
"concatenate_and_rewrite",
"(",
"paths",
",",
"output_filename",
",",
"variant",
")",
"compre... | 45.5 | 19.166667 |
def _choi_to_kraus(data, input_dim, output_dim, atol=ATOL_DEFAULT):
"""Transform Choi representation to Kraus representation."""
# Check if hermitian matrix
if is_hermitian_matrix(data, atol=atol):
# Get eigen-decomposition of Choi-matrix
w, v = la.eigh(data)
# Check eigenvaleus are ... | [
"def",
"_choi_to_kraus",
"(",
"data",
",",
"input_dim",
",",
"output_dim",
",",
"atol",
"=",
"ATOL_DEFAULT",
")",
":",
"# Check if hermitian matrix",
"if",
"is_hermitian_matrix",
"(",
"data",
",",
"atol",
"=",
"atol",
")",
":",
"# Get eigen-decomposition of Choi-mat... | 44.1 | 14.766667 |
def _load_contents(self, polib, resource):
"""
Parses machine object (MO) format using polib
@type resource: str
@param resource: resource
@rtype: list
"""
import struct
try:
return polib.mofile(resource)
except (ValueError, Attribute... | [
"def",
"_load_contents",
"(",
"self",
",",
"polib",
",",
"resource",
")",
":",
"import",
"struct",
"try",
":",
"return",
"polib",
".",
"mofile",
"(",
"resource",
")",
"except",
"(",
"ValueError",
",",
"AttributeError",
",",
"struct",
".",
"error",
")",
"... | 28.5 | 14.875 |
def _match_stmt(ctx, stmt, specs, canonical):
"""Match stmt against the spec.
Return None | spec'
spec' is an updated spec with the matching spec consumed
"""
(spec, canspec) = specs
i = 0
while i < len(spec):
(keywd, occurance) = spec[i]
if keywd == '$any':
retu... | [
"def",
"_match_stmt",
"(",
"ctx",
",",
"stmt",
",",
"specs",
",",
"canonical",
")",
":",
"(",
"spec",
",",
"canspec",
")",
"=",
"specs",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"spec",
")",
":",
"(",
"keywd",
",",
"occurance",
")",
"=",
"... | 41.840426 | 15.095745 |
def _get_distinct_objs(objs):
"""
Return a list with distinct elements of "objs" (different ids).
Preserves order.
"""
ids = set()
res = []
for obj in objs:
if not id(obj) in ids:
ids.add(id(obj))
res.append(obj)
return res | [
"def",
"_get_distinct_objs",
"(",
"objs",
")",
":",
"ids",
"=",
"set",
"(",
")",
"res",
"=",
"[",
"]",
"for",
"obj",
"in",
"objs",
":",
"if",
"not",
"id",
"(",
"obj",
")",
"in",
"ids",
":",
"ids",
".",
"add",
"(",
"id",
"(",
"obj",
")",
")",
... | 23 | 16 |
def hdfgroup_to_nifti1image(h5group):
"""Returns a nibabel Nifti1Image from a HDF5 group datasets
Parameters
----------
h5group: h5py.Group
HDF5 group
Returns
-------
nibabel Nifti1Image
"""
try:
data = h5group['data'][:]
affine = h5group['affine'][:]
... | [
"def",
"hdfgroup_to_nifti1image",
"(",
"h5group",
")",
":",
"try",
":",
"data",
"=",
"h5group",
"[",
"'data'",
"]",
"[",
":",
"]",
"affine",
"=",
"h5group",
"[",
"'affine'",
"]",
"[",
":",
"]",
"extra",
"=",
"None",
"if",
"'extra'",
"in",
"h5group",
... | 23.642857 | 23.714286 |
def set_connection(self, service_name, to_cache):
"""
Sets a connection class within the cache.
:param service_name: The service a given ``Connection`` talks to. Ex.
``sqs``, ``sns``, ``dynamodb``, etc.
:type service_name: string
:param to_cache: The class to be cac... | [
"def",
"set_connection",
"(",
"self",
",",
"service_name",
",",
"to_cache",
")",
":",
"self",
".",
"services",
".",
"setdefault",
"(",
"service_name",
",",
"{",
"}",
")",
"self",
".",
"services",
"[",
"service_name",
"]",
"[",
"'connection'",
"]",
"=",
"... | 37.076923 | 16.461538 |
def load_hdu(self, imname, hdulist, num_hdu):
"""Display an astropy.io.fits HDU in a remote Ginga reference viewer.
Parameters
----------
imname : str
A name to use for the image in the reference viewer.
hdulist : `~astropy.io.fits.HDUList`
This should b... | [
"def",
"load_hdu",
"(",
"self",
",",
"imname",
",",
"hdulist",
",",
"num_hdu",
")",
":",
"buf_io",
"=",
"BytesIO",
"(",
")",
"hdulist",
".",
"writeto",
"(",
"buf_io",
")",
"load_fits_buffer",
"=",
"self",
".",
"_client",
".",
"lookup_attr",
"(",
"'load_f... | 29.966667 | 23.7 |
def sync(self, *args):
"""
Synchronise the settings. This means that the pixel start
values are shifted downwards so that they are synchronised
with a full-frame binned version. This does nothing if the
binning factor == 1
"""
xbin = self.xbin.value()
ybin... | [
"def",
"sync",
"(",
"self",
",",
"*",
"args",
")",
":",
"xbin",
"=",
"self",
".",
"xbin",
".",
"value",
"(",
")",
"ybin",
"=",
"self",
".",
"ybin",
".",
"value",
"(",
")",
"n",
"=",
"0",
"for",
"xs",
",",
"ys",
",",
"nx",
",",
"ny",
"in",
... | 33.08 | 13.24 |
def experiments_fmri_create(self, experiment_url, data_file):
"""Upload given data file as fMRI for experiment with given Url.
Parameters
----------
experiment_url : string
Url for experiment resource
data_file: Abs. Path to file on disk
Functional data f... | [
"def",
"experiments_fmri_create",
"(",
"self",
",",
"experiment_url",
",",
"data_file",
")",
":",
"# Get the experiment",
"experiment",
"=",
"self",
".",
"experiments_get",
"(",
"experiment_url",
")",
"# Upload data",
"FunctionalDataHandle",
".",
"create",
"(",
"exper... | 32.416667 | 15.708333 |
def get_all_targets(self):
"""Returns all targets for all batches of this Executor."""
result = []
for batch in self.batches:
result.extend(batch.targets)
return result | [
"def",
"get_all_targets",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"for",
"batch",
"in",
"self",
".",
"batches",
":",
"result",
".",
"extend",
"(",
"batch",
".",
"targets",
")",
"return",
"result"
] | 34.5 | 10 |
def fetch_googl():
"""Returns stock prices for Google company."""
yql = YQL('GOOGL', '2014-01-01', '2014-01-10')
for item in yql:
print item.get('date'), item.get('price')
yql.select('GOOGL', '2014-01-01', '2014-01-10')
for item in yql:
print item.get('date'), item.get('price') | [
"def",
"fetch_googl",
"(",
")",
":",
"yql",
"=",
"YQL",
"(",
"'GOOGL'",
",",
"'2014-01-01'",
",",
"'2014-01-10'",
")",
"for",
"item",
"in",
"yql",
":",
"print",
"item",
".",
"get",
"(",
"'date'",
")",
",",
"item",
".",
"get",
"(",
"'price'",
")",
"... | 27.909091 | 20.090909 |
def get_instance(self, data):
"""Retrieve an existing record by primary key(s). If the schema instance
is transient, return None.
:param data: Serialized data to inform lookup.
"""
if self.transient:
return None
props = get_primary_keys(self.opts.model)
... | [
"def",
"get_instance",
"(",
"self",
",",
"data",
")",
":",
"if",
"self",
".",
"transient",
":",
"return",
"None",
"props",
"=",
"get_primary_keys",
"(",
"self",
".",
"opts",
".",
"model",
")",
"filters",
"=",
"{",
"prop",
".",
"key",
":",
"data",
"."... | 39.538462 | 15.461538 |
def _read_csv_table(path):
"""Lee un CSV a una lista de diccionarios."""
with open(path, 'rb') as csvfile:
reader = csv.DictReader(csvfile)
table = list(reader)
return table | [
"def",
"_read_csv_table",
"(",
"path",
")",
":",
"with",
"open",
"(",
"path",
",",
"'rb'",
")",
"as",
"csvfile",
":",
"reader",
"=",
"csv",
".",
"DictReader",
"(",
"csvfile",
")",
"table",
"=",
"list",
"(",
"reader",
")",
"return",
"table"
] | 32.666667 | 8.833333 |
def catread(args):
"""
%prog catread fastqfile1 fastqfile2
Concatenate paired end reads into one. Useful for example to do single-end
mapping and perform filtering on the whole read pair level.
"""
p = OptionParser(catread.__doc__)
opts, args = p.parse_args(args)
if len(args) != 2:
... | [
"def",
"catread",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"catread",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"2",
":",
"sys",
".",
"exit",
"(",
... | 32 | 17.68 |
def create_multiprocessing(parallel_data, queue=None):
'''
This function will be called from another process when running a map in
parallel mode. The result from the create is always a json object.
'''
salt.utils.crypt.reinit_crypto()
parallel_data['opts']['output'] = 'json'
cloud = Cloud(p... | [
"def",
"create_multiprocessing",
"(",
"parallel_data",
",",
"queue",
"=",
"None",
")",
":",
"salt",
".",
"utils",
".",
"crypt",
".",
"reinit_crypto",
"(",
")",
"parallel_data",
"[",
"'opts'",
"]",
"[",
"'output'",
"]",
"=",
"'json'",
"cloud",
"=",
"Cloud",... | 35.074074 | 23.592593 |
def fetch_items(self, category, **kwargs):
"""Fetch events
:param category: the category of items to fetch
:param kwargs: backend arguments
:returns: a generator of items
"""
logger.info("Looking for events at url '%s'", self.url)
nevents = 0 # number of event... | [
"def",
"fetch_items",
"(",
"self",
",",
"category",
",",
"*",
"*",
"kwargs",
")",
":",
"logger",
".",
"info",
"(",
"\"Looking for events at url '%s'\"",
",",
"self",
".",
"url",
")",
"nevents",
"=",
"0",
"# number of events processed",
"raw_cells",
"=",
"self"... | 27.5 | 17.7 |
def get_output_str(item, detect_numerics, precision, sign_value):
"""Returns the final string which should be displayed"""
if detect_numerics:
item = _convert_to_numeric(item)
if isinstance(item, float):
item = round(item, precision)
try:
item = '{:{sign}}'.format(item, sign=sign... | [
"def",
"get_output_str",
"(",
"item",
",",
"detect_numerics",
",",
"precision",
",",
"sign_value",
")",
":",
"if",
"detect_numerics",
":",
"item",
"=",
"_convert_to_numeric",
"(",
"item",
")",
"if",
"isinstance",
"(",
"item",
",",
"float",
")",
":",
"item",
... | 35.818182 | 13.454545 |
def preview(df,preview_rows = 20):#,preview_max_cols = 0):
""" Returns a preview of a dataframe, which contains both header
rows and tail rows.
"""
if preview_rows < 4:
preview_rows = 4
preview_rows = min(preview_rows,df.shape[0])
outer = math.floor(preview_rows / 4)
return pd.concat... | [
"def",
"preview",
"(",
"df",
",",
"preview_rows",
"=",
"20",
")",
":",
"#,preview_max_cols = 0):",
"if",
"preview_rows",
"<",
"4",
":",
"preview_rows",
"=",
"4",
"preview_rows",
"=",
"min",
"(",
"preview_rows",
",",
"df",
".",
"shape",
"[",
"0",
"]",
")"... | 39.545455 | 9.818182 |
def reboot(self, timeout=1):
"""Reboot the device"""
namespace = System.getServiceType("reboot")
uri = self.getControlURL(namespace)
self.execute(uri, namespace, "Reboot", timeout=timeout) | [
"def",
"reboot",
"(",
"self",
",",
"timeout",
"=",
"1",
")",
":",
"namespace",
"=",
"System",
".",
"getServiceType",
"(",
"\"reboot\"",
")",
"uri",
"=",
"self",
".",
"getControlURL",
"(",
"namespace",
")",
"self",
".",
"execute",
"(",
"uri",
",",
"name... | 36 | 14.833333 |
def set_interactive(enabled=True, app=None):
"""Activate the IPython hook for VisPy. If the app is not specified, the
default is used.
"""
if enabled:
inputhook_manager.enable_gui('vispy', app)
else:
inputhook_manager.disable_gui() | [
"def",
"set_interactive",
"(",
"enabled",
"=",
"True",
",",
"app",
"=",
"None",
")",
":",
"if",
"enabled",
":",
"inputhook_manager",
".",
"enable_gui",
"(",
"'vispy'",
",",
"app",
")",
"else",
":",
"inputhook_manager",
".",
"disable_gui",
"(",
")"
] | 32.625 | 11.375 |
def mkdir_p(sftp, path):
"""Create remote path including parent directories if needed
https://stackoverflow.com/a/14819803
"""
try:
sftp.chdir(path)
except IOError:
dirname, basename = os.path.split(path.rstrip('/'))
mkdir_p(sftp, dirname)
sftp.mkdir(basename)
... | [
"def",
"mkdir_p",
"(",
"sftp",
",",
"path",
")",
":",
"try",
":",
"sftp",
".",
"chdir",
"(",
"path",
")",
"except",
"IOError",
":",
"dirname",
",",
"basename",
"=",
"os",
".",
"path",
".",
"split",
"(",
"path",
".",
"rstrip",
"(",
"'/'",
")",
")"... | 29.166667 | 13.25 |
def check_authenticator_response(password, nt_response, peer_challenge, authenticator_challenge, user_name, received_response):
"""CheckAuthenticatorResponse"""
my_resppnse = generate_authenticator_response(password, nt_response, peer_challenge, authenticator_challenge, user_name)
return my_resppnse == rec... | [
"def",
"check_authenticator_response",
"(",
"password",
",",
"nt_response",
",",
"peer_challenge",
",",
"authenticator_challenge",
",",
"user_name",
",",
"received_response",
")",
":",
"my_resppnse",
"=",
"generate_authenticator_response",
"(",
"password",
",",
"nt_respon... | 66 | 42.8 |
def get_group(self, group_descriptor):
"""GetGroup.
[Preview API] Get a group by its descriptor.
:param str group_descriptor: The descriptor of the desired graph group.
:rtype: :class:`<GraphGroup> <azure.devops.v5_0.graph.models.GraphGroup>`
"""
route_values = {}
... | [
"def",
"get_group",
"(",
"self",
",",
"group_descriptor",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"group_descriptor",
"is",
"not",
"None",
":",
"route_values",
"[",
"'groupDescriptor'",
"]",
"=",
"self",
".",
"_serialize",
".",
"url",
"(",
"'group_des... | 53.642857 | 19.571429 |
def fieldmap(self):
'''
Dictionary of field_id: field_name, as defined in self.fields property
'''
if hasattr(self, '_sql_fieldmap') and self._sql_fieldmap:
fieldmap = self._sql_fieldmap
else:
fieldmap = defaultdict(str)
fields = copy(self.fiel... | [
"def",
"fieldmap",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_sql_fieldmap'",
")",
"and",
"self",
".",
"_sql_fieldmap",
":",
"fieldmap",
"=",
"self",
".",
"_sql_fieldmap",
"else",
":",
"fieldmap",
"=",
"defaultdict",
"(",
"str",
")",
"f... | 37.2 | 14 |
def _authentication(request_fun):
"""Decorator to handle autologin and authentication errors.
*request_fun* is a function taking no arguments that needs to
be run with this ``Context`` logged into Splunk.
``_authentication``'s behavior depends on whether the
``autologin`` field of ``Context`` is s... | [
"def",
"_authentication",
"(",
"request_fun",
")",
":",
"@",
"wraps",
"(",
"request_fun",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"token",
"is",
"_NoAuthenticationToken",
":",
"# Not yet... | 41.884058 | 18.782609 |
def formula_1980(household, period, parameters):
'''
To compute this allowance, the 'rent' value must be provided for the same month, but 'housing_occupancy_status' is not necessary.
'''
return household('rent', period) * parameters(period).benefits.housing_allowance | [
"def",
"formula_1980",
"(",
"household",
",",
"period",
",",
"parameters",
")",
":",
"return",
"household",
"(",
"'rent'",
",",
"period",
")",
"*",
"parameters",
"(",
"period",
")",
".",
"benefits",
".",
"housing_allowance"
] | 59 | 42.2 |
def parse_arguments(args, clone_list):
"""
Makes parsing arguments a function.
"""
returned_string=""
host_number = args.host
if args.show_list:
print(generate_host_string(clone_list, "Available hosts: "))
exit()
if args.decrypt:
for i in args.files:
print... | [
"def",
"parse_arguments",
"(",
"args",
",",
"clone_list",
")",
":",
"returned_string",
"=",
"\"\"",
"host_number",
"=",
"args",
".",
"host",
"if",
"args",
".",
"show_list",
":",
"print",
"(",
"generate_host_string",
"(",
"clone_list",
",",
"\"Available hosts: \"... | 45.138462 | 18.861538 |
def to_array(self):
"""
Serializes this InlineQuery to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(InlineQuery, self).to_array()
array['id'] = u(self.id) # py2: type unicode, py3: type str
array['from']... | [
"def",
"to_array",
"(",
"self",
")",
":",
"array",
"=",
"super",
"(",
"InlineQuery",
",",
"self",
")",
".",
"to_array",
"(",
")",
"array",
"[",
"'id'",
"]",
"=",
"u",
"(",
"self",
".",
"id",
")",
"# py2: type unicode, py3: type str",
"array",
"[",
"'fr... | 42.133333 | 19.866667 |
def _authenticate_x509(credentials, sock_info):
"""Authenticate using MONGODB-X509.
"""
query = SON([('authenticate', 1),
('mechanism', 'MONGODB-X509')])
if credentials.username is not None:
query['user'] = credentials.username
elif sock_info.max_wire_version < 5:
ra... | [
"def",
"_authenticate_x509",
"(",
"credentials",
",",
"sock_info",
")",
":",
"query",
"=",
"SON",
"(",
"[",
"(",
"'authenticate'",
",",
"1",
")",
",",
"(",
"'mechanism'",
",",
"'MONGODB-X509'",
")",
"]",
")",
"if",
"credentials",
".",
"username",
"is",
"... | 42.5 | 7 |
def watchdog(sleep_interval):
"""Watch project files, restart worker process if a change happened.
:param sleep_interval: interval in second.
:return: Nothing
"""
mtimes = {}
worker_process = restart_with_reloader()
signal.signal(
signal.SIGTERM, lambda *args: kill_program_completly... | [
"def",
"watchdog",
"(",
"sleep_interval",
")",
":",
"mtimes",
"=",
"{",
"}",
"worker_process",
"=",
"restart_with_reloader",
"(",
")",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGTERM",
",",
"lambda",
"*",
"args",
":",
"kill_program_completly",
"(",
"wo... | 31.060606 | 17.030303 |
def erase_down (self): # <ESC>[0J -or- <ESC>[J
'''Erases the screen from the current line down to the bottom of the
screen.'''
self.erase_end_of_line ()
self.fill_region (self.cur_r + 1, 1, self.rows, self.cols) | [
"def",
"erase_down",
"(",
"self",
")",
":",
"# <ESC>[0J -or- <ESC>[J",
"self",
".",
"erase_end_of_line",
"(",
")",
"self",
".",
"fill_region",
"(",
"self",
".",
"cur_r",
"+",
"1",
",",
"1",
",",
"self",
".",
"rows",
",",
"self",
".",
"cols",
")"
] | 39.833333 | 22.833333 |
def valid_domains(self):
"""
:return:
A list of unicode strings of valid domain names for the certificate.
Wildcard certificates will have a domain in the form: *.example.com
"""
if self._valid_domains is None:
self._valid_domains = []
# ... | [
"def",
"valid_domains",
"(",
"self",
")",
":",
"if",
"self",
".",
"_valid_domains",
"is",
"None",
":",
"self",
".",
"_valid_domains",
"=",
"[",
"]",
"# For the subject alt name extension, we can look at the name of",
"# the choice selected since it distinguishes between domai... | 49.878788 | 25.878788 |
def update_custom_service_account(self, account, nickname, password):
"""
修改客服帐号。
:param account: 客服账号的用户名
:param nickname: 客服账号的昵称
:param password: 客服账号的密码
:return: 返回的 JSON 数据包
"""
return self.post(
url="https://api.weixin.qq.com/customservi... | [
"def",
"update_custom_service_account",
"(",
"self",
",",
"account",
",",
"nickname",
",",
"password",
")",
":",
"return",
"self",
".",
"post",
"(",
"url",
"=",
"\"https://api.weixin.qq.com/customservice/kfaccount/update\"",
",",
"data",
"=",
"{",
"\"kf_account\"",
... | 28.352941 | 15.764706 |
def shell_comment(c):
'Do not shell-escape raw strings in comments, but do handle line breaks.'
return ShellQuoted('# {c}').format(c=ShellQuoted(
(raw_shell(c) if isinstance(c, ShellQuoted) else c)
.replace('\n', '\n# ')
)) | [
"def",
"shell_comment",
"(",
"c",
")",
":",
"return",
"ShellQuoted",
"(",
"'# {c}'",
")",
".",
"format",
"(",
"c",
"=",
"ShellQuoted",
"(",
"(",
"raw_shell",
"(",
"c",
")",
"if",
"isinstance",
"(",
"c",
",",
"ShellQuoted",
")",
"else",
"c",
")",
".",... | 41.666667 | 21.333333 |
def _training_stats(self):
"""
Return a dictionary of statistics collected during creation of the
model. These statistics are also available with the ``get`` method and
are described in more detail in that method's documentation.
Returns
-------
out : dict
... | [
"def",
"_training_stats",
"(",
"self",
")",
":",
"fields",
"=",
"self",
".",
"_list_fields",
"(",
")",
"stat_fields",
"=",
"[",
"'training_time'",
",",
"'training_iterations'",
"]",
"if",
"'validation_perplexity'",
"in",
"fields",
":",
"stat_fields",
".",
"appen... | 30.606061 | 20.909091 |
def getRequestedNameIface(self, iface_num=0, num=None, default_hostname=None, default_domain=None):
"""Return the dns name associated to the net interface."""
full_name = self.getValue("net_interface.%d.dns_name" % iface_num)
if full_name:
replaced_full_name = system.replaceTemplat... | [
"def",
"getRequestedNameIface",
"(",
"self",
",",
"iface_num",
"=",
"0",
",",
"num",
"=",
"None",
",",
"default_hostname",
"=",
"None",
",",
"default_domain",
"=",
"None",
")",
":",
"full_name",
"=",
"self",
".",
"getValue",
"(",
"\"net_interface.%d.dns_name\"... | 41.588235 | 22.176471 |
def run_command(self, data):
"""
check the given command and send to the correct dispatcher
"""
command = data.get("command")
if self.debug:
self.py3_wrapper.log("Running remote command %s" % command)
if command == "refresh":
self.refresh(data)
... | [
"def",
"run_command",
"(",
"self",
",",
"data",
")",
":",
"command",
"=",
"data",
".",
"get",
"(",
"\"command\"",
")",
"if",
"self",
".",
"debug",
":",
"self",
".",
"py3_wrapper",
".",
"log",
"(",
"\"Running remote command %s\"",
"%",
"command",
")",
"if... | 34.769231 | 10.461538 |
def select_current_cell_in_visible_portion(self):
"""Select cell under cursor in the visible portion of the file
cell = group of lines separated by CELL_SEPARATORS
returns
-the textCursor
-a boolean indicating if the entire file is selected
-a boolean indicating ... | [
"def",
"select_current_cell_in_visible_portion",
"(",
"self",
")",
":",
"cursor",
"=",
"self",
".",
"textCursor",
"(",
")",
"cursor",
".",
"movePosition",
"(",
"QTextCursor",
".",
"StartOfBlock",
")",
"cur_pos",
"=",
"prev_pos",
"=",
"cursor",
".",
"position",
... | 46.016129 | 13.225806 |
async def connect(self):
""" Connect to target. """
self.tls_context = None
if self.tls:
self.tls_context = self.create_tls_context()
(self.reader, self.writer) = await asyncio.open_connection(
host=self.hostname,
port=self.port,
local_ad... | [
"async",
"def",
"connect",
"(",
"self",
")",
":",
"self",
".",
"tls_context",
"=",
"None",
"if",
"self",
".",
"tls",
":",
"self",
".",
"tls_context",
"=",
"self",
".",
"create_tls_context",
"(",
")",
"(",
"self",
".",
"reader",
",",
"self",
".",
"wri... | 29 | 17.142857 |
def compute_dkl(f, x, samples, prior_samples, **kwargs):
r"""
Compute the Kullback-Leibler divergence at each value of `x` for the prior
and posterior defined by `prior_samples` and `samples`.
Parameters
----------
f: function
function :math:`f(x;\theta)` (or list of functions for each ... | [
"def",
"compute_dkl",
"(",
"f",
",",
"x",
",",
"samples",
",",
"prior_samples",
",",
"*",
"*",
"kwargs",
")",
":",
"logZ",
"=",
"kwargs",
".",
"pop",
"(",
"'logZ'",
",",
"None",
")",
"weights",
"=",
"kwargs",
".",
"pop",
"(",
"'weights'",
",",
"Non... | 34 | 21.927083 |
def post_url(self, url, form):
"""
Internally used to retrieve the contents of a URL using
the POST request method.
The `form` parameter is a mechanize.HTMLForm object
This method will use a POST request type regardless of the method
used in the `form`.
"""
... | [
"def",
"post_url",
"(",
"self",
",",
"url",
",",
"form",
")",
":",
"_r",
"=",
"self",
".",
"br",
".",
"open",
"(",
"url",
",",
"form",
".",
"click_request_data",
"(",
")",
"[",
"1",
"]",
")",
"# check that we've not been redirected to the login page or an er... | 40 | 16.588235 |
def forward(self, observations):
""" Calculate model outputs """
input_data = self.input_block(observations)
base_output = self.backbone(input_data)
action_output = self.action_head(base_output)
value_output = self.value_head(base_output)
return action_output, value_ou... | [
"def",
"forward",
"(",
"self",
",",
"observations",
")",
":",
"input_data",
"=",
"self",
".",
"input_block",
"(",
"observations",
")",
"base_output",
"=",
"self",
".",
"backbone",
"(",
"input_data",
")",
"action_output",
"=",
"self",
".",
"action_head",
"(",... | 31.5 | 17.2 |
def createWidgets(self):
"""Build GUI."""
# Create Setup button
self.setup = Button(self.master, width=20, padx=3, pady=3)
self.setup["text"] = "Setup"
self.setup["command"] = self.setupMovie
self.setup.grid(row=1, column=0, padx=2, pady=2)
# Create Play button
self.start = Button(self.... | [
"def",
"createWidgets",
"(",
"self",
")",
":",
"# Create Setup button",
"self",
".",
"setup",
"=",
"Button",
"(",
"self",
".",
"master",
",",
"width",
"=",
"20",
",",
"padx",
"=",
"3",
",",
"pady",
"=",
"3",
")",
"self",
".",
"setup",
"[",
"\"text\""... | 37.413793 | 16.103448 |
def on_up(self, host):
"""
Intended for internal use only.
"""
if self.is_shutdown:
return
log.debug("Waiting to acquire lock for handling up status of node %s", host)
with host.lock:
if host._currently_handling_node_up:
log.debug(... | [
"def",
"on_up",
"(",
"self",
",",
"host",
")",
":",
"if",
"self",
".",
"is_shutdown",
":",
"return",
"log",
".",
"debug",
"(",
"\"Waiting to acquire lock for handling up status of node %s\"",
",",
"host",
")",
"with",
"host",
".",
"lock",
":",
"if",
"host",
... | 37.366197 | 23 |
def set_foreign_key(self, parent_table, parent_column, child_table, child_column):
"""Create a Foreign Key constraint on a column from a table."""
self.execute('ALTER TABLE {0} ADD FOREIGN KEY ({1}) REFERENCES {2}({3})'.format(parent_table, parent_column,
... | [
"def",
"set_foreign_key",
"(",
"self",
",",
"parent_table",
",",
"parent_column",
",",
"child_table",
",",
"child_column",
")",
":",
"self",
".",
"execute",
"(",
"'ALTER TABLE {0} ADD FOREIGN KEY ({1}) REFERENCES {2}({3})'",
".",
"format",
"(",
"parent_table",
",",
"p... | 96 | 48.25 |
def decode_link(self, link):
"""
Decodes an RpbLink message into a tuple
:param link: an RpbLink message
:type link: riak.pb.riak_pb2.RpbLink
:rtype tuple
"""
if link.HasField("bucket"):
bucket = bytes_to_str(link.bucket)
else:
bu... | [
"def",
"decode_link",
"(",
"self",
",",
"link",
")",
":",
"if",
"link",
".",
"HasField",
"(",
"\"bucket\"",
")",
":",
"bucket",
"=",
"bytes_to_str",
"(",
"link",
".",
"bucket",
")",
"else",
":",
"bucket",
"=",
"None",
"if",
"link",
".",
"HasField",
"... | 24.608696 | 14.347826 |
def update_hparams_for_universal_transformer(hparams):
"""Adds default hparams for all of the variants of the Universal Transformer.
Args:
hparams: default hparams (usually one of the standard hparams from
transformer model (like "transformer_base")
Returns:
hparams with default values for Univers... | [
"def",
"update_hparams_for_universal_transformer",
"(",
"hparams",
")",
":",
"hparams",
".",
"daisy_chain_variables",
"=",
"False",
"# Breaks multi-gpu in while loops.",
"# If not None, mixes vanilla transformer with Universal Transformer.",
"# Options: None, \"before_ut\", and \"after_ut\... | 40.552941 | 21.470588 |
def find_donor_catchments(self, include_subject_catchment='auto'):
"""
Find list of suitable donor cachments, ranked by hydrological similarity distance measure. This method is
implicitly called when calling the :meth:`.growth_curve` method unless the attribute :attr:`.donor_catchments`
... | [
"def",
"find_donor_catchments",
"(",
"self",
",",
"include_subject_catchment",
"=",
"'auto'",
")",
":",
"# Only if we have access to db with gauged catchment data",
"if",
"self",
".",
"gauged_cachments",
":",
"self",
".",
"donor_catchments",
"=",
"self",
".",
"gauged_cach... | 58.5 | 35.25 |
def make_utool_json_encoder(allow_pickle=False):
"""
References:
http://stackoverflow.com/questions/8230315/python-sets-are
http://stackoverflow.com/questions/11561932/why-does-json
https://github.com/jsonpickle/jsonpickle
http://stackoverflow.com/questions/24369666/typeerror-b1
... | [
"def",
"make_utool_json_encoder",
"(",
"allow_pickle",
"=",
"False",
")",
":",
"import",
"utool",
"as",
"ut",
"PYOBJECT_TAG",
"=",
"'__PYTHON_OBJECT__'",
"UUID_TAG",
"=",
"'__UUID__'",
"SLICE_TAG",
"=",
"'__SLICE__'",
"def",
"decode_pickle",
"(",
"text",
")",
":",... | 33.809524 | 17.257143 |
def language_file_exists(language_code):
"""
Check if TinyMCE has a language file for the specified lang code
:param language_code: language code
:type language_code: str
:return: check result
:rtype: bool
"""
filename = '{0}.js'.format(language_code)
path = os.path.join('tinymce', ... | [
"def",
"language_file_exists",
"(",
"language_code",
")",
":",
"filename",
"=",
"'{0}.js'",
".",
"format",
"(",
"language_code",
")",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'tinymce'",
",",
"'js'",
",",
"'tinymce'",
",",
"'langs'",
",",
"filena... | 32.166667 | 13 |
def _get_base_state(self):
'''
Get the base state of the object, as defined by the app.layout code, as a python dict
'''
base_app_inst = self.stateless_app.as_dash_app().as_dash_instance() # pylint: disable=no-member
# Get base layout response, from a base object
base_re... | [
"def",
"_get_base_state",
"(",
"self",
")",
":",
"base_app_inst",
"=",
"self",
".",
"stateless_app",
".",
"as_dash_app",
"(",
")",
".",
"as_dash_instance",
"(",
")",
"# pylint: disable=no-member",
"# Get base layout response, from a base object",
"base_resp",
"=",
"base... | 40.266667 | 32 |
def finish(self):
"""Wait for GL commands to to finish
This creates a GLIR command for glFinish and then processes the
GLIR commands. If the GLIR interpreter is remote (e.g. WebGL), this
function will return before GL has finished processing the commands.
"""
if ... | [
"def",
"finish",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'flush_commands'",
")",
":",
"context",
"=",
"self",
"else",
":",
"context",
"=",
"get_current_canvas",
"(",
")",
".",
"context",
"context",
".",
"glir",
".",
"command",
"(",
"... | 39.538462 | 17.461538 |
def add_external_reference(self,term_id, external_ref):
"""
Adds an external reference for the given term
@type term_id: string
@param term_id: the term identifier
@type external_ref: L{CexternalReference}
@param external_ref: the external reference object
"""
... | [
"def",
"add_external_reference",
"(",
"self",
",",
"term_id",
",",
"external_ref",
")",
":",
"if",
"term_id",
"in",
"self",
".",
"idx",
":",
"term_obj",
"=",
"Cterm",
"(",
"self",
".",
"idx",
"[",
"term_id",
"]",
",",
"self",
".",
"type",
")",
"term_ob... | 40.923077 | 12.615385 |
def set_col_name(self, index, name):
"""
Sets the column name.
:param index: the 0-based row index
:type index: int
:param name: the name of the column
:type name: str
"""
javabridge.call(self.jobject, "setColName", "(ILjava/lang/String;)V", index, name) | [
"def",
"set_col_name",
"(",
"self",
",",
"index",
",",
"name",
")",
":",
"javabridge",
".",
"call",
"(",
"self",
".",
"jobject",
",",
"\"setColName\"",
",",
"\"(ILjava/lang/String;)V\"",
",",
"index",
",",
"name",
")"
] | 31 | 14.4 |
def _copy_scratch_to_state(args: Dict[str, Any]):
"""Copes scratch shards to state shards."""
np.copyto(_state_shard(args), _scratch_shard(args)) | [
"def",
"_copy_scratch_to_state",
"(",
"args",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
":",
"np",
".",
"copyto",
"(",
"_state_shard",
"(",
"args",
")",
",",
"_scratch_shard",
"(",
"args",
")",
")"
] | 50.333333 | 8 |
def p_nonfluent_def(self, p):
'''nonfluent_def : IDENT LPAREN param_list RPAREN COLON LCURLY NON_FLUENT COMMA type_spec COMMA DEFAULT ASSIGN_EQUAL range_const RCURLY SEMI
| IDENT COLON LCURLY NON_FLUENT COMMA type_spec COMMA DEFAULT ASSIGN_EQUAL range_const RCURLY SEMI'''
if len... | [
"def",
"p_nonfluent_def",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"16",
":",
"p",
"[",
"0",
"]",
"=",
"PVariable",
"(",
"name",
"=",
"p",
"[",
"1",
"]",
",",
"fluent_type",
"=",
"'non-fluent'",
",",
"range_type",
"=",
... | 78.857143 | 54.285714 |
def mean(self):
"""Returns the mean value."""
if self.counter.value > 0:
return self.sum.value / self.counter.value
return 0.0 | [
"def",
"mean",
"(",
"self",
")",
":",
"if",
"self",
".",
"counter",
".",
"value",
">",
"0",
":",
"return",
"self",
".",
"sum",
".",
"value",
"/",
"self",
".",
"counter",
".",
"value",
"return",
"0.0"
] | 31.6 | 13.4 |
def _get_slave_timeout(self, dpid, port):
"""get the timeout time at some port of some datapath."""
slave = self._get_slave(dpid, port)
if slave:
return slave['timeout']
else:
return 0 | [
"def",
"_get_slave_timeout",
"(",
"self",
",",
"dpid",
",",
"port",
")",
":",
"slave",
"=",
"self",
".",
"_get_slave",
"(",
"dpid",
",",
"port",
")",
"if",
"slave",
":",
"return",
"slave",
"[",
"'timeout'",
"]",
"else",
":",
"return",
"0"
] | 33.428571 | 11.285714 |
def in_cwd():
"""
Return list of configs in current working directory.
If filename is ``.tmuxp.py``, ``.tmuxp.json``, ``.tmuxp.yaml``.
Returns
-------
list
configs in current working directory
"""
configs = []
for filename in os.listdir(os.getcwd()):
if filename.st... | [
"def",
"in_cwd",
"(",
")",
":",
"configs",
"=",
"[",
"]",
"for",
"filename",
"in",
"os",
".",
"listdir",
"(",
"os",
".",
"getcwd",
"(",
")",
")",
":",
"if",
"filename",
".",
"startswith",
"(",
"'.tmuxp'",
")",
"and",
"is_config_file",
"(",
"filename"... | 22.666667 | 22.666667 |
def parallel_update_objectinfo_cpdir(cpdir,
cpglob='checkplot-*.pkl*',
liststartindex=None,
maxobjects=None,
nworkers=NCPUS,
fast_mode=... | [
"def",
"parallel_update_objectinfo_cpdir",
"(",
"cpdir",
",",
"cpglob",
"=",
"'checkplot-*.pkl*'",
",",
"liststartindex",
"=",
"None",
",",
"maxobjects",
"=",
"None",
",",
"nworkers",
"=",
"NCPUS",
",",
"fast_mode",
"=",
"False",
",",
"findercmap",
"=",
"'gray_r... | 42.068571 | 25.394286 |
def remove_from_user(self, name, *args):
"""Remove attributes from a user.
"""
user = self.get_user(name=name)
attrs_ = user['user']
for a in args:
del attrs_[a] | [
"def",
"remove_from_user",
"(",
"self",
",",
"name",
",",
"*",
"args",
")",
":",
"user",
"=",
"self",
".",
"get_user",
"(",
"name",
"=",
"name",
")",
"attrs_",
"=",
"user",
"[",
"'user'",
"]",
"for",
"a",
"in",
"args",
":",
"del",
"attrs_",
"[",
... | 29.571429 | 6.428571 |
def is_default(name=None, index=None):
"""
returns True if the specified configuration is the default one
"""
if not is_configured():
raise JutException('No configurations available, please run `jut config add`')
count = 1
for configuration in _CONFIG.sections():
if index != ... | [
"def",
"is_default",
"(",
"name",
"=",
"None",
",",
"index",
"=",
"None",
")",
":",
"if",
"not",
"is_configured",
"(",
")",
":",
"raise",
"JutException",
"(",
"'No configurations available, please run `jut config add`'",
")",
"count",
"=",
"1",
"for",
"configura... | 25.652174 | 25.478261 |
def method_or_name(namespace, x):
'''
If x is a ``str``, get ``namespace.x``.
Otherwise, simply return ``x``.
'''
if not isinstance(x, str):
return x
if hasattr(namespace, x):
return getattr(namespace, x)
attrs = [y for y in dir(namespace) if not y.startswith('_')]
msg... | [
"def",
"method_or_name",
"(",
"namespace",
",",
"x",
")",
":",
"if",
"not",
"isinstance",
"(",
"x",
",",
"str",
")",
":",
"return",
"x",
"if",
"hasattr",
"(",
"namespace",
",",
"x",
")",
":",
"return",
"getattr",
"(",
"namespace",
",",
"x",
")",
"a... | 27.5625 | 19.8125 |
def get_process_info(self, pid=None):
'''
get_process_info(self, pid=None)
Get process general information.
:Parameters:
* *pid* (`string`) -- Identifier of an existing process
'''
pid = self._get_pid(pid)
return self._call_rest_api('get', '/processes/... | [
"def",
"get_process_info",
"(",
"self",
",",
"pid",
"=",
"None",
")",
":",
"pid",
"=",
"self",
".",
"_get_pid",
"(",
"pid",
")",
"return",
"self",
".",
"_call_rest_api",
"(",
"'get'",
",",
"'/processes/'",
"+",
"pid",
",",
"error",
"=",
"'Failed to fetch... | 27.615385 | 25.923077 |
def resource(self, api_path=None, base_path='/api/now', chunk_size=None, **kwargs):
"""Creates a new :class:`Resource` object after validating paths
:param api_path: Path to the API to operate on
:param base_path: (optional) Base path override
:param chunk_size: Response stream parser c... | [
"def",
"resource",
"(",
"self",
",",
"api_path",
"=",
"None",
",",
"base_path",
"=",
"'/api/now'",
",",
"chunk_size",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"path",
"in",
"[",
"api_path",
",",
"base_path",
"]",
":",
"URLBuilder",
".",
... | 41.26087 | 16.521739 |
def add_ip_address_list(list_name):
'''
Retrieves a list of all IP address lists.
list_name(str): The name of the specific IP address list to add.
CLI Example:
.. code-block:: bash
salt '*' bluecoat_sslv.add_ip_address_list MyIPAddressList
'''
payload = {"jsonrpc": "2.0",
... | [
"def",
"add_ip_address_list",
"(",
"list_name",
")",
":",
"payload",
"=",
"{",
"\"jsonrpc\"",
":",
"\"2.0\"",
",",
"\"id\"",
":",
"\"ID0\"",
",",
"\"method\"",
":",
"\"add_policy_ip_addresses_list\"",
",",
"\"params\"",
":",
"[",
"{",
"\"list_name\"",
":",
"list... | 25.714286 | 24.952381 |
def _to_temperature(self, temperature):
""" Step to a given temperature.
:param temperature: Get to this temperature.
"""
self._to_value(self._temperature, temperature,
self.command_set.temperature_steps,
self._warmer, self._cooler) | [
"def",
"_to_temperature",
"(",
"self",
",",
"temperature",
")",
":",
"self",
".",
"_to_value",
"(",
"self",
".",
"_temperature",
",",
"temperature",
",",
"self",
".",
"command_set",
".",
"temperature_steps",
",",
"self",
".",
"_warmer",
",",
"self",
".",
"... | 38 | 11.875 |
def process(self, metric):
"""
Process metric by sending it to datadog api
"""
self.queue.append(metric)
if len(self.queue) >= self.queue_size:
logging.debug("Queue is full, sending logs to Logentries")
self._send() | [
"def",
"process",
"(",
"self",
",",
"metric",
")",
":",
"self",
".",
"queue",
".",
"append",
"(",
"metric",
")",
"if",
"len",
"(",
"self",
".",
"queue",
")",
">=",
"self",
".",
"queue_size",
":",
"logging",
".",
"debug",
"(",
"\"Queue is full, sending ... | 30.222222 | 13.777778 |
def can_editions(self):
"""
bool: :const:`True` if :attr:`address` can register the number of
editions of :attr:`piece_address` else :const:`False`.
In order to register the number of editions:
1. There needs to a least one transaction for the :attr:`piece_address`
(the... | [
"def",
"can_editions",
"(",
"self",
")",
":",
"chain",
"=",
"BlockchainSpider",
".",
"chain",
"(",
"self",
".",
"_tree",
",",
"REGISTERED_PIECE_CODE",
")",
"if",
"len",
"(",
"chain",
")",
"==",
"0",
":",
"self",
".",
"reason",
"=",
"'Master edition not yet... | 34.62069 | 24.965517 |
def run(self, args):
"""
Remove permissions from the user with user_full_name or email on the remote project with project_name.
:param args Namespace arguments parsed from the command line
"""
email = args.email # email of person to remove permissions from (None if... | [
"def",
"run",
"(",
"self",
",",
"args",
")",
":",
"email",
"=",
"args",
".",
"email",
"# email of person to remove permissions from (None if username specified)",
"username",
"=",
"args",
".",
"username",
"# username of person to remove permissions from (None if email is specif... | 73.090909 | 42 |
def update_text(self, token, match):
"""Update text from results of regex match"""
if isinstance(self.text, MatchGroup):
self.text = self.text.get_group_value(token, match) | [
"def",
"update_text",
"(",
"self",
",",
"token",
",",
"match",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"text",
",",
"MatchGroup",
")",
":",
"self",
".",
"text",
"=",
"self",
".",
"text",
".",
"get_group_value",
"(",
"token",
",",
"match",
")"... | 49.25 | 8 |
def encrypt(key_id, plaintext, encryption_context=None, grant_tokens=None,
region=None, key=None, keyid=None, profile=None):
'''
Encrypt plaintext into cipher text using specified key.
CLI example::
salt myminion boto_kms.encrypt 'alias/mykey' 'myplaindata' '{"aws:username":"myuser"}'
... | [
"def",
"encrypt",
"(",
"key_id",
",",
"plaintext",
",",
"encryption_context",
"=",
"None",
",",
"grant_tokens",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
... | 32.434783 | 25.304348 |
def get_3d_markers_residual(
self, component_info=None, data=None, component_position=None
):
"""Get 3D markers with residual."""
return self._get_3d_markers(
RT3DMarkerPositionResidual, component_info, data, component_position
) | [
"def",
"get_3d_markers_residual",
"(",
"self",
",",
"component_info",
"=",
"None",
",",
"data",
"=",
"None",
",",
"component_position",
"=",
"None",
")",
":",
"return",
"self",
".",
"_get_3d_markers",
"(",
"RT3DMarkerPositionResidual",
",",
"component_info",
",",
... | 38.714286 | 21.428571 |
def copy(self):
"""Return a deep copy"""
result = Scalar(self.size, self.deriv)
result.v = self.v
if self.deriv > 0: result.d[:] = self.d[:]
if self.deriv > 1: result.dd[:] = self.dd[:]
return result | [
"def",
"copy",
"(",
"self",
")",
":",
"result",
"=",
"Scalar",
"(",
"self",
".",
"size",
",",
"self",
".",
"deriv",
")",
"result",
".",
"v",
"=",
"self",
".",
"v",
"if",
"self",
".",
"deriv",
">",
"0",
":",
"result",
".",
"d",
"[",
":",
"]",
... | 34.428571 | 12.428571 |
def on_error(self, headers, body):
"""
Increment the error count. See :py:meth:`ConnectionListener.on_error`
:param dict headers: headers in the message
:param body: the message content
"""
if log.isEnabledFor(logging.DEBUG):
log.debug("received an error %s [... | [
"def",
"on_error",
"(",
"self",
",",
"headers",
",",
"body",
")",
":",
"if",
"log",
".",
"isEnabledFor",
"(",
"logging",
".",
"DEBUG",
")",
":",
"log",
".",
"debug",
"(",
"\"received an error %s [%s]\"",
",",
"body",
",",
"headers",
")",
"else",
":",
"... | 34.916667 | 14.583333 |
def get(self, timeout: Union[float, datetime.timedelta] = None) -> Awaitable[_T]:
"""Remove and return an item from the queue.
Returns an awaitable which resolves once an item is available, or raises
`tornado.util.TimeoutError` after a timeout.
``timeout`` may be a number denoting a ti... | [
"def",
"get",
"(",
"self",
",",
"timeout",
":",
"Union",
"[",
"float",
",",
"datetime",
".",
"timedelta",
"]",
"=",
"None",
")",
"->",
"Awaitable",
"[",
"_T",
"]",
":",
"future",
"=",
"Future",
"(",
")",
"# type: Future[_T]",
"try",
":",
"future",
".... | 40.107143 | 22.357143 |
def _calc_overlap_count(
markers1: dict,
markers2: dict,
):
"""Calculate overlap count between the values of two dictionaries
Note: dict values must be sets
"""
overlaps=np.zeros((len(markers1), len(markers2)))
j=0
for marker_group in markers1:
tmp = [len(markers2[i].intersecti... | [
"def",
"_calc_overlap_count",
"(",
"markers1",
":",
"dict",
",",
"markers2",
":",
"dict",
",",
")",
":",
"overlaps",
"=",
"np",
".",
"zeros",
"(",
"(",
"len",
"(",
"markers1",
")",
",",
"len",
"(",
"markers2",
")",
")",
")",
"j",
"=",
"0",
"for",
... | 24.764706 | 22.882353 |
def resnet_imagenet_34_td_unit_05_05():
"""Set of hyperparameters."""
hp = resnet_imagenet_34()
hp.use_td = "unit"
hp.targeting_rate = 0.5
hp.keep_prob = 0.5
return hp | [
"def",
"resnet_imagenet_34_td_unit_05_05",
"(",
")",
":",
"hp",
"=",
"resnet_imagenet_34",
"(",
")",
"hp",
".",
"use_td",
"=",
"\"unit\"",
"hp",
".",
"targeting_rate",
"=",
"0.5",
"hp",
".",
"keep_prob",
"=",
"0.5",
"return",
"hp"
] | 21.625 | 17.25 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.