text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def extract_tar(tar_path, target_folder):
"""
Extract the content of the tar-file at `tar_path` into `target_folder`.
"""
with tarfile.open(tar_path, 'r') as archive:
archive.extractall(target_folder) | [
"def",
"extract_tar",
"(",
"tar_path",
",",
"target_folder",
")",
":",
"with",
"tarfile",
".",
"open",
"(",
"tar_path",
",",
"'r'",
")",
"as",
"archive",
":",
"archive",
".",
"extractall",
"(",
"target_folder",
")"
] | 36.5 | 7.5 |
def yield_name2value(self, idx1=None, idx2=None) \
-> Iterator[Tuple[str, str]]:
"""Sequentially return name-value-pairs describing the current state
of the target variables.
The names are automatically generated and contain both the name of
the |Device| of the respective |V... | [
"def",
"yield_name2value",
"(",
"self",
",",
"idx1",
"=",
"None",
",",
"idx2",
"=",
"None",
")",
"->",
"Iterator",
"[",
"Tuple",
"[",
"str",
",",
"str",
"]",
"]",
":",
"for",
"device",
",",
"name",
"in",
"self",
".",
"_device2name",
".",
"items",
"... | 42.135593 | 16.220339 |
def tolist(val):
"""Convert a value that may be a list or a (possibly comma-separated)
string into a list. The exception: None is returned as None, not [None].
>>> tolist(["one", "two"])
['one', 'two']
>>> tolist("hello")
['hello']
>>> tolist("separate,values, with, commas, spaces , are ... | [
"def",
"tolist",
"(",
"val",
")",
":",
"if",
"val",
"is",
"None",
":",
"return",
"None",
"try",
":",
"# might already be a list",
"val",
".",
"extend",
"(",
"[",
"]",
")",
"return",
"val",
"except",
"AttributeError",
":",
"pass",
"# might be a string",
"tr... | 27.48 | 19.88 |
def _embedding_classical_mds(matrix, dimensions=3, additive_correct=False):
"""
Private method to calculate CMDS embedding
:param dimensions: (int)
:return: coordinate matrix (np.array)
"""
if additive_correct:
dbc = double_centre(_additive_correct(matrix))
else:
dbc = double... | [
"def",
"_embedding_classical_mds",
"(",
"matrix",
",",
"dimensions",
"=",
"3",
",",
"additive_correct",
"=",
"False",
")",
":",
"if",
"additive_correct",
":",
"dbc",
"=",
"double_centre",
"(",
"_additive_correct",
"(",
"matrix",
")",
")",
"else",
":",
"dbc",
... | 33.333333 | 12.933333 |
def letter_scales(counts):
"""Convert letter counts to frequencies, sorted increasing."""
try:
scale = 1.0 / sum(counts.values())
except ZeroDivisionError:
# This logo is all gaps, nothing can be done
return []
freqs = [(aa, cnt*scale) for aa, cnt in counts.iteritems() if cnt]
... | [
"def",
"letter_scales",
"(",
"counts",
")",
":",
"try",
":",
"scale",
"=",
"1.0",
"/",
"sum",
"(",
"counts",
".",
"values",
"(",
")",
")",
"except",
"ZeroDivisionError",
":",
"# This logo is all gaps, nothing can be done",
"return",
"[",
"]",
"freqs",
"=",
"... | 36.7 | 14.8 |
def validate_auth_mechanism(option, value):
"""Validate the authMechanism URI option.
"""
# CRAM-MD5 is for server testing only. Undocumented,
# unsupported, may be removed at any time. You have
# been warned.
if value not in MECHANISMS and value != 'CRAM-MD5':
raise ValueError("%s must ... | [
"def",
"validate_auth_mechanism",
"(",
"option",
",",
"value",
")",
":",
"# CRAM-MD5 is for server testing only. Undocumented,",
"# unsupported, may be removed at any time. You have",
"# been warned.",
"if",
"value",
"not",
"in",
"MECHANISMS",
"and",
"value",
"!=",
"'CRAM-MD5'"... | 41 | 14.333333 |
def set_render_manager(self, agent: BaseAgent):
"""
Sets the render manager for the agent.
:param agent: An instance of an agent.
"""
rendering_manager = self.game_interface.renderer.get_rendering_manager(self.index, self.team)
agent._set_renderer(rendering_manager) | [
"def",
"set_render_manager",
"(",
"self",
",",
"agent",
":",
"BaseAgent",
")",
":",
"rendering_manager",
"=",
"self",
".",
"game_interface",
".",
"renderer",
".",
"get_rendering_manager",
"(",
"self",
".",
"index",
",",
"self",
".",
"team",
")",
"agent",
"."... | 44 | 12.285714 |
def get_env(name, default=None):
"""Get the environment variable or return exception"""
if name in os.environ:
return os.environ[name]
if default is not None:
return default
error_msg = "Set the {} env variable".format(name)
raise ImproperlyConfigured(error_msg) | [
"def",
"get_env",
"(",
"name",
",",
"default",
"=",
"None",
")",
":",
"if",
"name",
"in",
"os",
".",
"environ",
":",
"return",
"os",
".",
"environ",
"[",
"name",
"]",
"if",
"default",
"is",
"not",
"None",
":",
"return",
"default",
"error_msg",
"=",
... | 29.1 | 15.7 |
def bar(h1: Histogram1D, ax: Axes, *, errors: bool = False, **kwargs):
"""Bar plot of 1D histograms."""
show_stats = kwargs.pop("show_stats", False)
show_values = kwargs.pop("show_values", False)
value_format = kwargs.pop("value_format", None)
density = kwargs.pop("density", False)
cumulative = ... | [
"def",
"bar",
"(",
"h1",
":",
"Histogram1D",
",",
"ax",
":",
"Axes",
",",
"*",
",",
"errors",
":",
"bool",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"show_stats",
"=",
"kwargs",
".",
"pop",
"(",
"\"show_stats\"",
",",
"False",
")",
"show_val... | 35.945946 | 18 |
def start(self):
"""
Start the connection. This should be called after all
listeners have been registered. If this method is not called,
no frames will be received by the connection.
"""
self.running = True
self.attempt_connection()
receiver_thread = self.... | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"running",
"=",
"True",
"self",
".",
"attempt_connection",
"(",
")",
"receiver_thread",
"=",
"self",
".",
"create_thread_fc",
"(",
"self",
".",
"__receiver_loop",
")",
"receiver_thread",
".",
"name",
"=",
... | 43.272727 | 17.818182 |
def count_token_occurrences(cls, words):
"""
Creates a key/value set of word/count for a given sample of text
:param words: full list of all tokens, non-unique
:type words: list
:return: key/value pairs of words and their counts in the list
:rtype: dict
"""
... | [
"def",
"count_token_occurrences",
"(",
"cls",
",",
"words",
")",
":",
"counts",
"=",
"{",
"}",
"for",
"word",
"in",
"words",
":",
"if",
"word",
"in",
"counts",
":",
"counts",
"[",
"word",
"]",
"+=",
"1",
"else",
":",
"counts",
"[",
"word",
"]",
"="... | 30.25 | 16 |
def strip_bitmap_str(payload):
"""strip(8 byte) wlan.ba.bm
:payload: ctypes.structure
:return: str
bitmap
"""
bitmap = struct.unpack('BBBBBBBB', payload)
bitmap_str = ''
for elem in bitmap:
bitmap_str += format(elem, '08b')[::-1]
re... | [
"def",
"strip_bitmap_str",
"(",
"payload",
")",
":",
"bitmap",
"=",
"struct",
".",
"unpack",
"(",
"'BBBBBBBB'",
",",
"payload",
")",
"bitmap_str",
"=",
"''",
"for",
"elem",
"in",
"bitmap",
":",
"bitmap_str",
"+=",
"format",
"(",
"elem",
",",
"'08b'",
")"... | 29.545455 | 11.363636 |
def thread_safe(method):
""" wraps method with lock acquire/release cycle
decorator requires class instance to have field self.lock of type threading.Lock or threading.RLock """
@functools.wraps(method)
def _locker(self, *args, **kwargs):
assert hasattr(self, 'lock'), \
'thread_saf... | [
"def",
"thread_safe",
"(",
"method",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"method",
")",
"def",
"_locker",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"hasattr",
"(",
"self",
",",
"'lock'",
")",
",",
"'thre... | 37.809524 | 20.952381 |
def rotatePoints(points, rotationDegrees, pivotx=0, pivoty=0):
"""
Rotates each x and y tuple in `points`` by `rotationDegrees`. The points
are rotated around the origin by default, but can be rotated around another
pivot point by specifying `pivotx` and `pivoty`.
The points are rotated countercloc... | [
"def",
"rotatePoints",
"(",
"points",
",",
"rotationDegrees",
",",
"pivotx",
"=",
"0",
",",
"pivoty",
"=",
"0",
")",
":",
"rotationRadians",
"=",
"math",
".",
"radians",
"(",
"rotationDegrees",
"%",
"360",
")",
"for",
"x",
",",
"y",
"in",
"points",
":"... | 33.115385 | 25.884615 |
def deconv_stride2_multistep(x,
nbr_steps,
output_filters,
name=None,
reuse=None):
"""Use a deconvolution to upsample x by 2**`nbr_steps`.
Args:
x: a `Tensor` with shape `[batch, spatial, depth]`... | [
"def",
"deconv_stride2_multistep",
"(",
"x",
",",
"nbr_steps",
",",
"output_filters",
",",
"name",
"=",
"None",
",",
"reuse",
"=",
"None",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",
"default_name",
"=",
"\"deconv_stride2_multistep\"",
","... | 30.901639 | 17.163934 |
def is_bool(tg_type, inc_array=False):
"""Tells if the given tango type is boolean
:param tg_type: tango type
:type tg_type: :class:`tango.CmdArgType`
:param inc_array: (optional, default is False) determines if include array
in the list of checked types
:type inc_array: :py:o... | [
"def",
"is_bool",
"(",
"tg_type",
",",
"inc_array",
"=",
"False",
")",
":",
"global",
"_scalar_bool_types",
",",
"_array_bool_types",
"if",
"tg_type",
"in",
"_scalar_bool_types",
":",
"return",
"True",
"if",
"not",
"inc_array",
":",
"return",
"False",
"return",
... | 33.888889 | 14.777778 |
def status_mercurial(path, ignore_set, options):
"""Run hg status.
Returns a 2-element tuple:
* Text lines describing the status of the repository.
* Empty sequence of subrepos, since hg does not support them.
"""
lines = run(['hg', '--config', 'extensions.color=!', 'st'], cwd=path)
subrepo... | [
"def",
"status_mercurial",
"(",
"path",
",",
"ignore_set",
",",
"options",
")",
":",
"lines",
"=",
"run",
"(",
"[",
"'hg'",
",",
"'--config'",
",",
"'extensions.color=!'",
",",
"'st'",
"]",
",",
"cwd",
"=",
"path",
")",
"subrepos",
"=",
"(",
")",
"retu... | 39 | 18.8 |
def matches_rule(message, rule, destinations = None) :
"does Message message match against the specified rule."
if not isinstance(message, Message) :
raise TypeError("message must be a Message")
#end if
rule = unformat_rule(rule)
eavesdrop = rule.get("eavesdrop", "false") == "true"
def ... | [
"def",
"matches_rule",
"(",
"message",
",",
"rule",
",",
"destinations",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"message",
",",
"Message",
")",
":",
"raise",
"TypeError",
"(",
"\"message must be a Message\"",
")",
"#end if",
"rule",
"=",
"unf... | 32.251497 | 19.017964 |
def set_trace():
"""Call pdb.set_trace in the calling frame, first restoring
sys.stdout to the real output stream. Note that sys.stdout is NOT
reset to whatever it was before the call once pdb is done!
"""
import pdb
import sys
stdout = sys.stdout
sys.stdout = sys.__stdout__
pdb.Pdb(... | [
"def",
"set_trace",
"(",
")",
":",
"import",
"pdb",
"import",
"sys",
"stdout",
"=",
"sys",
".",
"stdout",
"sys",
".",
"stdout",
"=",
"sys",
".",
"__stdout__",
"pdb",
".",
"Pdb",
"(",
")",
".",
"set_trace",
"(",
"sys",
".",
"_getframe",
"(",
")",
".... | 34.6 | 16 |
def srfrec(body, longitude, latitude):
"""
Convert planetocentric latitude and longitude of a surface
point on a specified body to rectangular coordinates.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/srfrec_c.html
:param body: NAIF integer code of an extended body.
:type body: int
... | [
"def",
"srfrec",
"(",
"body",
",",
"longitude",
",",
"latitude",
")",
":",
"body",
"=",
"ctypes",
".",
"c_int",
"(",
"body",
")",
"longitude",
"=",
"ctypes",
".",
"c_double",
"(",
"longitude",
")",
"latitude",
"=",
"ctypes",
".",
"c_double",
"(",
"lati... | 36.636364 | 12.909091 |
def _DropCommonSuffixes(filename):
"""Drops common suffixes like _test.cc or -inl.h from filename.
For example:
>>> _DropCommonSuffixes('foo/foo-inl.h')
'foo/foo'
>>> _DropCommonSuffixes('foo/bar/foo.cc')
'foo/bar/foo'
>>> _DropCommonSuffixes('foo/foo_internal.h')
'foo/foo'
>>> _DropCom... | [
"def",
"_DropCommonSuffixes",
"(",
"filename",
")",
":",
"for",
"suffix",
"in",
"(",
"'test.cc'",
",",
"'regtest.cc'",
",",
"'unittest.cc'",
",",
"'inl.h'",
",",
"'impl.h'",
",",
"'internal.h'",
")",
":",
"if",
"(",
"filename",
".",
"endswith",
"(",
"suffix"... | 31.4 | 16.76 |
def hashfile(fname, blocksize=65536, count=0):
"""Compute md5 hex-hash of a file
Parameters
----------
fname: str
path to the file
blocksize: int
block size in bytes read from the file
(set to `0` to hash the entire file)
count: int
number of blocks read from the... | [
"def",
"hashfile",
"(",
"fname",
",",
"blocksize",
"=",
"65536",
",",
"count",
"=",
"0",
")",
":",
"hasher",
"=",
"hashlib",
".",
"md5",
"(",
")",
"fname",
"=",
"pathlib",
".",
"Path",
"(",
"fname",
")",
"with",
"fname",
".",
"open",
"(",
"'rb'",
... | 26.2 | 13.88 |
def publish(self):
"""
Iterate over the scheduler collections and apply any actions found
"""
try:
for collection in self.settings.get("scheduler").get("collections"):
yield self.publish_for_collection(collection)
except Exception as ex:
... | [
"def",
"publish",
"(",
"self",
")",
":",
"try",
":",
"for",
"collection",
"in",
"self",
".",
"settings",
".",
"get",
"(",
"\"scheduler\"",
")",
".",
"get",
"(",
"\"collections\"",
")",
":",
"yield",
"self",
".",
"publish_for_collection",
"(",
"collection",... | 33.2 | 20.2 |
def load(self):
"""
Load user configuration based on settings.
"""
# Must reverse because we want the sources assigned to higher-up Config instances
# to overrides sources assigned to lower Config instances.
for section in reversed(list(self.iter_sections(recursive=True,... | [
"def",
"load",
"(",
"self",
")",
":",
"# Must reverse because we want the sources assigned to higher-up Config instances",
"# to overrides sources assigned to lower Config instances.",
"for",
"section",
"in",
"reversed",
"(",
"list",
"(",
"self",
".",
"iter_sections",
"(",
"rec... | 39.4 | 20.066667 |
def file_name_increase(file_name, file_location):
"""
Function to increase a filename by a number 1
Args:
file_name: The name of file to check
file_location: The location of the file, derive from the os module
Returns: returns a good filename.
"""
add_one = 1
file_name_temp... | [
"def",
"file_name_increase",
"(",
"file_name",
",",
"file_location",
")",
":",
"add_one",
"=",
"1",
"file_name_temp",
"=",
"file_name",
"while",
"verify_file_exists",
"(",
"file_name_temp",
",",
"file_location",
")",
":",
"try",
":",
"name",
",",
"file_extension",... | 35.26087 | 19.782609 |
def get_subclasses(modulepath, parent_class):
"""given a module return all the parent_class subclasses that are found in
that module and any submodules.
:param modulepath: string, a path like foo.bar.che
:param parent_class: object, the class whose children you are looking for
:returns: set, all th... | [
"def",
"get_subclasses",
"(",
"modulepath",
",",
"parent_class",
")",
":",
"if",
"isinstance",
"(",
"modulepath",
",",
"ModuleType",
")",
":",
"modules",
"=",
"get_modules",
"(",
"modulepath",
".",
"__name__",
")",
"else",
":",
"modules",
"=",
"get_modules",
... | 36.1 | 20.25 |
def get_authorization(self, **kwargs):
"""Gets the authorization object for the view."""
if self.authorization is not None:
return self.authorization
auth_class = self.get_authorization_class()
auth_user = self.get_authorization_user()
auth_kwargs = {
'to... | [
"def",
"get_authorization",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"authorization",
"is",
"not",
"None",
":",
"return",
"self",
".",
"authorization",
"auth_class",
"=",
"self",
".",
"get_authorization_class",
"(",
")",
"auth_user"... | 34.722222 | 18.888889 |
def circle_intersection(self, p: "Point2", r: Union[int, float]) -> Set["Point2"]:
""" self is point1, p is point2, r is the radius for circles originating in both points
Used in ramp finding """
assert self != p
distanceBetweenPoints = self.distance_to(p)
assert r > distanceBetw... | [
"def",
"circle_intersection",
"(",
"self",
",",
"p",
":",
"\"Point2\"",
",",
"r",
":",
"Union",
"[",
"int",
",",
"float",
"]",
")",
"->",
"Set",
"[",
"\"Point2\"",
"]",
":",
"assert",
"self",
"!=",
"p",
"distanceBetweenPoints",
"=",
"self",
".",
"dista... | 56.695652 | 25.173913 |
def create_zone(server, token, domain, identifier, dtype, master=None):
"""Create zone records.
Arguments:
server: TonicDNS API server
token: TonicDNS API authentication token
domain: Specify domain name
identifier: Template ID
dtype: MASTER|SLAVE|NATI... | [
"def",
"create_zone",
"(",
"server",
",",
"token",
",",
"domain",
",",
"identifier",
",",
"dtype",
",",
"master",
"=",
"None",
")",
":",
"method",
"=",
"'PUT'",
"uri",
"=",
"'https://'",
"+",
"server",
"+",
"'/zone'",
"obj",
"=",
"JSONConverter",
"(",
... | 32 | 16.636364 |
def _hash_internal(method, salt, password):
"""Internal password hash helper. Supports plaintext without salt,
unsalted and salted passwords. In case salted passwords are used
hmac is used.
"""
if method == 'plain':
return password, method
if isinstance(password, text_type):
p... | [
"def",
"_hash_internal",
"(",
"method",
",",
"salt",
",",
"password",
")",
":",
"if",
"method",
"==",
"'plain'",
":",
"return",
"password",
",",
"method",
"if",
"isinstance",
"(",
"password",
",",
"text_type",
")",
":",
"password",
"=",
"password",
".",
... | 32.853659 | 16.317073 |
def register(self, key, **kwargs):
"""Registers metadata for a metric and returns a composite key"""
dimensions = dict((k, str(v)) for k, v in kwargs.items())
composite_key = self._composite_name(key, dimensions)
self._metadata[composite_key] = {
'metric': key,
'd... | [
"def",
"register",
"(",
"self",
",",
"key",
",",
"*",
"*",
"kwargs",
")",
":",
"dimensions",
"=",
"dict",
"(",
"(",
"k",
",",
"str",
"(",
"v",
")",
")",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
")",
"composite_key",
"=",
... | 41.444444 | 12.666667 |
def _open(filename, mode="r"):
"""
Universal open file facility.
With normal files, this function behaves as the open builtin.
With gzip-ed files, it decompress or compress according to the specified mode.
In addition, when filename is '-', it opens the standard input or output according to
the ... | [
"def",
"_open",
"(",
"filename",
",",
"mode",
"=",
"\"r\"",
")",
":",
"if",
"filename",
".",
"endswith",
"(",
"\".gz\"",
")",
":",
"return",
"GzipFile",
"(",
"filename",
",",
"mode",
",",
"COMPRESSION_LEVEL",
")",
"elif",
"filename",
"==",
"\"-\"",
":",
... | 35.947368 | 15.315789 |
def from_jwt(self, txt, keyjar, verify=True, **kwargs):
"""
Given a signed and/or encrypted JWT, verify its correctness and then
create a class instance from the content.
:param txt: The JWT
:param key: keys that might be used to decrypt and/or verify the
signature o... | [
"def",
"from_jwt",
"(",
"self",
",",
"txt",
",",
"keyjar",
",",
"verify",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"algarg",
"=",
"{",
"}",
"if",
"'encalg'",
"in",
"kwargs",
":",
"algarg",
"[",
"'alg'",
"]",
"=",
"kwargs",
"[",
"'encalg'",
... | 35.674699 | 18.807229 |
def from_files(cls, files, **options):
"""Create an APNG from multiple files.
This is a shortcut of::
im = APNG()
for file in files:
im.append_file(file, **options)
:arg list files: A list of filename. See :meth:`PNG.open`.
:arg dict options: Options for :class:`FrameControl`.
:rtype: APN... | [
"def",
"from_files",
"(",
"cls",
",",
"files",
",",
"*",
"*",
"options",
")",
":",
"im",
"=",
"cls",
"(",
")",
"for",
"file",
"in",
"files",
":",
"im",
".",
"append_file",
"(",
"file",
",",
"*",
"*",
"options",
")",
"return",
"im"
] | 23.058824 | 19 |
def check_number_status(self, number_id):
"""
Check if a number is valid/registered in the whatsapp service
:param number_id: number id
:return:
"""
number_status = self.wapi_functions.checkNumberStatus(number_id)
return NumberStatus(number_status, self) | [
"def",
"check_number_status",
"(",
"self",
",",
"number_id",
")",
":",
"number_status",
"=",
"self",
".",
"wapi_functions",
".",
"checkNumberStatus",
"(",
"number_id",
")",
"return",
"NumberStatus",
"(",
"number_status",
",",
"self",
")"
] | 33.666667 | 15.444444 |
def search_for_oath_code(hsm, key_handle, nonce, aead, user_code, interval=30,
tolerance=0):
"""
Try to validate an OATH TOTP OTP generated by a token whose secret key is
available to the YubiHSM through the AEAD.
The parameter `aead' is either a string, or an instance of YHSM_... | [
"def",
"search_for_oath_code",
"(",
"hsm",
",",
"key_handle",
",",
"nonce",
",",
"aead",
",",
"user_code",
",",
"interval",
"=",
"30",
",",
"tolerance",
"=",
"0",
")",
":",
"# timecounter is the lowest acceptable value based on tolerance",
"timecounter",
"=",
"timec... | 40.3125 | 26.8125 |
def step1(self, username, password):
"""First authentication step."""
self._check_initialized()
context = AtvSRPContext(
str(username), str(password),
prime=constants.PRIME_2048,
generator=constants.PRIME_2048_GEN)
self.session = SRPClientSession(
... | [
"def",
"step1",
"(",
"self",
",",
"username",
",",
"password",
")",
":",
"self",
".",
"_check_initialized",
"(",
")",
"context",
"=",
"AtvSRPContext",
"(",
"str",
"(",
"username",
")",
",",
"str",
"(",
"password",
")",
",",
"prime",
"=",
"constants",
"... | 41.666667 | 6.111111 |
def get_version(self, version_id=None):
"""Return specific version ``ObjectVersion`` instance or HEAD.
:param version_id: Version ID of the object.
:returns: :class:`~invenio_files_rest.models.ObjectVersion` instance or
HEAD of the stored object.
"""
return ObjectVer... | [
"def",
"get_version",
"(",
"self",
",",
"version_id",
"=",
"None",
")",
":",
"return",
"ObjectVersion",
".",
"get",
"(",
"bucket",
"=",
"self",
".",
"obj",
".",
"bucket",
",",
"key",
"=",
"self",
".",
"obj",
".",
"key",
",",
"version_id",
"=",
"versi... | 46.444444 | 15.888889 |
def _compute_diff(configured, expected):
'''Computes the differences between the actual config and the expected config'''
diff = {
'add': {},
'update': {},
'remove': {}
}
configured_users = set(configured.keys())
expected_users = set(expected.keys())
add_usernames = e... | [
"def",
"_compute_diff",
"(",
"configured",
",",
"expected",
")",
":",
"diff",
"=",
"{",
"'add'",
":",
"{",
"}",
",",
"'update'",
":",
"{",
"}",
",",
"'remove'",
":",
"{",
"}",
"}",
"configured_users",
"=",
"set",
"(",
"configured",
".",
"keys",
"(",
... | 30.210526 | 23.736842 |
def _add_interface(self, interface_id, mgt=None, **kw):
"""
Add the Cluster interface. If adding a cluster interface to
an existing node, retrieve the existing interface and call
this method. Use the supported format for defining an interface.
"""
_kw = copy.deepcopy(kw) ... | [
"def",
"_add_interface",
"(",
"self",
",",
"interface_id",
",",
"mgt",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"_kw",
"=",
"copy",
".",
"deepcopy",
"(",
"kw",
")",
"# Preserve original kw, especially lists",
"mgt",
"=",
"mgt",
"if",
"mgt",
"else",
"{... | 43.540541 | 19.459459 |
def fit(self, X, y=None):
"""
Fits the learning curve with the wrapped model to the specified data.
Draws training and test score curves and saves the scores to the
estimator.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Trainin... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
")",
":",
"# arguments to pass to sk_learning_curve",
"sklc_kwargs",
"=",
"{",
"key",
":",
"self",
".",
"get_params",
"(",
")",
"[",
"key",
"]",
"for",
"key",
"in",
"(",
"'groups'",
",",
"'tra... | 38.893617 | 24.042553 |
def Import(context, request):
""" Read analysis results from an XML string
"""
errors = []
logs = []
# Do import stuff here
logs.append("Generic XML Import is not available")
results = {'errors': errors, 'log': logs}
return json.dumps(results) | [
"def",
"Import",
"(",
"context",
",",
"request",
")",
":",
"errors",
"=",
"[",
"]",
"logs",
"=",
"[",
"]",
"# Do import stuff here",
"logs",
".",
"append",
"(",
"\"Generic XML Import is not available\"",
")",
"results",
"=",
"{",
"'errors'",
":",
"errors",
"... | 24.272727 | 16.909091 |
def cast2theano_var(self, array_like, name=None):
'''Cast `numpy.ndarray` into `theano.tensor` keeping `dtype` and `ndim`
compatible
'''
# extract the information of the input value
array = np.asarray(array_like)
args = (name, array.dtype)
ndim = array.ndim
... | [
"def",
"cast2theano_var",
"(",
"self",
",",
"array_like",
",",
"name",
"=",
"None",
")",
":",
"# extract the information of the input value",
"array",
"=",
"np",
".",
"asarray",
"(",
"array_like",
")",
"args",
"=",
"(",
"name",
",",
"array",
".",
"dtype",
")... | 32.954545 | 16.227273 |
def constrained_by(self):
"""
returns a list of parameters that constrain this parameter
"""
if self._is_constraint is None:
return []
params = []
for var in self.is_constraint._vars:
param = var.get_parameter()
if param.uniqueid != sel... | [
"def",
"constrained_by",
"(",
"self",
")",
":",
"if",
"self",
".",
"_is_constraint",
"is",
"None",
":",
"return",
"[",
"]",
"params",
"=",
"[",
"]",
"for",
"var",
"in",
"self",
".",
"is_constraint",
".",
"_vars",
":",
"param",
"=",
"var",
".",
"get_p... | 31.583333 | 9.75 |
def absent(name, domain, user=None):
'''
Make sure the defaults value is absent
name
The key of the given domain to remove
domain
The name of the domain to remove from
user
The user to write the defaults to
'''
ret = {'name': name,
'result': True,
... | [
"def",
"absent",
"(",
"name",
",",
"domain",
",",
"user",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"}",
"}",
"out",
"=",
"__salt__",
"[",... | 21.857143 | 25.714286 |
def roll_time_series(df_or_dict, column_id, column_sort, column_kind, rolling_direction, max_timeshift=None):
"""
This method creates sub windows of the time series. It rolls the (sorted) data frames for each kind and each id
separately in the "time" domain (which is represented by the sort order of the sor... | [
"def",
"roll_time_series",
"(",
"df_or_dict",
",",
"column_id",
",",
"column_sort",
",",
"column_kind",
",",
"rolling_direction",
",",
"max_timeshift",
"=",
"None",
")",
":",
"if",
"rolling_direction",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"Rolling directi... | 45.432203 | 27.584746 |
def parse_namespacepath(parser, event, node): #pylint: disable=unused-argument
"""Parse namespace path element and return tuple of
host and namespace
<!ELEMENT NAMESPACEPATH (HOST, LOCALNAMESPACEPATH)>
"""
(next_event, next_node) = six.next(parser)
if not _is_start(next_event, next_... | [
"def",
"parse_namespacepath",
"(",
"parser",
",",
"event",
",",
"node",
")",
":",
"#pylint: disable=unused-argument",
"(",
"next_event",
",",
"next_node",
")",
"=",
"six",
".",
"next",
"(",
"parser",
")",
"if",
"not",
"_is_start",
"(",
"next_event",
",",
"ne... | 31.62963 | 23.62963 |
def on_post(self, req, resp):
"""
Send a POST request with id/nic/interval/filter/iters and it will start
a container for collection with those specifications
"""
resp.content_type = falcon.MEDIA_TEXT
resp.status = falcon.HTTP_200
# verify payload is in the corre... | [
"def",
"on_post",
"(",
"self",
",",
"req",
",",
"resp",
")",
":",
"resp",
".",
"content_type",
"=",
"falcon",
".",
"MEDIA_TEXT",
"resp",
".",
"status",
"=",
"falcon",
".",
"HTTP_200",
"# verify payload is in the correct format",
"# default to no filter",
"payload"... | 37.974026 | 21.974026 |
def indices(self, fit):
"""return the set of indices to be reevaluated for noise
measurement.
Given the first values are the earliest, this is a useful policy also
with a time changing objective.
"""
## meta_parameters.noise_reeval_multiplier == 1.0
lam_reev = 1... | [
"def",
"indices",
"(",
"self",
",",
"fit",
")",
":",
"## meta_parameters.noise_reeval_multiplier == 1.0",
"lam_reev",
"=",
"1.0",
"*",
"(",
"self",
".",
"lam_reeval",
"if",
"self",
".",
"lam_reeval",
"else",
"2",
"+",
"len",
"(",
"fit",
")",
"/",
"20",
")"... | 47.903226 | 22 |
def _get_string(data, position, obj_end, dummy):
"""Decode a BSON string to python unicode string."""
length = _UNPACK_INT(data[position:position + 4])[0]
position += 4
if length < 1 or obj_end - position < length:
raise InvalidBSON("invalid string length")
end = position + length - 1
if... | [
"def",
"_get_string",
"(",
"data",
",",
"position",
",",
"obj_end",
",",
"dummy",
")",
":",
"length",
"=",
"_UNPACK_INT",
"(",
"data",
"[",
"position",
":",
"position",
"+",
"4",
"]",
")",
"[",
"0",
"]",
"position",
"+=",
"4",
"if",
"length",
"<",
... | 46.1 | 11.7 |
def create(self, *args, **kwargs):
"""Create a new activity belonging to this subprocess.
See :func:`pykechain.Client.create_activity` for available parameters.
:raises IllegalArgumentError: if the `Activity` is not a `SUBPROCESS`.
:raises APIError: if an Error occurs.
"""
... | [
"def",
"create",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"activity_type",
"!=",
"ActivityType",
".",
"SUBPROCESS",
":",
"raise",
"IllegalArgumentError",
"(",
"\"One can only create a task under a subprocess.\"",
")",
... | 47.454545 | 23.727273 |
def read(sensor, pin, platform=None):
"""Read DHT sensor of specified sensor type (DHT11, DHT22, or AM2302) on
specified pin and return a tuple of humidity (as a floating point value
in percent) and temperature (as a floating point value in Celsius). Note that
because the sensor requires strict timing t... | [
"def",
"read",
"(",
"sensor",
",",
"pin",
",",
"platform",
"=",
"None",
")",
":",
"if",
"sensor",
"not",
"in",
"SENSORS",
":",
"raise",
"ValueError",
"(",
"'Expected DHT11, DHT22, or AM2302 sensor value.'",
")",
"if",
"platform",
"is",
"None",
":",
"platform",... | 58.823529 | 23.352941 |
def wrap(self, row: Union[Mapping[str, Any], Sequence[Any]]):
"""Return row tuple for row."""
return (
self.dataclass(
**{
ident: row[column_name]
for ident, column_name in self.ids_and_column_names.items()
}
... | [
"def",
"wrap",
"(",
"self",
",",
"row",
":",
"Union",
"[",
"Mapping",
"[",
"str",
",",
"Any",
"]",
",",
"Sequence",
"[",
"Any",
"]",
"]",
")",
":",
"return",
"(",
"self",
".",
"dataclass",
"(",
"*",
"*",
"{",
"ident",
":",
"row",
"[",
"column_n... | 35.571429 | 20.642857 |
def find_executable(executable_name):
"""Tries to find executable in PATH environment
It uses ``shutil.which`` method in Python3 and
``distutils.spawn.find_executable`` method in Python2.7 to find the
absolute path to the 'name' executable.
:param executable_name: name of the executable
:return... | [
"def",
"find_executable",
"(",
"executable_name",
")",
":",
"if",
"six",
".",
"PY3",
":",
"executable_abs",
"=",
"shutil",
".",
"which",
"(",
"executable_name",
")",
"else",
":",
"import",
"distutils",
".",
"spawn",
"executable_abs",
"=",
"distutils",
".",
"... | 37.125 | 19 |
def _expand_overlap(dna, oligo_indices, index, oligos, length_max):
'''Given an overlap to increase, increases smaller oligo.
:param dna: Sequence being split into oligos.
:type dna: coral.DNA
:param oligo_indices: index of oligo starts and stops
:type oligo_indices: list
:param index: index of... | [
"def",
"_expand_overlap",
"(",
"dna",
",",
"oligo_indices",
",",
"index",
",",
"oligos",
",",
"length_max",
")",
":",
"left_len",
"=",
"len",
"(",
"oligos",
"[",
"index",
"]",
")",
"right_len",
"=",
"len",
"(",
"oligos",
"[",
"index",
"+",
"1",
"]",
... | 35.447368 | 20.394737 |
def sanitize_filename(filename):
"""
Make sure filenames are valid paths.
Returns:
str:
"""
sanitized_filename = re.sub(r'[/\\:*?"<>|]', '-', filename)
sanitized_filename = sanitized_filename.replace('&', 'and')
sanitized_filename = sanitized_filename.replace('"', '')
sanitized_... | [
"def",
"sanitize_filename",
"(",
"filename",
")",
":",
"sanitized_filename",
"=",
"re",
".",
"sub",
"(",
"r'[/\\\\:*?\"<>|]'",
",",
"'-'",
",",
"filename",
")",
"sanitized_filename",
"=",
"sanitized_filename",
".",
"replace",
"(",
"'&'",
",",
"'and'",
")",
"sa... | 32.473684 | 19.526316 |
def setdbo(self, bond1, bond2, dboval):
"""Set the double bond orientation for bond1 and bond2
based on this bond"""
# this bond must be a double bond
if self.bondtype != 2:
raise FrownsError("To set double bond order, center bond must be double!")
assert dboval in [D... | [
"def",
"setdbo",
"(",
"self",
",",
"bond1",
",",
"bond2",
",",
"dboval",
")",
":",
"# this bond must be a double bond",
"if",
"self",
".",
"bondtype",
"!=",
"2",
":",
"raise",
"FrownsError",
"(",
"\"To set double bond order, center bond must be double!\"",
")",
"ass... | 47.333333 | 15.666667 |
def assert_ge(left, right, message=None, extra=None):
"""Raises an AssertionError if left_hand < right_hand."""
assert left >= right, _assert_fail_message(message, left, right, "<", extra) | [
"def",
"assert_ge",
"(",
"left",
",",
"right",
",",
"message",
"=",
"None",
",",
"extra",
"=",
"None",
")",
":",
"assert",
"left",
">=",
"right",
",",
"_assert_fail_message",
"(",
"message",
",",
"left",
",",
"right",
",",
"\"<\"",
",",
"extra",
")"
] | 64.666667 | 17.666667 |
def translate(curve, z0):
"""Shifts the curve by the complex quantity z such that
translate(curve, z0).point(t) = curve.point(t) + z0"""
if isinstance(curve, Path):
return Path(*[translate(seg, z0) for seg in curve])
elif is_bezier_segment(curve):
return bpoints2bezier([bpt + z0 for bpt ... | [
"def",
"translate",
"(",
"curve",
",",
"z0",
")",
":",
"if",
"isinstance",
"(",
"curve",
",",
"Path",
")",
":",
"return",
"Path",
"(",
"*",
"[",
"translate",
"(",
"seg",
",",
"z0",
")",
"for",
"seg",
"in",
"curve",
"]",
")",
"elif",
"is_bezier_segm... | 48.666667 | 17 |
def AgregarDatoPDF(self, campo, valor, pagina='T'):
"Agrego un dato a la factura (internamente)"
# corrijo path relativo para las imágenes (compatibilidad hacia atrás):
if campo == 'fondo' and valor.startswith(self.InstallDir):
if not os.path.exists(valor):
valor = os... | [
"def",
"AgregarDatoPDF",
"(",
"self",
",",
"campo",
",",
"valor",
",",
"pagina",
"=",
"'T'",
")",
":",
"# corrijo path relativo para las imágenes (compatibilidad hacia atrás):",
"if",
"campo",
"==",
"'fondo'",
"and",
"valor",
".",
"startswith",
"(",
"self",
".",
"... | 54.555556 | 20.777778 |
def get_sha(self) -> str:
"""
:return: SHA of the latest commit
:rtype: str
"""
current_sha: str = self.repo.head.commit.hexsha
LOGGER.debug('current commit SHA: %s', current_sha)
return current_sha | [
"def",
"get_sha",
"(",
"self",
")",
"->",
"str",
":",
"current_sha",
":",
"str",
"=",
"self",
".",
"repo",
".",
"head",
".",
"commit",
".",
"hexsha",
"LOGGER",
".",
"debug",
"(",
"'current commit SHA: %s'",
",",
"current_sha",
")",
"return",
"current_sha"
... | 30.875 | 10.625 |
def edge_nei_overlap_bu(CIJ):
'''
This function determines the neighbors of two nodes that are linked by
an edge, and then computes their overlap. Connection matrix must be
binary and directed. Entries of 'EC' that are 'inf' indicate that no
edge is present. Entries of 'EC' that are 0 denote "loc... | [
"def",
"edge_nei_overlap_bu",
"(",
"CIJ",
")",
":",
"ik",
",",
"jk",
"=",
"np",
".",
"where",
"(",
"CIJ",
")",
"lel",
"=",
"len",
"(",
"CIJ",
"[",
"ik",
",",
"jk",
"]",
")",
"n",
"=",
"len",
"(",
"CIJ",
")",
"deg",
"=",
"degrees_und",
"(",
"C... | 32.644444 | 21.222222 |
def report(self, simulation, state):
"""Generate a report.
Parameters
----------
simulation : Simulation
The Simulation to generate a report for
state : State
The current state of the simulation
"""
if not self._initialized:
se... | [
"def",
"report",
"(",
"self",
",",
"simulation",
",",
"state",
")",
":",
"if",
"not",
"self",
".",
"_initialized",
":",
"self",
".",
"_initialized",
"=",
"True",
"self",
".",
"_steps",
"[",
"0",
"]",
"+=",
"self",
".",
"interval",
"positions",
"=",
"... | 31.272727 | 15 |
def _get_scaled_image(self, resource):
"""
Get scaled watermark image
:param resource: Image.Image
:return: Image.Image
"""
image = self._get_image()
original_width, original_height = resource.size
k = image.size[0] / float(image.size[1])
if imag... | [
"def",
"_get_scaled_image",
"(",
"self",
",",
"resource",
")",
":",
"image",
"=",
"self",
".",
"_get_image",
"(",
")",
"original_width",
",",
"original_height",
"=",
"resource",
".",
"size",
"k",
"=",
"image",
".",
"size",
"[",
"0",
"]",
"/",
"float",
... | 31.47619 | 16.904762 |
def describe_subnet(subnet_id=None, subnet_name=None, region=None,
key=None, keyid=None, profile=None):
'''
Given a subnet id or name, describe its properties.
Returns a dictionary of interesting properties.
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
... | [
"def",
"describe_subnet",
"(",
"subnet_id",
"=",
"None",
",",
"subnet_name",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"subnet",
"=",
"_get_resource",... | 40.194444 | 30.083333 |
def merge_conf_file(self, result, conf_file_path):
"Merge a configuration in file with current configuration"
conf = parse_conf_file(conf_file_path)
conf_file_name = os.path.splitext(os.path.basename(conf_file_path))[0]
result_part = result
if not conf_file_name in File.TOP_LEVE... | [
"def",
"merge_conf_file",
"(",
"self",
",",
"result",
",",
"conf_file_path",
")",
":",
"conf",
"=",
"parse_conf_file",
"(",
"conf_file_path",
")",
"conf_file_name",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"con... | 42.875 | 17.25 |
def clip_by_value(t, clip_value_min, clip_value_max, name=None):
"""
A wrapper for clip_by_value that casts the clipping range if needed.
"""
def cast_clip(clip):
"""
Cast clipping range argument if needed.
"""
if t.dtype in (tf.float32, tf.float64):
if hasattr(clip, 'dtype'):
# Co... | [
"def",
"clip_by_value",
"(",
"t",
",",
"clip_value_min",
",",
"clip_value_max",
",",
"name",
"=",
"None",
")",
":",
"def",
"cast_clip",
"(",
"clip",
")",
":",
"\"\"\"\n Cast clipping range argument if needed.\n \"\"\"",
"if",
"t",
".",
"dtype",
"in",
"(",
... | 32.1 | 12.8 |
def generate_john_smith_chunk(path_to_original):
'''
This _looks_ like a Chunk only in that it generates StreamItem
instances when iterated upon.
'''
## Every StreamItem has a stream_time property. It usually comes
## from the document creation time. Here, we assume the JS corpus
## was cr... | [
"def",
"generate_john_smith_chunk",
"(",
"path_to_original",
")",
":",
"## Every StreamItem has a stream_time property. It usually comes",
"## from the document creation time. Here, we assume the JS corpus",
"## was created at one moment at the end of 1998:",
"creation_time",
"=",
"'1998-12-... | 43.253521 | 23.253521 |
def results(self):
"""Print results
"""
print("")
per = int(round((float(self.cf) / (self.cf + self.cn)) * 100))
if per > 90:
color = self.meta.color["GREEN"]
elif per < 90 and per > 60:
color = self.meta.color["YELLOW"]
elif per < 60:
... | [
"def",
"results",
"(",
"self",
")",
":",
"print",
"(",
"\"\"",
")",
"per",
"=",
"int",
"(",
"round",
"(",
"(",
"float",
"(",
"self",
".",
"cf",
")",
"/",
"(",
"self",
".",
"cf",
"+",
"self",
".",
"cn",
")",
")",
"*",
"100",
")",
")",
"if",
... | 37.666667 | 13.238095 |
def format_data_type(self, data_type):
"""Helper function to format a data type.
This returns the name if it's a struct or union, otherwise
(i.e. for primitive types) it renders the name and the
parameters.
"""
s = data_type.name
for type_class, key_list in self.... | [
"def",
"format_data_type",
"(",
"self",
",",
"data_type",
")",
":",
"s",
"=",
"data_type",
".",
"name",
"for",
"type_class",
",",
"key_list",
"in",
"self",
".",
"_data_type_map",
":",
"if",
"isinstance",
"(",
"data_type",
",",
"type_class",
")",
":",
"args... | 38.555556 | 13.888889 |
def noise4d(self, x, y, z, w):
"""
Generate 4D OpenSimplex noise from X,Y,Z,W coordinates.
"""
# Place input coordinates on simplectic honeycomb.
stretch_offset = (x + y + z + w) * STRETCH_CONSTANT_4D
xs = x + stretch_offset
ys = y + stretch_offset
zs = z ... | [
"def",
"noise4d",
"(",
"self",
",",
"x",
",",
"y",
",",
"z",
",",
"w",
")",
":",
"# Place input coordinates on simplectic honeycomb.",
"stretch_offset",
"=",
"(",
"x",
"+",
"y",
"+",
"z",
"+",
"w",
")",
"*",
"STRETCH_CONSTANT_4D",
"xs",
"=",
"x",
"+",
... | 40.446309 | 17.691275 |
def is_pyclustering_instance(model):
"""
Checks if the clustering.rst algorithm belongs to pyclustering
:param model: the clustering.rst algorithm model
:return: the truth value (Boolean)
"""
return any(isinstance(model, i) for i in [xmeans, clarans, rock, optics]) | [
"def",
"is_pyclustering_instance",
"(",
"model",
")",
":",
"return",
"any",
"(",
"isinstance",
"(",
"model",
",",
"i",
")",
"for",
"i",
"in",
"[",
"xmeans",
",",
"clarans",
",",
"rock",
",",
"optics",
"]",
")"
] | 38.375 | 16.625 |
def _mdens_deriv(self,m):
"""Derivative of the density as a function of m"""
return -self.a3*(self.a+3.*m)/m**2/(self.a+m)**3 | [
"def",
"_mdens_deriv",
"(",
"self",
",",
"m",
")",
":",
"return",
"-",
"self",
".",
"a3",
"*",
"(",
"self",
".",
"a",
"+",
"3.",
"*",
"m",
")",
"/",
"m",
"**",
"2",
"/",
"(",
"self",
".",
"a",
"+",
"m",
")",
"**",
"3"
] | 46.333333 | 10.333333 |
def parse(
self,
value: str,
type_: typing.Type[typing.Any] = str,
subtype: typing.Type[typing.Any] = str,
) -> typing.Any:
"""
Parse value from string.
Convert :code:`value` to
.. code-block:: python
>>> parser = Config()
>>> ... | [
"def",
"parse",
"(",
"self",
",",
"value",
":",
"str",
",",
"type_",
":",
"typing",
".",
"Type",
"[",
"typing",
".",
"Any",
"]",
"=",
"str",
",",
"subtype",
":",
"typing",
".",
"Type",
"[",
"typing",
".",
"Any",
"]",
"=",
"str",
",",
")",
"->",... | 26.97619 | 17.261905 |
def __git_add(args=''):
"""
Add files to staging.
The function call will return 0 if the command success.
"""
command = ['git', 'add', '.']
Shell.msg('Adding files...')
if APISettings.DEBUG:
Git.__debug(command, True)
for key in args:
... | [
"def",
"__git_add",
"(",
"args",
"=",
"''",
")",
":",
"command",
"=",
"[",
"'git'",
",",
"'add'",
",",
"'.'",
"]",
"Shell",
".",
"msg",
"(",
"'Adding files...'",
")",
"if",
"APISettings",
".",
"DEBUG",
":",
"Git",
".",
"__debug",
"(",
"command",
",",... | 24.8125 | 14.4375 |
def read_named_socket(self, socket_name, socket_type):
"""A multi-tenant, named alternative to ProcessManager.socket."""
return self.read_metadata_by_name(self._name, 'socket_{}'.format(socket_name), socket_type) | [
"def",
"read_named_socket",
"(",
"self",
",",
"socket_name",
",",
"socket_type",
")",
":",
"return",
"self",
".",
"read_metadata_by_name",
"(",
"self",
".",
"_name",
",",
"'socket_{}'",
".",
"format",
"(",
"socket_name",
")",
",",
"socket_type",
")"
] | 72.666667 | 23 |
def lowercase(state):
"""Convert all column names to their lower case versions to improve robustness
:Example:
Suppose we are testing the following SELECT statements
* solution: ``SELECT artist_id as id FROM artists``
* student : ``SELECT artist_id as ID FROM artists``
We... | [
"def",
"lowercase",
"(",
"state",
")",
":",
"return",
"state",
".",
"to_child",
"(",
"student_result",
"=",
"{",
"k",
".",
"lower",
"(",
")",
":",
"v",
"for",
"k",
",",
"v",
"in",
"state",
".",
"student_result",
".",
"items",
"(",
")",
"}",
",",
... | 33.130435 | 25 |
def parse_quantity(string):
"""
Parse quantity allows to convert the value in the resources spec like:
resources:
requests:
cpu: "100m"
memory": "200Mi"
limits:
memory: "300Mi"
:param string: str
:return: float
"""
... | [
"def",
"parse_quantity",
"(",
"string",
")",
":",
"number",
",",
"unit",
"=",
"''",
",",
"''",
"for",
"char",
"in",
"string",
":",
"if",
"char",
".",
"isdigit",
"(",
")",
"or",
"char",
"==",
"'.'",
":",
"number",
"+=",
"char",
"else",
":",
"unit",
... | 28.105263 | 14.526316 |
def set_dtreat_indt(self, t=None, indt=None):
""" Store the desired index array for the time vector
If an array of indices (refering to self.ddataRef['t'] is not provided,
uses self.select_t(t=t) to produce it
"""
lC = [indt is not None, t is not None]
if all(lC):
... | [
"def",
"set_dtreat_indt",
"(",
"self",
",",
"t",
"=",
"None",
",",
"indt",
"=",
"None",
")",
":",
"lC",
"=",
"[",
"indt",
"is",
"not",
"None",
",",
"t",
"is",
"not",
"None",
"]",
"if",
"all",
"(",
"lC",
")",
":",
"msg",
"=",
"\"Please provide eit... | 33.777778 | 17.111111 |
def set_state(self, color_hex):
"""
:param color_hex: a hex string indicating the color of the porkfolio nose
:return: nothing
From the api...
"the color of the nose is not in the desired_state
but on the object itself."
"""
root_name = self.json_s... | [
"def",
"set_state",
"(",
"self",
",",
"color_hex",
")",
":",
"root_name",
"=",
"self",
".",
"json_state",
".",
"get",
"(",
"'piggy_bank_id'",
",",
"self",
".",
"name",
"(",
")",
")",
"response",
"=",
"self",
".",
"api_interface",
".",
"set_device_state",
... | 40.153846 | 14.615385 |
def delete(filething):
""" delete(filething)
Arguments:
filething (filething)
Raises:
mutagen.MutagenError
Remove tags from a file.
"""
t = OggOpus(filething)
filething.fileobj.seek(0)
t.delete(filething) | [
"def",
"delete",
"(",
"filething",
")",
":",
"t",
"=",
"OggOpus",
"(",
"filething",
")",
"filething",
".",
"fileobj",
".",
"seek",
"(",
"0",
")",
"t",
".",
"delete",
"(",
"filething",
")"
] | 17.285714 | 19.285714 |
def date_range_for_webtrends(cls, start_at=None, end_at=None):
"""
Get the day dates in between start and end formatted for query.
This returns dates inclusive e.g. final day is (end_at, end_at+1 day)
"""
if start_at and end_at:
start_date = cls.parse_standard_date_st... | [
"def",
"date_range_for_webtrends",
"(",
"cls",
",",
"start_at",
"=",
"None",
",",
"end_at",
"=",
"None",
")",
":",
"if",
"start_at",
"and",
"end_at",
":",
"start_date",
"=",
"cls",
".",
"parse_standard_date_string_to_date",
"(",
"start_at",
")",
"end_date",
"=... | 45.1 | 17.2 |
def get_default_bios_settings(self, only_allowed_settings=True):
"""Get default BIOS settings.
:param: only_allowed_settings: True when only allowed BIOS settings
are to be returned. If False, All the BIOS settings supported
by iLO are returned.
:return: a dictio... | [
"def",
"get_default_bios_settings",
"(",
"self",
",",
"only_allowed_settings",
"=",
"True",
")",
":",
"headers_bios",
",",
"bios_uri",
",",
"bios_settings",
"=",
"self",
".",
"_check_bios_resource",
"(",
")",
"# Get the BaseConfig resource.",
"try",
":",
"base_config_... | 43.585366 | 20.560976 |
def _splitHeaders(headers):
"""
Split an HTTP header whose components are separated with commas.
Each component is then split on semicolons and the component arguments
converted into a `dict`.
@return: `list` of 2-`tuple` of `bytes`, `dict`
@return: List of header arguments and mapping of comp... | [
"def",
"_splitHeaders",
"(",
"headers",
")",
":",
"return",
"[",
"cgi",
".",
"parse_header",
"(",
"value",
")",
"for",
"value",
"in",
"chain",
".",
"from_iterable",
"(",
"s",
".",
"split",
"(",
"','",
")",
"for",
"s",
"in",
"headers",
"if",
"s",
")",... | 33.6 | 18 |
def group_join(
self,
inner_enumerable,
outer_key=lambda x: x,
inner_key=lambda x: x,
result_func=lambda x: x
):
"""
Return enumerable of group join between two enumerables
:param inner_enumerable: inner enumerable to join to self
... | [
"def",
"group_join",
"(",
"self",
",",
"inner_enumerable",
",",
"outer_key",
"=",
"lambda",
"x",
":",
"x",
",",
"inner_key",
"=",
"lambda",
"x",
":",
"x",
",",
"result_func",
"=",
"lambda",
"x",
":",
"x",
")",
":",
"if",
"not",
"isinstance",
"(",
"in... | 35.111111 | 17.611111 |
def ordinal_float(dt):
"""Like datetime.ordinal, but rather than integer allows fractional days (so float not ordinal at all)
Similar to the Microsoft Excel numerical representation of a datetime object
>>> ordinal_float(datetime.datetime(1970, 1, 1))
719163.0
>>> ordinal_float(datetime.datetime(1... | [
"def",
"ordinal_float",
"(",
"dt",
")",
":",
"try",
":",
"return",
"dt",
".",
"toordinal",
"(",
")",
"+",
"(",
"(",
"(",
"(",
"dt",
".",
"microsecond",
"/",
"1000000.",
")",
"+",
"dt",
".",
"second",
")",
"/",
"60.",
"+",
"dt",
".",
"minute",
"... | 39.85 | 23.7 |
def move(self, destination=None, position=None, save=False):
""" Moves this node and places it as a child node of the `destination`
:class:`CTENode` (or makes it a root node if `destination` is
``None``).
Optionally, `position` can be a callable which is invoked prior to
... | [
"def",
"move",
"(",
"self",
",",
"destination",
"=",
"None",
",",
"position",
"=",
"None",
",",
"save",
"=",
"False",
")",
":",
"return",
"self",
".",
"__class__",
".",
"objects",
".",
"move",
"(",
"self",
",",
"destination",
",",
"position",
",",
"s... | 47.851852 | 27.444444 |
async def get_power_parameters_for(
cls, system_ids: typing.Sequence[str]):
"""
Get a list of power parameters for specified systems.
*WARNING*: This method is considered 'alpha' and may be modified
in future.
:param system_ids: The system IDs to get power parameters... | [
"async",
"def",
"get_power_parameters_for",
"(",
"cls",
",",
"system_ids",
":",
"typing",
".",
"Sequence",
"[",
"str",
"]",
")",
":",
"if",
"len",
"(",
"system_ids",
")",
"==",
"0",
":",
"return",
"{",
"}",
"data",
"=",
"await",
"cls",
".",
"_handler",... | 35.769231 | 17.923077 |
def get_data_range(self, arr=None, preference='cell'):
"""Get the non-NaN min and max of a named scalar array
Parameters
----------
arr : str, np.ndarray, optional
The name of the array to get the range. If None, the active scalar
is used
preference : st... | [
"def",
"get_data_range",
"(",
"self",
",",
"arr",
"=",
"None",
",",
"preference",
"=",
"'cell'",
")",
":",
"if",
"arr",
"is",
"None",
":",
"# use active scalar array",
"_",
",",
"arr",
"=",
"self",
".",
"active_scalar_info",
"if",
"isinstance",
"(",
"arr",... | 36.875 | 16.833333 |
def getPostStates(self):
'''
Calculates end-of-period assets for each consumer of this type.
Parameters
----------
None
Returns
-------
None
'''
self.aLvlNow = self.mLvlNow - self.cLvlNow - self.MedPriceNow*self.MedNow
return None | [
"def",
"getPostStates",
"(",
"self",
")",
":",
"self",
".",
"aLvlNow",
"=",
"self",
".",
"mLvlNow",
"-",
"self",
".",
"cLvlNow",
"-",
"self",
".",
"MedPriceNow",
"*",
"self",
".",
"MedNow",
"return",
"None"
] | 21.928571 | 28.357143 |
def write(self, b):
"""Write bytes to buffer."""
self._checkClosed()
if isinstance(b, str):
raise TypeError("can't write str to binary stream")
with self._write_lock:
self._write_buf.extend(b)
self._flush_unlocked()
return len(b) | [
"def",
"write",
"(",
"self",
",",
"b",
")",
":",
"self",
".",
"_checkClosed",
"(",
")",
"if",
"isinstance",
"(",
"b",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"can't write str to binary stream\"",
")",
"with",
"self",
".",
"_write_lock",
":",
"... | 30.1 | 14.1 |
def _reset(self, index, total, percentage_step, length):
"""Resets to the progressbar to start a new one"""
self._start_time = datetime.datetime.now()
self._start_index = index
self._current_index = index
self._percentage_step = percentage_step
self._total = float(total)
... | [
"def",
"_reset",
"(",
"self",
",",
"index",
",",
"total",
",",
"percentage_step",
",",
"length",
")",
":",
"self",
".",
"_start_time",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"self",
".",
"_start_index",
"=",
"index",
"self",
".",
"_cur... | 46.636364 | 10.272727 |
def as_string(self, default_from=None):
"""Creates the email"""
encoding = self.charset or 'utf-8'
attachments = self.attachments or []
if len(attachments) == 0 and not self.html:
# No html content and zero attachments means plain text
msg = self._mimetext(self... | [
"def",
"as_string",
"(",
"self",
",",
"default_from",
"=",
"None",
")",
":",
"encoding",
"=",
"self",
".",
"charset",
"or",
"'utf-8'",
"attachments",
"=",
"self",
".",
"attachments",
"or",
"[",
"]",
"if",
"len",
"(",
"attachments",
")",
"==",
"0",
"and... | 35.826087 | 20.275362 |
def disconnect(self, close=True):
"""
Logs off the session
:param close: Will close all tree connects in a session
"""
if not self._connected:
# already disconnected so let's return
return
if close:
for open in list(self.open_table.va... | [
"def",
"disconnect",
"(",
"self",
",",
"close",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"_connected",
":",
"# already disconnected so let's return",
"return",
"if",
"close",
":",
"for",
"open",
"in",
"list",
"(",
"self",
".",
"open_table",
".",
"v... | 34.9 | 18.833333 |
def get_prices(self, instruments, stream=True):
"""
See more:
http://developer.oanda.com/rest-live/rates/#getCurrentPrices
"""
url = "{0}/{1}/prices".format(
self.domain_stream if stream else self.domain,
self.API_VERSION
)
params =... | [
"def",
"get_prices",
"(",
"self",
",",
"instruments",
",",
"stream",
"=",
"True",
")",
":",
"url",
"=",
"\"{0}/{1}/prices\"",
".",
"format",
"(",
"self",
".",
"domain_stream",
"if",
"stream",
"else",
"self",
".",
"domain",
",",
"self",
".",
"API_VERSION",
... | 31.727273 | 18.272727 |
def wrap_line(line, maxline=79, result=[], count=count):
""" We have a line that is too long,
so we're going to try to wrap it.
"""
# Extract the indentation
append = result.append
extend = result.extend
indentation = line[0]
lenfirst = len(indentation)
indent = lenfirst - len... | [
"def",
"wrap_line",
"(",
"line",
",",
"maxline",
"=",
"79",
",",
"result",
"=",
"[",
"]",
",",
"count",
"=",
"count",
")",
":",
"# Extract the indentation",
"append",
"=",
"result",
".",
"append",
"extend",
"=",
"result",
".",
"extend",
"indentation",
"=... | 29.646341 | 16.609756 |
def set_common_fields(self, warc_type: str, content_type: str):
'''Set the required fields for the record.'''
self.fields[self.WARC_TYPE] = warc_type
self.fields[self.CONTENT_TYPE] = content_type
self.fields[self.WARC_DATE] = wpull.util.datetime_str()
self.fields[self.WARC_RECORD... | [
"def",
"set_common_fields",
"(",
"self",
",",
"warc_type",
":",
"str",
",",
"content_type",
":",
"str",
")",
":",
"self",
".",
"fields",
"[",
"self",
".",
"WARC_TYPE",
"]",
"=",
"warc_type",
"self",
".",
"fields",
"[",
"self",
".",
"CONTENT_TYPE",
"]",
... | 59 | 19 |
def get_client(url, username, password, allow_insecure, ca_bundle):
"""Create a new client for the HNV REST API."""
return _HNVClient(url, username, password, allow_insecure, ca_bundle) | [
"def",
"get_client",
"(",
"url",
",",
"username",
",",
"password",
",",
"allow_insecure",
",",
"ca_bundle",
")",
":",
"return",
"_HNVClient",
"(",
"url",
",",
"username",
",",
"password",
",",
"allow_insecure",
",",
"ca_bundle",
")"
] | 63.666667 | 20 |
def bottom(self, z: float = 0.0) -> Location:
"""
:param z: the z distance in mm
:return: a Point corresponding to the absolute position of the
bottom-center of the well (with the front-left corner of
slot 1 as (0,0,0)). If z is specified, returns a point
... | [
"def",
"bottom",
"(",
"self",
",",
"z",
":",
"float",
"=",
"0.0",
")",
"->",
"Location",
":",
"top",
"=",
"self",
".",
"top",
"(",
")",
"bottom_z",
"=",
"top",
".",
"point",
".",
"z",
"-",
"self",
".",
"_depth",
"+",
"z",
"return",
"Location",
... | 47.181818 | 15.727273 |
def solve_ng(self, structure, wavelength_step=0.01, filename="ng.dat"):
r"""
Solve for the group index, :math:`n_g`, of a structure at a particular
wavelength.
Args:
structure (Structure): The target structure to solve
for modes.
wavelength_step (... | [
"def",
"solve_ng",
"(",
"self",
",",
"structure",
",",
"wavelength_step",
"=",
"0.01",
",",
"filename",
"=",
"\"ng.dat\"",
")",
":",
"wl_nom",
"=",
"structure",
".",
"_wl",
"self",
".",
"solve",
"(",
"structure",
")",
"n_ctrs",
"=",
"self",
".",
"n_effs"... | 35.204545 | 23.409091 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.