text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def BinaryBool(pred):
""" Lifts predicates that take an argument into the DSL. """
class Predicate(Bool):
def __init__(self, value, ignore_case=False):
self.value = caseless(value) if ignore_case else value
self.ignore_case = ignore_case
def __call__(self, data):
... | [
"def",
"BinaryBool",
"(",
"pred",
")",
":",
"class",
"Predicate",
"(",
"Bool",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"value",
",",
"ignore_case",
"=",
"False",
")",
":",
"self",
".",
"value",
"=",
"caseless",
"(",
"value",
")",
"if",
"ignore... | 34.888889 | 15.666667 |
def get_files_crc32(self):
"""
Calculates and returns a dictionary of filenames and CRC32
:returns: dict of filename: CRC32
"""
if self.files_crc32 == {}:
for i in self.get_files():
self._get_crc32(i)
return self.files_crc32 | [
"def",
"get_files_crc32",
"(",
"self",
")",
":",
"if",
"self",
".",
"files_crc32",
"==",
"{",
"}",
":",
"for",
"i",
"in",
"self",
".",
"get_files",
"(",
")",
":",
"self",
".",
"_get_crc32",
"(",
"i",
")",
"return",
"self",
".",
"files_crc32"
] | 26.545455 | 13.090909 |
def CaptureToImage(self, savePath: str, x: int = 0, y: int = 0, width: int = 0, height: int = 0) -> bool:
"""
Capture control to a image file.
savePath: str, should end with .bmp, .jpg, .jpeg, .png, .gif, .tif, .tiff.
x, y: int, the point in control's internal position(from 0,0).
... | [
"def",
"CaptureToImage",
"(",
"self",
",",
"savePath",
":",
"str",
",",
"x",
":",
"int",
"=",
"0",
",",
"y",
":",
"int",
"=",
"0",
",",
"width",
":",
"int",
"=",
"0",
",",
"height",
":",
"int",
"=",
"0",
")",
"->",
"bool",
":",
"bitmap",
"=",... | 55 | 24.846154 |
def get_vnetwork_vswitches_input_datacenter(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vnetwork_vswitches = ET.Element("get_vnetwork_vswitches")
config = get_vnetwork_vswitches
input = ET.SubElement(get_vnetwork_vswitches, "input")
... | [
"def",
"get_vnetwork_vswitches_input_datacenter",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_vnetwork_vswitches",
"=",
"ET",
".",
"Element",
"(",
"\"get_vnetwork_vswitches\"",
")",
"config",
... | 41.75 | 13.833333 |
def search_fast(self, text):
"""do a sloppy quick "search" via the json index"""
resp = self.impl.get(
"{base_url}/{text}/json".format(base_url=self.base_url, text=text)
)
return resp.json()["info"]["package_url"] | [
"def",
"search_fast",
"(",
"self",
",",
"text",
")",
":",
"resp",
"=",
"self",
".",
"impl",
".",
"get",
"(",
"\"{base_url}/{text}/json\"",
".",
"format",
"(",
"base_url",
"=",
"self",
".",
"base_url",
",",
"text",
"=",
"text",
")",
")",
"return",
"resp... | 33.142857 | 20.142857 |
def add_step(self, step):
"""
Adds a new step to the waterfall.
:param step: Step to add
:return: Waterfall dialog for fluent calls to `add_step()`.
"""
if not step:
raise TypeError('WaterfallDialog.add_step(): step cannot be None.')
self.... | [
"def",
"add_step",
"(",
"self",
",",
"step",
")",
":",
"if",
"not",
"step",
":",
"raise",
"TypeError",
"(",
"'WaterfallDialog.add_step(): step cannot be None.'",
")",
"self",
".",
"_steps",
".",
"append",
"(",
"step",
")",
"return",
"self"
] | 29 | 17.333333 |
def check(context: click.Context, family: str):
"""Delete an analysis log from the database."""
analysis_obj = context.obj['store'].analyses(family=family).first()
if analysis_obj is None:
LOG.error('no analysis found')
context.abort()
config_path = Path(analysis_obj.config_path)
if... | [
"def",
"check",
"(",
"context",
":",
"click",
".",
"Context",
",",
"family",
":",
"str",
")",
":",
"analysis_obj",
"=",
"context",
".",
"obj",
"[",
"'store'",
"]",
".",
"analyses",
"(",
"family",
"=",
"family",
")",
".",
"first",
"(",
")",
"if",
"a... | 40.115942 | 21.927536 |
def wait_gone(self, timeout=None, raise_error=True):
"""
Args:
timeout (float): default timeout
raise_error (bool): return bool or raise error
Returns:
bool: works when raise_error is False
Raises:
WDAElementNotDisappearError
... | [
"def",
"wait_gone",
"(",
"self",
",",
"timeout",
"=",
"None",
",",
"raise_error",
"=",
"True",
")",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"if",
"timeout",
"is",
"None",
"or",
"timeout",
"<=",
"0",
":",
"timeout",
"=",
"self",
".",
... | 30.666667 | 13.809524 |
def _inherit_docstrings(parent, excluded=[]):
"""Creates a decorator which overwrites a decorated class' __doc__
attribute with parent's __doc__ attribute. Also overwrites __doc__ of
methods and properties defined in the class with the __doc__ of matching
methods and properties in parent.
Args:
... | [
"def",
"_inherit_docstrings",
"(",
"parent",
",",
"excluded",
"=",
"[",
"]",
")",
":",
"def",
"decorator",
"(",
"cls",
")",
":",
"if",
"parent",
"not",
"in",
"excluded",
":",
"cls",
".",
"__doc__",
"=",
"parent",
".",
"__doc__",
"for",
"attr",
",",
"... | 38.848485 | 20.575758 |
def _union_indexes(indexes, sort=True):
"""
Return the union of indexes.
The behavior of sort and names is not consistent.
Parameters
----------
indexes : list of Index or list objects
sort : bool, default True
Whether the result index should come out sorted or not.
Returns
... | [
"def",
"_union_indexes",
"(",
"indexes",
",",
"sort",
"=",
"True",
")",
":",
"if",
"len",
"(",
"indexes",
")",
"==",
"0",
":",
"raise",
"AssertionError",
"(",
"'Must have at least 1 Index to union'",
")",
"if",
"len",
"(",
"indexes",
")",
"==",
"1",
":",
... | 26.146667 | 18.973333 |
def get(self):
"""Return the sparkline."""
ret = sparklines(self.percents)[0]
if self.__with_text:
percents_without_none = [x for x in self.percents if x is not None]
if len(percents_without_none) > 0:
ret = '{}{:5.1f}%'.format(ret, percents_without_none[-... | [
"def",
"get",
"(",
"self",
")",
":",
"ret",
"=",
"sparklines",
"(",
"self",
".",
"percents",
")",
"[",
"0",
"]",
"if",
"self",
".",
"__with_text",
":",
"percents_without_none",
"=",
"[",
"x",
"for",
"x",
"in",
"self",
".",
"percents",
"if",
"x",
"i... | 43.25 | 16.125 |
def read(self, page):
"""Send a READ command to retrieve data from the tag.
The *page* argument specifies the offset in multiples of 4
bytes (i.e. page number 1 will return bytes 4 to 19). The data
returned is a byte array of length 16 or None if the block is
outside the readabl... | [
"def",
"read",
"(",
"self",
",",
"page",
")",
":",
"log",
".",
"debug",
"(",
"\"read pages {0} to {1}\"",
".",
"format",
"(",
"page",
",",
"page",
"+",
"3",
")",
")",
"data",
"=",
"self",
".",
"transceive",
"(",
"\"\\x30\"",
"+",
"chr",
"(",
"page",
... | 38.148148 | 23.185185 |
def validate_stream(stream):
"""
Check that the stream name is well-formed.
"""
if not STREAM_REGEX.match(stream) or len(stream) > MAX_STREAM_LENGTH:
raise InvalidStreamName(stream) | [
"def",
"validate_stream",
"(",
"stream",
")",
":",
"if",
"not",
"STREAM_REGEX",
".",
"match",
"(",
"stream",
")",
"or",
"len",
"(",
"stream",
")",
">",
"MAX_STREAM_LENGTH",
":",
"raise",
"InvalidStreamName",
"(",
"stream",
")"
] | 31.333333 | 8.666667 |
def get_operation(cls, morph_type):
""" Maps morphological operation type to function
:param morph_type: Morphological operation type
:type morph_type: MorphologicalOperations
:return: function
"""
return {
cls.OPENING: skimage.morphology.opening,
... | [
"def",
"get_operation",
"(",
"cls",
",",
"morph_type",
")",
":",
"return",
"{",
"cls",
".",
"OPENING",
":",
"skimage",
".",
"morphology",
".",
"opening",
",",
"cls",
".",
"CLOSING",
":",
"skimage",
".",
"morphology",
".",
"closing",
",",
"cls",
".",
"D... | 38.785714 | 13.642857 |
def mnist_tutorial_cw(train_start=0, train_end=60000, test_start=0,
test_end=10000, viz_enabled=VIZ_ENABLED,
nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE,
source_samples=SOURCE_SAMPLES,
learning_rate=LEARNING_RATE,
... | [
"def",
"mnist_tutorial_cw",
"(",
"train_start",
"=",
"0",
",",
"train_end",
"=",
"60000",
",",
"test_start",
"=",
"0",
",",
"test_end",
"=",
"10000",
",",
"viz_enabled",
"=",
"VIZ_ENABLED",
",",
"nb_epochs",
"=",
"NB_EPOCHS",
",",
"batch_size",
"=",
"BATCH_S... | 35.835897 | 19.774359 |
def translate(self, dx, dy):
"""
Move the polygons from one place to another
Parameters
----------
dx : number
distance to move in the x-direction
dy : number
distance to move in the y-direction
Returns
-------
out : ``Pol... | [
"def",
"translate",
"(",
"self",
",",
"dx",
",",
"dy",
")",
":",
"vec",
"=",
"numpy",
".",
"array",
"(",
"(",
"dx",
",",
"dy",
")",
")",
"self",
".",
"polygons",
"=",
"[",
"points",
"+",
"vec",
"for",
"points",
"in",
"self",
".",
"polygons",
"]... | 24.789474 | 17.526316 |
def validate(self, value):
'''Return a boolean indicating if the value is a valid URI'''
if self.blank and value == '':
return True
if URIValidator.uri_regex.match(value):
self._choice = value
return True
else:
self.error_message = '%s is n... | [
"def",
"validate",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"blank",
"and",
"value",
"==",
"''",
":",
"return",
"True",
"if",
"URIValidator",
".",
"uri_regex",
".",
"match",
"(",
"value",
")",
":",
"self",
".",
"_choice",
"=",
"value",... | 35.9 | 16.1 |
def loadBinaryItemContainer(zippedfile, jsonHook):
"""Imports binaryItems from a zipfile generated by
:func:`writeBinaryItemContainer`.
:param zipfile: can be either a path to a file (a string) or a file-like
object
:param jsonHook: a custom decoding function for JSON formated strings of the
... | [
"def",
"loadBinaryItemContainer",
"(",
"zippedfile",
",",
"jsonHook",
")",
":",
"binaryItemContainer",
"=",
"dict",
"(",
")",
"with",
"zipfile",
".",
"ZipFile",
"(",
"zippedfile",
",",
"'r'",
")",
"as",
"containerZip",
":",
"#Convert the zipfile data into a str obje... | 48.666667 | 17.305556 |
def add_serverconnection_methods(cls):
"""Add a bunch of methods to an :class:`irc.client.SimpleIRCClient`
to send commands and messages.
Basically it wraps a bunch of methdos from
:class:`irc.client.ServerConnection` to be
:meth:`irc.schedule.IScheduler.execute_after`.
That way, you can easily... | [
"def",
"add_serverconnection_methods",
"(",
"cls",
")",
":",
"methods",
"=",
"[",
"'action'",
",",
"'admin'",
",",
"'cap'",
",",
"'ctcp'",
",",
"'ctcp_reply'",
",",
"'globops'",
",",
"'info'",
",",
"'invite'",
",",
"'ison'",
",",
"'join'",
",",
"'kick'",
"... | 44.566667 | 18.1 |
def pack(self, value=None):
"""Pack this structure updating the length and padding it."""
self._update_length()
packet = super().pack()
return self._complete_last_byte(packet) | [
"def",
"pack",
"(",
"self",
",",
"value",
"=",
"None",
")",
":",
"self",
".",
"_update_length",
"(",
")",
"packet",
"=",
"super",
"(",
")",
".",
"pack",
"(",
")",
"return",
"self",
".",
"_complete_last_byte",
"(",
"packet",
")"
] | 40.6 | 8 |
def post_note(self):
""" Post note and return the URL of the posted note """
if self.args.note_title:
note_title = self.args.note_title
else:
note_title = None
note_content = self.args.note_content
mynote = self.pump.Note(display_name=note_title, content=... | [
"def",
"post_note",
"(",
"self",
")",
":",
"if",
"self",
".",
"args",
".",
"note_title",
":",
"note_title",
"=",
"self",
".",
"args",
".",
"note_title",
"else",
":",
"note_title",
"=",
"None",
"note_content",
"=",
"self",
".",
"args",
".",
"note_content"... | 32.571429 | 16.214286 |
def make_app(global_conf, full_stack=True, static_files=True, **app_conf):
"""Create a Pylons WSGI application and return it
``global_conf``
The inherited configuration for this application. Normally from
the [DEFAULT] section of the Paste ini file.
``full_stack``
Whether this appl... | [
"def",
"make_app",
"(",
"global_conf",
",",
"full_stack",
"=",
"True",
",",
"static_files",
"=",
"True",
",",
"*",
"*",
"app_conf",
")",
":",
"# Configure the Pylons environment",
"config",
"=",
"load_environment",
"(",
"global_conf",
",",
"app_conf",
")",
"# Th... | 34.472727 | 22.654545 |
def get_idx_by_name(self, name):
# type: (str) -> Optional[int]
""" get_idx_by_name returns the index of a matching registered header
This implementation will prefer returning a static entry index whenever
possible. If multiple matching header name are found in the static
table,... | [
"def",
"get_idx_by_name",
"(",
"self",
",",
"name",
")",
":",
"# type: (str) -> Optional[int]",
"name",
"=",
"name",
".",
"lower",
"(",
")",
"for",
"key",
",",
"val",
"in",
"six",
".",
"iteritems",
"(",
"type",
"(",
"self",
")",
".",
"_static_entries",
"... | 44.777778 | 18.222222 |
def tokenparser(fmt, keys=None, token_cache={}):
"""Divide the format string into tokens and parse them.
Return stretchy token and list of [initialiser, length, value]
initialiser is one of: hex, oct, bin, uint, int, se, ue, 0x, 0o, 0b etc.
length is None if not known, as is value.
If the token is... | [
"def",
"tokenparser",
"(",
"fmt",
",",
"keys",
"=",
"None",
",",
"token_cache",
"=",
"{",
"}",
")",
":",
"try",
":",
"return",
"token_cache",
"[",
"(",
"fmt",
",",
"keys",
")",
"]",
"except",
"KeyError",
":",
"token_key",
"=",
"(",
"fmt",
",",
"key... | 42.11 | 15.85 |
def set_templates_dir(self):
"""Auto-connect slot activated when templates dir checkbox is toggled.
"""
is_checked = self.custom_templates_dir_checkbox.isChecked()
if is_checked:
# Show previous templates dir
path = setting(
key='reportTemplatePath... | [
"def",
"set_templates_dir",
"(",
"self",
")",
":",
"is_checked",
"=",
"self",
".",
"custom_templates_dir_checkbox",
".",
"isChecked",
"(",
")",
"if",
"is_checked",
":",
"# Show previous templates dir",
"path",
"=",
"setting",
"(",
"key",
"=",
"'reportTemplatePath'",... | 35.411765 | 12.294118 |
def main():
"""
fetches hek data and makes thematic maps as requested
"""
args = get_args()
config = Config(args.config)
# Load dates
if os.path.isfile(args.dates):
with open(args.dates) as f:
dates = [dateparser.parse(line.split(" ")[0]) for line in f.readlines()]
e... | [
"def",
"main",
"(",
")",
":",
"args",
"=",
"get_args",
"(",
")",
"config",
"=",
"Config",
"(",
"args",
".",
"config",
")",
"# Load dates",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"args",
".",
"dates",
")",
":",
"with",
"open",
"(",
"args",
"... | 37.1 | 21.3 |
def shutdown(self):
"""Forcefully shutdown the entire pool, closing all non-executing
connections.
:raises: ConnectionBusyError
"""
with self._lock:
for cid in list(self.connections.keys()):
if self.connections[cid].executing:
rai... | [
"def",
"shutdown",
"(",
"self",
")",
":",
"with",
"self",
".",
"_lock",
":",
"for",
"cid",
"in",
"list",
"(",
"self",
".",
"connections",
".",
"keys",
"(",
")",
")",
":",
"if",
"self",
".",
"connections",
"[",
"cid",
"]",
".",
"executing",
":",
"... | 34.6 | 13.133333 |
def distance_to_current_waypoint():
"""
Gets distance in metres to the current waypoint.
It returns None for the first waypoint (Home location).
"""
nextwaypoint = vehicle.commands.next
if nextwaypoint==0:
return None
missionitem=vehicle.commands[nextwaypoint-1] #commands are zero i... | [
"def",
"distance_to_current_waypoint",
"(",
")",
":",
"nextwaypoint",
"=",
"vehicle",
".",
"commands",
".",
"next",
"if",
"nextwaypoint",
"==",
"0",
":",
"return",
"None",
"missionitem",
"=",
"vehicle",
".",
"commands",
"[",
"nextwaypoint",
"-",
"1",
"]",
"#... | 38.2 | 17 |
def apply_completion(self, completion):
"""
Insert a given completion.
"""
assert isinstance(completion, Completion)
# If there was already a completion active, cancel that one.
if self.complete_state:
self.go_to_completion(None)
self.complete_state =... | [
"def",
"apply_completion",
"(",
"self",
",",
"completion",
")",
":",
"assert",
"isinstance",
"(",
"completion",
",",
"Completion",
")",
"# If there was already a completion active, cancel that one.",
"if",
"self",
".",
"complete_state",
":",
"self",
".",
"go_to_completi... | 33.285714 | 12.142857 |
def get_attributes(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if attributes are set on an ELB.
CLI example:
.. code-block:: bash
salt myminion boto_elb.get_attributes myelb
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
ret... | [
"def",
"get_attributes",
"(",
"name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key",
",",
"keyid... | 40.674419 | 21.651163 |
def set_locations(self, locations, values):
"""
For a list of locations set the values.
:param locations: list of index locations
:param values: list of values or a single value
:return: nothing
"""
indexes = [self._index[x] for x in locations]
self.set(... | [
"def",
"set_locations",
"(",
"self",
",",
"locations",
",",
"values",
")",
":",
"indexes",
"=",
"[",
"self",
".",
"_index",
"[",
"x",
"]",
"for",
"x",
"in",
"locations",
"]",
"self",
".",
"set",
"(",
"indexes",
",",
"values",
")"
] | 29.636364 | 13.636364 |
def elemental_abund(self,cycle,zrange=[1,85],ylim=[0,0],title_items=None,
ref=-1,ref_filename=None,z_pin=None,pin=None,
pin_filename=None,zchi2=None,logeps=False,dilution=None,show_names=True,label='',
colour='black',plotlines=':',plotlabels=True,m... | [
"def",
"elemental_abund",
"(",
"self",
",",
"cycle",
",",
"zrange",
"=",
"[",
"1",
",",
"85",
"]",
",",
"ylim",
"=",
"[",
"0",
",",
"0",
"]",
",",
"title_items",
"=",
"None",
",",
"ref",
"=",
"-",
"1",
",",
"ref_filename",
"=",
"None",
",",
"z_... | 51.540476 | 22.459524 |
def transform_standard_normal(df):
"""Transform a series or the rows of a dataframe to the values of a standard
normal based on rank."""
import pandas as pd
import scipy.stats as stats
if type(df) == pd.core.frame.DataFrame:
gc_ranks = df.rank(axis=1)
gc_ranks = gc_ranks / (gc_ranks.... | [
"def",
"transform_standard_normal",
"(",
"df",
")",
":",
"import",
"pandas",
"as",
"pd",
"import",
"scipy",
".",
"stats",
"as",
"stats",
"if",
"type",
"(",
"df",
")",
"==",
"pd",
".",
"core",
".",
"frame",
".",
"DataFrame",
":",
"gc_ranks",
"=",
"df",
... | 42.941176 | 9.647059 |
def BitVecSym(
name: str, size: int, annotations: Annotations = None
) -> z3.BitVecRef:
"""Creates a new bit vector with a symbolic value."""
return z3.BitVec(name, size) | [
"def",
"BitVecSym",
"(",
"name",
":",
"str",
",",
"size",
":",
"int",
",",
"annotations",
":",
"Annotations",
"=",
"None",
")",
"->",
"z3",
".",
"BitVecRef",
":",
"return",
"z3",
".",
"BitVec",
"(",
"name",
",",
"size",
")"
] | 38.8 | 13.8 |
def get_capabilities_properties(d_info,
capa_keys,
gpu_ids,
fpga_ids=None,
**kwargs):
"""get capabilities properties
This function returns a dictionary which contains keys
and the... | [
"def",
"get_capabilities_properties",
"(",
"d_info",
",",
"capa_keys",
",",
"gpu_ids",
",",
"fpga_ids",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"snmp_client",
"=",
"snmp",
".",
"SNMPClient",
"(",
"d_info",
"[",
"'irmc_address'",
"]",
",",
"d_info",
... | 40.086207 | 21.517241 |
def config():
'''
Shows the current configuration.
'''
config = get_config()
print('Client version: {0}'.format(click.style(__version__, bold=True)))
print('API endpoint: {0}'.format(click.style(str(config.endpoint), bold=True)))
print('API version: {0}'.format(click.style(config.version, bo... | [
"def",
"config",
"(",
")",
":",
"config",
"=",
"get_config",
"(",
")",
"print",
"(",
"'Client version: {0}'",
".",
"format",
"(",
"click",
".",
"style",
"(",
"__version__",
",",
"bold",
"=",
"True",
")",
")",
")",
"print",
"(",
"'API endpoint: {0}'",
"."... | 51.6 | 26.533333 |
def polls_slug_get(self, slug, **kwargs):
"""
Poll
A Poll on Pollster is a collection of questions and responses published by a reputable survey house. This endpoint provides raw data from the survey house, plus Pollster-provided metadata about each question. Pollster editors don't include ever... | [
"def",
"polls_slug_get",
"(",
"self",
",",
"slug",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"polls_slug_get_with_http_info"... | 55.769231 | 34.461538 |
def parse_datetime(value):
"""
Convert datetime string to datetime object.
Helper function to convert a datetime string found in json responses to a datetime object with timezone information.
The server is storing all datetime strings as UTC (ZULU time). This function supports time zone offsets. When
... | [
"def",
"parse_datetime",
"(",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"# do not process the value",
"return",
"None",
"def",
"_get_fixed_timezone",
"(",
"offset",
")",
":",
"\"\"\"Return a tzinfo instance with a fixed offset from UTC.\"\"\"",
"if",
"isinstanc... | 39.338983 | 21.508475 |
def set_mac_addr_adv_interval(self, name, vrid, value=None, disable=False,
default=False, run=True):
"""Set the mac_addr_adv_interval property of the vrrp
Args:
name (string): The interface to configure.
vrid (integer): The vrid number for the v... | [
"def",
"set_mac_addr_adv_interval",
"(",
"self",
",",
"name",
",",
"vrid",
",",
"value",
"=",
"None",
",",
"disable",
"=",
"False",
",",
"default",
"=",
"False",
",",
"run",
"=",
"True",
")",
":",
"if",
"not",
"default",
"and",
"not",
"disable",
":",
... | 40.136364 | 23 |
def from_numpy_arrays(freq_data, noise_data, length, delta_f, low_freq_cutoff):
"""Interpolate n PSD (as two 1-dimensional arrays of frequency and data)
to the desired length, delta_f and low frequency cutoff.
Parameters
----------
freq_data : array
Array of frequencies.
noise_data : ar... | [
"def",
"from_numpy_arrays",
"(",
"freq_data",
",",
"noise_data",
",",
"length",
",",
"delta_f",
",",
"low_freq_cutoff",
")",
":",
"# Only include points above the low frequency cutoff",
"if",
"freq_data",
"[",
"0",
"]",
">",
"low_freq_cutoff",
":",
"raise",
"ValueErro... | 32.529412 | 20.901961 |
def load_msgpack(blob, **kwargs):
"""
Load a dict packed with msgpack into kwargs for
a Trimesh constructor
Parameters
----------
blob : bytes
msgpack packed dict containing
keys 'vertices' and 'faces'
Returns
----------
loaded : dict
Keyword args for Trimesh const... | [
"def",
"load_msgpack",
"(",
"blob",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"msgpack",
"if",
"hasattr",
"(",
"blob",
",",
"'read'",
")",
":",
"data",
"=",
"msgpack",
".",
"load",
"(",
"blob",
")",
"else",
":",
"data",
"=",
"msgpack",
".",
"loa... | 21.08 | 17.64 |
def _validate(url):
"""Validate a url.
:param str url: Polling URL extracted from response header.
:raises: ValueError if URL has no scheme or host.
"""
if url is None:
return
parsed = urlparse(url)
if not parsed.scheme or not parsed.netloc:
raise ValueError("Invalid URL hea... | [
"def",
"_validate",
"(",
"url",
")",
":",
"if",
"url",
"is",
"None",
":",
"return",
"parsed",
"=",
"urlparse",
"(",
"url",
")",
"if",
"not",
"parsed",
".",
"scheme",
"or",
"not",
"parsed",
".",
"netloc",
":",
"raise",
"ValueError",
"(",
"\"Invalid URL ... | 28.636364 | 15.454545 |
def add_data_file(self, from_fp, timestamp=None, content_type=None):
# type: (IO, Optional[datetime.datetime], Optional[str]) -> Text
"""Copy inputs to data/ folder."""
self.self_check()
tmp_dir, tmp_prefix = os.path.split(self.temp_prefix)
with tempfile.NamedTemporaryFile(
... | [
"def",
"add_data_file",
"(",
"self",
",",
"from_fp",
",",
"timestamp",
"=",
"None",
",",
"content_type",
"=",
"None",
")",
":",
"# type: (IO, Optional[datetime.datetime], Optional[str]) -> Text",
"self",
".",
"self_check",
"(",
")",
"tmp_dir",
",",
"tmp_prefix",
"="... | 42.076923 | 17.717949 |
def is_compatible(self, model, version):
""" Check if this flag is compatible with a YubiKey of version 'ver'. """
if not model in self.models:
return False
if self.max_ykver:
return (version >= self.min_ykver and
version <= self.max_ykver)
els... | [
"def",
"is_compatible",
"(",
"self",
",",
"model",
",",
"version",
")",
":",
"if",
"not",
"model",
"in",
"self",
".",
"models",
":",
"return",
"False",
"if",
"self",
".",
"max_ykver",
":",
"return",
"(",
"version",
">=",
"self",
".",
"min_ykver",
"and"... | 39.888889 | 8.888889 |
def put(self, request, id, format=None):
"""
Update an existing bot
---
serializer: BotUpdateSerializer
responseMessages:
- code: 401
message: Not authenticated
- code: 400
message: Not valid request
"""
bot = se... | [
"def",
"put",
"(",
"self",
",",
"request",
",",
"id",
",",
"format",
"=",
"None",
")",
":",
"bot",
"=",
"self",
".",
"get_bot",
"(",
"id",
",",
"request",
".",
"user",
")",
"serializer",
"=",
"BotUpdateSerializer",
"(",
"bot",
",",
"data",
"=",
"re... | 34.571429 | 13.047619 |
def forest(self, data: ['SASdata', str] = None,
autotune: str = None,
code: str = None,
crossvalidation: str = None,
grow: str = None,
id: str = None,
input: [str, list, dict] = None,
output: [str, bool, 'SASdata'] ... | [
"def",
"forest",
"(",
"self",
",",
"data",
":",
"[",
"'SASdata'",
",",
"str",
"]",
"=",
"None",
",",
"autotune",
":",
"str",
"=",
"None",
",",
"code",
":",
"str",
"=",
"None",
",",
"crossvalidation",
":",
"str",
"=",
"None",
",",
"grow",
":",
"st... | 57.25641 | 26.435897 |
def alter_function(self, dbName, funcName, newFunc):
"""
Parameters:
- dbName
- funcName
- newFunc
"""
self.send_alter_function(dbName, funcName, newFunc)
self.recv_alter_function() | [
"def",
"alter_function",
"(",
"self",
",",
"dbName",
",",
"funcName",
",",
"newFunc",
")",
":",
"self",
".",
"send_alter_function",
"(",
"dbName",
",",
"funcName",
",",
"newFunc",
")",
"self",
".",
"recv_alter_function",
"(",
")"
] | 23.111111 | 15.555556 |
def add_target(self, name=None):
"""
Add an SCons target to this nest.
The function decorated will be immediately called with each of the
output directories and current control dictionaries. Each result will
be added to the respective control dictionary for later nests to
... | [
"def",
"add_target",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"def",
"deco",
"(",
"func",
")",
":",
"def",
"nestfunc",
"(",
"control",
")",
":",
"destdir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"dest_dir",
",",
"control",
... | 38.15 | 18.85 |
def map(self, **kwargs):
''' Change a name on the fly. Compat with kr/env. '''
return { key: str(self._envars[kwargs[key]]) # str strips Entry
for key in kwargs } | [
"def",
"map",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"{",
"key",
":",
"str",
"(",
"self",
".",
"_envars",
"[",
"kwargs",
"[",
"key",
"]",
"]",
")",
"# str strips Entry",
"for",
"key",
"in",
"kwargs",
"}"
] | 48.5 | 18.5 |
def get_sections(need_info):
"""Gets the hierarchy of the section nodes as a list starting at the
section of the current need and then its parent sections"""
sections = []
current_node = need_info['target_node']
while current_node:
if isinstance(current_node, nodes.section):
titl... | [
"def",
"get_sections",
"(",
"need_info",
")",
":",
"sections",
"=",
"[",
"]",
"current_node",
"=",
"need_info",
"[",
"'target_node'",
"]",
"while",
"current_node",
":",
"if",
"isinstance",
"(",
"current_node",
",",
"nodes",
".",
"section",
")",
":",
"title",... | 47.625 | 15.5625 |
def aggregate_rate(rate_key, count_key):
"""
Compute an aggregate rate for `rate_key` weighted according to
`count_rate`.
"""
def inner(docs):
total = sum(doc[count_key] for doc in docs)
weighted_total = sum(doc[rate_key] * doc[count_key] for doc in docs)
total_rate = weighte... | [
"def",
"aggregate_rate",
"(",
"rate_key",
",",
"count_key",
")",
":",
"def",
"inner",
"(",
"docs",
")",
":",
"total",
"=",
"sum",
"(",
"doc",
"[",
"count_key",
"]",
"for",
"doc",
"in",
"docs",
")",
"weighted_total",
"=",
"sum",
"(",
"doc",
"[",
"rate... | 31.5 | 15.666667 |
def check_messages(filename, report_empty=False):
"""
Checks messages in `filename` in various ways:
* Translations must have the same slots as the English.
* Messages can't have astral characters in them.
If `report_empty` is True, will also report empty translation strings.
Returns the pro... | [
"def",
"check_messages",
"(",
"filename",
",",
"report_empty",
"=",
"False",
")",
":",
"problems",
"=",
"[",
"]",
"pomsgs",
"=",
"polib",
".",
"pofile",
"(",
"filename",
")",
"for",
"msg",
"in",
"pomsgs",
":",
"# Check for characters Javascript can't support.",
... | 36.032258 | 20.645161 |
def init_with_context(self, context):
"""
Please refer to
:meth:`~admin_tools.menu.items.MenuItem.init_with_context`
documentation from :class:`~admin_tools.menu.items.MenuItem` class.
"""
items = self._visible_models(context['request'])
apps = {}
for mode... | [
"def",
"init_with_context",
"(",
"self",
",",
"context",
")",
":",
"items",
"=",
"self",
".",
"_visible_models",
"(",
"context",
"[",
"'request'",
"]",
")",
"apps",
"=",
"{",
"}",
"for",
"model",
",",
"perms",
"in",
"items",
":",
"if",
"not",
"(",
"p... | 41.875 | 15.75 |
def check_event(self, event):
# type: (ServiceEvent) -> bool
"""
Tests if the given service event must be handled or ignored, based
on the state of the iPOPO service and on the content of the event.
:param event: A service event
:return: True if the event can be handled,... | [
"def",
"check_event",
"(",
"self",
",",
"event",
")",
":",
"# type: (ServiceEvent) -> bool",
"with",
"self",
".",
"_lock",
":",
"if",
"self",
".",
"state",
"==",
"StoredInstance",
".",
"KILLED",
":",
"# This call may have been blocked by the internal state lock,",
"# ... | 39.3125 | 20.0625 |
def is_icao_assigned(icao):
""" Check whether the ICAO address is assigned (Annex 10, Vol 3)"""
if (icao is None) or (not isinstance(icao, str)) or (len(icao)!=6):
return False
icaoint = hex2int(icao)
if 0x200000 < icaoint < 0x27FFFF: return False # AFI
if 0x280000 < icaoint < 0x28FF... | [
"def",
"is_icao_assigned",
"(",
"icao",
")",
":",
"if",
"(",
"icao",
"is",
"None",
")",
"or",
"(",
"not",
"isinstance",
"(",
"icao",
",",
"str",
")",
")",
"or",
"(",
"len",
"(",
"icao",
")",
"!=",
"6",
")",
":",
"return",
"False",
"icaoint",
"=",... | 41.947368 | 24.631579 |
def info(self, **kwargs):
"""
Get the detailed information about a particular credit record. This is
currently only supported with the new credit model found in TV. These
ids can be found from any TV credit response as well as the tv_credits
and combined_credits methods for pe... | [
"def",
"info",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"path",
"=",
"self",
".",
"_get_credit_id_path",
"(",
"'info'",
")",
"response",
"=",
"self",
".",
"_GET",
"(",
"path",
",",
"kwargs",
")",
"self",
".",
"_set_attrs_to_values",
"(",
"respon... | 40.208333 | 22.875 |
def add_widget_to_content(self, widget):
"""Subclasses should call this to add content in the section's top level column."""
self.__section_content_column.add_spacing(4)
self.__section_content_column.add(widget) | [
"def",
"add_widget_to_content",
"(",
"self",
",",
"widget",
")",
":",
"self",
".",
"__section_content_column",
".",
"add_spacing",
"(",
"4",
")",
"self",
".",
"__section_content_column",
".",
"add",
"(",
"widget",
")"
] | 58 | 5.25 |
def main(arguments=None):
"""Main command line entry point."""
if not arguments:
arguments = sys.argv[1:]
wordlist, sowpods, by_length, start, end = argument_parser(arguments)
for word in wordlist:
pretty_print(
word,
anagrams_in_word(word, sowpods, start, end),... | [
"def",
"main",
"(",
"arguments",
"=",
"None",
")",
":",
"if",
"not",
"arguments",
":",
"arguments",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"wordlist",
",",
"sowpods",
",",
"by_length",
",",
"start",
",",
"end",
"=",
"argument_parser",
"(",
"arg... | 26.230769 | 21.307692 |
def create_dump():
""" Create the grammar for the 'dump' statement """
dump = upkey("dump").setResultsName("action")
return (
dump
+ upkey("schema")
+ Optional(Group(delimitedList(table)).setResultsName("tables"))
) | [
"def",
"create_dump",
"(",
")",
":",
"dump",
"=",
"upkey",
"(",
"\"dump\"",
")",
".",
"setResultsName",
"(",
"\"action\"",
")",
"return",
"(",
"dump",
"+",
"upkey",
"(",
"\"schema\"",
")",
"+",
"Optional",
"(",
"Group",
"(",
"delimitedList",
"(",
"table"... | 31 | 21.125 |
def get_scale(self, gg):
"""
Create a scale
"""
# This method does some introspection to save users from
# scale mismatch error. This could happen when the
# aesthetic is mapped to a categorical but the limits
# are not provided in categorical form. We only handle... | [
"def",
"get_scale",
"(",
"self",
",",
"gg",
")",
":",
"# This method does some introspection to save users from",
"# scale mismatch error. This could happen when the",
"# aesthetic is mapped to a categorical but the limits",
"# are not provided in categorical form. We only handle",
"# the ca... | 41.526316 | 14.315789 |
def read_setup_py_source(self): # type: () -> None
"""
Read setup.py to string
:return:
"""
if not self.setup_file_name:
self.setup_source = ""
if not self.setup_source:
self.setup_source = self._read_file(self.setup_file_name) | [
"def",
"read_setup_py_source",
"(",
"self",
")",
":",
"# type: () -> None",
"if",
"not",
"self",
".",
"setup_file_name",
":",
"self",
".",
"setup_source",
"=",
"\"\"",
"if",
"not",
"self",
".",
"setup_source",
":",
"self",
".",
"setup_source",
"=",
"self",
"... | 32.444444 | 10 |
def get(self, block=1, delay=None):
"""Get a request from a queue, optionally block until a request
is available."""
if _debug: IOQueue._debug("get block=%r delay=%r", block, delay)
# if the queue is empty and we do not block return None
if not block and not self.notempty.isSet(... | [
"def",
"get",
"(",
"self",
",",
"block",
"=",
"1",
",",
"delay",
"=",
"None",
")",
":",
"if",
"_debug",
":",
"IOQueue",
".",
"_debug",
"(",
"\"get block=%r delay=%r\"",
",",
"block",
",",
"delay",
")",
"# if the queue is empty and we do not block return None",
... | 30.833333 | 17.066667 |
def _pki_minions(self):
'''
Retreive complete minion list from PKI dir.
Respects cache if configured
'''
minions = []
pki_cache_fn = os.path.join(self.opts['pki_dir'], self.acc, '.key_cache')
try:
os.makedirs(os.path.dirname(pki_cache_fn))
exce... | [
"def",
"_pki_minions",
"(",
"self",
")",
":",
"minions",
"=",
"[",
"]",
"pki_cache_fn",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"opts",
"[",
"'pki_dir'",
"]",
",",
"self",
".",
"acc",
",",
"'.key_cache'",
")",
"try",
":",
"os",
".",
... | 41.580645 | 24.483871 |
def wait_command(self, start_func, turns=1, end_func=None):
"""Call ``start_func``, and wait to call ``end_func`` after simulating ``turns`` (default 1)
:param start_func: function to call before waiting
:param turns: number of turns to wait
:param end_func: function to call after waiti... | [
"def",
"wait_command",
"(",
"self",
",",
"start_func",
",",
"turns",
"=",
"1",
",",
"end_func",
"=",
"None",
")",
":",
"start_func",
"(",
")",
"self",
".",
"wait_turns",
"(",
"turns",
",",
"cb",
"=",
"end_func",
")"
] | 37.818182 | 15.909091 |
def std(self, axis=None, keepdims=False):
"""
Return the standard deviation of the array over the given axis.
Parameters
----------
axis : tuple or int, optional, default=None
Axis to compute statistic over, if None
will compute over all axes
kee... | [
"def",
"std",
"(",
"self",
",",
"axis",
"=",
"None",
",",
"keepdims",
"=",
"False",
")",
":",
"return",
"self",
".",
"_stat",
"(",
"axis",
",",
"name",
"=",
"'stdev'",
",",
"keepdims",
"=",
"keepdims",
")"
] | 34.642857 | 16.785714 |
def TeArraySizeCheck(self):
"""
Checks that Te and q0 array sizes are compatible
For finite difference solution.
"""
# Only if they are both defined and are arrays
# Both being arrays is a possible bug in this check routine that I have
# intentionally introduced
if type(self.Te) == np.n... | [
"def",
"TeArraySizeCheck",
"(",
"self",
")",
":",
"# Only if they are both defined and are arrays",
"# Both being arrays is a possible bug in this check routine that I have ",
"# intentionally introduced",
"if",
"type",
"(",
"self",
".",
"Te",
")",
"==",
"np",
".",
"ndarray",
... | 44.2 | 16.6 |
def json_data(self, data=None):
"""Adds the default_data to data and dumps it to a json."""
if data is None:
data = {}
data.update(self.default_data)
return json.dumps(data) | [
"def",
"json_data",
"(",
"self",
",",
"data",
"=",
"None",
")",
":",
"if",
"data",
"is",
"None",
":",
"data",
"=",
"{",
"}",
"data",
".",
"update",
"(",
"self",
".",
"default_data",
")",
"return",
"json",
".",
"dumps",
"(",
"data",
")"
] | 35.333333 | 9.166667 |
def mean_rate(self):
"""
Returns the mean rate of the events since the start of the process.
"""
if self.counter.value == 0:
return 0.0
else:
elapsed = time() - self.start_time
return self.counter.value / elapsed | [
"def",
"mean_rate",
"(",
"self",
")",
":",
"if",
"self",
".",
"counter",
".",
"value",
"==",
"0",
":",
"return",
"0.0",
"else",
":",
"elapsed",
"=",
"time",
"(",
")",
"-",
"self",
".",
"start_time",
"return",
"self",
".",
"counter",
".",
"value",
"... | 31.111111 | 13.111111 |
def load(self):
"""Loads configuration file"""
# Config files prior to 0.2.4 dor not have config version keys
old_config = not self.cfg_file.Exists("config_version")
# Reset data
self.data.__dict__.update(self.defaults.__dict__)
for key in self.defaults.__dict__:
... | [
"def",
"load",
"(",
"self",
")",
":",
"# Config files prior to 0.2.4 dor not have config version keys",
"old_config",
"=",
"not",
"self",
".",
"cfg_file",
".",
"Exists",
"(",
"\"config_version\"",
")",
"# Reset data",
"self",
".",
"data",
".",
"__dict__",
".",
"upda... | 38.307692 | 20.923077 |
async def update(self) -> None:
"""Get the latest data from api.entur.org."""
headers = {'ET-Client-Name': self._client_name}
request = {
'query': self.get_gql_query(),
'variables': {
'stops': self.stops,
'quays': self.quays,
... | [
"async",
"def",
"update",
"(",
"self",
")",
"->",
"None",
":",
"headers",
"=",
"{",
"'ET-Client-Name'",
":",
"self",
".",
"_client_name",
"}",
"request",
"=",
"{",
"'query'",
":",
"self",
".",
"get_gql_query",
"(",
")",
",",
"'variables'",
":",
"{",
"'... | 33.395349 | 17.651163 |
def _truncate_to_field(model, field_name, value):
"""
Shorten data to fit in the specified model field.
If the data were too big for the field, it would cause a failure to
insert, so we shorten it, truncating in the middle (because
valuable information often shows up at the end.
"""
field =... | [
"def",
"_truncate_to_field",
"(",
"model",
",",
"field_name",
",",
"value",
")",
":",
"field",
"=",
"model",
".",
"_meta",
".",
"get_field",
"(",
"field_name",
")",
"# pylint: disable=protected-access",
"if",
"len",
"(",
"value",
")",
">",
"field",
".",
"max... | 40.352941 | 15.647059 |
def _post_analysis(self):
"""
Post-CFG-construction.
:return: None
"""
self._make_completed_functions()
new_changes = self._iteratively_analyze_function_features()
functions_do_not_return = new_changes['functions_do_not_return']
self._update_function_cal... | [
"def",
"_post_analysis",
"(",
"self",
")",
":",
"self",
".",
"_make_completed_functions",
"(",
")",
"new_changes",
"=",
"self",
".",
"_iteratively_analyze_function_features",
"(",
")",
"functions_do_not_return",
"=",
"new_changes",
"[",
"'functions_do_not_return'",
"]",... | 31.904762 | 18.952381 |
def update_source(self, id, **kwargs): # noqa: E501
"""Update metadata (description or tags) for a specific source. # noqa: E501
The \"hidden\" property is stored as a tag. To set the value, add \"hidden\": <value> to the list of tags. # noqa: E501
This method makes a synchronous HTTP ... | [
"def",
"update_source",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"update_source_... | 53.045455 | 26.318182 |
def IsFile(path):
'''
:param unicode path:
Path to a file (local or ftp)
:raises NotImplementedProtocol:
If checking for a non-local, non-ftp file
:rtype: bool
:returns:
True if the file exists
.. seealso:: FTP LIMITATIONS at this module's doc for performance issues in... | [
"def",
"IsFile",
"(",
"path",
")",
":",
"from",
"six",
".",
"moves",
".",
"urllib",
".",
"parse",
"import",
"urlparse",
"url",
"=",
"urlparse",
"(",
"path",
")",
"if",
"_UrlIsLocal",
"(",
"url",
")",
":",
"if",
"IsLink",
"(",
"path",
")",
":",
"ret... | 27.25 | 20.678571 |
def import_jwks_as_json(self, jwks, issuer):
"""
Imports all the keys that are represented in a JWKS expressed as a
JSON object
:param jwks: JSON representation of a JWKS
:param issuer: Who 'owns' the JWKS
"""
return self.import_jwks(json.loads(jwks), issuer) | [
"def",
"import_jwks_as_json",
"(",
"self",
",",
"jwks",
",",
"issuer",
")",
":",
"return",
"self",
".",
"import_jwks",
"(",
"json",
".",
"loads",
"(",
"jwks",
")",
",",
"issuer",
")"
] | 34.222222 | 14.222222 |
def kafka_kip(enrich):
""" Kafka Improvement Proposals process study """
def extract_vote_and_binding(body):
""" Extracts the vote and binding for a KIP process included in message body """
vote = 0
binding = 0 # by default the votes are binding for +1
nlines = 0
for... | [
"def",
"kafka_kip",
"(",
"enrich",
")",
":",
"def",
"extract_vote_and_binding",
"(",
"body",
")",
":",
"\"\"\" Extracts the vote and binding for a KIP process included in message body \"\"\"",
"vote",
"=",
"0",
"binding",
"=",
"0",
"# by default the votes are binding for +1",
... | 36.886199 | 19.581114 |
def get_tasks():
'''Get a list of known tasks with their routing queue'''
return {
name: get_task_queue(name, cls)
for name, cls in celery.tasks.items()
# Exclude celery internal tasks
if not name.startswith('celery.')
# Exclude udata test tasks
and not name.start... | [
"def",
"get_tasks",
"(",
")",
":",
"return",
"{",
"name",
":",
"get_task_queue",
"(",
"name",
",",
"cls",
")",
"for",
"name",
",",
"cls",
"in",
"celery",
".",
"tasks",
".",
"items",
"(",
")",
"# Exclude celery internal tasks",
"if",
"not",
"name",
".",
... | 33.1 | 12.1 |
def _extract_zip_if_possible(descriptor):
"""If descriptor is a path to zip file extract and return (tempdir, descriptor)
"""
tempdir = None
result = descriptor
try:
if isinstance(descriptor, six.string_types):
res = requests.get(descriptor)
res.raise_for_status()
... | [
"def",
"_extract_zip_if_possible",
"(",
"descriptor",
")",
":",
"tempdir",
"=",
"None",
"result",
"=",
"descriptor",
"try",
":",
"if",
"isinstance",
"(",
"descriptor",
",",
"six",
".",
"string_types",
")",
":",
"res",
"=",
"requests",
".",
"get",
"(",
"des... | 35.175 | 14.075 |
def Run(self):
"""Run the iteration."""
count = 0
for count, input_data in enumerate(self.GetInput()):
if count % 2000 == 0:
logging.debug("%d processed.", count)
args = (input_data, self.out_queue, self.token)
self.thread_pool.AddTask(
target=self.IterFunction, args=args... | [
"def",
"Run",
"(",
"self",
")",
":",
"count",
"=",
"0",
"for",
"count",
",",
"input_data",
"in",
"enumerate",
"(",
"self",
".",
"GetInput",
"(",
")",
")",
":",
"if",
"count",
"%",
"2000",
"==",
"0",
":",
"logging",
".",
"debug",
"(",
"\"%d processe... | 33.26087 | 20.913043 |
def _add_raster_layer(self, raster_layer, layer_name, save_style=False):
"""Add a raster layer to the folder.
:param raster_layer: The layer to add.
:type raster_layer: QgsRasterLayer
:param layer_name: The name of the layer in the datastore.
:type layer_name: str
:par... | [
"def",
"_add_raster_layer",
"(",
"self",
",",
"raster_layer",
",",
"layer_name",
",",
"save_style",
"=",
"False",
")",
":",
"source",
"=",
"gdal",
".",
"Open",
"(",
"raster_layer",
".",
"source",
"(",
")",
")",
"array",
"=",
"source",
".",
"GetRasterBand",... | 32.136364 | 20.704545 |
def removeDuplicates(inFileName, outFileName) :
"""removes duplicated lines from a 'inFileName' CSV file, the results are witten in 'outFileName'"""
f = open(inFileName)
legend = f.readline()
data = ''
h = {}
h[legend] = 0
lines = f.readlines()
for l in lines :
if not h.has_key(l) :
h[l] = 0
data +=... | [
"def",
"removeDuplicates",
"(",
"inFileName",
",",
"outFileName",
")",
":",
"f",
"=",
"open",
"(",
"inFileName",
")",
"legend",
"=",
"f",
".",
"readline",
"(",
")",
"data",
"=",
"''",
"h",
"=",
"{",
"}",
"h",
"[",
"legend",
"]",
"=",
"0",
"lines",
... | 19.047619 | 24.52381 |
def runSearchRnaQuantificationSets(self, request):
"""
Returns a SearchRnaQuantificationSetsResponse for the specified
SearchRnaQuantificationSetsRequest object.
"""
return self.runSearchRequest(
request, protocol.SearchRnaQuantificationSetsRequest,
protoc... | [
"def",
"runSearchRnaQuantificationSets",
"(",
"self",
",",
"request",
")",
":",
"return",
"self",
".",
"runSearchRequest",
"(",
"request",
",",
"protocol",
".",
"SearchRnaQuantificationSetsRequest",
",",
"protocol",
".",
"SearchRnaQuantificationSetsResponse",
",",
"self... | 44.444444 | 11.555556 |
def accel_increase_height(self, *args):
"""Callback to increase height.
"""
height = self.settings.general.get_int('window-height')
self.settings.general.set_int('window-height', min(height + 2, 100))
return True | [
"def",
"accel_increase_height",
"(",
"self",
",",
"*",
"args",
")",
":",
"height",
"=",
"self",
".",
"settings",
".",
"general",
".",
"get_int",
"(",
"'window-height'",
")",
"self",
".",
"settings",
".",
"general",
".",
"set_int",
"(",
"'window-height'",
"... | 41.166667 | 13.5 |
def get_foreign_keys(cls):
"""Get foreign keys and models they refer to, so we can pre-process
the data for load_bulk
"""
foreign_keys = {}
for field in cls._meta.fields:
if (
field.get_internal_type() == 'ForeignKey' and
field.name != ... | [
"def",
"get_foreign_keys",
"(",
"cls",
")",
":",
"foreign_keys",
"=",
"{",
"}",
"for",
"field",
"in",
"cls",
".",
"_meta",
".",
"fields",
":",
"if",
"(",
"field",
".",
"get_internal_type",
"(",
")",
"==",
"'ForeignKey'",
"and",
"field",
".",
"name",
"!... | 37.066667 | 13.333333 |
def _spoken_representation_L2(lst_lst_char):
"""
>>> lst = [['M', 'O', 'R', 'S', 'E'], ['C', 'O', 'D', 'E']]
>>> _spoken_representation_L2(lst)
'-- --- .-. ... . (space) -.-. --- -.. .'
"""
s = ''
inter_char = ' '
inter_word = ' (space) '
for i, word in enumerate(lst_lst_char):
... | [
"def",
"_spoken_representation_L2",
"(",
"lst_lst_char",
")",
":",
"s",
"=",
"''",
"inter_char",
"=",
"' '",
"inter_word",
"=",
"' (space) '",
"for",
"i",
",",
"word",
"in",
"enumerate",
"(",
"lst_lst_char",
")",
":",
"if",
"i",
">=",
"1",
":",
"s",
"+="... | 29.058824 | 11.529412 |
def _put_resource_dict(self):
""" Creates PDF reference to resource objects.
"""
self.session._add_object(2)
self.session._out('<<')
self.session._out('/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]')
self.session._out('/Font <<')
for font in self.document... | [
"def",
"_put_resource_dict",
"(",
"self",
")",
":",
"self",
".",
"session",
".",
"_add_object",
"(",
"2",
")",
"self",
".",
"session",
".",
"_out",
"(",
"'<<'",
")",
"self",
".",
"session",
".",
"_out",
"(",
"'/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]'",
... | 40.666667 | 11.944444 |
def DisplayTree(node, children, level=0):
"""Recursively display a node and each of its children.
Args:
node: The node we're displaying the children of.
children: Children of the parent node.
level: How deep in the tree we are.
"""
value = ''
node_type = ''
if 'caseValue' in node:
case_val... | [
"def",
"DisplayTree",
"(",
"node",
",",
"children",
",",
"level",
"=",
"0",
")",
":",
"value",
"=",
"''",
"node_type",
"=",
"''",
"if",
"'caseValue'",
"in",
"node",
":",
"case_value",
"=",
"node",
"[",
"'caseValue'",
"]",
"node_type",
"=",
"case_value",
... | 33.551724 | 18.310345 |
def mkrelease(finish='yes', version=''):
"""Allocates the next version number and marks current develop branch
state as a new release with the allocated version number.
Syncs new state with origin repository.
"""
if not version:
version = _version_format(_version_guess_next())
if _git_g... | [
"def",
"mkrelease",
"(",
"finish",
"=",
"'yes'",
",",
"version",
"=",
"''",
")",
":",
"if",
"not",
"version",
":",
"version",
"=",
"_version_format",
"(",
"_version_guess_next",
"(",
")",
")",
"if",
"_git_get_current_branch",
"(",
")",
"!=",
"'release/'",
... | 39.541667 | 16.291667 |
def aitoffImageToSphere(x, y):
"""
Inverse Hammer-Aitoff projection (deg).
"""
x = x - 360.*(x>180)
x = np.asarray(np.radians(x))
y = np.asarray(np.radians(y))
z = np.sqrt(1. - (x / 4.)**2 - (y / 2.)**2) # rad
lon = 2. * np.arctan2((2. * z**2) - 1, (z / 2.) * x)
lat = np.arcsin( y * ... | [
"def",
"aitoffImageToSphere",
"(",
"x",
",",
"y",
")",
":",
"x",
"=",
"x",
"-",
"360.",
"*",
"(",
"x",
">",
"180",
")",
"x",
"=",
"np",
".",
"asarray",
"(",
"np",
".",
"radians",
"(",
"x",
")",
")",
"y",
"=",
"np",
".",
"asarray",
"(",
"np"... | 34 | 9.636364 |
def encode(cls, value):
"""
convert a boolean value into something we can persist to redis.
An empty string is the representation for False.
:param value: bool
:return: bytes
"""
if value not in [True, False]:
raise InvalidValue('not a boolean')
... | [
"def",
"encode",
"(",
"cls",
",",
"value",
")",
":",
"if",
"value",
"not",
"in",
"[",
"True",
",",
"False",
"]",
":",
"raise",
"InvalidValue",
"(",
"'not a boolean'",
")",
"return",
"b'1'",
"if",
"value",
"else",
"b''"
] | 28.5 | 15.666667 |
def _metrics_options(p):
""" Add options specific to metrics subcommand. """
_default_options(p, blacklist=['log-group', 'output-dir', 'cache', 'quiet'])
p.add_argument(
'--start', type=date_parse,
help='Start date (requires --end, overrides --days)')
p.add_argument(
'--end', ty... | [
"def",
"_metrics_options",
"(",
"p",
")",
":",
"_default_options",
"(",
"p",
",",
"blacklist",
"=",
"[",
"'log-group'",
",",
"'output-dir'",
",",
"'cache'",
",",
"'quiet'",
"]",
")",
"p",
".",
"add_argument",
"(",
"'--start'",
",",
"type",
"=",
"date_parse... | 41.461538 | 19.538462 |
def set_key(self, key, modifiers: typing.List[Key]=None):
"""This is called when the user successfully finishes recording a key combination."""
if modifiers is None:
modifiers = [] # type: typing.List[Key]
if key in self.KEY_MAP:
key = self.KEY_MAP[key]
self._set... | [
"def",
"set_key",
"(",
"self",
",",
"key",
",",
"modifiers",
":",
"typing",
".",
"List",
"[",
"Key",
"]",
"=",
"None",
")",
":",
"if",
"modifiers",
"is",
"None",
":",
"modifiers",
"=",
"[",
"]",
"# type: typing.List[Key]",
"if",
"key",
"in",
"self",
... | 49.533333 | 13.066667 |
def compare_balance(self, operator, or_equals, amount):
"""Additional step using regex matcher to compare the current balance with some number"""
amount = int(amount)
if operator == 'less':
if or_equals:
self.assertLessEqual(self.balance, amount)
else:
... | [
"def",
"compare_balance",
"(",
"self",
",",
"operator",
",",
"or_equals",
",",
"amount",
")",
":",
"amount",
"=",
"int",
"(",
"amount",
")",
"if",
"operator",
"==",
"'less'",
":",
"if",
"or_equals",
":",
"self",
".",
"assertLessEqual",
"(",
"self",
".",
... | 42.333333 | 14.916667 |
def QA_util_format_date2str(cursor_date):
"""
对输入日期进行格式化处理,返回格式为 "%Y-%m-%d" 格式字符串
支持格式包括:
1. str: "%Y%m%d" "%Y%m%d%H%M%S", "%Y%m%d %H:%M:%S",
"%Y-%m-%d", "%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H%M%S"
2. datetime.datetime
3. pd.Timestamp
4. int -> 自动在右边加 0 然后转换,譬如 '20190302093' --> "2019... | [
"def",
"QA_util_format_date2str",
"(",
"cursor_date",
")",
":",
"if",
"isinstance",
"(",
"cursor_date",
",",
"datetime",
".",
"datetime",
")",
":",
"cursor_date",
"=",
"str",
"(",
"cursor_date",
")",
"[",
":",
"10",
"]",
"elif",
"isinstance",
"(",
"cursor_da... | 35.2 | 16 |
def _resizeColumnToContents(self, header, data, col, limit_ms):
"""Resize a column by its contents."""
hdr_width = self._sizeHintForColumn(header, col, limit_ms)
data_width = self._sizeHintForColumn(data, col, limit_ms)
if data_width > hdr_width:
width = min(self.max_wid... | [
"def",
"_resizeColumnToContents",
"(",
"self",
",",
"header",
",",
"data",
",",
"col",
",",
"limit_ms",
")",
":",
"hdr_width",
"=",
"self",
".",
"_sizeHintForColumn",
"(",
"header",
",",
"col",
",",
"limit_ms",
")",
"data_width",
"=",
"self",
".",
"_sizeHi... | 51 | 16.083333 |
def connect(self):
"""
Establish a connection to APNs. If already connected, the function does nothing. If the
connection fails, the function retries up to MAX_CONNECTION_RETRIES times.
"""
retries = 0
while retries < MAX_CONNECTION_RETRIES:
try:
... | [
"def",
"connect",
"(",
"self",
")",
":",
"retries",
"=",
"0",
"while",
"retries",
"<",
"MAX_CONNECTION_RETRIES",
":",
"try",
":",
"self",
".",
"_connection",
".",
"connect",
"(",
")",
"logger",
".",
"info",
"(",
"'Connected to APNs'",
")",
"return",
"excep... | 42.888889 | 22.222222 |
def login_token(api, username, password):
"""Login using pre routeros 6.43 authorization method."""
sentence = api('/login')
token = tuple(sentence)[0]['ret']
encoded = encode_password(token, password)
tuple(api('/login', **{'name': username, 'response': encoded})) | [
"def",
"login_token",
"(",
"api",
",",
"username",
",",
"password",
")",
":",
"sentence",
"=",
"api",
"(",
"'/login'",
")",
"token",
"=",
"tuple",
"(",
"sentence",
")",
"[",
"0",
"]",
"[",
"'ret'",
"]",
"encoded",
"=",
"encode_password",
"(",
"token",
... | 46.666667 | 8.166667 |
def add_message(self, text, type=None):
"""Add a message with an optional type."""
key = self._msg_key
self.setdefault(key, [])
self[key].append(message(type, text))
self.save() | [
"def",
"add_message",
"(",
"self",
",",
"text",
",",
"type",
"=",
"None",
")",
":",
"key",
"=",
"self",
".",
"_msg_key",
"self",
".",
"setdefault",
"(",
"key",
",",
"[",
"]",
")",
"self",
"[",
"key",
"]",
".",
"append",
"(",
"message",
"(",
"type... | 35.333333 | 8 |
def _dlinear_seaborn_(self, label=None, style=None, opts=None):
"""
Returns a Seaborn linear regression plot with marginal distribution
"""
color, size = self._get_color_size(style)
try:
fig = sns.jointplot(self.x, self.y, color=color,
... | [
"def",
"_dlinear_seaborn_",
"(",
"self",
",",
"label",
"=",
"None",
",",
"style",
"=",
"None",
",",
"opts",
"=",
"None",
")",
":",
"color",
",",
"size",
"=",
"self",
".",
"_get_color_size",
"(",
"style",
")",
"try",
":",
"fig",
"=",
"sns",
".",
"jo... | 43.615385 | 17 |
def matrix_to_blockmatrix(self, blocksize):
"""
turns an n*m Matrix into a (n/blocksize)*(m/blocksize matrix).
Each element is another blocksize*blocksize matrix.
"""
if self.get_width() % blocksize or self.get_height() % blocksize:
raise ValueError("Number of rows an... | [
"def",
"matrix_to_blockmatrix",
"(",
"self",
",",
"blocksize",
")",
":",
"if",
"self",
".",
"get_width",
"(",
")",
"%",
"blocksize",
"or",
"self",
".",
"get_height",
"(",
")",
"%",
"blocksize",
":",
"raise",
"ValueError",
"(",
"\"Number of rows and columns hav... | 62.2 | 29.266667 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.