text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def add(self, data):
"""
>>> ob = OutBuffer().add(OutBuffer.sizelimit * b"x")
>>> ob.add(b"y") # doctest: +ELLIPSIS
Traceback (most recent call last):
...
OmapiSizeLimitError: ...
@type data: bytes
@returns: self
@raises OmapiSizeLimitError:
"""
if len(self) + len(data) > self.sizelimit:
raise... | [
"def",
"add",
"(",
"self",
",",
"data",
")",
":",
"if",
"len",
"(",
"self",
")",
"+",
"len",
"(",
"data",
")",
">",
"self",
".",
"sizelimit",
":",
"raise",
"OmapiSizeLimitError",
"(",
")",
"self",
".",
"buff",
".",
"write",
"(",
"data",
")",
"ret... | 22.8125 | 15.0625 |
def validNormalizeAttributeValue(self, doc, name, value):
"""Does the validation related extra step of the normalization
of attribute values: If the declared value is not CDATA,
then the XML processor must further process the normalized
attribute value by discarding any leading an... | [
"def",
"validNormalizeAttributeValue",
"(",
"self",
",",
"doc",
",",
"name",
",",
"value",
")",
":",
"if",
"doc",
"is",
"None",
":",
"doc__o",
"=",
"None",
"else",
":",
"doc__o",
"=",
"doc",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"xmlValidNormalizeAtt... | 57.454545 | 18.363636 |
def new(self, item_lists, processor:PreProcessor=None, **kwargs)->'ItemList':
"Create a new `ItemList` from `items`, keeping the same attributes."
processor = ifnone(processor, self.processor)
copy_d = {o:getattr(self,o) for o in self.copy_new}
kwargs = {**copy_d, **kwargs}
retur... | [
"def",
"new",
"(",
"self",
",",
"item_lists",
",",
"processor",
":",
"PreProcessor",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
"->",
"'ItemList'",
":",
"processor",
"=",
"ifnone",
"(",
"processor",
",",
"self",
".",
"processor",
")",
"copy_d",
"=",
"{... | 62.333333 | 23.333333 |
def get_impl_ver(env):
"""Return implementation version."""
impl_ver = env.config_var("py_version_nodot")
if not impl_ver or get_abbr_impl(env) == "pp":
impl_ver = "".join(map(str, get_impl_version_info(env)))
return impl_ver | [
"def",
"get_impl_ver",
"(",
"env",
")",
":",
"impl_ver",
"=",
"env",
".",
"config_var",
"(",
"\"py_version_nodot\"",
")",
"if",
"not",
"impl_ver",
"or",
"get_abbr_impl",
"(",
"env",
")",
"==",
"\"pp\"",
":",
"impl_ver",
"=",
"\"\"",
".",
"join",
"(",
"ma... | 34.857143 | 17.428571 |
def get_enabled_regions(exec_type, json_spec, from_command_line, executable_builder_exeception):
"""
Return a list of regions in which the global executable (app or global workflow)
will be enabled, based on the "regionalOption" in their JSON specification
and/or --region CLI argument used with "dx buil... | [
"def",
"get_enabled_regions",
"(",
"exec_type",
",",
"json_spec",
",",
"from_command_line",
",",
"executable_builder_exeception",
")",
":",
"from_spec",
"=",
"json_spec",
".",
"get",
"(",
"'regionalOptions'",
")",
"if",
"from_spec",
"is",
"not",
"None",
":",
"asse... | 41.133333 | 24.133333 |
def distance(self, other):
"""Distance to another point on the sphere"""
return math.acos(self._pos3d.dot(other.vector)) | [
"def",
"distance",
"(",
"self",
",",
"other",
")",
":",
"return",
"math",
".",
"acos",
"(",
"self",
".",
"_pos3d",
".",
"dot",
"(",
"other",
".",
"vector",
")",
")"
] | 44.666667 | 9.666667 |
def _transform(self, *transforms):
"""
Copies the given Sequence and appends new transformation
:param transform: transform to apply or list of transforms to apply
:return: transformed sequence
"""
sequence = None
for transform in transforms:
if sequen... | [
"def",
"_transform",
"(",
"self",
",",
"*",
"transforms",
")",
":",
"sequence",
"=",
"None",
"for",
"transform",
"in",
"transforms",
":",
"if",
"sequence",
":",
"sequence",
"=",
"Sequence",
"(",
"sequence",
",",
"transform",
"=",
"transform",
")",
"else",
... | 37.153846 | 14.846154 |
def _retry_from_retry_config(retry_params, retry_codes):
"""Creates a Retry object given a gapic retry configuration.
Args:
retry_params (dict): The retry parameter values, for example::
{
"initial_retry_delay_millis": 1000,
"retry_delay_multiplier": 2.5,
... | [
"def",
"_retry_from_retry_config",
"(",
"retry_params",
",",
"retry_codes",
")",
":",
"exception_classes",
"=",
"[",
"_exception_class_for_grpc_status_name",
"(",
"code",
")",
"for",
"code",
"in",
"retry_codes",
"]",
"return",
"retry",
".",
"Retry",
"(",
"retry",
... | 38.46875 | 23.5625 |
def parse(self, response):
"""
Checks any given response on being an article and if positiv,
passes the response to the pipeline.
:param obj response: The scrapy response
"""
if not self.helper.parse_crawler.content_type(response):
return
for request... | [
"def",
"parse",
"(",
"self",
",",
"response",
")",
":",
"if",
"not",
"self",
".",
"helper",
".",
"parse_crawler",
".",
"content_type",
"(",
"response",
")",
":",
"return",
"for",
"request",
"in",
"self",
".",
"helper",
".",
"parse_crawler",
".",
"recursi... | 37.294118 | 20.823529 |
def _create_header(self):
"""
Function to create the GroupHeader (GrpHdr) in the
CstmrCdtTrfInitn Node
"""
# Retrieve the node to which we will append the group header.
CstmrCdtTrfInitn_node = self._xml.find('CstmrCdtTrfInitn')
# Create the header nodes.
... | [
"def",
"_create_header",
"(",
"self",
")",
":",
"# Retrieve the node to which we will append the group header.",
"CstmrCdtTrfInitn_node",
"=",
"self",
".",
"_xml",
".",
"find",
"(",
"'CstmrCdtTrfInitn'",
")",
"# Create the header nodes.",
"GrpHdr_node",
"=",
"ET",
".",
"E... | 35.9375 | 11.5 |
def _use_memcache(self, key, options=None):
"""Return whether to use memcache for this key.
Args:
key: Key instance.
options: ContextOptions instance, or None.
Returns:
True if the key should be cached in memcache, False otherwise.
"""
flag = ContextOptions.use_memcache(options)
... | [
"def",
"_use_memcache",
"(",
"self",
",",
"key",
",",
"options",
"=",
"None",
")",
":",
"flag",
"=",
"ContextOptions",
".",
"use_memcache",
"(",
"options",
")",
"if",
"flag",
"is",
"None",
":",
"flag",
"=",
"self",
".",
"_memcache_policy",
"(",
"key",
... | 27.722222 | 18.277778 |
def wallet_key_valid(self, wallet):
"""
Returns if a **wallet** key is valid
:param wallet: Wallet to check key is valid
:type wallet: str
>>> rpc.wallet_key_valid(
... wallet="000D1BAEC8EC208142C99059B393051BAC8380F9B5A2E6B2489A277D81789F3F"
... )
T... | [
"def",
"wallet_key_valid",
"(",
"self",
",",
"wallet",
")",
":",
"wallet",
"=",
"self",
".",
"_process_value",
"(",
"wallet",
",",
"'wallet'",
")",
"payload",
"=",
"{",
"\"wallet\"",
":",
"wallet",
"}",
"resp",
"=",
"self",
".",
"call",
"(",
"'wallet_key... | 25.1 | 21.1 |
def set_image(self, image, filename=None, resize=False):
"""
Set the poster or thumbnail of a this Vidoe.
"""
if self.id:
data = self.connection.post('add_image', filename,
video_id=self.id, image=image.to_dict(), resize=resize)
if data:
... | [
"def",
"set_image",
"(",
"self",
",",
"image",
",",
"filename",
"=",
"None",
",",
"resize",
"=",
"False",
")",
":",
"if",
"self",
".",
"id",
":",
"data",
"=",
"self",
".",
"connection",
".",
"post",
"(",
"'add_image'",
",",
"filename",
",",
"video_id... | 38.555556 | 14.111111 |
def hide_routemap_holder_route_map_content_match_metric_metric_rmm(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
hide_routemap_holder = ET.SubElement(config, "hide-routemap-holder", xmlns="urn:brocade.com:mgmt:brocade-ip-policy")
route_map = ET.SubElem... | [
"def",
"hide_routemap_holder_route_map_content_match_metric_metric_rmm",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"hide_routemap_holder",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"hide-... | 50.45 | 17.6 |
def route(self, path, routinemethod, container = None, host = None, vhost = None, method = [b'GET', b'HEAD']):
'''
Route specified path to a WSGI-styled routine factory
:param path: path to match, can be a regular expression
:param routinemethod: factory function routi... | [
"def",
"route",
"(",
"self",
",",
"path",
",",
"routinemethod",
",",
"container",
"=",
"None",
",",
"host",
"=",
"None",
",",
"vhost",
"=",
"None",
",",
"method",
"=",
"[",
"b'GET'",
",",
"b'HEAD'",
"]",
")",
":",
"self",
".",
"routeevent",
"(",
"p... | 46.789474 | 33 |
def _remove_stashed_checkpoints(self, till_3pc_key=None):
"""
Remove stashed received checkpoints up to `till_3pc_key` if provided,
otherwise remove all stashed received checkpoints
"""
if till_3pc_key is None:
self.stashedRecvdCheckpoints.clear()
self.log... | [
"def",
"_remove_stashed_checkpoints",
"(",
"self",
",",
"till_3pc_key",
"=",
"None",
")",
":",
"if",
"till_3pc_key",
"is",
"None",
":",
"self",
".",
"stashedRecvdCheckpoints",
".",
"clear",
"(",
")",
"self",
".",
"logger",
".",
"info",
"(",
"'{} removing all s... | 50.04 | 24.36 |
def with_known_args(self, **kwargs):
"""Send only known keyword-arguments to the phase when called."""
argspec = inspect.getargspec(self.func)
stored = {}
for key, arg in six.iteritems(kwargs):
if key in argspec.args or argspec.keywords:
stored[key] = arg
if stored:
return self.w... | [
"def",
"with_known_args",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"argspec",
"=",
"inspect",
".",
"getargspec",
"(",
"self",
".",
"func",
")",
"stored",
"=",
"{",
"}",
"for",
"key",
",",
"arg",
"in",
"six",
".",
"iteritems",
"(",
"kwargs",
... | 34.5 | 11.2 |
def init_datamembers(self, rec):
"""Initialize current GOTerm with data members for storing optional attributes."""
# pylint: disable=multiple-statements
if 'synonym' in self.optional_attrs: rec.synonym = []
if 'xref' in self.optional_attrs: rec.xref = set()
if 'subs... | [
"def",
"init_datamembers",
"(",
"self",
",",
"rec",
")",
":",
"# pylint: disable=multiple-statements",
"if",
"'synonym'",
"in",
"self",
".",
"optional_attrs",
":",
"rec",
".",
"synonym",
"=",
"[",
"]",
"if",
"'xref'",
"in",
"self",
".",
"optional_attrs",
":",
... | 55.2 | 13.8 |
def date_matches(self, timestamp):
"""Determine whether the timestamp date is equal to the argument date."""
if self.date is None:
return False
timestamp = datetime.fromtimestamp(float(timestamp), self.timezone)
if self.date.date() == timestamp.date():
return Tru... | [
"def",
"date_matches",
"(",
"self",
",",
"timestamp",
")",
":",
"if",
"self",
".",
"date",
"is",
"None",
":",
"return",
"False",
"timestamp",
"=",
"datetime",
".",
"fromtimestamp",
"(",
"float",
"(",
"timestamp",
")",
",",
"self",
".",
"timezone",
")",
... | 33.4 | 19.3 |
def _get_bounds(self):
"""
Subclasses may override this method.
"""
from fontTools.pens.boundsPen import BoundsPen
pen = BoundsPen(self.layer)
self.draw(pen)
return pen.bounds | [
"def",
"_get_bounds",
"(",
"self",
")",
":",
"from",
"fontTools",
".",
"pens",
".",
"boundsPen",
"import",
"BoundsPen",
"pen",
"=",
"BoundsPen",
"(",
"self",
".",
"layer",
")",
"self",
".",
"draw",
"(",
"pen",
")",
"return",
"pen",
".",
"bounds"
] | 28 | 9.25 |
def beta_code(self, text):
"""Replace method. Note: regex.subn() returns a tuple (new_string,
number_of_subs_made).
"""
text = text.upper().replace('-', '')
for (pattern, repl) in self.pattern1:
text = pattern.subn(repl, text)[0]
for (pattern, repl) in self.pa... | [
"def",
"beta_code",
"(",
"self",
",",
"text",
")",
":",
"text",
"=",
"text",
".",
"upper",
"(",
")",
".",
"replace",
"(",
"'-'",
",",
"''",
")",
"for",
"(",
"pattern",
",",
"repl",
")",
"in",
"self",
".",
"pattern1",
":",
"text",
"=",
"pattern",
... | 40.461538 | 7.153846 |
def transceive(self, data, timeout=0.1, retries=2):
"""Send a Type 2 Tag command and receive the response.
:meth:`transceive` is a type 2 tag specific wrapper around the
:meth:`nfc.ContactlessFrontend.exchange` method. It can be
used to send custom commands as a sequence of *data* bytes... | [
"def",
"transceive",
"(",
"self",
",",
"data",
",",
"timeout",
"=",
"0.1",
",",
"retries",
"=",
"2",
")",
":",
"log",
".",
"debug",
"(",
"\">> {0} ({1:f}s)\"",
".",
"format",
"(",
"hexlify",
"(",
"data",
")",
",",
"timeout",
")",
")",
"if",
"not",
... | 43.837209 | 21.534884 |
def uniform_partition(min_pt=None, max_pt=None, shape=None, cell_sides=None,
nodes_on_bdry=False):
"""Return a partition with equally sized cells.
Parameters
----------
min_pt, max_pt : float or sequence of float, optional
Vectors defining the lower/upper limits of the int... | [
"def",
"uniform_partition",
"(",
"min_pt",
"=",
"None",
",",
"max_pt",
"=",
"None",
",",
"shape",
"=",
"None",
",",
"cell_sides",
"=",
"None",
",",
"nodes_on_bdry",
"=",
"False",
")",
":",
"# Normalize partition parameters",
"# np.size(None) == 1, so that would scre... | 42.83432 | 22.147929 |
def has_active_condition(self, condition, instances):
"""
Given a list of instances, and the condition active for
this switch, returns a boolean representing if the
conditional is met, including a non-instance default.
"""
return_value = None
for instance in insta... | [
"def",
"has_active_condition",
"(",
"self",
",",
"condition",
",",
"instances",
")",
":",
"return_value",
"=",
"None",
"for",
"instance",
"in",
"instances",
"+",
"[",
"None",
"]",
":",
"if",
"not",
"self",
".",
"can_execute",
"(",
"instance",
")",
":",
"... | 37.875 | 11 |
def _read_master_branch_resource(self, fn, is_json=False):
"""This will force the current branch to master! """
with self._master_branch_repo_lock:
ga = self._create_git_action_for_global_resource()
with ga.lock():
ga.checkout_master()
if os.path.e... | [
"def",
"_read_master_branch_resource",
"(",
"self",
",",
"fn",
",",
"is_json",
"=",
"False",
")",
":",
"with",
"self",
".",
"_master_branch_repo_lock",
":",
"ga",
"=",
"self",
".",
"_create_git_action_for_global_resource",
"(",
")",
"with",
"ga",
".",
"lock",
... | 43.615385 | 10.230769 |
def select_action(self, pos1, pos2, ctrl, shift):
"""Return a `sc_pb.Action` with the selection filled."""
assert pos1.surf.surf_type == pos2.surf.surf_type
assert pos1.surf.world_to_obs == pos2.surf.world_to_obs
action = sc_pb.Action()
action_spatial = pos1.action_spatial(action)
if pos1.worl... | [
"def",
"select_action",
"(",
"self",
",",
"pos1",
",",
"pos2",
",",
"ctrl",
",",
"shift",
")",
":",
"assert",
"pos1",
".",
"surf",
".",
"surf_type",
"==",
"pos2",
".",
"surf",
".",
"surf_type",
"assert",
"pos1",
".",
"surf",
".",
"world_to_obs",
"==",
... | 38.633333 | 19.9 |
def local_transform_runner(transform_py_name, value, fields, params, config, message_writer=message):
"""
Internal API: The local transform runner is responsible for executing the local transform.
Parameters:
transform - The name or module of the transform to execute (i.e sploitego.transforms.wha... | [
"def",
"local_transform_runner",
"(",
"transform_py_name",
",",
"value",
",",
"fields",
",",
"params",
",",
"config",
",",
"message_writer",
"=",
"message",
")",
":",
"transform",
"=",
"None",
"try",
":",
"transform",
"=",
"load_object",
"(",
"transform_py_name"... | 47.147541 | 31.344262 |
def _improve_class_docs(app, cls, lines):
"""Improve the documentation of a class."""
if issubclass(cls, models.Model):
_add_model_fields_as_params(app, cls, lines)
elif issubclass(cls, forms.Form):
_add_form_fields(cls, lines) | [
"def",
"_improve_class_docs",
"(",
"app",
",",
"cls",
",",
"lines",
")",
":",
"if",
"issubclass",
"(",
"cls",
",",
"models",
".",
"Model",
")",
":",
"_add_model_fields_as_params",
"(",
"app",
",",
"cls",
",",
"lines",
")",
"elif",
"issubclass",
"(",
"cls... | 41.666667 | 3.833333 |
def __generate_file(self, template_filename, context, generated_filename, force=False):
"""
Generate **one** (source code) file from a template.
The file is **only** generated if needed, i.e. if ``force`` is set to ``True`` or if generated file is older
than the template file. The gener... | [
"def",
"__generate_file",
"(",
"self",
",",
"template_filename",
",",
"context",
",",
"generated_filename",
",",
"force",
"=",
"False",
")",
":",
"# TODO: maybe avoid reading same template file again and again... i.e. parse it once and generate all needed files without reparsing the ... | 60.333333 | 41.666667 |
def hsvToRGB(h, s, v):
"""
Convert HSV (hue, saturation, value) color space to RGB (red, green blue)
color space.
**Parameters**
**h** : float
Hue, a number in [0, 360].
**s** : float
Saturation, a number in [0, 1].
**v... | [
"def",
"hsvToRGB",
"(",
"h",
",",
"s",
",",
"v",
")",
":",
"hi",
"=",
"math",
".",
"floor",
"(",
"h",
"/",
"60.0",
")",
"%",
"6",
"f",
"=",
"(",
"h",
"/",
"60.0",
")",
"-",
"math",
".",
"floor",
"(",
"h",
"/",
"60.0",
")",
"p",
"=",
"v"... | 19.818182 | 24 |
def copy_file(stream, target, maxread=-1, buffer_size=2*16):
''' Read from :stream and write to :target until :maxread or EOF. '''
size, read = 0, stream.read
while 1:
to_read = buffer_size if maxread < 0 else min(buffer_size, maxread-size)
part = read(to_read)
if not part:
... | [
"def",
"copy_file",
"(",
"stream",
",",
"target",
",",
"maxread",
"=",
"-",
"1",
",",
"buffer_size",
"=",
"2",
"*",
"16",
")",
":",
"size",
",",
"read",
"=",
"0",
",",
"stream",
".",
"read",
"while",
"1",
":",
"to_read",
"=",
"buffer_size",
"if",
... | 37.8 | 20.8 |
def line_shortening_rank(candidate, indent_word, max_line_length,
experimental=False):
"""Return rank of candidate.
This is for sorting candidates.
"""
if not candidate.strip():
return 0
rank = 0
lines = candidate.rstrip().split('\n')
offset = 0
if (
... | [
"def",
"line_shortening_rank",
"(",
"candidate",
",",
"indent_word",
",",
"max_line_length",
",",
"experimental",
"=",
"False",
")",
":",
"if",
"not",
"candidate",
".",
"strip",
"(",
")",
":",
"return",
"0",
"rank",
"=",
"0",
"lines",
"=",
"candidate",
"."... | 30.739726 | 21.047945 |
def retrieve(self, id) :
"""
Retrieve a single contact
Returns a single contact available to the user, according to the unique contact ID provided
If the specified contact does not exist, the request will return an error
:calls: ``get /contacts/{id}``
:param int id: Uni... | [
"def",
"retrieve",
"(",
"self",
",",
"id",
")",
":",
"_",
",",
"_",
",",
"contact",
"=",
"self",
".",
"http_client",
".",
"get",
"(",
"\"/contacts/{id}\"",
".",
"format",
"(",
"id",
"=",
"id",
")",
")",
"return",
"contact"
] | 37.6 | 25.866667 |
def prefilter_lines(self, lines, continue_prompt=False):
"""Prefilter multiple input lines of text.
This is the main entry point for prefiltering multiple lines of
input. This simply calls :meth:`prefilter_line` for each line of
input.
This covers cases where there are multipl... | [
"def",
"prefilter_lines",
"(",
"self",
",",
"lines",
",",
"continue_prompt",
"=",
"False",
")",
":",
"llines",
"=",
"lines",
".",
"rstrip",
"(",
"'\\n'",
")",
".",
"split",
"(",
"'\\n'",
")",
"# We can get multiple lines in one shot, where multiline input 'blends'",... | 44.666667 | 25.541667 |
def _proc_asym_top(self):
"""
Handles assymetric top molecules, which cannot contain rotational
symmetry larger than 2.
"""
self._check_R2_axes_asym()
if len(self.rot_sym) == 0:
logger.debug("No rotation symmetries detected.")
self._proc_no_rot_sym... | [
"def",
"_proc_asym_top",
"(",
"self",
")",
":",
"self",
".",
"_check_R2_axes_asym",
"(",
")",
"if",
"len",
"(",
"self",
".",
"rot_sym",
")",
"==",
"0",
":",
"logger",
".",
"debug",
"(",
"\"No rotation symmetries detected.\"",
")",
"self",
".",
"_proc_no_rot_... | 35.266667 | 10.866667 |
def article_views(
self, project, articles,
access='all-access', agent='all-agents', granularity='daily',
start=None, end=None):
"""
Get pageview counts for one or more articles
See `<https://wikimedia.org/api/rest_v1/metrics/pageviews/?doc\\
#... | [
"def",
"article_views",
"(",
"self",
",",
"project",
",",
"articles",
",",
"access",
"=",
"'all-access'",
",",
"agent",
"=",
"'all-agents'",
",",
"granularity",
"=",
"'daily'",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
")",
":",
"endDate",
"=",... | 37.183673 | 19.673469 |
def get_spn(unit):
"""获取文本行中非中文字符数的个数
Keyword arguments:
unit -- 文本行
Return:
spn -- 特殊字符数
"""
spn = 0
match_re = re.findall(no_chinese, unit)
if match_re:
string = ''.join(match_re)
spn = len(string)
return int(spn) | [
"def",
"get_spn",
"(",
"unit",
")",
":",
"spn",
"=",
"0",
"match_re",
"=",
"re",
".",
"findall",
"(",
"no_chinese",
",",
"unit",
")",
"if",
"match_re",
":",
"string",
"=",
"''",
".",
"join",
"(",
"match_re",
")",
"spn",
"=",
"len",
"(",
"string",
... | 21.285714 | 15.5 |
def parse_keyring(self, namespace=None):
"""Find settings from keyring."""
results = {}
if not keyring:
return results
if not namespace:
namespace = self.prog
for option in self._options:
secret = keyring.get_password(namespace, option.name)
... | [
"def",
"parse_keyring",
"(",
"self",
",",
"namespace",
"=",
"None",
")",
":",
"results",
"=",
"{",
"}",
"if",
"not",
"keyring",
":",
"return",
"results",
"if",
"not",
"namespace",
":",
"namespace",
"=",
"self",
".",
"prog",
"for",
"option",
"in",
"self... | 34.25 | 13 |
def schema(self):
"""
The generated budget data package schema for this resource.
If the resource has any fields that do not conform to the
provided specification this will raise a
NotABudgetDataPackageException.
"""
if self.headers is None:
raise exc... | [
"def",
"schema",
"(",
"self",
")",
":",
"if",
"self",
".",
"headers",
"is",
"None",
":",
"raise",
"exceptions",
".",
"NoResourceLoadedException",
"(",
"'Resource must be loaded to find schema'",
")",
"try",
":",
"fields",
"=",
"self",
".",
"specification",
".",
... | 38.76 | 16.6 |
def getImage(self):
"""Returns the project image when available."""
value = self.__getNone(self.__dataItem['image']['url'])
if value == None:
return None
else:
return Sitools2Abstract.getBaseUrl(self) + self.__dataItem['image']['url'] | [
"def",
"getImage",
"(",
"self",
")",
":",
"value",
"=",
"self",
".",
"__getNone",
"(",
"self",
".",
"__dataItem",
"[",
"'image'",
"]",
"[",
"'url'",
"]",
")",
"if",
"value",
"==",
"None",
":",
"return",
"None",
"else",
":",
"return",
"Sitools2Abstract"... | 40.571429 | 21.285714 |
def _get_rating(self, entry):
"""Get the rating and share for a specific row"""
r_info = ''
for string in entry[2].strings:
r_info += string
rating, share = r_info.split('/')
return (rating, share.strip('*')) | [
"def",
"_get_rating",
"(",
"self",
",",
"entry",
")",
":",
"r_info",
"=",
"''",
"for",
"string",
"in",
"entry",
"[",
"2",
"]",
".",
"strings",
":",
"r_info",
"+=",
"string",
"rating",
",",
"share",
"=",
"r_info",
".",
"split",
"(",
"'/'",
")",
"ret... | 36.285714 | 6.714286 |
def get_ctm(self):
"""Copies the scaled font’s font current transform matrix.
Note that the translation offsets ``(x0, y0)`` of the CTM
are ignored by :class:`ScaledFont`.
So, the matrix this method returns always has 0 as ``x0`` and ``y0``.
:returns: A new :class:`Matrix` obje... | [
"def",
"get_ctm",
"(",
"self",
")",
":",
"matrix",
"=",
"Matrix",
"(",
")",
"cairo",
".",
"cairo_scaled_font_get_ctm",
"(",
"self",
".",
"_pointer",
",",
"matrix",
".",
"_pointer",
")",
"self",
".",
"_check_status",
"(",
")",
"return",
"matrix"
] | 33.714286 | 20.785714 |
def save_json(py_obj, json_path):
"""Serialize a native object to JSON and save it normalized, pretty printed to a
file.
The JSON string is normalized by sorting any dictionary keys.
Args:
py_obj: object
Any object that can be represented in JSON. Some types, such as datetimes are
... | [
"def",
"save_json",
"(",
"py_obj",
",",
"json_path",
")",
":",
"with",
"open",
"(",
"json_path",
",",
"'w'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"serialize_to_normalized_pretty_json",
"(",
"py_obj",
")",
")"
] | 31.380952 | 23.904762 |
def error_map(func):
"""Wrap exceptions raised by requests.
.. py:decorator:: error_map
"""
@six.wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except exceptions.RequestException as err:
raise TVDBRequestException(
... | [
"def",
"error_map",
"(",
"func",
")",
":",
"@",
"six",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except"... | 29.466667 | 13.8 |
def subarc(self, from_angle=None, to_angle=None):
'''
Creates a sub-arc from a given angle (or beginning of this arc) to a given angle (or end of this arc).
Verifies that from_angle and to_angle are within the arc and properly ordered.
If from_angle is None, start of this arc is used ins... | [
"def",
"subarc",
"(",
"self",
",",
"from_angle",
"=",
"None",
",",
"to_angle",
"=",
"None",
")",
":",
"if",
"from_angle",
"is",
"None",
":",
"from_angle",
"=",
"self",
".",
"from_angle",
"if",
"to_angle",
"is",
"None",
":",
"to_angle",
"=",
"self",
"."... | 50.809524 | 21.761905 |
def recordings(self):
"""
Access the recordings
:returns: twilio.rest.video.v1.room.recording.RoomRecordingList
:rtype: twilio.rest.video.v1.room.recording.RoomRecordingList
"""
if self._recordings is None:
self._recordings = RoomRecordingList(self._version, ... | [
"def",
"recordings",
"(",
"self",
")",
":",
"if",
"self",
".",
"_recordings",
"is",
"None",
":",
"self",
".",
"_recordings",
"=",
"RoomRecordingList",
"(",
"self",
".",
"_version",
",",
"room_sid",
"=",
"self",
".",
"_solution",
"[",
"'sid'",
"]",
",",
... | 37.6 | 20 |
def _finalize_stats(self, ipyclient):
""" write final tree files """
## print stats file location:
#print(STATSOUT.format(opr(self.files.stats)))
## print finished tree information ---------------------
print(FINALTREES.format(opr(self.trees.tree)))
## print bootstrap ... | [
"def",
"_finalize_stats",
"(",
"self",
",",
"ipyclient",
")",
":",
"## print stats file location:",
"#print(STATSOUT.format(opr(self.files.stats)))",
"## print finished tree information ---------------------",
"print",
"(",
"FINALTREES",
".",
"format",
"(",
"opr",
"(",
"self",
... | 41 | 18.111111 |
def cli(env, columns, sortby, volume_id):
"""List suitable replication datacenters for the given volume."""
file_storage_manager = SoftLayer.FileStorageManager(env.client)
legal_centers = file_storage_manager.get_replication_locations(
volume_id
)
if not legal_centers:
click.echo("... | [
"def",
"cli",
"(",
"env",
",",
"columns",
",",
"sortby",
",",
"volume_id",
")",
":",
"file_storage_manager",
"=",
"SoftLayer",
".",
"FileStorageManager",
"(",
"env",
".",
"client",
")",
"legal_centers",
"=",
"file_storage_manager",
".",
"get_replication_locations"... | 35.388889 | 21.777778 |
def _set_sample_rate_cpu(self, v, load=False):
"""
Setter method for sample_rate_cpu, mapped from YANG variable /resource_monitor/cpu/sample_rate_cpu (uint32)
If this variable is read-only (config: false) in the
source YANG file, then _set_sample_rate_cpu is considered as a private
method. Backends ... | [
"def",
"_set_sample_rate_cpu",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
... | 95.136364 | 45.136364 |
def do_file(self, filename):
""" Read and execute a .dql file """
with open(filename, "r") as infile:
self._run_cmd(infile.read()) | [
"def",
"do_file",
"(",
"self",
",",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"\"r\"",
")",
"as",
"infile",
":",
"self",
".",
"_run_cmd",
"(",
"infile",
".",
"read",
"(",
")",
")"
] | 38.75 | 3.75 |
def add_not_null(self, model, *names):
"""Add not null."""
for name in names:
field = model._meta.fields[name]
field.null = False
self.ops.append(self.migrator.add_not_null(model._meta.table_name, field.column_name))
return model | [
"def",
"add_not_null",
"(",
"self",
",",
"model",
",",
"*",
"names",
")",
":",
"for",
"name",
"in",
"names",
":",
"field",
"=",
"model",
".",
"_meta",
".",
"fields",
"[",
"name",
"]",
"field",
".",
"null",
"=",
"False",
"self",
".",
"ops",
".",
"... | 40.428571 | 15.428571 |
def create(self, quality_score, issue=values.unset):
"""
Create a new FeedbackInstance
:param unicode quality_score: The call quality expressed as an integer from 1 to 5
:param FeedbackInstance.Issues issue: Issues experienced during the call
:returns: Newly created FeedbackIns... | [
"def",
"create",
"(",
"self",
",",
"quality_score",
",",
"issue",
"=",
"values",
".",
"unset",
")",
":",
"return",
"self",
".",
"_proxy",
".",
"create",
"(",
"quality_score",
",",
"issue",
"=",
"issue",
",",
")"
] | 42.545455 | 22.909091 |
def read_i2c_block_data(self, addr, cmd, len=32):
"""read_i2c_block_data(addr, cmd, len=32) -> results
Perform I2C Block Read transaction.
"""
self._set_addr(addr)
data = ffi.new("union i2c_smbus_data *")
data.block[0] = len
if len == 32:
arg = SMBUS.... | [
"def",
"read_i2c_block_data",
"(",
"self",
",",
"addr",
",",
"cmd",
",",
"len",
"=",
"32",
")",
":",
"self",
".",
"_set_addr",
"(",
"addr",
")",
"data",
"=",
"ffi",
".",
"new",
"(",
"\"union i2c_smbus_data *\"",
")",
"data",
".",
"block",
"[",
"0",
"... | 37.888889 | 11.277778 |
def triads(key):
"""Return all the triads in key.
Implemented using a cache.
"""
if _triads_cache.has_key(key):
return _triads_cache[key]
res = map(lambda x: triad(x, key), keys.get_notes(key))
_triads_cache[key] = res
return res | [
"def",
"triads",
"(",
"key",
")",
":",
"if",
"_triads_cache",
".",
"has_key",
"(",
"key",
")",
":",
"return",
"_triads_cache",
"[",
"key",
"]",
"res",
"=",
"map",
"(",
"lambda",
"x",
":",
"triad",
"(",
"x",
",",
"key",
")",
",",
"keys",
".",
"get... | 25.7 | 14.4 |
def read_stream(cls, stream, validate=True):
"""
Read torrent metainfo from file-like object
:param stream: Readable file-like object (e.g. :class:`io.BytesIO`)
:param bool validate: Whether to run :meth:`validate` on the new Torrent
object
:raises ReadError: if rea... | [
"def",
"read_stream",
"(",
"cls",
",",
"stream",
",",
"validate",
"=",
"True",
")",
":",
"try",
":",
"content",
"=",
"stream",
".",
"read",
"(",
"cls",
".",
"MAX_TORRENT_FILE_SIZE",
")",
"except",
"OSError",
"as",
"e",
":",
"raise",
"error",
".",
"Read... | 40.098361 | 22.786885 |
def defadj(self, singular, plural):
"""
Set the adjective plural of singular to plural.
"""
self.checkpat(singular)
self.checkpatplural(plural)
self.pl_adj_user_defined.extend((singular, plural))
return 1 | [
"def",
"defadj",
"(",
"self",
",",
"singular",
",",
"plural",
")",
":",
"self",
".",
"checkpat",
"(",
"singular",
")",
"self",
".",
"checkpatplural",
"(",
"plural",
")",
"self",
".",
"pl_adj_user_defined",
".",
"extend",
"(",
"(",
"singular",
",",
"plura... | 28.111111 | 13 |
def wallet_frontiers(self, wallet):
"""
Returns a list of pairs of account and block hash representing the
head block starting for accounts from **wallet**
:param wallet: Wallet to return frontiers for
:type wallet: str
:raises: :py:exc:`nano.rpc.RPCException`
... | [
"def",
"wallet_frontiers",
"(",
"self",
",",
"wallet",
")",
":",
"wallet",
"=",
"self",
".",
"_process_value",
"(",
"wallet",
",",
"'wallet'",
")",
"payload",
"=",
"{",
"\"wallet\"",
":",
"wallet",
"}",
"resp",
"=",
"self",
".",
"call",
"(",
"'wallet_fro... | 30.653846 | 26.730769 |
def _get_hosts_from_names(self, names):
""" validate hostnames from a list of names
"""
result = set()
hosts = map(lambda x: x.strip(), names.split(','))
for h in hosts:
if valid_hostname(h.split(':')[0]):
result.add(h if ':' in h else '%s:%d' % (h, se... | [
"def",
"_get_hosts_from_names",
"(",
"self",
",",
"names",
")",
":",
"result",
"=",
"set",
"(",
")",
"hosts",
"=",
"map",
"(",
"lambda",
"x",
":",
"x",
".",
"strip",
"(",
")",
",",
"names",
".",
"split",
"(",
"','",
")",
")",
"for",
"h",
"in",
... | 39.727273 | 14.454545 |
def split_command(cmd, posix=None):
'''
- cmd is string list -> nothing to do
- cmd is string -> split it using shlex
:param cmd: string ('ls -l') or list of strings (['ls','-l'])
:rtype: string list
'''
if not isinstance(cmd, string_types):
# cmd is string list
pass
e... | [
"def",
"split_command",
"(",
"cmd",
",",
"posix",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"cmd",
",",
"string_types",
")",
":",
"# cmd is string list",
"pass",
"else",
":",
"if",
"not",
"PY3",
":",
"# cmd is string",
"# The shlex module currentl... | 36.785714 | 19.285714 |
def cache_file(self, path, saltenv='base', cachedir=None, source_hash=None):
'''
Pull a file down from the file server and store it in the minion
file cache
'''
return self.get_url(
path, '', True, saltenv, cachedir=cachedir, source_hash=source_hash) | [
"def",
"cache_file",
"(",
"self",
",",
"path",
",",
"saltenv",
"=",
"'base'",
",",
"cachedir",
"=",
"None",
",",
"source_hash",
"=",
"None",
")",
":",
"return",
"self",
".",
"get_url",
"(",
"path",
",",
"''",
",",
"True",
",",
"saltenv",
",",
"cached... | 42.285714 | 28.571429 |
def discover(email, credentials):
"""
Performs the autodiscover dance and returns the primary SMTP address of the account and a Protocol on success. The
autodiscover and EWS server might not be the same, so we use a different Protocol to do the autodiscover request,
and return a hopefully-cached Protoco... | [
"def",
"discover",
"(",
"email",
",",
"credentials",
")",
":",
"log",
".",
"debug",
"(",
"'Attempting autodiscover on email %s'",
",",
"email",
")",
"if",
"not",
"isinstance",
"(",
"credentials",
",",
"Credentials",
")",
":",
"raise",
"ValueError",
"(",
"\"'cr... | 63.254902 | 29.215686 |
def setValue(self, newText):
"""Sets a text value (string) into the text field."""
newText = str(newText) # attempt to convert to string (might be int or float ...)
if self.text == newText:
return # nothing to change
self.text = newText # save the new text
... | [
"def",
"setValue",
"(",
"self",
",",
"newText",
")",
":",
"newText",
"=",
"str",
"(",
"newText",
")",
"# attempt to convert to string (might be int or float ...)\r",
"if",
"self",
".",
"text",
"==",
"newText",
":",
"return",
"# nothing to change\r",
"self",
".",
... | 47.311688 | 22.246753 |
def operator(self, lhs, min_precedence):
"""Climb operator precedence as long as there are operators.
This function implements a basic precedence climbing parser to deal
with binary operators in a sane fashion. The outer loop will keep
spinning as long as the next token is an operator w... | [
"def",
"operator",
"(",
"self",
",",
"lhs",
",",
"min_precedence",
")",
":",
"# Spin as long as the next token is an operator of higher",
"# precedence. (This may not do anything, which is fine.)",
"while",
"self",
".",
"accept_operator",
"(",
"precedence",
"=",
"min_precedence... | 45.72549 | 22.45098 |
def kaczmarz(ops, x, rhs, niter, omega=1, projection=None, random=False,
callback=None, callback_loop='outer'):
r"""Optimized implementation of Kaczmarz's method.
Solves the inverse problem given by the set of equations::
A_n(x) = rhs_n
This is also known as the Landweber-Kaczmarz's ... | [
"def",
"kaczmarz",
"(",
"ops",
",",
"x",
",",
"rhs",
",",
"niter",
",",
"omega",
"=",
"1",
",",
"projection",
"=",
"None",
",",
"random",
"=",
"False",
",",
"callback",
"=",
"None",
",",
"callback_loop",
"=",
"'outer'",
")",
":",
"domain",
"=",
"op... | 36.679389 | 23.480916 |
def create_guest_screen_info(self, display, status, primary, change_origin, origin_x, origin_y, width, height, bits_per_pixel):
"""Make a IGuestScreenInfo object with the provided parameters.
in display of type int
The number of the guest display.
in status of type :class:`GuestMon... | [
"def",
"create_guest_screen_info",
"(",
"self",
",",
"display",
",",
"status",
",",
"primary",
",",
"change_origin",
",",
"origin_x",
",",
"origin_y",
",",
"width",
",",
"height",
",",
"bits_per_pixel",
")",
":",
"if",
"not",
"isinstance",
"(",
"display",
",... | 44.672414 | 23.293103 |
def stage(self, name):
"""
Method for searching specific stage by it's name.
:param name: name of the stage to search.
:return: found stage or None.
:rtype: yagocd.resources.stage.StageInstance
"""
for stage in self.stages():
if stage.data.name == nam... | [
"def",
"stage",
"(",
"self",
",",
"name",
")",
":",
"for",
"stage",
"in",
"self",
".",
"stages",
"(",
")",
":",
"if",
"stage",
".",
"data",
".",
"name",
"==",
"name",
":",
"return",
"stage"
] | 31 | 10.636364 |
def is_ip_valid(self, ip_to_check=None):
"""
Check if the given IP is a valid IPv4.
:param ip_to_check: The IP to test.
:type ip_to_check: str
:return: The validity of the IP.
:rtype: bool
.. note::
We only test IPv4 because for now we only them for... | [
"def",
"is_ip_valid",
"(",
"self",
",",
"ip_to_check",
"=",
"None",
")",
":",
"# We initate our regex which will match for valid IPv4.",
"regex_ipv4",
"=",
"r\"^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-... | 35.27027 | 23.216216 |
def _spectrum(self, photon_energy):
"""Compute intrinsic synchrotron differential spectrum for energies in
``photon_energy``
Compute synchrotron for random magnetic field according to
approximation of Aharonian, Kelner, and Prosekin 2010, PhysRev D 82,
3002 (`arXiv:1006.1045 <ht... | [
"def",
"_spectrum",
"(",
"self",
",",
"photon_energy",
")",
":",
"outspecene",
"=",
"_validate_ene",
"(",
"photon_energy",
")",
"from",
"scipy",
".",
"special",
"import",
"cbrt",
"def",
"Gtilde",
"(",
"x",
")",
":",
"\"\"\"\n AKP10 Eq. D7\n\n ... | 30.724638 | 20.623188 |
def call(name, function, *args, **kwargs):
'''
Executes a Salt function inside a running container
.. versionadded:: 2016.11.0
The container does not need to have Salt installed, but Python is required.
name
Container name or ID
function
Salt execution module function
CL... | [
"def",
"call",
"(",
"name",
",",
"function",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# where to put the salt-thin",
"thin_dest_path",
"=",
"_generate_tmp_path",
"(",
")",
"mkdirp_thin_argv",
"=",
"[",
"'mkdir'",
",",
"'-p'",
",",
"thin_dest_path"... | 34.287356 | 21.528736 |
def _ParseJournalEntry(self, file_object, file_offset):
"""Parses a journal entry.
This method will generate an event per ENTRY object.
Args:
file_object (dfvfs.FileIO): a file-like object.
file_offset (int): offset of the entry object relative to the start
of the file-like object.
... | [
"def",
"_ParseJournalEntry",
"(",
"self",
",",
"file_object",
",",
"file_offset",
")",
":",
"entry_object",
"=",
"self",
".",
"_ParseEntryObject",
"(",
"file_object",
",",
"file_offset",
")",
"# The data is read separately for performance reasons.",
"entry_item_map",
"=",... | 35.041667 | 24.104167 |
def update_free_shipping_by_id(cls, free_shipping_id, free_shipping, **kwargs):
"""Update FreeShipping
Update attributes of FreeShipping
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_... | [
"def",
"update_free_shipping_by_id",
"(",
"cls",
",",
"free_shipping_id",
",",
"free_shipping",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"c... | 48.909091 | 25.772727 |
def download_object(self, object_name):
"""
Download an object.
:param str object_name: The object to fetch.
"""
return self._client.download_object(
self._instance, self.name, object_name) | [
"def",
"download_object",
"(",
"self",
",",
"object_name",
")",
":",
"return",
"self",
".",
"_client",
".",
"download_object",
"(",
"self",
".",
"_instance",
",",
"self",
".",
"name",
",",
"object_name",
")"
] | 29.375 | 10.125 |
def plot_circular(widths, colors, curviness=0.2, mask=True, topo=None, topomaps=None, axes=None, order=None):
"""Circluar connectivity plot.
Topos are arranged in a circle, with arrows indicating connectivity
Parameters
----------
widths : float or array, shape (n_channels, n_channels)
Wid... | [
"def",
"plot_circular",
"(",
"widths",
",",
"colors",
",",
"curviness",
"=",
"0.2",
",",
"mask",
"=",
"True",
",",
"topo",
"=",
"None",
",",
"topomaps",
"=",
"None",
",",
"axes",
"=",
"None",
",",
"order",
"=",
"None",
")",
":",
"colors",
"=",
"np"... | 28.792857 | 21.4 |
def ManagerMock(manager, *return_value):
"""
Set the results to two items:
>>> objects = ManagerMock(Post.objects, 'queryset', 'result')
>>> assert objects.filter() == objects.all()
Force an exception:
>>> objects = ManagerMock(Post.objects, Exception())
See QuerySetMock for more about h... | [
"def",
"ManagerMock",
"(",
"manager",
",",
"*",
"return_value",
")",
":",
"def",
"make_get_query_set",
"(",
"self",
",",
"model",
")",
":",
"def",
"_get",
"(",
"*",
"a",
",",
"*",
"*",
"k",
")",
":",
"return",
"QuerySetMock",
"(",
"model",
",",
"*",
... | 27.617647 | 17.676471 |
def add(self, key, value):
"""
Method to accept a list of values and append to flat list.
QueryDict.appendlist(), if given a list, will append the list,
which creates nested lists. In most cases, we want to be able
to pass in a list (for convenience) but have it appended into
... | [
"def",
"add",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"for",
"val",
"in",
"value",
":",
"self",
".",
"appendlist",
"(",
"key",
",",
"val",
")",
"else",
":",
"self",
".",
"appendlis... | 41.357143 | 15.928571 |
def run_main(args: argparse.Namespace, do_exit=True) -> None:
"""Runs the checks and exits.
To extend this tool, use this function and set do_exit to False
to get returned the status code.
"""
if args.init:
generate()
return None # exit after generate instead of starting to lint
... | [
"def",
"run_main",
"(",
"args",
":",
"argparse",
".",
"Namespace",
",",
"do_exit",
"=",
"True",
")",
"->",
"None",
":",
"if",
"args",
".",
"init",
":",
"generate",
"(",
")",
"return",
"None",
"# exit after generate instead of starting to lint",
"handler",
"=",... | 26.117647 | 20.647059 |
def parse_duration(duration, timestamp=None):
"""
Interprets a ISO8601 duration value relative to a given timestamp.
:param duration: The duration, as a string.
:type: string
:param timestamp: The unix timestamp we should apply the duration to.
Optiona... | [
"def",
"parse_duration",
"(",
"duration",
",",
"timestamp",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"duration",
",",
"basestring",
")",
"assert",
"timestamp",
"is",
"None",
"or",
"isinstance",
"(",
"timestamp",
",",
"int",
")",
"timedelta",
"=",
... | 35.73913 | 20.608696 |
def get_badge(self):
"""
The related ``Badge`` object.
"""
try:
obj = Badge.objects.using(self.db_read).get(slug=self.slug)
logger.debug('✓ Badge %s: fetched from db (%s)', obj.slug, self.db_read)
except Badge.DoesNotExist:
obj = None
r... | [
"def",
"get_badge",
"(",
"self",
")",
":",
"try",
":",
"obj",
"=",
"Badge",
".",
"objects",
".",
"using",
"(",
"self",
".",
"db_read",
")",
".",
"get",
"(",
"slug",
"=",
"self",
".",
"slug",
")",
"logger",
".",
"debug",
"(",
"'✓ Badge %s: fetched fro... | 32 | 17.2 |
def get_speed_steering(self, steering, speed):
"""
Calculate the speed_sp for each motor in a pair to achieve the specified
steering. Note that calling this function alone will not make the
motors move, it only calculates the speed. A run_* function must be called
afterwards to m... | [
"def",
"get_speed_steering",
"(",
"self",
",",
"steering",
",",
"speed",
")",
":",
"assert",
"steering",
">=",
"-",
"100",
"and",
"steering",
"<=",
"100",
",",
"\"{} is an invalid steering, must be between -100 and 100 (inclusive)\"",
".",
"format",
"(",
"steering",
... | 42.114286 | 25.771429 |
def render_koji(self):
"""
if there is yum repo specified, don't pick stuff from koji
"""
phase = 'prebuild_plugins'
plugin = 'koji'
if not self.dj.dock_json_has_plugin_conf(phase, plugin):
return
if self.spec.yum_repourls.value:
logger.in... | [
"def",
"render_koji",
"(",
"self",
")",
":",
"phase",
"=",
"'prebuild_plugins'",
"plugin",
"=",
"'koji'",
"if",
"not",
"self",
".",
"dj",
".",
"dock_json_has_plugin_conf",
"(",
"phase",
",",
"plugin",
")",
":",
"return",
"if",
"self",
".",
"spec",
".",
"... | 44.964286 | 16.535714 |
def _split_list(cls, items, separator=",", last_separator=" and "):
"""
Splits a string listing elements into an actual list.
Parameters
----------
items: :class:`str`
A string listing elements.
separator: :class:`str`
The separator between each i... | [
"def",
"_split_list",
"(",
"cls",
",",
"items",
",",
"separator",
"=",
"\",\"",
",",
"last_separator",
"=",
"\" and \"",
")",
":",
"if",
"items",
"is",
"None",
":",
"return",
"None",
"items",
"=",
"items",
".",
"split",
"(",
"separator",
")",
"last_item"... | 32.777778 | 14.407407 |
def cacheLock(self):
"""
This is a context manager to acquire a lock on the Lock file that will be used to
prevent synchronous cache operations between workers.
:yields: File descriptor for cache lock file in w mode
"""
cacheLockFile = open(self.cacheLockFile, 'w')
... | [
"def",
"cacheLock",
"(",
"self",
")",
":",
"cacheLockFile",
"=",
"open",
"(",
"self",
".",
"cacheLockFile",
",",
"'w'",
")",
"try",
":",
"flock",
"(",
"cacheLockFile",
",",
"LOCK_EX",
")",
"logger",
".",
"debug",
"(",
"\"CACHE: Obtained lock on file %s\"",
"... | 40.882353 | 19.352941 |
def reset(self, new_damping=None):
"""
Keeps all user supplied options the same, but resets counters etc.
"""
self._num_iter = 0
self._inner_run_counter = 0
self._J_update_counter = self.update_J_frequency
self._fresh_JTJ = False
self._has_run = False
... | [
"def",
"reset",
"(",
"self",
",",
"new_damping",
"=",
"None",
")",
":",
"self",
".",
"_num_iter",
"=",
"0",
"self",
".",
"_inner_run_counter",
"=",
"0",
"self",
".",
"_J_update_counter",
"=",
"self",
".",
"update_J_frequency",
"self",
".",
"_fresh_JTJ",
"=... | 36.583333 | 10.916667 |
def rank_motifs(stats, metrics=("roc_auc", "recall_at_fdr")):
"""Determine mean rank of motifs based on metrics."""
rank = {}
combined_metrics = []
motif_ids = stats.keys()
background = list(stats.values())[0].keys()
for metric in metrics:
mean_metric_stats = [np.mean(
[stats... | [
"def",
"rank_motifs",
"(",
"stats",
",",
"metrics",
"=",
"(",
"\"roc_auc\"",
",",
"\"recall_at_fdr\"",
")",
")",
":",
"rank",
"=",
"{",
"}",
"combined_metrics",
"=",
"[",
"]",
"motif_ids",
"=",
"stats",
".",
"keys",
"(",
")",
"background",
"=",
"list",
... | 36.875 | 19.1875 |
def random_mixed_actions(nums_actions, random_state=None):
"""
Return a tuple of random mixed actions (vectors of floats).
Parameters
----------
nums_actions : tuple(int)
Tuple of the numbers of actions, one for each player.
random_state : int or np.random.RandomState, optional
... | [
"def",
"random_mixed_actions",
"(",
"nums_actions",
",",
"random_state",
"=",
"None",
")",
":",
"random_state",
"=",
"check_random_state",
"(",
"random_state",
")",
"action_profile",
"=",
"tuple",
"(",
"[",
"probvec",
"(",
"1",
",",
"num_actions",
",",
"random_s... | 31.518519 | 21.444444 |
def delete(config, username, type):
"""Delete an LDAP user."""
client = Client()
client.prepare_connection()
user_api = API(client)
user_api.delete(username, type) | [
"def",
"delete",
"(",
"config",
",",
"username",
",",
"type",
")",
":",
"client",
"=",
"Client",
"(",
")",
"client",
".",
"prepare_connection",
"(",
")",
"user_api",
"=",
"API",
"(",
"client",
")",
"user_api",
".",
"delete",
"(",
"username",
",",
"type... | 33 | 6 |
def send_data(self):
"""Send data packets from the local file to the server"""
if not self.connection._sock:
raise err.InterfaceError("(0, '')")
conn = self.connection
try:
with open(self.filename, 'rb') as open_file:
packet_size = min(conn.max_al... | [
"def",
"send_data",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"connection",
".",
"_sock",
":",
"raise",
"err",
".",
"InterfaceError",
"(",
"\"(0, '')\"",
")",
"conn",
"=",
"self",
".",
"connection",
"try",
":",
"with",
"open",
"(",
"self",
".",
... | 41.315789 | 18.842105 |
def write(self, offset, data):
"""Write a string of bytes to the specified `offset` in bytes, relative
to the base physical address of the MMIO region.
Args:
offset (int, long): offset from base physical address, in bytes.
data (bytes, bytearray, list): a byte array or l... | [
"def",
"write",
"(",
"self",
",",
"offset",
",",
"data",
")",
":",
"if",
"not",
"isinstance",
"(",
"offset",
",",
"(",
"int",
",",
"long",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"Invalid offset type, should be integer.\"",
")",
"if",
"not",
"isinstanc... | 41.75 | 23.416667 |
def disconnected(self, client):
"""Call this method when a client disconnected."""
if client not in self.clients:
# already disconnected.
return
self.clients.remove(client)
self._log_disconnected(client)
self._close(client) | [
"def",
"disconnected",
"(",
"self",
",",
"client",
")",
":",
"if",
"client",
"not",
"in",
"self",
".",
"clients",
":",
"# already disconnected.",
"return",
"self",
".",
"clients",
".",
"remove",
"(",
"client",
")",
"self",
".",
"_log_disconnected",
"(",
"c... | 35 | 7.25 |
def from_ssl_socket(cls, ssl_socket):
"""Load certificate data from an SSL socket.
"""
cert = cls()
try:
data = ssl_socket.getpeercert()
except AttributeError:
# PyPy doesn't have .getppercert
return cert
logger.debug("Certificate data ... | [
"def",
"from_ssl_socket",
"(",
"cls",
",",
"ssl_socket",
")",
":",
"cert",
"=",
"cls",
"(",
")",
"try",
":",
"data",
"=",
"ssl_socket",
".",
"getpeercert",
"(",
")",
"except",
"AttributeError",
":",
"# PyPy doesn't have .getppercert",
"return",
"cert",
"logger... | 38.566667 | 11.4 |
def info(self):
"""Returns the name and version of the current shell"""
proc = Popen(['zsh', '-c', 'echo $ZSH_VERSION'],
stdout=PIPE, stderr=DEVNULL)
version = proc.stdout.read().decode('utf-8').strip()
return u'ZSH {}'.format(version) | [
"def",
"info",
"(",
"self",
")",
":",
"proc",
"=",
"Popen",
"(",
"[",
"'zsh'",
",",
"'-c'",
",",
"'echo $ZSH_VERSION'",
"]",
",",
"stdout",
"=",
"PIPE",
",",
"stderr",
"=",
"DEVNULL",
")",
"version",
"=",
"proc",
".",
"stdout",
".",
"read",
"(",
")... | 47.166667 | 11.666667 |
def put(self, transfer_id, amount, created_timestamp, receipt):
"""
:param transfer_id: int of the account_id to deposit the money to
:param amount: float of the amount to transfer
:param created_timestamp: str of the validated receipt that money has been received
... | [
"def",
"put",
"(",
"self",
",",
"transfer_id",
",",
"amount",
",",
"created_timestamp",
",",
"receipt",
")",
":",
"return",
"self",
".",
"connection",
".",
"put",
"(",
"'account/transfer/claim'",
",",
"data",
"=",
"dict",
"(",
"transfer_id",
"=",
"transfer_i... | 58.076923 | 22.538462 |
def enumerate_zones(self):
""" Return a list of (zone_id, zone_name) tuples """
zones = []
for controller in range(1, 8):
for zone in range(1, 17):
zone_id = ZoneID(zone, controller)
try:
name = yield from self.get_zone_variable(zon... | [
"def",
"enumerate_zones",
"(",
"self",
")",
":",
"zones",
"=",
"[",
"]",
"for",
"controller",
"in",
"range",
"(",
"1",
",",
"8",
")",
":",
"for",
"zone",
"in",
"range",
"(",
"1",
",",
"17",
")",
":",
"zone_id",
"=",
"ZoneID",
"(",
"zone",
",",
... | 37.846154 | 12.923077 |
def check_cdims(cls, ops, kwargs):
"""Check that all operands (`ops`) have equal channel dimension."""
if not len({o.cdim for o in ops}) == 1:
raise ValueError("Not all operands have the same cdim:" + str(ops))
return ops, kwargs | [
"def",
"check_cdims",
"(",
"cls",
",",
"ops",
",",
"kwargs",
")",
":",
"if",
"not",
"len",
"(",
"{",
"o",
".",
"cdim",
"for",
"o",
"in",
"ops",
"}",
")",
"==",
"1",
":",
"raise",
"ValueError",
"(",
"\"Not all operands have the same cdim:\"",
"+",
"str"... | 49 | 12.4 |
def copy(self, request, **kwargs):
# pylint: disable=unused-argument
'''
Copy instance with deps.
'''
instance = self.copy_instance(self.get_object())
serializer = self.get_serializer(instance, data=request.data, partial=True)
serializer.is_valid()
seriali... | [
"def",
"copy",
"(",
"self",
",",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=unused-argument",
"instance",
"=",
"self",
".",
"copy_instance",
"(",
"self",
".",
"get_object",
"(",
")",
")",
"serializer",
"=",
"self",
".",
"get_serializer"... | 39.2 | 18.8 |
def limit_text_to_be_path_element(text, max_length=None, separator='_'):
""" Replace characters that are not in the valid character set of RAFCON.
:param text: the string to be cleaned
:param max_length: the maximum length of the output string
:param separator: the separator used for rafcon.core.storag... | [
"def",
"limit_text_to_be_path_element",
"(",
"text",
",",
"max_length",
"=",
"None",
",",
"separator",
"=",
"'_'",
")",
":",
"# TODO: Should there not only be one method i.e. either this one or \"clean_path_element\"",
"elements_to_replace",
"=",
"{",
"' '",
":",
"'_'",
","... | 47.6875 | 20.3125 |
def set_bpf_filter_on_all_devices(filterstr):
'''
Long method name, but self-explanatory. Set the bpf
filter on all devices that have been opened.
'''
with PcapLiveDevice._lock:
for dev in PcapLiveDevice._OpenDevices.values():
_PcapFfi.instance()._set... | [
"def",
"set_bpf_filter_on_all_devices",
"(",
"filterstr",
")",
":",
"with",
"PcapLiveDevice",
".",
"_lock",
":",
"for",
"dev",
"in",
"PcapLiveDevice",
".",
"_OpenDevices",
".",
"values",
"(",
")",
":",
"_PcapFfi",
".",
"instance",
"(",
")",
".",
"_set_filter",... | 42 | 18 |
def storage_factory(storage_service, trajectory=None, **kwargs):
"""Creates a storage service, to be extended if new storage services are added
:param storage_service:
Storage Service instance of constructor or a string pointing to a file
:param trajectory:
A trajectory instance
:pa... | [
"def",
"storage_factory",
"(",
"storage_service",
",",
"trajectory",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'filename'",
"in",
"kwargs",
"and",
"storage_service",
"is",
"None",
":",
"filename",
"=",
"kwargs",
"[",
"'filename'",
"]",
"_",
",... | 32.702703 | 24.513514 |
def register(self, *magic_objects):
"""Register one or more instances of Magics.
Take one or more classes or instances of classes that subclass the main
`core.Magic` class, and register them with IPython to use the magic
functions they provide. The registration process will then ensur... | [
"def",
"register",
"(",
"self",
",",
"*",
"magic_objects",
")",
":",
"# Start by validating them to ensure they have all had their magic",
"# methods registered at the instance level",
"for",
"m",
"in",
"magic_objects",
":",
"if",
"not",
"m",
".",
"registered",
":",
"rais... | 45.942857 | 23.4 |
def __parse(self):
"""
Parse
Accept the text file. We'll open it, read it, and return a compiled dictionary to write to a json file
May write a chronology CSV and a data CSV if those sections are available
:return:
"""
logger_noaa_lpd.info("enter parse")
... | [
"def",
"__parse",
"(",
"self",
")",
":",
"logger_noaa_lpd",
".",
"info",
"(",
"\"enter parse\"",
")",
"# Strings",
"missing_str",
"=",
"''",
"data_filename",
"=",
"''",
"# Counters",
"grant_id",
"=",
"0",
"funding_id",
"=",
"0",
"data_col_ct",
"=",
"1",
"lin... | 54.672686 | 26.889391 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.