text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def _get_machines_cache_from_srv(self, srv):
"""Fetch list of etcd-cluster member by resolving _etcd-server._tcp. SRV record.
This record should contain list of host and peer ports which could be used to run
'GET http://{host}:{port}/members' request (peer protocol)"""
ret = []
... | [
"def",
"_get_machines_cache_from_srv",
"(",
"self",
",",
"srv",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"r",
"in",
"[",
"'-client-ssl'",
",",
"'-client'",
",",
"'-ssl'",
",",
"''",
",",
"'-server-ssl'",
",",
"'-server'",
"]",
":",
"protocol",
"=",
"'https... | 47.321429 | 19 |
def updated_current_fields(
self,
update_fields):
"""updated_current_fields
:param update_fields: dict with values for
updating fields_to_add
"""
self.fields_to_add = {}
for k in self.org_fields:
self.fields_to_ad... | [
"def",
"updated_current_fields",
"(",
"self",
",",
"update_fields",
")",
":",
"self",
".",
"fields_to_add",
"=",
"{",
"}",
"for",
"k",
"in",
"self",
".",
"org_fields",
":",
"self",
".",
"fields_to_add",
"[",
"k",
"]",
"=",
"self",
".",
"org_fields",
"[",... | 31.916667 | 12.416667 |
def process_env_chg(self):
""" Reads and processes ENVCHANGE stream.
Stream info url: http://msdn.microsoft.com/en-us/library/dd303449.aspx
"""
self.log_response_message("got ENVCHANGE message")
r = self._reader
size = r.get_smallint()
type_id = r.get_byte()
... | [
"def",
"process_env_chg",
"(",
"self",
")",
":",
"self",
".",
"log_response_message",
"(",
"\"got ENVCHANGE message\"",
")",
"r",
"=",
"self",
".",
"_reader",
"size",
"=",
"r",
".",
"get_smallint",
"(",
")",
"type_id",
"=",
"r",
".",
"get_byte",
"(",
")",
... | 45.5 | 13.817073 |
def constructTotalCounts(self, logger):
'''
This function constructs the total count for each valid character in the array or loads them if they already exist.
These will always be stored in '<DIR>/totalCounts.p', a pickled file
'''
self.totalSize = self.bwt.shape[0]
... | [
"def",
"constructTotalCounts",
"(",
"self",
",",
"logger",
")",
":",
"self",
".",
"totalSize",
"=",
"self",
".",
"bwt",
".",
"shape",
"[",
"0",
"]",
"abtFN",
"=",
"self",
".",
"dirName",
"+",
"'/totalCounts.p'",
"if",
"os",
".",
"path",
".",
"exists",
... | 42 | 22.857143 |
def initialize(name='', pool_size=10, host='localhost', password='', port=5432, user=''):
"""Initialize a new database connection and return the pool object.
Saves a reference to that instance in a module-level variable, so applications with only one database
can just call this function and not worry about... | [
"def",
"initialize",
"(",
"name",
"=",
"''",
",",
"pool_size",
"=",
"10",
",",
"host",
"=",
"'localhost'",
",",
"password",
"=",
"''",
",",
"port",
"=",
"5432",
",",
"user",
"=",
"''",
")",
":",
"global",
"pool",
"instance",
"=",
"Pool",
"(",
"name... | 44.818182 | 31.727273 |
def normalizedFluctuationCorrelationFunctionMultiple(A_kn, B_kn=None, N_max=None, norm=True, truncate=False):
"""Compute the normalized fluctuation (cross) correlation function of (two) timeseries from multiple timeseries samples.
C(t) = (<A(t) B(t)> - <A><B>) / (<AB> - <A><B>)
This may be useful in diagno... | [
"def",
"normalizedFluctuationCorrelationFunctionMultiple",
"(",
"A_kn",
",",
"B_kn",
"=",
"None",
",",
"N_max",
"=",
"None",
",",
"norm",
"=",
"True",
",",
"truncate",
"=",
"False",
")",
":",
"# If B_kn is not specified, define it to be identical with A_kn.",
"if",
"B... | 36.840278 | 27.013889 |
def generateLatticeFile(self, beamline, filename=None, format='elegant'):
""" generate simulation files for lattice analysis,
e.g. ".lte" for elegant, ".madx" for madx
input parameters:
:param beamline: keyword for beamline
:param filename: name of lte/mad file,
... | [
"def",
"generateLatticeFile",
"(",
"self",
",",
"beamline",
",",
"filename",
"=",
"None",
",",
"format",
"=",
"'elegant'",
")",
":",
"\"\"\"\n if not self.isBeamline(beamline):\n print(\"%s is a valid defined beamline, do not process.\" % (beamline))\n re... | 41.670886 | 20.43038 |
def get_asset_contents_by_genus_type_for_asset(self, asset_content_genus_type, asset_id):
"""Gets an ``AssetContentList`` from the given GenusType and Asset Id.
In plenary mode, the returned list contains all known asset contents or
an error results. Otherwise, the returned list may contain onl... | [
"def",
"get_asset_contents_by_genus_type_for_asset",
"(",
"self",
",",
"asset_content_genus_type",
",",
"asset_id",
")",
":",
"return",
"AssetContentList",
"(",
"self",
".",
"_provider_session",
".",
"get_asset_contents_by_genus_type_for_asset",
"(",
"asset_content_genus_type",... | 53.761905 | 28.761905 |
def _drawContents(self, reason=None, initiator=None):
""" Draws the table contents from the sliced array of the collected repo tree item.
See AbstractInspector.updateContents for the reason and initiator description.
"""
logger.debug("TableInspector._drawContents: {}".format(self))
... | [
"def",
"_drawContents",
"(",
"self",
",",
"reason",
"=",
"None",
",",
"initiator",
"=",
"None",
")",
":",
"logger",
".",
"debug",
"(",
"\"TableInspector._drawContents: {}\"",
".",
"format",
"(",
"self",
")",
")",
"oldTableIndex",
"=",
"self",
".",
"tableView... | 55.25 | 29.41 |
def uniform_partition_fromgrid(grid, min_pt=None, max_pt=None):
"""Return a partition of an interval product based on a given grid.
This method is complementary to `uniform_partition_fromintv` in that
it infers the set to be partitioned from a given grid and optional
parameters for ``min_pt`` and ``max... | [
"def",
"uniform_partition_fromgrid",
"(",
"grid",
",",
"min_pt",
"=",
"None",
",",
"max_pt",
"=",
"None",
")",
":",
"# Make dictionaries from `min_pt` and `max_pt` and fill with `None` where",
"# no value is given (taking negative indices into account)",
"if",
"min_pt",
"is",
"... | 38.054054 | 21.369369 |
def maybe_start_recording(tokens, index):
"""Return a new _RSTCommentBlockRecorder when its time to record."""
if tokens[index].type == TokenType.BeginRSTComment:
return _RSTCommentBlockRecorder(index, tokens[index].line)
return None | [
"def",
"maybe_start_recording",
"(",
"tokens",
",",
"index",
")",
":",
"if",
"tokens",
"[",
"index",
"]",
".",
"type",
"==",
"TokenType",
".",
"BeginRSTComment",
":",
"return",
"_RSTCommentBlockRecorder",
"(",
"index",
",",
"tokens",
"[",
"index",
"]",
".",
... | 44.166667 | 18.5 |
def num_no_signups(self):
"""How many people have not signed up?"""
signup_users_count = User.objects.get_students().count()
return signup_users_count - self.num_signups() | [
"def",
"num_no_signups",
"(",
"self",
")",
":",
"signup_users_count",
"=",
"User",
".",
"objects",
".",
"get_students",
"(",
")",
".",
"count",
"(",
")",
"return",
"signup_users_count",
"-",
"self",
".",
"num_signups",
"(",
")"
] | 48 | 13.25 |
def _indent(self, element, level=0, prefix="\t"):
"""
In-place Element text auto-indent, for pretty printing.
Code from: http://effbot.org/zone/element-lib.htm#prettyprint
:param element: An Element object
:param level: Level of indentation
:param prefix: String to use ... | [
"def",
"_indent",
"(",
"self",
",",
"element",
",",
"level",
"=",
"0",
",",
"prefix",
"=",
"\"\\t\"",
")",
":",
"element_prefix",
"=",
"\"\\r\\n{0}\"",
".",
"format",
"(",
"level",
"*",
"prefix",
")",
"if",
"len",
"(",
"element",
")",
":",
"if",
"not... | 35.483871 | 19.096774 |
def find_table_links(self):
"""
When given a url, this function will find all the available table names
for that EPA dataset.
"""
html = urlopen(self.model_url).read()
doc = lh.fromstring(html)
href_list = [area.attrib['href'] for area in doc.cssselect('map area')... | [
"def",
"find_table_links",
"(",
"self",
")",
":",
"html",
"=",
"urlopen",
"(",
"self",
".",
"model_url",
")",
".",
"read",
"(",
")",
"doc",
"=",
"lh",
".",
"fromstring",
"(",
"html",
")",
"href_list",
"=",
"[",
"area",
".",
"attrib",
"[",
"'href'",
... | 39 | 14.8 |
def _add_intermol_molecule_type(intermol_system, parent):
"""Create a molecule type for the parent and add bonds. """
from intermol.moleculetype import MoleculeType
from intermol.forces.bond import Bond as InterMolBond
molecule_type = MoleculeType(name=parent.name)
intermol_syst... | [
"def",
"_add_intermol_molecule_type",
"(",
"intermol_system",
",",
"parent",
")",
":",
"from",
"intermol",
".",
"moleculetype",
"import",
"MoleculeType",
"from",
"intermol",
".",
"forces",
".",
"bond",
"import",
"Bond",
"as",
"InterMolBond",
"molecule_type",
"=",
... | 43.785714 | 19 |
def zap_disk(block_device):
'''
Clear a block device of partition table. Relies on sgdisk, which is
installed as pat of the 'gdisk' package in Ubuntu.
:param block_device: str: Full path of block device to clean.
'''
# https://github.com/ceph/ceph/commit/fdd7f8d83afa25c4e09aaedd90ab93f3b64a677b... | [
"def",
"zap_disk",
"(",
"block_device",
")",
":",
"# https://github.com/ceph/ceph/commit/fdd7f8d83afa25c4e09aaedd90ab93f3b64a677b",
"# sometimes sgdisk exits non-zero; this is OK, dd will clean up",
"call",
"(",
"[",
"'sgdisk'",
",",
"'--zap-all'",
",",
"'--'",
",",
"block_device",... | 48.5 | 22.166667 |
def convert_to_base_types(obj, ignore_keys=tuple(), tuple_type=tuple,
json_safe=True):
"""Recursively convert objects into base types.
This is used to convert some special types of objects used internally into
base types for more friendly output via mechanisms such as JSON. It is used
... | [
"def",
"convert_to_base_types",
"(",
"obj",
",",
"ignore_keys",
"=",
"tuple",
"(",
")",
",",
"tuple_type",
"=",
"tuple",
",",
"json_safe",
"=",
"True",
")",
":",
"# Because it's *really* annoying to pass a single string accidentally.",
"assert",
"not",
"isinstance",
"... | 43.367089 | 23.797468 |
def range_matches(self, other):
"""
Whether the begins equal and the ends equal. Compare __eq__().
:param other: Interval
:return: True or False
:rtype: bool
"""
return (
self.begin == other.begin and
self.end == other.end
) | [
"def",
"range_matches",
"(",
"self",
",",
"other",
")",
":",
"return",
"(",
"self",
".",
"begin",
"==",
"other",
".",
"begin",
"and",
"self",
".",
"end",
"==",
"other",
".",
"end",
")"
] | 27.545455 | 13 |
def confirm_installation(self, requirement, missing_dependencies, install_command):
"""
Ask the operator's permission to install missing system packages.
:param requirement: A :class:`.Requirement` object.
:param missing_dependencies: A list of strings with missing dependencies.
... | [
"def",
"confirm_installation",
"(",
"self",
",",
"requirement",
",",
"missing_dependencies",
",",
"install_command",
")",
":",
"try",
":",
"return",
"prompt_for_confirmation",
"(",
"format",
"(",
"\"Do you want me to install %s %s?\"",
",",
"\"this\"",
"if",
"len",
"(... | 50.25 | 23.45 |
def ecdsa_sign(private_key, data, hash_algorithm):
"""
Generates an ECDSA signature in pure Python (thus slow)
:param private_key:
The PrivateKey to generate the signature with
:param data:
A byte string of the data the signature is for
:param hash_algorithm:
A unicode str... | [
"def",
"ecdsa_sign",
"(",
"private_key",
",",
"data",
",",
"hash_algorithm",
")",
":",
"if",
"not",
"hasattr",
"(",
"private_key",
",",
"'asn1'",
")",
"or",
"not",
"isinstance",
"(",
"private_key",
".",
"asn1",
",",
"keys",
".",
"PrivateKeyInfo",
")",
":",... | 26.220472 | 23.84252 |
def _insert_glsl(vertex, fragment, to_insert):
"""Insert snippets in a shader.
to_insert is a dict `{(shader_type, location): snippet}`.
Snippets can contain `{{ var }}` placeholders for the transformed variable
name.
"""
# Find the place where to insert the GLSL snippet.
# This is "gl_Po... | [
"def",
"_insert_glsl",
"(",
"vertex",
",",
"fragment",
",",
"to_insert",
")",
":",
"# Find the place where to insert the GLSL snippet.",
"# This is \"gl_Position = transform(data_var_name);\" where",
"# data_var_name is typically an attribute.",
"vs_regex",
"=",
"re",
".",
"compile... | 36.693878 | 21.469388 |
def read_csv(filename, delimiter=",", skip=0, guess_type=True, has_header=True, use_types={}):
"""Read a CSV file
Usage
-----
>>> data = read_csv(filename, delimiter=delimiter, skip=skip,
guess_type=guess_type, has_header=True, use_types={})
# Use specific types
>>> types = {"... | [
"def",
"read_csv",
"(",
"filename",
",",
"delimiter",
"=",
"\",\"",
",",
"skip",
"=",
"0",
",",
"guess_type",
"=",
"True",
",",
"has_header",
"=",
"True",
",",
"use_types",
"=",
"{",
"}",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
... | 30.470588 | 23.205882 |
def flatatt(self, **attr):
'''Return a string with attributes to add to the tag'''
cs = ''
attr = self._attr
classes = self._classes
data = self._data
css = self._css
attr = attr.copy() if attr else {}
if classes:
cs = ' '.join(classes)
... | [
"def",
"flatatt",
"(",
"self",
",",
"*",
"*",
"attr",
")",
":",
"cs",
"=",
"''",
"attr",
"=",
"self",
".",
"_attr",
"classes",
"=",
"self",
".",
"_classes",
"data",
"=",
"self",
".",
"_data",
"css",
"=",
"self",
".",
"_css",
"attr",
"=",
"attr",
... | 31.809524 | 16 |
def _convert_time(self, time_str):
"""
Convert a string representation of the time (as returned by blockr.io api) into unix
timestamp
:param time_utc_str: string representation of the time
:return: unix timestamp
"""
dt = datetime.strptime(time_str, "%Y-%m-%dT%H:... | [
"def",
"_convert_time",
"(",
"self",
",",
"time_str",
")",
":",
"dt",
"=",
"datetime",
".",
"strptime",
"(",
"time_str",
",",
"\"%Y-%m-%dT%H:%M:%SZ\"",
")",
"return",
"int",
"(",
"time",
".",
"mktime",
"(",
"dt",
".",
"utctimetuple",
"(",
")",
")",
")"
] | 37 | 18.4 |
def assess(model, reaction, flux_coefficient_cutoff=0.001, solver=None):
"""Assesses production capacity.
Assesses the capacity of the model to produce the precursors for the
reaction and absorb the production of the reaction while the reaction is
operating at, or above, the specified cutoff.
Para... | [
"def",
"assess",
"(",
"model",
",",
"reaction",
",",
"flux_coefficient_cutoff",
"=",
"0.001",
",",
"solver",
"=",
"None",
")",
":",
"reaction",
"=",
"model",
".",
"reactions",
".",
"get_by_any",
"(",
"reaction",
")",
"[",
"0",
"]",
"with",
"model",
"as",... | 36.55814 | 23.651163 |
def getDatastream(self, pid, dsID, asOfDateTime=None, validateChecksum=False):
"""Get information about a single datastream on a Fedora object; optionally,
get information for the version of the datastream as of a particular date time.
:param pid: object pid
:param dsID: datastream id
... | [
"def",
"getDatastream",
"(",
"self",
",",
"pid",
",",
"dsID",
",",
"asOfDateTime",
"=",
"None",
",",
"validateChecksum",
"=",
"False",
")",
":",
"# /objects/{pid}/datastreams/{dsID} ? [asOfDateTime] [format] [validateChecksum]",
"http_args",
"=",
"{",
"}",
"if",
"vali... | 55.636364 | 24.227273 |
def stem(self, word):
"""Return Snowball Dutch stem.
Parameters
----------
word : str
The word to stem
Returns
-------
str
Word stem
Examples
--------
>>> stmr = SnowballDutch()
>>> stmr.stem('lezen')
... | [
"def",
"stem",
"(",
"self",
",",
"word",
")",
":",
"# lowercase, normalize, decompose, filter umlauts & acutes out, and",
"# compose",
"word",
"=",
"normalize",
"(",
"'NFC'",
",",
"text_type",
"(",
"word",
".",
"lower",
"(",
")",
")",
")",
"word",
"=",
"word",
... | 31.685714 | 15.807143 |
def Get(self):
"""Fetches user's data and returns it wrapped in a Grruser object."""
args = user_management_pb2.ApiGetGrrUserArgs(username=self.username)
data = self._context.SendRequest("GetGrrUser", args)
return GrrUser(data=data, context=self._context) | [
"def",
"Get",
"(",
"self",
")",
":",
"args",
"=",
"user_management_pb2",
".",
"ApiGetGrrUserArgs",
"(",
"username",
"=",
"self",
".",
"username",
")",
"data",
"=",
"self",
".",
"_context",
".",
"SendRequest",
"(",
"\"GetGrrUser\"",
",",
"args",
")",
"retur... | 44.5 | 21 |
def _handle_start_node(self, attrs):
"""
Handle opening node element
:param attrs: Attributes of the element
:type attrs: Dict
"""
self._curr = {
'attributes': dict(attrs),
'lat': None,
'lon': None,
'node_id': None,
... | [
"def",
"_handle_start_node",
"(",
"self",
",",
"attrs",
")",
":",
"self",
".",
"_curr",
"=",
"{",
"'attributes'",
":",
"dict",
"(",
"attrs",
")",
",",
"'lat'",
":",
"None",
",",
"'lon'",
":",
"None",
",",
"'node_id'",
":",
"None",
",",
"'tags'",
":",... | 33.347826 | 11.26087 |
def _run_freebayes_caller(align_bams, items, ref_file, assoc_files,
region=None, out_file=None, somatic=None):
"""Detect SNPs and indels with FreeBayes.
Performs post-filtering to remove very low quality variants which
can cause issues feeding into GATK. Breaks variants into indiv... | [
"def",
"_run_freebayes_caller",
"(",
"align_bams",
",",
"items",
",",
"ref_file",
",",
"assoc_files",
",",
"region",
"=",
"None",
",",
"out_file",
"=",
"None",
",",
"somatic",
"=",
"None",
")",
":",
"config",
"=",
"items",
"[",
"0",
"]",
"[",
"\"config\"... | 64.372093 | 29.627907 |
def _process_json(response_body):
"""
Returns a UwPassword objects
"""
data = json.loads(response_body)
uwpassword = UwPassword(uwnetid=data["uwNetID"],
kerb_status=data["kerbStatus"],
interval=None,
last_change=None... | [
"def",
"_process_json",
"(",
"response_body",
")",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"response_body",
")",
"uwpassword",
"=",
"UwPassword",
"(",
"uwnetid",
"=",
"data",
"[",
"\"uwNetID\"",
"]",
",",
"kerb_status",
"=",
"data",
"[",
"\"kerbStatus\"... | 35.257143 | 15.6 |
def unregister(cls, plugin):
"""
Unregisters the given plugin from the system based on its name.
:param plugin | <Plugin>
"""
plugs = getattr(cls, '_%s__plugins' % cls.__name__, {})
try:
plugs.pop(plugin.name())
except AttributeError:
... | [
"def",
"unregister",
"(",
"cls",
",",
"plugin",
")",
":",
"plugs",
"=",
"getattr",
"(",
"cls",
",",
"'_%s__plugins'",
"%",
"cls",
".",
"__name__",
",",
"{",
"}",
")",
"try",
":",
"plugs",
".",
"pop",
"(",
"plugin",
".",
"name",
"(",
")",
")",
"ex... | 28.076923 | 15.769231 |
def relaxation_decomp(P, p0, obs, times=[1], k=None, ncv=None):
r"""Relaxation experiment.
The relaxation experiment describes the time-evolution
of an expectation value starting in a non-equilibrium
situation.
Parameters
----------
P : (M, M) ndarray
Transition matrix
p0 : (M,... | [
"def",
"relaxation_decomp",
"(",
"P",
",",
"p0",
",",
"obs",
",",
"times",
"=",
"[",
"1",
"]",
",",
"k",
"=",
"None",
",",
"ncv",
"=",
"None",
")",
":",
"R",
",",
"D",
",",
"L",
"=",
"rdl_decomposition",
"(",
"P",
",",
"k",
"=",
"k",
",",
"... | 30.833333 | 16.761905 |
def get_delivery_notes_per_page(self, per_page=1000, page=1, params=None):
"""
Get delivery notes per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list
""... | [
"def",
"get_delivery_notes_per_page",
"(",
"self",
",",
"per_page",
"=",
"1000",
",",
"page",
"=",
"1",
",",
"params",
"=",
"None",
")",
":",
"return",
"self",
".",
"_get_resource_per_page",
"(",
"resource",
"=",
"DELIVERY_NOTES",
",",
"per_page",
"=",
"per_... | 42.5 | 21.1 |
def classify_intersection8(s, curve1, surface1, curve2, surface2):
"""Image for :func:`._surface_helpers.classify_intersection` docstring."""
if NO_IMAGES:
return
ax = classify_help(s, curve1, surface1, curve2, surface2, None)
ax.set_xlim(-1.125, 1.125)
ax.set_ylim(-0.125, 1.125)
save_i... | [
"def",
"classify_intersection8",
"(",
"s",
",",
"curve1",
",",
"surface1",
",",
"curve2",
",",
"surface2",
")",
":",
"if",
"NO_IMAGES",
":",
"return",
"ax",
"=",
"classify_help",
"(",
"s",
",",
"curve1",
",",
"surface1",
",",
"curve2",
",",
"surface2",
"... | 39.666667 | 19.666667 |
def insert_before(self, value: Union[RawValue, Value],
raw: bool = False) -> "ArrayEntry":
"""Insert a new entry before the receiver.
Args:
value: The value of the new entry.
raw: Flag to be set if `value` is raw.
Returns:
An instance n... | [
"def",
"insert_before",
"(",
"self",
",",
"value",
":",
"Union",
"[",
"RawValue",
",",
"Value",
"]",
",",
"raw",
":",
"bool",
"=",
"False",
")",
"->",
"\"ArrayEntry\"",
":",
"return",
"ArrayEntry",
"(",
"self",
".",
"index",
",",
"self",
".",
"before",... | 39.928571 | 20 |
def rpc_get_consensus_at( self, block_id, **con_info ):
"""
Return the consensus hash at a block number.
Return {'status': True, 'consensus': ...} on success
Return {'error': ...} on error
"""
if not check_block(block_id):
return {'error': 'Invalid block heigh... | [
"def",
"rpc_get_consensus_at",
"(",
"self",
",",
"block_id",
",",
"*",
"*",
"con_info",
")",
":",
"if",
"not",
"check_block",
"(",
"block_id",
")",
":",
"return",
"{",
"'error'",
":",
"'Invalid block height'",
",",
"'http_status'",
":",
"400",
"}",
"db",
"... | 39.384615 | 14.153846 |
def initialize(sdkopts=(), sdklibname=None):
'''Attempts to initialize the SDK with the specified options.
Even if initialization fails, a dummy SDK will be available so that SDK
functions can be called but will do nothing.
If you call this function multiple times, you must call :func:`shutdown`
j... | [
"def",
"initialize",
"(",
"sdkopts",
"=",
"(",
")",
",",
"sdklibname",
"=",
"None",
")",
":",
"global",
"_sdk_ref_count",
"#pylint:disable=global-statement",
"global",
"_sdk_instance",
"#pylint:disable=global-statement",
"with",
"_sdk_ref_lk",
":",
"logger",
".",
"deb... | 43.294118 | 24.764706 |
def bivnorm (sx, sy, cxy):
"""Given the parameters of a Gaussian bivariate distribution, compute the
correct normalization for the equivalent 2D Gaussian. It's 1 / (2 pi sqrt
(sx**2 sy**2 - cxy**2). This function adds a lot of sanity checking.
Inputs:
* sx: standard deviation (not variance) of x v... | [
"def",
"bivnorm",
"(",
"sx",
",",
"sy",
",",
"cxy",
")",
":",
"_bivcheck",
"(",
"sx",
",",
"sy",
",",
"cxy",
")",
"from",
"numpy",
"import",
"pi",
",",
"sqrt",
"t",
"=",
"(",
"sx",
"*",
"sy",
")",
"**",
"2",
"-",
"cxy",
"**",
"2",
"if",
"t"... | 35.043478 | 22 |
def noteoff(self, chan, key):
"""Stop a note."""
if key < 0 or key > 128:
return False
if chan < 0:
return False
return fluid_synth_noteoff(self.synth, chan, key) | [
"def",
"noteoff",
"(",
"self",
",",
"chan",
",",
"key",
")",
":",
"if",
"key",
"<",
"0",
"or",
"key",
">",
"128",
":",
"return",
"False",
"if",
"chan",
"<",
"0",
":",
"return",
"False",
"return",
"fluid_synth_noteoff",
"(",
"self",
".",
"synth",
",... | 30.285714 | 12.571429 |
def atexit_rmglob(path,
glob=glob.glob,
isdir=os.path.isdir,
isfile=os.path.isfile,
remove=os.remove,
rmtree=shutil.rmtree): # pragma: no cover
"""Ensure removal of multiple files at interpreter exit."""
for p in glob(pat... | [
"def",
"atexit_rmglob",
"(",
"path",
",",
"glob",
"=",
"glob",
".",
"glob",
",",
"isdir",
"=",
"os",
".",
"path",
".",
"isdir",
",",
"isfile",
"=",
"os",
".",
"path",
".",
"isfile",
",",
"remove",
"=",
"os",
".",
"remove",
",",
"rmtree",
"=",
"sh... | 33.416667 | 11.833333 |
def upload_workflow_description_file(self, filename):
'''Uploads workflow description from a *YAML* file.
Parameters
----------
filename: str
path to the file from which description should be read
See also
--------
:meth:`tmclient.api.TmClient.upload... | [
"def",
"upload_workflow_description_file",
"(",
"self",
",",
"filename",
")",
":",
"if",
"(",
"not",
"filename",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"'yml'",
")",
"and",
"not",
"filename",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"'yaml'",... | 36.047619 | 23.190476 |
def _init_channel(self):
"""
build the grpc channel used for both publisher and subscriber
:return: None
"""
host = self._get_host()
port = self._get_grpc_port()
if 'TLS_PEM_FILE' in os.environ:
with open(os.environ['TLS_PEM_FILE'], mode='rb') as f: ... | [
"def",
"_init_channel",
"(",
"self",
")",
":",
"host",
"=",
"self",
".",
"_get_host",
"(",
")",
"port",
"=",
"self",
".",
"_get_grpc_port",
"(",
")",
"if",
"'TLS_PEM_FILE'",
"in",
"os",
".",
"environ",
":",
"with",
"open",
"(",
"os",
".",
"environ",
... | 38.411765 | 20.764706 |
def _active_mounts(ret):
'''
List active mounts on Linux systems
'''
_list = _list_mounts()
filename = '/proc/self/mounts'
if not os.access(filename, os.R_OK):
msg = 'File not readable {0}'
raise CommandExecutionError(msg.format(filename))
with salt.utils.files.fopen(filenam... | [
"def",
"_active_mounts",
"(",
"ret",
")",
":",
"_list",
"=",
"_list_mounts",
"(",
")",
"filename",
"=",
"'/proc/self/mounts'",
"if",
"not",
"os",
".",
"access",
"(",
"filename",
",",
"os",
".",
"R_OK",
")",
":",
"msg",
"=",
"'File not readable {0}'",
"rais... | 37.666667 | 18.333333 |
def setMaximumHeight(self, height):
"""
Sets the maximum height value to the inputed height and emits the \
sizeConstraintChanged signal.
:param height | <int>
"""
super(XView, self).setMaximumHeight(height)
if ( not self.signalsBlocked() ):... | [
"def",
"setMaximumHeight",
"(",
"self",
",",
"height",
")",
":",
"super",
"(",
"XView",
",",
"self",
")",
".",
"setMaximumHeight",
"(",
"height",
")",
"if",
"(",
"not",
"self",
".",
"signalsBlocked",
"(",
")",
")",
":",
"self",
".",
"sizeConstraintChange... | 32.363636 | 11.818182 |
def register_callback_query_handler(self, callback, *custom_filters, state=None, run_task=None, **kwargs):
"""
Register handler for callback query
Example:
.. code-block:: python3
dp.register_callback_query_handler(some_callback_handler, lambda callback_query: True)
... | [
"def",
"register_callback_query_handler",
"(",
"self",
",",
"callback",
",",
"*",
"custom_filters",
",",
"state",
"=",
"None",
",",
"run_task",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"filters_set",
"=",
"self",
".",
"filters_factory",
".",
"resolve"... | 40.333333 | 27.47619 |
def create(self, interface):
"""
Method to add an interface.
:param interface: List containing interface's desired to be created on database.
:return: Id.
"""
data = {'interfaces': interface}
return super(ApiInterfaceRequest, self).post('api/v3/interface/', data) | [
"def",
"create",
"(",
"self",
",",
"interface",
")",
":",
"data",
"=",
"{",
"'interfaces'",
":",
"interface",
"}",
"return",
"super",
"(",
"ApiInterfaceRequest",
",",
"self",
")",
".",
"post",
"(",
"'api/v3/interface/'",
",",
"data",
")"
] | 34.666667 | 18.222222 |
def _inherited_dashboard(dashboard, base_dashboards_from_pillar, ret):
'''Return a dashboard with properties from parents.'''
base_dashboards = []
for base_dashboard_from_pillar in base_dashboards_from_pillar:
base_dashboard = __salt__['pillar.get'](base_dashboard_from_pillar)
if base_dashbo... | [
"def",
"_inherited_dashboard",
"(",
"dashboard",
",",
"base_dashboards_from_pillar",
",",
"ret",
")",
":",
"base_dashboards",
"=",
"[",
"]",
"for",
"base_dashboard_from_pillar",
"in",
"base_dashboards_from_pillar",
":",
"base_dashboard",
"=",
"__salt__",
"[",
"'pillar.g... | 44.454545 | 16.090909 |
def relative_file(self, module, file):
"""Load a file relative to a module.
:param str module: can be
- a path to a folder
- a path to a file
- a module name
:param str folder: the path of a folder relative to :paramref:`module`
:return: the result of the... | [
"def",
"relative_file",
"(",
"self",
",",
"module",
",",
"file",
")",
":",
"path",
"=",
"self",
".",
"_relative_to_absolute",
"(",
"module",
",",
"file",
")",
"return",
"self",
".",
"path",
"(",
"path",
")"
] | 27.8 | 18.266667 |
def length_squared(x, keep_dims=False, name=None, reduction_dim=None):
"""Computes the squared length of x.
Args:
x: A tensor.
keep_dims: If true, reduction does not change the rank of the input.
name: Optional name for this op.
reduction_dim: The dimension to reduce, by default choose the last one... | [
"def",
"length_squared",
"(",
"x",
",",
"keep_dims",
"=",
"False",
",",
"name",
"=",
"None",
",",
"reduction_dim",
"=",
"None",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"name",
",",
"'length_squared'",
",",
"[",
"x",
"]",
")",
"as",
"scope",
"... | 32.285714 | 17.285714 |
def enclosing_frame(frame=None, level=2):
"""Get an enclosing frame that skips decorator code"""
frame = frame or sys._getframe(level)
while frame.f_globals.get('__name__') == __name__: frame = frame.f_back
return frame | [
"def",
"enclosing_frame",
"(",
"frame",
"=",
"None",
",",
"level",
"=",
"2",
")",
":",
"frame",
"=",
"frame",
"or",
"sys",
".",
"_getframe",
"(",
"level",
")",
"while",
"frame",
".",
"f_globals",
".",
"get",
"(",
"'__name__'",
")",
"==",
"__name__",
... | 46.2 | 12.2 |
def getUpperDetectionLimit(self):
"""Returns the Upper Detection Limit (UDL) that applies to this
analysis in particular. If no value set or the analysis service
doesn't allow manual input of detection limits, returns the value set
by default in the Analysis Service
"""
i... | [
"def",
"getUpperDetectionLimit",
"(",
"self",
")",
":",
"if",
"self",
".",
"isUpperDetectionLimit",
"(",
")",
":",
"result",
"=",
"self",
".",
"getResult",
"(",
")",
"try",
":",
"# in this case, the result itself is the LDL.",
"return",
"float",
"(",
"result",
"... | 50 | 14.352941 |
def move_siblings(
start, end, new_,
keep_start_boundary=False,
keep_end_boundary=False
):
"""a helper function that will replace a start/end node pair
by a new containing element, effectively moving all in-between siblings
This is particularly helpful to replace for /for loops in ta... | [
"def",
"move_siblings",
"(",
"start",
",",
"end",
",",
"new_",
",",
"keep_start_boundary",
"=",
"False",
",",
"keep_end_boundary",
"=",
"False",
")",
":",
"old_",
"=",
"start",
".",
"getparent",
"(",
")",
"if",
"keep_start_boundary",
":",
"new_",
".",
"app... | 29.877193 | 20.842105 |
def access_specifier(self):
"""
Retrieves the access specifier (if any) of the entity pointed at by the
cursor.
"""
if not hasattr(self, '_access_specifier'):
self._access_specifier = conf.lib.clang_getCXXAccessSpecifier(self)
return AccessSpecifier.from_id(s... | [
"def",
"access_specifier",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_access_specifier'",
")",
":",
"self",
".",
"_access_specifier",
"=",
"conf",
".",
"lib",
".",
"clang_getCXXAccessSpecifier",
"(",
"self",
")",
"return",
"AccessSpeci... | 37.111111 | 20.888889 |
def readBoolean(self):
"""
Read C{Boolean}.
@raise ValueError: Error reading Boolean.
@rtype: C{bool}
@return: A Boolean value, C{True} if the byte
is nonzero, C{False} otherwise.
"""
byte = self.stream.read(1)
if byte == '\x00':
retu... | [
"def",
"readBoolean",
"(",
"self",
")",
":",
"byte",
"=",
"self",
".",
"stream",
".",
"read",
"(",
"1",
")",
"if",
"byte",
"==",
"'\\x00'",
":",
"return",
"False",
"elif",
"byte",
"==",
"'\\x01'",
":",
"return",
"True",
"else",
":",
"raise",
"ValueEr... | 25.470588 | 15.235294 |
def shapeplot_animate(v,lines,nframes=None,tscale='linear',\
clim=[-80,50],cmap=cm.YlOrBr_r):
""" Returns animate function which updates color of shapeplot """
if nframes is None:
nframes = v.shape[0]
if tscale == 'linear':
def animate(i):
i_t = int((i/nfram... | [
"def",
"shapeplot_animate",
"(",
"v",
",",
"lines",
",",
"nframes",
"=",
"None",
",",
"tscale",
"=",
"'linear'",
",",
"clim",
"=",
"[",
"-",
"80",
",",
"50",
"]",
",",
"cmap",
"=",
"cm",
".",
"YlOrBr_r",
")",
":",
"if",
"nframes",
"is",
"None",
"... | 41.333333 | 21.190476 |
def objects(self, cls=None):
"""
Return an iterater over all objects in this directory which are
instances of `cls`. By default, iterate over all objects (`cls=None`).
Parameters
----------
cls : a class, optional (default=None)
If a class is specified, only... | [
"def",
"objects",
"(",
"self",
",",
"cls",
"=",
"None",
")",
":",
"objs",
"=",
"(",
"asrootpy",
"(",
"x",
".",
"ReadObj",
"(",
")",
",",
"warn",
"=",
"False",
")",
"for",
"x",
"in",
"self",
".",
"GetListOfKeys",
"(",
")",
")",
"if",
"cls",
"is"... | 27.225806 | 22.193548 |
def spill(self, src, dest):
"""
Spill a workspace, i.e. unpack it and turn it into a workspace.
See https://ocr-d.github.com/ocrd_zip#unpacking-ocrd-zip-to-a-workspace
Arguments:
src (string): Path to OCRD-ZIP
dest (string): Path to directory to unpack data fold... | [
"def",
"spill",
"(",
"self",
",",
"src",
",",
"dest",
")",
":",
"# print(dest)",
"if",
"exists",
"(",
"dest",
")",
"and",
"not",
"isdir",
"(",
"dest",
")",
":",
"raise",
"Exception",
"(",
"\"Not a directory: %s\"",
"%",
"dest",
")",
"# If dest is an exist... | 31.288462 | 19.980769 |
def text(self, obj):
"""Add literal text to the output."""
width = len(obj)
if self.buffer:
text = self.buffer[-1]
if not isinstance(text, Text):
text = Text()
self.buffer.append(text)
text.add(obj, width)
self.buffe... | [
"def",
"text",
"(",
"self",
",",
"obj",
")",
":",
"width",
"=",
"len",
"(",
"obj",
")",
"if",
"self",
".",
"buffer",
":",
"text",
"=",
"self",
".",
"buffer",
"[",
"-",
"1",
"]",
"if",
"not",
"isinstance",
"(",
"text",
",",
"Text",
")",
":",
"... | 32.142857 | 8.5 |
def refresh(self):
""" Refreshes the editor panels (resize and update margins) """
_logger().log(5, 'refresh_panels')
self.resize()
self._update(self.editor.contentsRect(), 0,
force_update_margins=True) | [
"def",
"refresh",
"(",
"self",
")",
":",
"_logger",
"(",
")",
".",
"log",
"(",
"5",
",",
"'refresh_panels'",
")",
"self",
".",
"resize",
"(",
")",
"self",
".",
"_update",
"(",
"self",
".",
"editor",
".",
"contentsRect",
"(",
")",
",",
"0",
",",
"... | 41.666667 | 10.166667 |
def hand_shake(self, actor, run=True):
'''Perform the hand shake for ``actor``
The hand shake occurs when the ``actor`` is in starting state.
It performs the following actions:
* set the ``actor`` as the actor of the current thread
* bind two additional callbacks to the ``start... | [
"def",
"hand_shake",
"(",
"self",
",",
"actor",
",",
"run",
"=",
"True",
")",
":",
"try",
":",
"assert",
"actor",
".",
"state",
"==",
"ACTOR_STATES",
".",
"STARTING",
"if",
"actor",
".",
"cfg",
".",
"debug",
":",
"actor",
".",
"logger",
".",
"debug",... | 35.454545 | 17.454545 |
def read_function(data, window, ij, g_args):
"""Takes an array, and sets any value above the mean to the max, the rest to 0"""
output = (data[0] > numpy.mean(data[0])).astype(data[0].dtype) * data[0].max()
return output | [
"def",
"read_function",
"(",
"data",
",",
"window",
",",
"ij",
",",
"g_args",
")",
":",
"output",
"=",
"(",
"data",
"[",
"0",
"]",
">",
"numpy",
".",
"mean",
"(",
"data",
"[",
"0",
"]",
")",
")",
".",
"astype",
"(",
"data",
"[",
"0",
"]",
"."... | 57 | 17.25 |
def POST(self):
""" Handles POST request """
if self.user_manager.session_logged_in() or not self.app.allow_registration:
raise web.notfound()
reset = None
msg = ""
error = False
data = web.input()
if "register" in data:
msg, error = self.... | [
"def",
"POST",
"(",
"self",
")",
":",
"if",
"self",
".",
"user_manager",
".",
"session_logged_in",
"(",
")",
"or",
"not",
"self",
".",
"app",
".",
"allow_registration",
":",
"raise",
"web",
".",
"notfound",
"(",
")",
"reset",
"=",
"None",
"msg",
"=",
... | 33.619048 | 18.285714 |
def inform(self, msg):
"""Send an inform message to a particular client.
Should only be used for asynchronous informs. Informs
that are part of the response to a request should use
:meth:`reply_inform` so that the message identifier
from the original request can be attached to t... | [
"def",
"inform",
"(",
"self",
",",
"msg",
")",
":",
"assert",
"(",
"msg",
".",
"mtype",
"==",
"Message",
".",
"INFORM",
")",
"return",
"self",
".",
"_send_message",
"(",
"msg",
")"
] | 31 | 17.823529 |
def get_sonos_favorites(self, start=0, max_items=100):
"""Get Sonos favorites.
See :meth:`get_favorite_radio_shows` for return type and remarks.
"""
message = 'The output type of this method will probably change in '\
'the future to use SoCo data structures'
wa... | [
"def",
"get_sonos_favorites",
"(",
"self",
",",
"start",
"=",
"0",
",",
"max_items",
"=",
"100",
")",
":",
"message",
"=",
"'The output type of this method will probably change in '",
"'the future to use SoCo data structures'",
"warnings",
".",
"warn",
"(",
"message",
"... | 46.333333 | 19.444444 |
def run(self):
""" Runs the printer loop in a subprocess. This is called by
multiprocessing.
"""
try:
self._loop()
except Exception:
# Send the exception through the exc_queue, so the parent
# process can check it.
typ, val, tb ... | [
"def",
"run",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_loop",
"(",
")",
"except",
"Exception",
":",
"# Send the exception through the exc_queue, so the parent",
"# process can check it.",
"typ",
",",
"val",
",",
"tb",
"=",
"sys",
".",
"exc_info",
"(",
... | 36.416667 | 13.5 |
def fallback_move(fobj, dest, src, count, BUFFER_SIZE=2 ** 16):
"""Moves data around using read()/write().
Args:
fileobj (fileobj)
dest (int): The destination offset
src (int): The source offset
count (int) The amount of data to move
Raises:
IOError: In case an opera... | [
"def",
"fallback_move",
"(",
"fobj",
",",
"dest",
",",
"src",
",",
"count",
",",
"BUFFER_SIZE",
"=",
"2",
"**",
"16",
")",
":",
"if",
"dest",
"<",
"0",
"or",
"src",
"<",
"0",
"or",
"count",
"<",
"0",
":",
"raise",
"ValueError",
"fobj",
".",
"seek... | 28.878049 | 15.829268 |
def parse_template(template_path, **kwargs):
""" Load and render template.
First line of template should contain the subject of email.
Return tuple with subject and content.
"""
template = get_template(template_path)
context = Context(kwargs)
data = template.render(context).strip()
... | [
"def",
"parse_template",
"(",
"template_path",
",",
"*",
"*",
"kwargs",
")",
":",
"template",
"=",
"get_template",
"(",
"template_path",
")",
"context",
"=",
"Context",
"(",
"kwargs",
")",
"data",
"=",
"template",
".",
"render",
"(",
"context",
")",
".",
... | 40.6 | 6.8 |
def layout(self,
scene,
nodes,
center=None,
padX=None,
padY=None,
direction=None,
animationGroup=None):
"""
Lays out the nodes for this scene based on a block layering algorithm.
... | [
"def",
"layout",
"(",
"self",
",",
"scene",
",",
"nodes",
",",
"center",
"=",
"None",
",",
"padX",
"=",
"None",
",",
"padY",
"=",
"None",
",",
"direction",
"=",
"None",
",",
"animationGroup",
"=",
"None",
")",
":",
"nodes",
"=",
"filter",
"(",
"lam... | 41.283401 | 15.769231 |
def get_property(obj, name):
"""
Gets value of object property specified by its name.
:param obj: an object to read property from.
:param name: a name of the property to get.
:return: the property value or null if property doesn't exist or introspection failed.
"""
... | [
"def",
"get_property",
"(",
"obj",
",",
"name",
")",
":",
"if",
"obj",
"==",
"None",
":",
"raise",
"Exception",
"(",
"\"Object cannot be null\"",
")",
"if",
"name",
"==",
"None",
":",
"raise",
"Exception",
"(",
"\"Property name cannot be null\"",
")",
"name",
... | 28.733333 | 21.933333 |
def get_complete_version(version=None):
"""Returns a tuple of the promise version. If version argument is non-empty,
then checks for correctness of the tuple provided.
"""
if version is None:
from promise import VERSION
return VERSION
else:
assert len(version) == 5
a... | [
"def",
"get_complete_version",
"(",
"version",
"=",
"None",
")",
":",
"if",
"version",
"is",
"None",
":",
"from",
"promise",
"import",
"VERSION",
"return",
"VERSION",
"else",
":",
"assert",
"len",
"(",
"version",
")",
"==",
"5",
"assert",
"version",
"[",
... | 29.230769 | 16.692308 |
def can_solve(cls, filter_):
"""Tells if the solver is able to resolve the given filter.
Arguments
---------
filter_ : subclass of dataql.resources.BaseFilter
The subclass or ``BaseFilter`` to check if it is solvable by the current solver class.
Returns
----... | [
"def",
"can_solve",
"(",
"cls",
",",
"filter_",
")",
":",
"for",
"solvable_filter",
"in",
"cls",
".",
"solvable_filters",
":",
"if",
"isinstance",
"(",
"filter_",
",",
"solvable_filter",
")",
":",
"return",
"True",
"return",
"False"
] | 28.793103 | 24.103448 |
def _add_constraints(self, relation):
"""Add the given relation as one or more constraints
Return a list of the names of the constraints added.
"""
expression = relation.expression
names = []
for value_set in expression.value_sets():
values = ((self._variable... | [
"def",
"_add_constraints",
"(",
"self",
",",
"relation",
")",
":",
"expression",
"=",
"relation",
".",
"expression",
"names",
"=",
"[",
"]",
"for",
"value_set",
"in",
"expression",
".",
"value_sets",
"(",
")",
":",
"values",
"=",
"(",
"(",
"self",
".",
... | 38.444444 | 13.944444 |
def flavor_list(profile=None, **kwargs):
'''
Return a list of available flavors (nova flavor-list)
CLI Example:
.. code-block:: bash
salt '*' nova.flavor_list
'''
filters = kwargs.get('filter', {})
conn = _auth(profile, **kwargs)
return conn.flavor_list(**filters) | [
"def",
"flavor_list",
"(",
"profile",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"filters",
"=",
"kwargs",
".",
"get",
"(",
"'filter'",
",",
"{",
"}",
")",
"conn",
"=",
"_auth",
"(",
"profile",
",",
"*",
"*",
"kwargs",
")",
"return",
"conn",
... | 22.692308 | 19.923077 |
def jinja_block_as_fragment_extension(name, tagname=None, classname=None):
"""Creates a fragment extension which will just act as a replacement of the
block statement.
"""
if tagname is None:
tagname = name
if classname is None:
classname = "%sBlockFragmentExtension" % name.capitaliz... | [
"def",
"jinja_block_as_fragment_extension",
"(",
"name",
",",
"tagname",
"=",
"None",
",",
"classname",
"=",
"None",
")",
":",
"if",
"tagname",
"is",
"None",
":",
"tagname",
"=",
"name",
"if",
"classname",
"is",
"None",
":",
"classname",
"=",
"\"%sBlockFragm... | 46.2 | 19.6 |
def run(arguments: typing.List[str] = None):
"""Executes the cauldron command"""
initialize()
from cauldron.invoke import parser
from cauldron.invoke import invoker
args = parser.parse(arguments)
exit_code = invoker.run(args.get('command'), args)
sys.exit(exit_code) | [
"def",
"run",
"(",
"arguments",
":",
"typing",
".",
"List",
"[",
"str",
"]",
"=",
"None",
")",
":",
"initialize",
"(",
")",
"from",
"cauldron",
".",
"invoke",
"import",
"parser",
"from",
"cauldron",
".",
"invoke",
"import",
"invoker",
"args",
"=",
"par... | 28.7 | 14.8 |
def build_genome_alignment_from_directory(d_name, ref_spec, extensions=None,
index_exts=None,
fail_no_index=False):
"""
build a genome aligment by loading all files in a directory.
Fiel without indexes are loaded immediately; tho... | [
"def",
"build_genome_alignment_from_directory",
"(",
"d_name",
",",
"ref_spec",
",",
"extensions",
"=",
"None",
",",
"index_exts",
"=",
"None",
",",
"fail_no_index",
"=",
"False",
")",
":",
"if",
"index_exts",
"is",
"None",
"and",
"fail_no_index",
":",
"raise",
... | 48.142857 | 21.628571 |
def transform_file_output(result):
""" Transform to convert SDK file/dir list output to something that
more clearly distinguishes between files and directories. """
from collections import OrderedDict
new_result = []
iterable = result if isinstance(result, list) else result.get('items', result)
... | [
"def",
"transform_file_output",
"(",
"result",
")",
":",
"from",
"collections",
"import",
"OrderedDict",
"new_result",
"=",
"[",
"]",
"iterable",
"=",
"result",
"if",
"isinstance",
"(",
"result",
",",
"list",
")",
"else",
"result",
".",
"get",
"(",
"'items'"... | 46 | 21.684211 |
def create_file_vdev(size, *vdevs):
'''
Creates file based virtual devices for a zpool
CLI Example:
.. code-block:: bash
salt '*' zpool.create_file_vdev 7G /path/to/vdev1 [/path/to/vdev2] [...]
.. note::
Depending on file size, the above command may take a while to return.
... | [
"def",
"create_file_vdev",
"(",
"size",
",",
"*",
"vdevs",
")",
":",
"ret",
"=",
"OrderedDict",
"(",
")",
"err",
"=",
"OrderedDict",
"(",
")",
"_mkfile_cmd",
"=",
"salt",
".",
"utils",
".",
"path",
".",
"which",
"(",
"'mkfile'",
")",
"for",
"vdev",
"... | 26.268293 | 21.731707 |
def bank_short_name(self):
"""str or None: The short name of the bank associated with the BIC."""
entry = registry.get('bic').get(self.compact)
if entry:
return entry.get('short_name') | [
"def",
"bank_short_name",
"(",
"self",
")",
":",
"entry",
"=",
"registry",
".",
"get",
"(",
"'bic'",
")",
".",
"get",
"(",
"self",
".",
"compact",
")",
"if",
"entry",
":",
"return",
"entry",
".",
"get",
"(",
"'short_name'",
")"
] | 43.2 | 10.4 |
def distribute_javaclasses(self, javaclass_dir, dest_dir="src"):
'''Copy existing javaclasses from build dir to current dist dir.'''
info('Copying java files')
ensure_dir(dest_dir)
for filename in glob.glob(javaclass_dir):
shprint(sh.cp, '-a', filename, dest_dir) | [
"def",
"distribute_javaclasses",
"(",
"self",
",",
"javaclass_dir",
",",
"dest_dir",
"=",
"\"src\"",
")",
":",
"info",
"(",
"'Copying java files'",
")",
"ensure_dir",
"(",
"dest_dir",
")",
"for",
"filename",
"in",
"glob",
".",
"glob",
"(",
"javaclass_dir",
")"... | 50.333333 | 16.333333 |
def _make_like(self, column, format, value):
"""
make like condition
:param column: column object
:param format: '%_' '_%' '%_%'
:param value: column value
:return: condition object
"""
c = []
if format.startswith('%'):
c.appe... | [
"def",
"_make_like",
"(",
"self",
",",
"column",
",",
"format",
",",
"value",
")",
":",
"c",
"=",
"[",
"]",
"if",
"format",
".",
"startswith",
"(",
"'%'",
")",
":",
"c",
".",
"append",
"(",
"'%'",
")",
"c",
".",
"append",
"(",
"value",
")",
"if... | 29.266667 | 7.666667 |
def insert(self, member, score):
"""
Identical to __setitem__, but returns whether a member was
inserted (True) or updated (False)
"""
found = self.remove(member)
index = bisect_left(self._scores, (score, member))
self._scores.insert(index, (score, member))
... | [
"def",
"insert",
"(",
"self",
",",
"member",
",",
"score",
")",
":",
"found",
"=",
"self",
".",
"remove",
"(",
"member",
")",
"index",
"=",
"bisect_left",
"(",
"self",
".",
"_scores",
",",
"(",
"score",
",",
"member",
")",
")",
"self",
".",
"_score... | 36.7 | 8.9 |
def main(reactor):
"""Main command line entry point."""
parser = argparse.ArgumentParser(
description='Fetch a URI or series of URIs and print a title '
'or summary for each.',
epilog='If no URIs are passed on the command line, they are '
'read from standard in... | [
"def",
"main",
"(",
"reactor",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Fetch a URI or series of URIs and print a title '",
"'or summary for each.'",
",",
"epilog",
"=",
"'If no URIs are passed on the command line, they are '",
"'... | 44.15 | 15.55 |
def eval_policy(eval_positions):
"""Evaluate all positions with all models save the policy heatmaps as CSVs
CSV name is "heatmap-<position_name>-<model-index>.csv"
CSV format is: model number, value network output, policy network outputs
position_name is taken from the SGF file
Policy network outp... | [
"def",
"eval_policy",
"(",
"eval_positions",
")",
":",
"model_paths",
"=",
"oneoff_utils",
".",
"get_model_paths",
"(",
"fsdb",
".",
"models_dir",
"(",
")",
")",
"idx_start",
"=",
"FLAGS",
".",
"idx_start",
"eval_every",
"=",
"FLAGS",
".",
"eval_every",
"print... | 37.097561 | 22.390244 |
def p_const_expression_stringliteral(self, p):
'const_expression : stringliteral'
p[0] = StringConst(p[1], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | [
"def",
"p_const_expression_stringliteral",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"StringConst",
"(",
"p",
"[",
"1",
"]",
",",
"lineno",
"=",
"p",
".",
"lineno",
"(",
"1",
")",
")",
"p",
".",
"set_lineno",
"(",
"0",
",",
"p",
... | 44 | 6 |
def next(self):
" Move on to the next character in the text. "
char = self.char
if char == '\n':
self.lineno += 1
self.colno = 0
else:
self.colno += 1
self.index += 1
return self.char | [
"def",
"next",
"(",
"self",
")",
":",
"char",
"=",
"self",
".",
"char",
"if",
"char",
"==",
"'\\n'",
":",
"self",
".",
"lineno",
"+=",
"1",
"self",
".",
"colno",
"=",
"0",
"else",
":",
"self",
".",
"colno",
"+=",
"1",
"self",
".",
"index",
"+="... | 19.636364 | 22.181818 |
def get_actuators(self):
"""
Get actuators as a dictionary of format ``{name: status}``
"""
return {i.name: i.status for i in self.system.actuators} | [
"def",
"get_actuators",
"(",
"self",
")",
":",
"return",
"{",
"i",
".",
"name",
":",
"i",
".",
"status",
"for",
"i",
"in",
"self",
".",
"system",
".",
"actuators",
"}"
] | 36 | 14 |
def random_subset(self, relative_size, balance_labels=False, label_list_ids=None):
"""
Create a subview of random utterances with a approximate size relative to the full corpus.
By default x random utterances are selected with x equal to ``relative_size * corpus.num_utterances``.
Args:
... | [
"def",
"random_subset",
"(",
"self",
",",
"relative_size",
",",
"balance_labels",
"=",
"False",
",",
"label_list_ids",
"=",
"None",
")",
":",
"num_utterances_in_subset",
"=",
"round",
"(",
"relative_size",
"*",
"self",
".",
"corpus",
".",
"num_utterances",
")",
... | 57.973684 | 41.184211 |
def fetch_replace_restriction(self, ):
"""Fetch whether unloading is restricted
:returns: True, if unloading is restricted
:rtype: :class:`bool`
:raises: None
"""
inter = self.get_refobjinter()
restricted = self.status() is None
return restricted or inter... | [
"def",
"fetch_replace_restriction",
"(",
"self",
",",
")",
":",
"inter",
"=",
"self",
".",
"get_refobjinter",
"(",
")",
"restricted",
"=",
"self",
".",
"status",
"(",
")",
"is",
"None",
"return",
"restricted",
"or",
"inter",
".",
"fetch_action_restriction",
... | 35.3 | 12.2 |
def get_prtflds_all(self):
"""When converting to a namedtuple, get all possible fields in their original order."""
flds = []
dont_add = set(['_parents', 'method_flds', 'relationship_rev', 'relationship'])
# Fields: GO NS enrichment name ratio_in_study ratio_in_pop p_uncorrected
#... | [
"def",
"get_prtflds_all",
"(",
"self",
")",
":",
"flds",
"=",
"[",
"]",
"dont_add",
"=",
"set",
"(",
"[",
"'_parents'",
",",
"'method_flds'",
",",
"'relationship_rev'",
",",
"'relationship'",
"]",
")",
"# Fields: GO NS enrichment name ratio_in_study ratio_in_pop p_unc... | 61.333333 | 26.733333 |
def _Open(self, path_spec=None, mode='rb'):
"""Opens the file-like object defined by path specification.
Args:
path_spec (Optional[PathSpec]): path specification.
mode (Optional[str]): file access mode.
Raises:
AccessError: if the access to open the file was denied.
IOError: if the... | [
"def",
"_Open",
"(",
"self",
",",
"path_spec",
"=",
"None",
",",
"mode",
"=",
"'rb'",
")",
":",
"if",
"not",
"self",
".",
"_file_object_set_in_init",
"and",
"not",
"path_spec",
":",
"raise",
"ValueError",
"(",
"'Missing path specification.'",
")",
"if",
"sel... | 36.434783 | 19.608696 |
def as_command(self):
"""Creates the click command wrapping the function
"""
try:
params = self.unbound_func.__click_params__
params.reverse()
del self.unbound_func.__click_params__
except AttributeError:
params = []
help = inspect.... | [
"def",
"as_command",
"(",
"self",
")",
":",
"try",
":",
"params",
"=",
"self",
".",
"unbound_func",
".",
"__click_params__",
"params",
".",
"reverse",
"(",
")",
"del",
"self",
".",
"unbound_func",
".",
"__click_params__",
"except",
"AttributeError",
":",
"pa... | 41.375 | 13.416667 |
def send_action(self, recipient_id, action, notification_type=NotificationType.regular):
"""Send typing indicators or send read receipts to the specified recipient.
https://developers.facebook.com/docs/messenger-platform/send-api-reference/sender-actions
Input:
recipient_id: recipie... | [
"def",
"send_action",
"(",
"self",
",",
"recipient_id",
",",
"action",
",",
"notification_type",
"=",
"NotificationType",
".",
"regular",
")",
":",
"return",
"self",
".",
"send_recipient",
"(",
"recipient_id",
",",
"{",
"'sender_action'",
":",
"action",
"}",
"... | 44.307692 | 19.846154 |
def cone_search(lcc_server,
center_ra,
center_decl,
radiusarcmin=5.0,
result_visibility='unlisted',
email_when_done=False,
collections=None,
columns=None,
filters=None,
sortspe... | [
"def",
"cone_search",
"(",
"lcc_server",
",",
"center_ra",
",",
"center_decl",
",",
"radiusarcmin",
"=",
"5.0",
",",
"result_visibility",
"=",
"'unlisted'",
",",
"email_when_done",
"=",
"False",
",",
"collections",
"=",
"None",
",",
"columns",
"=",
"None",
","... | 35.379845 | 24.51938 |
def _load_types(root):
"""Returns {name: Type}"""
def text(t):
if t.tag == 'name':
return '{name}'
elif t.tag == 'apientry':
return '{apientry}'
out = []
if t.text:
out.append(_escape_tpl_str(t.text))
for x in t:
out.append(... | [
"def",
"_load_types",
"(",
"root",
")",
":",
"def",
"text",
"(",
"t",
")",
":",
"if",
"t",
".",
"tag",
"==",
"'name'",
":",
"return",
"'{name}'",
"elif",
"t",
".",
"tag",
"==",
"'apientry'",
":",
"return",
"'{apientry}'",
"out",
"=",
"[",
"]",
"if"... | 31.290323 | 14.193548 |
def _add_value(self, field_name: str, value, provenance_path=None) -> bool:
"""
Helper function to add values to a knowledge graph
Args:
field_name: a field in the knowledge graph, assumed correct
value: any Python type
Returns: True if the value is compliant wit... | [
"def",
"_add_value",
"(",
"self",
",",
"field_name",
":",
"str",
",",
"value",
",",
"provenance_path",
"=",
"None",
")",
"->",
"bool",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"value",
"=",
"[",
"value",
"]",
"all_valid",
... | 34.944444 | 22.166667 |
def sampler(self, n_samples, duration, random_state=None):
'''Construct a sampler object for this pump's operators.
Parameters
----------
n_samples : None or int > 0
The number of samples to generate
duration : int > 0
The duration (in frames) of each sa... | [
"def",
"sampler",
"(",
"self",
",",
"n_samples",
",",
"duration",
",",
"random_state",
"=",
"None",
")",
":",
"return",
"Sampler",
"(",
"n_samples",
",",
"duration",
",",
"random_state",
"=",
"random_state",
",",
"*",
"self",
".",
"ops",
")"
] | 28.147059 | 23.029412 |
def get(self, pk):
"""Return one and exactly one object
=====API DOCS=====
Return one and exactly one Tower setting.
:param pk: Primary key of the Tower setting to retrieve
:type pk: int
:returns: loaded JSON of the retrieved Tower setting object.
:rtype: dict
... | [
"def",
"get",
"(",
"self",
",",
"pk",
")",
":",
"# The Tower API doesn't provide a mechanism for retrieving a single",
"# setting value at a time, so fetch them all and filter",
"try",
":",
"return",
"next",
"(",
"s",
"for",
"s",
"in",
"self",
".",
"list",
"(",
")",
"... | 38 | 24.05 |
def search(self, **kwargs):
"""
Method to search object group permissions general based on extends search.
:param search: Dict containing QuerySets to find object group permissions general.
:param include: Array containing fields to include on response.
:param exclude: Array con... | [
"def",
"search",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"ApiObjectGroupPermissionGeneral",
",",
"self",
")",
".",
"get",
"(",
"self",
".",
"prepare_url",
"(",
"'api/v3/object-group-perm-general/'",
",",
"kwargs",
")",
")"
] | 56.928571 | 34.357143 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.