text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def stack_push(self, value: Union[int, bytes]) -> None:
"""
Push ``value`` onto the stack.
Raise `eth.exceptions.StackDepthLimit` if the stack is full.
"""
return self._stack.push(value) | [
"def",
"stack_push",
"(",
"self",
",",
"value",
":",
"Union",
"[",
"int",
",",
"bytes",
"]",
")",
"->",
"None",
":",
"return",
"self",
".",
"_stack",
".",
"push",
"(",
"value",
")"
] | 31.571429 | 12.428571 |
def add_form_widget_attr(field, attr_name, attr_value, replace=0):
"""
Adds widget attributes to a bound form field.
This is helpful if you would like to add a certain class to all your forms
(i.e. `form-control` to all form fields when you are using Bootstrap)::
{% load libs_tags %}
{... | [
"def",
"add_form_widget_attr",
"(",
"field",
",",
"attr_name",
",",
"attr_value",
",",
"replace",
"=",
"0",
")",
":",
"if",
"not",
"replace",
":",
"attr",
"=",
"field",
".",
"field",
".",
"widget",
".",
"attrs",
".",
"get",
"(",
"attr_name",
",",
"''",... | 33.586207 | 23.793103 |
def validate(self):
"""Validate workflow object.
This method currently validates the workflow object with the use of
cwltool. It writes the workflow to a tmp CWL file, reads it, validates
it and removes the tmp file again. By default, the workflow is written
to file using absolu... | [
"def",
"validate",
"(",
"self",
")",
":",
"# define tmpfile",
"(",
"fd",
",",
"tmpfile",
")",
"=",
"tempfile",
".",
"mkstemp",
"(",
")",
"os",
".",
"close",
"(",
"fd",
")",
"try",
":",
"# save workflow object to tmpfile,",
"# do not recursively call validate fun... | 39.65 | 18.3 |
def get_max_posteriors(self, parameters=None, squeeze=True, chains=None):
""" Gets the maximum posterior point in parameter space from the passed parameters.
Requires the chains to have set `posterior` values.
Parameters
----------
parameters : str|list[str]
... | [
"def",
"get_max_posteriors",
"(",
"self",
",",
"parameters",
"=",
"None",
",",
"squeeze",
"=",
"True",
",",
"chains",
"=",
"None",
")",
":",
"results",
"=",
"[",
"]",
"if",
"chains",
"is",
"None",
":",
"chains",
"=",
"self",
".",
"parent",
".",
"chai... | 35.382979 | 19.276596 |
def start_app_and_connect(self):
"""Starts snippet apk on the device and connects to it.
This wraps the main logic with safe handling
Raises:
AppStartPreCheckError, when pre-launch checks fail.
"""
try:
self._start_app_and_connect()
except AppSta... | [
"def",
"start_app_and_connect",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_start_app_and_connect",
"(",
")",
"except",
"AppStartPreCheckError",
":",
"# Precheck errors don't need cleanup, directly raise.",
"raise",
"except",
"Exception",
"as",
"e",
":",
"# Log th... | 38.458333 | 19.791667 |
def align_to_sort_bam(fastq1, fastq2, aligner, data):
"""Align to the named genome build, returning a sorted BAM file.
"""
names = data["rgnames"]
align_dir_parts = [data["dirs"]["work"], "align", names["sample"]]
if data.get("disambiguate"):
align_dir_parts.append(data["disambiguate"]["geno... | [
"def",
"align_to_sort_bam",
"(",
"fastq1",
",",
"fastq2",
",",
"aligner",
",",
"data",
")",
":",
"names",
"=",
"data",
"[",
"\"rgnames\"",
"]",
"align_dir_parts",
"=",
"[",
"data",
"[",
"\"dirs\"",
"]",
"[",
"\"work\"",
"]",
",",
"\"align\"",
",",
"names... | 51.071429 | 19.464286 |
def bin(self):
"""
Get the command used to run the tool.
Returns
-------
command : str
The tool system command.
"""
if self.local_bin:
return self.local_bin
else:
return self.config.bin(self.name) | [
"def",
"bin",
"(",
"self",
")",
":",
"if",
"self",
".",
"local_bin",
":",
"return",
"self",
".",
"local_bin",
"else",
":",
"return",
"self",
".",
"config",
".",
"bin",
"(",
"self",
".",
"name",
")"
] | 21.923077 | 15.153846 |
def _print_result_info(traces, events):
"""
Print a summary of the returned (voltage) traces and spike times
"""
print_v('Returning %i traces:'%len(traces))
for r in sorted(traces.keys()):
x = traces[r]
print_v(' %s (%s): %s -> %s (min: %s, max: %s, len: %i)'%(r, type(x), x[0],x[-1]... | [
"def",
"_print_result_info",
"(",
"traces",
",",
"events",
")",
":",
"print_v",
"(",
"'Returning %i traces:'",
"%",
"len",
"(",
"traces",
")",
")",
"for",
"r",
"in",
"sorted",
"(",
"traces",
".",
"keys",
"(",
")",
")",
":",
"x",
"=",
"traces",
"[",
"... | 45.583333 | 19.25 |
def get_my_choices_projects():
""" Retrieves all projects in the system
for the project management page
"""
proj_list = Project.objects.all()
proj_tuple = []
counter = 1
for proj in proj_list:
proj_tuple.append((counter, proj))
counter = counter + 1
return proj_tuple | [
"def",
"get_my_choices_projects",
"(",
")",
":",
"proj_list",
"=",
"Project",
".",
"objects",
".",
"all",
"(",
")",
"proj_tuple",
"=",
"[",
"]",
"counter",
"=",
"1",
"for",
"proj",
"in",
"proj_list",
":",
"proj_tuple",
".",
"append",
"(",
"(",
"counter",... | 25.75 | 12.166667 |
def create_logical_relationship(manager, logical_handle_id, other_handle_id, rel_type):
"""
Makes relationship between the two nodes and returns the relationship.
If a relationship is not possible NoRelationshipPossible exception is
raised.
"""
other_meta_type = get_node_meta_type(manager, other... | [
"def",
"create_logical_relationship",
"(",
"manager",
",",
"logical_handle_id",
",",
"other_handle_id",
",",
"rel_type",
")",
":",
"other_meta_type",
"=",
"get_node_meta_type",
"(",
"manager",
",",
"other_handle_id",
")",
"if",
"rel_type",
"==",
"'Depends_on'",
":",
... | 57.642857 | 28.928571 |
def packexe(exefile, srcdir):
"""Pack the files in srcdir into exefile using 7z.
Requires that stub files are available in checkouts/stubs"""
exefile = cygpath(os.path.abspath(exefile))
appbundle = exefile + ".app.7z"
# Make sure that appbundle doesn't already exist
# We don't want to risk app... | [
"def",
"packexe",
"(",
"exefile",
",",
"srcdir",
")",
":",
"exefile",
"=",
"cygpath",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"exefile",
")",
")",
"appbundle",
"=",
"exefile",
"+",
"\".app.7z\"",
"# Make sure that appbundle doesn't already exist",
"# We don... | 31.375 | 20.208333 |
def setMinimumSize(self, *args):
"""
Sets the minimum size value to the inputed size and emits the \
sizeConstraintChanged signal.
:param *args | <tuple>
"""
super(XView, self).setMinimumSize(*args)
if ( not self.signalsBlocked() ):
... | [
"def",
"setMinimumSize",
"(",
"self",
",",
"*",
"args",
")",
":",
"super",
"(",
"XView",
",",
"self",
")",
".",
"setMinimumSize",
"(",
"*",
"args",
")",
"if",
"(",
"not",
"self",
".",
"signalsBlocked",
"(",
")",
")",
":",
"self",
".",
"sizeConstraint... | 31.545455 | 11.363636 |
def build(self, force=False):
"Create the image gallery"
if not self.albums:
self.logger.warning("No albums found.")
return
def log_func(x):
# 63 is the total length of progressbar, label, percentage, etc
available_length = get_terminal_size()[0]... | [
"def",
"build",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"albums",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"\"No albums found.\"",
")",
"return",
"def",
"log_func",
"(",
"x",
")",
":",
"# 63 is the total lengt... | 41.536585 | 18.414634 |
def assert_visible(self, locator, msg=None):
"""
Hard assert for whether and element is present and visible in the current window/frame
:params locator: the locator of the element to search for
:params msg: (Optional) msg explaining the difference
"""
e = driver.find_ele... | [
"def",
"assert_visible",
"(",
"self",
",",
"locator",
",",
"msg",
"=",
"None",
")",
":",
"e",
"=",
"driver",
".",
"find_elements_by_locator",
"(",
"locator",
")",
"if",
"len",
"(",
"e",
")",
"==",
"0",
":",
"raise",
"AssertionError",
"(",
"\"Element at %... | 42.272727 | 19.545455 |
def winning_name(self):
"""
Returns a ``string`` of the winning team's name, such as 'Houston
Astros'.
"""
if self.winner == HOME:
return self._home_name.text()
return self._away_name.text() | [
"def",
"winning_name",
"(",
"self",
")",
":",
"if",
"self",
".",
"winner",
"==",
"HOME",
":",
"return",
"self",
".",
"_home_name",
".",
"text",
"(",
")",
"return",
"self",
".",
"_away_name",
".",
"text",
"(",
")"
] | 30.375 | 10.875 |
def import_task_modules():
"""
Import all installed apps and add modules to registry
"""
top_level_modules = settings.INSTALLED_APPS
module_names = []
for module in top_level_modules:
#Import package
mod = import_module(module)
#Find all modules in package path
fo... | [
"def",
"import_task_modules",
"(",
")",
":",
"top_level_modules",
"=",
"settings",
".",
"INSTALLED_APPS",
"module_names",
"=",
"[",
"]",
"for",
"module",
"in",
"top_level_modules",
":",
"#Import package",
"mod",
"=",
"import_module",
"(",
"module",
")",
"#Find all... | 42 | 14.666667 |
def plot_gain_offsets(dio_cross,dio_chan_per_coarse=8,feedtype='l',ax1=None,ax2=None,legend=True,**kwargs):
'''
Plots the calculated gain offsets of each coarse channel along with
the time averaged power spectra of the X and Y feeds
'''
#Get ON-OFF ND spectra
Idiff,Qdiff,Udiff,Vdiff,freqs = get_... | [
"def",
"plot_gain_offsets",
"(",
"dio_cross",
",",
"dio_chan_per_coarse",
"=",
"8",
",",
"feedtype",
"=",
"'l'",
",",
"ax1",
"=",
"None",
",",
"ax2",
"=",
"None",
",",
"legend",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"#Get ON-OFF ND spectra",
"I... | 35.510204 | 20.244898 |
def from_dict(cls, d):
"""
Construct a MSONable AdfKey object from the JSON dict.
Parameters
----------
d : dict
A dict of saved attributes.
Returns
-------
adfkey : AdfKey
An AdfKey object recovered from the JSON dict ``d``.
... | [
"def",
"from_dict",
"(",
"cls",
",",
"d",
")",
":",
"key",
"=",
"d",
".",
"get",
"(",
"\"name\"",
")",
"options",
"=",
"d",
".",
"get",
"(",
"\"options\"",
",",
"None",
")",
"subkey_list",
"=",
"d",
".",
"get",
"(",
"\"subkeys\"",
",",
"[",
"]",
... | 26.521739 | 18.26087 |
def cleanse(self):
"""Clean up some terms, like ensuring that the name is a slug"""
from .util import slugify
self.ensure_identifier()
try:
self.update_name()
except MetatabError:
identifier = self['Root'].find_first('Root.Identifier')
name... | [
"def",
"cleanse",
"(",
"self",
")",
":",
"from",
".",
"util",
"import",
"slugify",
"self",
".",
"ensure_identifier",
"(",
")",
"try",
":",
"self",
".",
"update_name",
"(",
")",
"except",
"MetatabError",
":",
"identifier",
"=",
"self",
"[",
"'Root'",
"]",... | 30.7 | 22.4 |
def is_subscribed_list(self, list_id, user_id):
"""
Check if user is a subscribed of specified list
:param list_id: list ID number
:param user_id: user ID number
:return: :code:`True` if user is subscribed of list, :code:`False` otherwise
"""
try:
ret... | [
"def",
"is_subscribed_list",
"(",
"self",
",",
"list_id",
",",
"user_id",
")",
":",
"try",
":",
"return",
"bool",
"(",
"self",
".",
"_client",
".",
"show_list_subscriber",
"(",
"list_id",
"=",
"list_id",
",",
"user_id",
"=",
"user_id",
")",
")",
"except",
... | 38.285714 | 19 |
def total_seconds(delta):
"""Return the total seconds of datetime.timedelta object.
Compute total seconds of datetime.timedelta, datetime.timedelta
doesn't have method total_seconds in Python2.6, calculate it manually.
"""
try:
return delta.total_seconds()
except AttributeError:
... | [
"def",
"total_seconds",
"(",
"delta",
")",
":",
"try",
":",
"return",
"delta",
".",
"total_seconds",
"(",
")",
"except",
"AttributeError",
":",
"return",
"(",
"(",
"delta",
".",
"days",
"*",
"24",
"*",
"3600",
")",
"+",
"delta",
".",
"seconds",
"+",
... | 37.818182 | 18 |
def save(self, *args, **kwargs):
""" Saves the topic instance. """
# It is vital to track the changes of the forum associated with a topic in order to
# maintain counters up-to-date.
old_instance = None
if self.pk:
old_instance = self.__class__._default_manager.get(pk... | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# It is vital to track the changes of the forum associated with a topic in order to",
"# maintain counters up-to-date.",
"old_instance",
"=",
"None",
"if",
"self",
".",
"pk",
":",
"old_ins... | 41.363636 | 20.045455 |
def _extract_multimap_field(blob, name):
'''Extracts multimap fields. Values can either be a scalar string or a list
of strings. We need to parse both. For example:
example:
a: foo/
b:
- bar/
- baz/'''
message = ('"{}" field must be a map whose values are ... | [
"def",
"_extract_multimap_field",
"(",
"blob",
",",
"name",
")",
":",
"message",
"=",
"(",
"'\"{}\" field must be a map whose values are either a string or '",
"'list of strings.'",
".",
"format",
"(",
"name",
")",
")",
"raw_map",
"=",
"typesafe_pop",
"(",
"blob",
","... | 42.56 | 17.6 |
def wait(self, timeout=None):
""" Wait for the job to complete, or a timeout to happen.
Args:
timeout: how long to wait before giving up (in seconds); default None which means no timeout.
Returns:
The Job
"""
if self._future:
try:
# Future.exception() will return rather t... | [
"def",
"wait",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"self",
".",
"_future",
":",
"try",
":",
"# Future.exception() will return rather than raise any exception so we use it.",
"self",
".",
"_future",
".",
"exception",
"(",
"timeout",
")",
"exce... | 29.68 | 19.68 |
def __calculate_dataset_difference(self, index_point):
"""!
@brief Calculate distance from each object to specified object.
@param[in] index_point (uint): Index point for which difference with other points is calculated.
@return (list) Distance to each object from input data from... | [
"def",
"__calculate_dataset_difference",
"(",
"self",
",",
"index_point",
")",
":",
"if",
"self",
".",
"__metric",
".",
"get_type",
"(",
")",
"!=",
"type_metric",
".",
"USER_DEFINED",
":",
"dataset_differences",
"=",
"self",
".",
"__metric",
"(",
"self",
".",
... | 40.8125 | 32.625 |
def pprint(obj, *args, **kwargs):
"""Pretty-printing function that can pretty-print OrderedDicts
like regular dictionaries. Useful for printing the output of
:meth:`marshmallow.Schema.dump`.
"""
if isinstance(obj, collections.OrderedDict):
print(json.dumps(obj, *args, **kwargs))
else:
... | [
"def",
"pprint",
"(",
"obj",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"collections",
".",
"OrderedDict",
")",
":",
"print",
"(",
"json",
".",
"dumps",
"(",
"obj",
",",
"*",
"args",
",",
"*",
"*",
... | 38.777778 | 9.111111 |
def new(self, data):
"""通过data新建一个stock_block
Arguments:
data {[type]} -- [description]
Returns:
[type] -- [description]
"""
temp = copy(self)
temp.__init__(data)
return temp | [
"def",
"new",
"(",
"self",
",",
"data",
")",
":",
"temp",
"=",
"copy",
"(",
"self",
")",
"temp",
".",
"__init__",
"(",
"data",
")",
"return",
"temp"
] | 20.416667 | 16.833333 |
def RenderHttpResponse(request):
"""Renders HTTP response to a given HTTP request."""
start_time = time.time()
response = HTTP_REQUEST_HANDLER.HandleRequest(request)
total_time = time.time() - start_time
method_name = response.headers.get("X-API-Method", "unknown")
if response.status_code == 200:
stat... | [
"def",
"RenderHttpResponse",
"(",
"request",
")",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"response",
"=",
"HTTP_REQUEST_HANDLER",
".",
"HandleRequest",
"(",
"request",
")",
"total_time",
"=",
"time",
".",
"time",
"(",
")",
"-",
"start_time",
... | 28.25 | 17.678571 |
def distance_to_point(self, p):
'''Returns the distance from the point to the interval. Zero if the point lies inside the interval.'''
if self.start <= p <= self.end:
return 0
else:
return min(abs(self.start - p), abs(self.end - p)) | [
"def",
"distance_to_point",
"(",
"self",
",",
"p",
")",
":",
"if",
"self",
".",
"start",
"<=",
"p",
"<=",
"self",
".",
"end",
":",
"return",
"0",
"else",
":",
"return",
"min",
"(",
"abs",
"(",
"self",
".",
"start",
"-",
"p",
")",
",",
"abs",
"(... | 45.833333 | 24.833333 |
def stop(name, kill=False):
'''
This is a compatibility function which provides the logic for
nspawn.poweroff and nspawn.terminate.
'''
if _sd_version() >= 219:
if kill:
action = 'terminate'
else:
action = 'poweroff'
ret = _machinectl('{0} {1}'.format(... | [
"def",
"stop",
"(",
"name",
",",
"kill",
"=",
"False",
")",
":",
"if",
"_sd_version",
"(",
")",
">=",
"219",
":",
"if",
"kill",
":",
"action",
"=",
"'terminate'",
"else",
":",
"action",
"=",
"'poweroff'",
"ret",
"=",
"_machinectl",
"(",
"'{0} {1}'",
... | 31.052632 | 21.368421 |
def size(self, pairs_only=False):
'''
Calculate the size of the lineage.
Inputs (optional)
-----------------
pairs_only: count only paired sequences
Returns
-------
Lineage size (int)
'''
if pairs_only:
return len(self.just_pa... | [
"def",
"size",
"(",
"self",
",",
"pairs_only",
"=",
"False",
")",
":",
"if",
"pairs_only",
":",
"return",
"len",
"(",
"self",
".",
"just_pairs",
")",
"else",
":",
"return",
"len",
"(",
"self",
".",
"heavies",
")"
] | 22.5 | 18.625 |
def color(teffs):
"""
Conventional color descriptions of stars.
Source: https://en.wikipedia.org/wiki/Stellar_classification
"""
colors = []
for t in teffs:
if t >= 7500:
colors.append('blue_white') # RGB:CAE1FF
elif t >= 6000:
colors.append('white') # R... | [
"def",
"color",
"(",
"teffs",
")",
":",
"colors",
"=",
"[",
"]",
"for",
"t",
"in",
"teffs",
":",
"if",
"t",
">=",
"7500",
":",
"colors",
".",
"append",
"(",
"'blue_white'",
")",
"# RGB:CAE1FF",
"elif",
"t",
">=",
"6000",
":",
"colors",
".",
"append... | 31.833333 | 16.5 |
def _create_default_config_file(self):
"""
If config file does not exists create and set default values.
"""
logger.info('Initialize Maya launcher, creating config file...\n')
self.add_section(self.DEFAULTS)
self.add_section(self.PATTERNS)
self.add_section(... | [
"def",
"_create_default_config_file",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"'Initialize Maya launcher, creating config file...\\n'",
")",
"self",
".",
"add_section",
"(",
"self",
".",
"DEFAULTS",
")",
"self",
".",
"add_section",
"(",
"self",
".",
"PA... | 44.304348 | 17.26087 |
def moment(year=None, month=None, day=None, hour=None, minute=None, second=None, msec=None, date=None, time=None):
"""
Create a time column from individual components.
Each parameter should be either an integer, or a single-column H2OFrame
containing the corresponding time parts for eac... | [
"def",
"moment",
"(",
"year",
"=",
"None",
",",
"month",
"=",
"None",
",",
"day",
"=",
"None",
",",
"hour",
"=",
"None",
",",
"minute",
"=",
"None",
",",
"second",
"=",
"None",
",",
"msec",
"=",
"None",
",",
"date",
"=",
"None",
",",
"time",
"=... | 55.73913 | 26.282609 |
def set_optional_elements(self):
"""Sets elements considered option by RSS spec"""
self.set_categories()
self.set_copyright()
self.set_generator()
self.set_image()
self.set_language()
self.set_last_build_date()
self.set_managing_editor()
self.set_p... | [
"def",
"set_optional_elements",
"(",
"self",
")",
":",
"self",
".",
"set_categories",
"(",
")",
"self",
".",
"set_copyright",
"(",
")",
"self",
".",
"set_generator",
"(",
")",
"self",
".",
"set_image",
"(",
")",
"self",
".",
"set_language",
"(",
")",
"se... | 31.384615 | 9.923077 |
def get_all_permissions_views(self):
"""
Returns a set of tuples with the perm name and view menu name
"""
perms_views = set()
for role in self.get_user_roles():
perms_views.update({(perm_view.permission.name, perm_view.view_menu.name)
... | [
"def",
"get_all_permissions_views",
"(",
"self",
")",
":",
"perms_views",
"=",
"set",
"(",
")",
"for",
"role",
"in",
"self",
".",
"get_user_roles",
"(",
")",
":",
"perms_views",
".",
"update",
"(",
"{",
"(",
"perm_view",
".",
"permission",
".",
"name",
"... | 41.555556 | 14.888889 |
def __duplicate_line_or_selection(self, after_current_line=True):
"""Duplicate current line or selected text"""
cursor = self.textCursor()
cursor.beginEditBlock()
start_pos, end_pos = self.__save_selection()
if to_text_string(cursor.selectedText()):
cursor.setPo... | [
"def",
"__duplicate_line_or_selection",
"(",
"self",
",",
"after_current_line",
"=",
"True",
")",
":",
"cursor",
"=",
"self",
".",
"textCursor",
"(",
")",
"cursor",
".",
"beginEditBlock",
"(",
")",
"start_pos",
",",
"end_pos",
"=",
"self",
".",
"__save_selecti... | 44.230769 | 14.641026 |
def _get(self, resource, payload=None):
''' Wrapper around requests.get that shorten caller url and takes care
of errors '''
# Avoid dangerous default function argument `{}`
payload = payload or {}
# Build the request and return json response
return requests.get(
... | [
"def",
"_get",
"(",
"self",
",",
"resource",
",",
"payload",
"=",
"None",
")",
":",
"# Avoid dangerous default function argument `{}`",
"payload",
"=",
"payload",
"or",
"{",
"}",
"# Build the request and return json response",
"return",
"requests",
".",
"get",
"(",
... | 40.181818 | 17.636364 |
def get_active_modifiers(self):
"""
Get a list of active keys. Uses XQueryKeymap.
:return: list of charcodemap_t instances
"""
keys = ctypes.pointer(charcodemap_t())
nkeys = ctypes.c_int(0)
_libxdo.xdo_get_active_modifiers(
self._xdo, ctypes.byref(ke... | [
"def",
"get_active_modifiers",
"(",
"self",
")",
":",
"keys",
"=",
"ctypes",
".",
"pointer",
"(",
"charcodemap_t",
"(",
")",
")",
"nkeys",
"=",
"ctypes",
".",
"c_int",
"(",
"0",
")",
"_libxdo",
".",
"xdo_get_active_modifiers",
"(",
"self",
".",
"_xdo",
"... | 32.25 | 13.416667 |
def start(self):
"""
start
"""
def main_thread():
# create resp, req thread pool
self._create_thread_pool()
# start connection, this will block until stop()
self.conn_thread = Thread(target=self._conn.connect)
self.conn_thread.d... | [
"def",
"start",
"(",
"self",
")",
":",
"def",
"main_thread",
"(",
")",
":",
"# create resp, req thread pool",
"self",
".",
"_create_thread_pool",
"(",
")",
"# start connection, this will block until stop()",
"self",
".",
"conn_thread",
"=",
"Thread",
"(",
"target",
... | 30.242424 | 15.636364 |
def Clamond(Re, eD, fast=False):
r'''Calculates Darcy friction factor using a solution accurate to almost
machine precision. Recommended very strongly. For details of the algorithm,
see [1]_.
Parameters
----------
Re : float
Reynolds number, [-]
eD : float
Relative roug... | [
"def",
"Clamond",
"(",
"Re",
",",
"eD",
",",
"fast",
"=",
"False",
")",
":",
"X1",
"=",
"eD",
"*",
"Re",
"*",
"0.1239681863354175460160858261654858382699",
"# (log(10)/18.574).evalf(40)",
"X2",
"=",
"log",
"(",
"Re",
")",
"-",
"0.77939748845568194064411397016537... | 34.942029 | 27.666667 |
def tpt(T, A, B, mu=None, qminus=None, qplus=None, rate_matrix=False):
r""" Computes the A->B reactive flux using transition path theory (TPT)
Parameters
----------
T : (M, M) ndarray or scipy.sparse matrix
Transition matrix (default) or Rate matrix (if rate_matrix=True)
A : array_like
... | [
"def",
"tpt",
"(",
"T",
",",
"A",
",",
"B",
",",
"mu",
"=",
"None",
",",
"qminus",
"=",
"None",
",",
"qplus",
"=",
"None",
",",
"rate_matrix",
"=",
"False",
")",
":",
"import",
"msmtools",
".",
"analysis",
"as",
"msmana",
"if",
"len",
"(",
"A",
... | 36.142857 | 20.846154 |
def get_nodes_with(self, obj):
"""Return nodes with `obj`."""
result = set()
if nx.__version__[0] == "1":
nodes = self.nodes_iter()
else:
nodes = self.nodes
for node in nodes:
if node[OBJ] == obj:
result.add(node)
retu... | [
"def",
"get_nodes_with",
"(",
"self",
",",
"obj",
")",
":",
"result",
"=",
"set",
"(",
")",
"if",
"nx",
".",
"__version__",
"[",
"0",
"]",
"==",
"\"1\"",
":",
"nodes",
"=",
"self",
".",
"nodes_iter",
"(",
")",
"else",
":",
"nodes",
"=",
"self",
"... | 24.384615 | 15.461538 |
def add_where_when(voevent, coords, obs_time, observatory_location,
allow_tz_naive_datetime=False):
"""
Add details of an observation to the WhereWhen section.
We
Args:
voevent(:class:`Voevent`): Root node of a VOEvent etree.
coords(:class:`.Position2D`): Sky co-ordi... | [
"def",
"add_where_when",
"(",
"voevent",
",",
"coords",
",",
"obs_time",
",",
"observatory_location",
",",
"allow_tz_naive_datetime",
"=",
"False",
")",
":",
"# .. todo:: Implement TimeError using datetime.timedelta",
"if",
"obs_time",
".",
"tzinfo",
"is",
"not",
"None"... | 43.884615 | 22.692308 |
def change_same_starting_points(flaglist):
"""Gets points at which changes begin"""
change_points = []
same_points = []
in_change = False
if flaglist and not flaglist[0]:
same_points.append(0)
for x, flag in enumerate(flaglist):
if flag and not in_change:
change_po... | [
"def",
"change_same_starting_points",
"(",
"flaglist",
")",
":",
"change_points",
"=",
"[",
"]",
"same_points",
"=",
"[",
"]",
"in_change",
"=",
"False",
"if",
"flaglist",
"and",
"not",
"flaglist",
"[",
"0",
"]",
":",
"same_points",
".",
"append",
"(",
"0"... | 25.631579 | 14.789474 |
def filter_image_sep2d(image, fh, fv, impl='numpy', padding=None):
"""Filter an image with a separable filter.
Parameters
----------
image : 2D array-like
The image to be filtered. It must have a real (vs. complex) dtype.
fh, fv : 1D array-like
Horizontal (axis 0) and vertical (axis... | [
"def",
"filter_image_sep2d",
"(",
"image",
",",
"fh",
",",
"fv",
",",
"impl",
"=",
"'numpy'",
",",
"padding",
"=",
"None",
")",
":",
"# TODO: generalize for nD",
"impl",
",",
"impl_in",
"=",
"str",
"(",
"impl",
")",
".",
"lower",
"(",
")",
",",
"impl",... | 38.076471 | 19.470588 |
def bleu_advanced(y_true: List[Any], y_predicted: List[Any],
weights: Tuple=(1,), smoothing_function=SMOOTH.method1,
auto_reweigh=False, penalty=True) -> float:
"""Calculate BLEU score
Parameters:
y_true: list of reference tokens
y_predicted: list of query to... | [
"def",
"bleu_advanced",
"(",
"y_true",
":",
"List",
"[",
"Any",
"]",
",",
"y_predicted",
":",
"List",
"[",
"Any",
"]",
",",
"weights",
":",
"Tuple",
"=",
"(",
"1",
",",
")",
",",
"smoothing_function",
"=",
"SMOOTH",
".",
"method1",
",",
"auto_reweigh",... | 31.413793 | 21.344828 |
def decrypt_token(self, username, token):
'''
Decrypt a token.
'''
version, user_type, _from = self._parse_username(username)
if (version > self.maximum_token_version or
version < self.minimum_token_version):
raise TokenValidationError('Unacceptable to... | [
"def",
"decrypt_token",
"(",
"self",
",",
"username",
",",
"token",
")",
":",
"version",
",",
"user_type",
",",
"_from",
"=",
"self",
".",
"_parse_username",
"(",
"username",
")",
"if",
"(",
"version",
">",
"self",
".",
"maximum_token_version",
"or",
"vers... | 42.727273 | 16.646465 |
def _collect_masters_map(self, response):
'''
Collect masters map from the network.
:return:
'''
while True:
try:
data, addr = self._socket.recvfrom(0x400)
if data:
if addr not in response:
re... | [
"def",
"_collect_masters_map",
"(",
"self",
",",
"response",
")",
":",
"while",
"True",
":",
"try",
":",
"data",
",",
"addr",
"=",
"self",
".",
"_socket",
".",
"recvfrom",
"(",
"0x400",
")",
"if",
"data",
":",
"if",
"addr",
"not",
"in",
"response",
"... | 32.833333 | 15.944444 |
def send_status(self, payload):
"""Send the daemon status and the current queue for displaying."""
answer = {}
data = []
# Get daemon status
if self.paused:
answer['status'] = 'paused'
else:
answer['status'] = 'running'
# Add current queue... | [
"def",
"send_status",
"(",
"self",
",",
"payload",
")",
":",
"answer",
"=",
"{",
"}",
"data",
"=",
"[",
"]",
"# Get daemon status",
"if",
"self",
".",
"paused",
":",
"answer",
"[",
"'status'",
"]",
"=",
"'paused'",
"else",
":",
"answer",
"[",
"'status'... | 33.807692 | 13.576923 |
def sign(shared_secret, msg):
"""Signs a message using a shared secret.
:param shared_secret: The shared secret used to sign the message
:param msg: The message to sign
:return: The signature as a string
.. doctest::
>>> from cloud.rpc import sign
>>> sign('sEcReT_KeY', 'hello world')
... | [
"def",
"sign",
"(",
"shared_secret",
",",
"msg",
")",
":",
"if",
"isinstance",
"(",
"msg",
",",
"unicode",
")",
":",
"msg",
"=",
"msg",
".",
"encode",
"(",
"'utf8'",
")",
"return",
"hashlib",
".",
"md5",
"(",
"msg",
"+",
"shared_secret",
")",
".",
... | 27.823529 | 15.823529 |
def wgsim(args):
"""
%prog wgsim fastafile
Run dwgsim on fastafile.
"""
p = OptionParser(wgsim.__doc__)
p.add_option("--erate", default=.01, type="float",
help="Base error rate of the read [default: %default]")
p.add_option("--noerrors", default=False, action="store_true",
... | [
"def",
"wgsim",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"wgsim",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--erate\"",
",",
"default",
"=",
".01",
",",
"type",
"=",
"\"float\"",
",",
"help",
"=",
"\"Base error rate of the read [def... | 31.895833 | 21.395833 |
def handle_stream(self, message):
"""
Acts on message reception
:param message: string of an incoming message
parse all the fields and builds an Event object that is passed to the callback function
"""
logging.debug("handle_stream(...)")
event = Event()
... | [
"def",
"handle_stream",
"(",
"self",
",",
"message",
")",
":",
"logging",
".",
"debug",
"(",
"\"handle_stream(...)\"",
")",
"event",
"=",
"Event",
"(",
")",
"for",
"line",
"in",
"message",
".",
"strip",
"(",
")",
".",
"splitlines",
"(",
")",
":",
"(",
... | 35.837838 | 13.405405 |
def hpai_body(self):
""" Create a body with HPAI information.
This is used for disconnect and connection state requests.
"""
body = []
# ============ IP Body ==========
body.extend([self.channel]) # Communication Channel Id
body.extend([0x00]) # Reserverd
... | [
"def",
"hpai_body",
"(",
"self",
")",
":",
"body",
"=",
"[",
"]",
"# ============ IP Body ==========",
"body",
".",
"extend",
"(",
"[",
"self",
".",
"channel",
"]",
")",
"# Communication Channel Id",
"body",
".",
"extend",
"(",
"[",
"0x00",
"]",
")",
"# Re... | 36.944444 | 15.444444 |
def u32le_list_to_byte_list(data):
"""! @brief Convert a word array into a byte array"""
res = []
for x in data:
res.append((x >> 0) & 0xff)
res.append((x >> 8) & 0xff)
res.append((x >> 16) & 0xff)
res.append((x >> 24) & 0xff)
return res | [
"def",
"u32le_list_to_byte_list",
"(",
"data",
")",
":",
"res",
"=",
"[",
"]",
"for",
"x",
"in",
"data",
":",
"res",
".",
"append",
"(",
"(",
"x",
">>",
"0",
")",
"&",
"0xff",
")",
"res",
".",
"append",
"(",
"(",
"x",
">>",
"8",
")",
"&",
"0x... | 30.777778 | 11.111111 |
def get_alpha(self, x: int, y: int) -> int:
"""Get the Image alpha of the pixel at x, y.
Args:
x (int): X pixel of the image. Starting from the left at 0.
y (int): Y pixel of the image. Starting from the top at 0.
Returns:
int: The alpha value of the pixel... | [
"def",
"get_alpha",
"(",
"self",
",",
"x",
":",
"int",
",",
"y",
":",
"int",
")",
"->",
"int",
":",
"return",
"lib",
".",
"TCOD_image_get_alpha",
"(",
"self",
".",
"image_c",
",",
"x",
",",
"y",
")"
] | 37.75 | 21 |
def balance_of_contacts(records, weighted=True):
"""
The balance of interactions per contact. For every contact,
the balance is the number of outgoing interactions divided by the total
number of interactions (in+out).
.. math::
\\forall \\,\\text{contact}\\,c,\\;\\text{balance}\,(c) = \\fra... | [
"def",
"balance_of_contacts",
"(",
"records",
",",
"weighted",
"=",
"True",
")",
":",
"counter_out",
"=",
"defaultdict",
"(",
"int",
")",
"counter",
"=",
"defaultdict",
"(",
"int",
")",
"for",
"r",
"in",
"records",
":",
"if",
"r",
".",
"direction",
"==",... | 34.066667 | 25.333333 |
def configure_filters(app):
""" Configure application filters (jinja2) """
for (name, filter) in _filters.iteritems():
app.jinja_env.filters[name] = filter | [
"def",
"configure_filters",
"(",
"app",
")",
":",
"for",
"(",
"name",
",",
"filter",
")",
"in",
"_filters",
".",
"iteritems",
"(",
")",
":",
"app",
".",
"jinja_env",
".",
"filters",
"[",
"name",
"]",
"=",
"filter"
] | 33.6 | 12.8 |
def docker_windows_reverse_fileuri_adjust(fileuri):
# type: (Text) -> (Text)
r"""
On docker in windows fileuri do not contain : in path
To convert this file uri to windows compatible add : after drive letter,
so file:///E/var becomes file:///E:/var
"""
if fileuri is not None and onWindows():... | [
"def",
"docker_windows_reverse_fileuri_adjust",
"(",
"fileuri",
")",
":",
"# type: (Text) -> (Text)",
"if",
"fileuri",
"is",
"not",
"None",
"and",
"onWindows",
"(",
")",
":",
"if",
"urllib",
".",
"parse",
".",
"urlsplit",
"(",
"fileuri",
")",
".",
"scheme",
"=... | 39.25 | 9.4375 |
def update_segment(self, selector, base, size, perms):
""" Only useful for setting FS right now. """
logger.info("Updating selector %s to 0x%02x (%s bytes) (%s)", selector, base, size, perms)
if selector == 99:
self.set_fs(base)
else:
logger.error("No way to write... | [
"def",
"update_segment",
"(",
"self",
",",
"selector",
",",
"base",
",",
"size",
",",
"perms",
")",
":",
"logger",
".",
"info",
"(",
"\"Updating selector %s to 0x%02x (%s bytes) (%s)\"",
",",
"selector",
",",
"base",
",",
"size",
",",
"perms",
")",
"if",
"se... | 48.285714 | 21.285714 |
def event_return(events):
'''
Return event to Pg server
Requires that configuration be enabled via 'event_return'
option in master config.
'''
with _get_serv(events, commit=True) as cur:
for event in events:
tag = event.get('tag', '')
data = event.get('data', '')... | [
"def",
"event_return",
"(",
"events",
")",
":",
"with",
"_get_serv",
"(",
"events",
",",
"commit",
"=",
"True",
")",
"as",
"cur",
":",
"for",
"event",
"in",
"events",
":",
"tag",
"=",
"event",
".",
"get",
"(",
"'tag'",
",",
"''",
")",
"data",
"=",
... | 38.066667 | 19.133333 |
def delete_alert(self, id, **kwargs): # noqa: E501
"""Delete a specific alert # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_alert(id, async_req=True)... | [
"def",
"delete_alert",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"delete_alert_wi... | 39.857143 | 17.333333 |
def drawOverlay(self, painter, option, rect, icon):
"""
Draws the overlay pixmap for this item.
:param painter | <QtGui.QPainter>
option | <QtGui.QSylteOptionIndex>
rect | <QtCore.QRect>
pixmap | <QtGui.QIcon>
... | [
"def",
"drawOverlay",
"(",
"self",
",",
"painter",
",",
"option",
",",
"rect",
",",
"icon",
")",
":",
"if",
"icon",
"and",
"not",
"icon",
".",
"isNull",
"(",
")",
":",
"painter",
".",
"drawPixmap",
"(",
"rect",
",",
"icon",
".",
"pixmap",
"(",
"rec... | 40.181818 | 11.090909 |
def get_hosts_unfinished(self, scan_id):
""" Get a list of finished hosts."""
unfinished_hosts = list()
for target in self.scans_table[scan_id]['finished_hosts']:
unfinished_hosts.extend(target_str_to_list(target))
for target in self.scans_table[scan_id]['finished_hosts']:
... | [
"def",
"get_hosts_unfinished",
"(",
"self",
",",
"scan_id",
")",
":",
"unfinished_hosts",
"=",
"list",
"(",
")",
"for",
"target",
"in",
"self",
".",
"scans_table",
"[",
"scan_id",
"]",
"[",
"'finished_hosts'",
"]",
":",
"unfinished_hosts",
".",
"extend",
"("... | 42 | 19.090909 |
def load_template(filename):
# type: (str) -> str
""" Load template from file.
The templates are part of the package and must be included as
``package_data`` in project ``setup.py``.
Args:
filename (str):
The template path. Relative to `peltak` package directory.
Returns:
... | [
"def",
"load_template",
"(",
"filename",
")",
":",
"# type: (str) -> str",
"template_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"PKG_DIR",
",",
"'templates'",
",",
"filename",
")",
"with",
"open",
"(",
"template_file",
")",
"as",
"fp",
":",
"return",
... | 28.588235 | 19.823529 |
def set_element_text_by_attr_key(self, attr_key, el_text, el_idx=0):
"""
Args:
attr_key : str
Name of attribute for which to search
el_text : str
Text to set for element.
el_idx : int
Index of element to use in the event that there are multiple sibling
ele... | [
"def",
"set_element_text_by_attr_key",
"(",
"self",
",",
"attr_key",
",",
"el_text",
",",
"el_idx",
"=",
"0",
")",
":",
"self",
".",
"get_element_by_attr_key",
"(",
"attr_key",
",",
"el_idx",
")",
".",
"text",
"=",
"el_text"
] | 29.285714 | 20.285714 |
def get_features(self, jid):
"""
Return the features supported by a service.
:param jid: Address of the PubSub service to query.
:type jid: :class:`aioxmpp.JID`
:return: Set of supported features
:rtype: set containing :class:`~.pubsub.xso.Feature` enumeration
... | [
"def",
"get_features",
"(",
"self",
",",
"jid",
")",
":",
"response",
"=",
"yield",
"from",
"self",
".",
"_disco",
".",
"query_info",
"(",
"jid",
")",
"result",
"=",
"set",
"(",
")",
"for",
"feature",
"in",
"response",
".",
"features",
":",
"try",
":... | 36.222222 | 20.222222 |
def __filter_non_working_providers(self):
'''
Remove any mis-configured cloud providers from the available listing
'''
for alias, drivers in six.iteritems(self.opts['providers'].copy()):
for driver in drivers.copy():
fun = '{0}.get_configured_provider'.format(... | [
"def",
"__filter_non_working_providers",
"(",
"self",
")",
":",
"for",
"alias",
",",
"drivers",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"opts",
"[",
"'providers'",
"]",
".",
"copy",
"(",
")",
")",
":",
"for",
"driver",
"in",
"drivers",
".",
"c... | 46.914894 | 22.446809 |
def close(self):
"""
Clean up files that were created.
"""
if self.file:
self.file.close()
self.file = None
# If temp_file is a folder, we do not remove it because we may
# still need it after the unpickler is disposed
if self.tmp_file and... | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"file",
":",
"self",
".",
"file",
".",
"close",
"(",
")",
"self",
".",
"file",
"=",
"None",
"# If temp_file is a folder, we do not remove it because we may",
"# still need it after the unpickler is disposed",
... | 31.615385 | 14.076923 |
def get_module_class(self):
"""Return the module and class as a tuple of the given class in the
initializer.
:param reload: if ``True`` then reload the module before returning the
class
"""
pkg, cname = self.parse_module_class()
logger.debug(f'pkg: {pkg}, class:... | [
"def",
"get_module_class",
"(",
"self",
")",
":",
"pkg",
",",
"cname",
"=",
"self",
".",
"parse_module_class",
"(",
")",
"logger",
".",
"debug",
"(",
"f'pkg: {pkg}, class: {cname}'",
")",
"pkg",
"=",
"pkg",
".",
"split",
"(",
"'.'",
")",
"mod",
"=",
"red... | 33.888889 | 16.666667 |
def convert_plugin_def(http_method, funcs):
"""
This function parses one of the elements of the definitions dict for a
plugin and extracts the relevant information
:param http_method: HTTP method that uses (GET, POST, DELETE, ...)
:param funcs: functions related to that HTTP met... | [
"def",
"convert_plugin_def",
"(",
"http_method",
",",
"funcs",
")",
":",
"methods",
"=",
"[",
"]",
"if",
"http_method",
"not",
"in",
"(",
"'GET'",
",",
"'PUT'",
",",
"'POST'",
",",
"'DELETE'",
")",
":",
"logger",
".",
"error",
"(",
"'Plugin load failure, H... | 38.545455 | 16.060606 |
def clan_badge_url(self):
'''Returns clan badge url'''
if self.clan_tag is None:
return None
url = self.raw_data.get('clan').get('badge').get('url')
if not url:
return None
return "http://api.cr-api.com" + url | [
"def",
"clan_badge_url",
"(",
"self",
")",
":",
"if",
"self",
".",
"clan_tag",
"is",
"None",
":",
"return",
"None",
"url",
"=",
"self",
".",
"raw_data",
".",
"get",
"(",
"'clan'",
")",
".",
"get",
"(",
"'badge'",
")",
".",
"get",
"(",
"'url'",
")",... | 33.25 | 13.5 |
def positions(weights, period, freq=None):
"""
Builds net position values time series, the portfolio percentage invested
in each position.
Parameters
----------
weights: pd.Series
pd.Series containing factor weights, the index contains timestamps at
which the trades are computed... | [
"def",
"positions",
"(",
"weights",
",",
"period",
",",
"freq",
"=",
"None",
")",
":",
"weights",
"=",
"weights",
".",
"unstack",
"(",
")",
"if",
"not",
"isinstance",
"(",
"period",
",",
"pd",
".",
"Timedelta",
")",
":",
"period",
"=",
"pd",
".",
"... | 35.9375 | 23.458333 |
def multiply(self, other):
"""Return the QuantumChannel self + other.
Args:
other (complex): a complex number.
Returns:
Chi: the scalar multiplication other * self as a Chi object.
Raises:
QiskitError: if other is not a valid scalar.
"""
... | [
"def",
"multiply",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"isinstance",
"(",
"other",
",",
"Number",
")",
":",
"raise",
"QiskitError",
"(",
"\"other is not a number\"",
")",
"return",
"Chi",
"(",
"other",
"*",
"self",
".",
"_data",
",",
"self"... | 31.666667 | 20.933333 |
def det(matrix):
'''Seem sto work fine.
>> from sympy import *
>> from sympy.abc import *
>> Matrix([[a, b], [c, d]]).det()
a*d - b*c
>> Matrix([[a, b, c], [d, e, f], [g, h, i]]).det()
a*e*i - a*f*h - b*d*i + b*f*g + c*d*h - c*e*g
A few terms can be slightly factored out of the... | [
"def",
"det",
"(",
"matrix",
")",
":",
"size",
"=",
"len",
"(",
"matrix",
")",
"if",
"size",
"==",
"1",
":",
"return",
"matrix",
"[",
"0",
"]",
"elif",
"size",
"==",
"2",
":",
"(",
"a",
",",
"b",
")",
",",
"(",
"c",
",",
"d",
")",
"=",
"m... | 32.902098 | 25.041958 |
def batch_at(features, labels, seq_begins, seq_lengths):
'''Extract a single batch of data to pass to the model being trained.
Parameters
----------
features, labels : ndarray
Arrays of the input features and target labels.
seq_begins : ndarray
Array of the start offsets of the spee... | [
"def",
"batch_at",
"(",
"features",
",",
"labels",
",",
"seq_begins",
",",
"seq_lengths",
")",
":",
"length",
"=",
"seq_lengths",
".",
"max",
"(",
")",
"feat",
"=",
"np",
".",
"zeros",
"(",
"(",
"BATCH_SIZE",
",",
"length",
",",
"features",
".",
"shape... | 40.62069 | 22.413793 |
def decode_bytes(f):
"""Decode a buffer length from a 2-byte unsigned int then read the
subsequent bytes.
Parameters
----------
f: file
File-like object with read method.
Raises
------
UnderflowDecodeError
When the end of stream is encountered before the end of the
... | [
"def",
"decode_bytes",
"(",
"f",
")",
":",
"buf",
"=",
"f",
".",
"read",
"(",
"FIELD_U16",
".",
"size",
")",
"if",
"len",
"(",
"buf",
")",
"<",
"FIELD_U16",
".",
"size",
":",
"raise",
"UnderflowDecodeError",
"(",
")",
"(",
"num_bytes",
",",
")",
"=... | 21.914286 | 20.571429 |
def createElementNS(self, namespace, qname):
'''
Keyword arguments:
namespace -- namespace of element to create
qname -- qualified name of new element
'''
document = self._getOwnerDocument()
node = document.createElementNS(namespace, qname)
return ... | [
"def",
"createElementNS",
"(",
"self",
",",
"namespace",
",",
"qname",
")",
":",
"document",
"=",
"self",
".",
"_getOwnerDocument",
"(",
")",
"node",
"=",
"document",
".",
"createElementNS",
"(",
"namespace",
",",
"qname",
")",
"return",
"ElementProxy",
"(",... | 37.666667 | 13.666667 |
def purge(self, connection):
"""Remove the connection from rotation"""
self._checkpid()
if connection.pid == self.pid:
idx = connection._pattern_idx
if connection in self._in_use_connections[idx]:
self._in_use_connections[idx].remove(connection)
... | [
"def",
"purge",
"(",
"self",
",",
"connection",
")",
":",
"self",
".",
"_checkpid",
"(",
")",
"if",
"connection",
".",
"pid",
"==",
"self",
".",
"pid",
":",
"idx",
"=",
"connection",
".",
"_pattern_idx",
"if",
"connection",
"in",
"self",
".",
"_in_use_... | 42.2 | 12.9 |
def initialize_ui(self):
"""
Initializes the Component ui.
:return: Method success.
:rtype: bool
"""
LOGGER.debug("> Initializing '{0}' Component ui.".format(self.__class__.__name__))
self.__model = ProjectsModel(self, default_project=self.__default_project)
... | [
"def",
"initialize_ui",
"(",
"self",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"> Initializing '{0}' Component ui.\"",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
")",
")",
"self",
".",
"__model",
"=",
"ProjectsModel",
"(",
"self",
",",
"de... | 55.986842 | 33.223684 |
async def _create_remote_user(self, **payload):
"""
This method creates a service record in the remote user service
with the given email.
Args:
uid (str): the user identifier to create
Returns:
(dict): a summary of the user that was... | [
"async",
"def",
"_create_remote_user",
"(",
"self",
",",
"*",
"*",
"payload",
")",
":",
"# the action for reading user entries",
"read_action",
"=",
"get_crud_action",
"(",
"method",
"=",
"'create'",
",",
"model",
"=",
"'user'",
")",
"# see if there is a matching user... | 36.105263 | 14.105263 |
def _verify_sector_identifier(self, request):
"""
Verify `sector_identifier_uri` is reachable and that it contains
`redirect_uri`s.
:param request: Provider registration request
:return: si_redirects, sector_id
:raises: InvalidSectorIdentifier
"""
si_url... | [
"def",
"_verify_sector_identifier",
"(",
"self",
",",
"request",
")",
":",
"si_url",
"=",
"request",
"[",
"\"sector_identifier_uri\"",
"]",
"try",
":",
"res",
"=",
"self",
".",
"endpoint_context",
".",
"httpc",
".",
"get",
"(",
"si_url",
")",
"except",
"Exce... | 34.971429 | 18.971429 |
def get_kernel_data(self):
"""Get the kernel data needed for this optimization routine to work."""
return {
'nmsimplex_scratch': LocalMemory(
'mot_float_type', self._nmr_parameters * 2 + (self._nmr_parameters + 1) ** 2 + 1),
'initial_simplex_scale': LocalMemory('m... | [
"def",
"get_kernel_data",
"(",
"self",
")",
":",
"return",
"{",
"'nmsimplex_scratch'",
":",
"LocalMemory",
"(",
"'mot_float_type'",
",",
"self",
".",
"_nmr_parameters",
"*",
"2",
"+",
"(",
"self",
".",
"_nmr_parameters",
"+",
"1",
")",
"**",
"2",
"+",
"1",... | 51.571429 | 25.714286 |
def parse_conf(self, keys=[]):
"""Parse configuration values from the database.
The extension must have been previously initialized.
If a key is not found in the database, it will be created with the
default value specified.
Arguments:
keys (list[str]): list of key... | [
"def",
"parse_conf",
"(",
"self",
",",
"keys",
"=",
"[",
"]",
")",
":",
"confs",
"=",
"self",
".",
"app",
".",
"config",
".",
"get",
"(",
"'WAFFLE_CONFS'",
",",
"{",
"}",
")",
"if",
"not",
"keys",
":",
"keys",
"=",
"confs",
".",
"keys",
"(",
")... | 29.511111 | 21.311111 |
def create_graph_from_data(self, data):
"""Run the algorithm on data.
Args:
data (pandas.DataFrame): DataFrame containing the data
Returns:
networkx.DiGraph: Solution given by the algorithm.
"""
# Building setup w/ arguments.
self.arguments['{SC... | [
"def",
"create_graph_from_data",
"(",
"self",
",",
"data",
")",
":",
"# Building setup w/ arguments.",
"self",
".",
"arguments",
"[",
"'{SCORE}'",
"]",
"=",
"self",
".",
"score",
"self",
".",
"arguments",
"[",
"'{VERBOSE}'",
"]",
"=",
"str",
"(",
"self",
"."... | 33.238095 | 18.47619 |
def upload_as_text(name, filename):
"""
Upload the IPList as text from a file.
:param str name: name of IPList
:param str filename: name of text file to upload
:return: None
"""
location = list(IPList.objects.filter(name))
if location:
iplist = location[0]
return iplist... | [
"def",
"upload_as_text",
"(",
"name",
",",
"filename",
")",
":",
"location",
"=",
"list",
"(",
"IPList",
".",
"objects",
".",
"filter",
"(",
"name",
")",
")",
"if",
"location",
":",
"iplist",
"=",
"location",
"[",
"0",
"]",
"return",
"iplist",
".",
"... | 29.166667 | 12.75 |
def _get_session(team, timeout=None):
"""
Creates a session or returns an existing session.
"""
global _sessions # pylint:disable=C0103
session = _sessions.get(team)
if session is None:
auth = _create_auth(team, timeout)
_sessions[team] = session = _create_session(team... | [
"def",
"_get_session",
"(",
"team",
",",
"timeout",
"=",
"None",
")",
":",
"global",
"_sessions",
"# pylint:disable=C0103",
"session",
"=",
"_sessions",
".",
"get",
"(",
"team",
")",
"if",
"session",
"is",
"None",
":",
"auth",
"=",
"_create_auth",
"(",
"te... | 28.230769 | 14.692308 |
def open_file(link, session=None, stream=True):
"""
Open local or remote file for reading.
:type link: pip._internal.index.Link or str
:type session: requests.Session
:param bool stream: Try to stream if remote, default True
:raises ValueError: If link points to a local directory.
:return: ... | [
"def",
"open_file",
"(",
"link",
",",
"session",
"=",
"None",
",",
"stream",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"link",
",",
"six",
".",
"string_types",
")",
":",
"try",
":",
"link",
"=",
"link",
".",
"url_without_fragment",
"except... | 34.533333 | 16.044444 |
def get_cache_key(self, name, filename=None):
"""Returns the unique hash key for this template name."""
hash = sha1(name.encode('utf-8'))
if filename is not None:
filename = '|' + filename
if isinstance(filename, text_type):
filename = filename.encode('utf... | [
"def",
"get_cache_key",
"(",
"self",
",",
"name",
",",
"filename",
"=",
"None",
")",
":",
"hash",
"=",
"sha1",
"(",
"name",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"if",
"filename",
"is",
"not",
"None",
":",
"filename",
"=",
"'|'",
"+",
"filename",
... | 42.444444 | 5.666667 |
def exception_handler(exctype, value, traceback):
"""
This exception handler catches KeyboardInterrupt to cancel the Runner and
also stops the Runner in case of an error.
"""
if exctype == KeyboardInterrupt:
pypro.console.out('') # Adds a new line after Ctrl+C character
pypro.consol... | [
"def",
"exception_handler",
"(",
"exctype",
",",
"value",
",",
"traceback",
")",
":",
"if",
"exctype",
"==",
"KeyboardInterrupt",
":",
"pypro",
".",
"console",
".",
"out",
"(",
"''",
")",
"# Adds a new line after Ctrl+C character",
"pypro",
".",
"console",
".",
... | 37.923077 | 13.615385 |
def display_date(d):
"""
Render a date/datetime (d) as a date, using the SPECTATOR_DATE_FORMAT
setting. Wrap the output in a <time> tag.
Time tags: http://www.brucelawson.co.uk/2012/best-of-time/
"""
stamp = d.strftime('%Y-%m-%d')
visible_date = d.strftime(app_settings.DATE_FORMAT)
ret... | [
"def",
"display_date",
"(",
"d",
")",
":",
"stamp",
"=",
"d",
".",
"strftime",
"(",
"'%Y-%m-%d'",
")",
"visible_date",
"=",
"d",
".",
"strftime",
"(",
"app_settings",
".",
"DATE_FORMAT",
")",
"return",
"format_html",
"(",
"'<time datetime=\"%(stamp)s\">%(visible... | 32.928571 | 17.928571 |
def format_hep(citation_elements):
"""Format hep-th report numbers with a dash
e.g. replaces hep-th-9711200 with hep-th/9711200
"""
prefixes = ('astro-ph-', 'hep-th-', 'hep-ph-', 'hep-ex-', 'hep-lat-',
'math-ph-')
for el in citation_elements:
if el['type'] == 'REPORTNUMBER':... | [
"def",
"format_hep",
"(",
"citation_elements",
")",
":",
"prefixes",
"=",
"(",
"'astro-ph-'",
",",
"'hep-th-'",
",",
"'hep-ph-'",
",",
"'hep-ex-'",
",",
"'hep-lat-'",
",",
"'math-ph-'",
")",
"for",
"el",
"in",
"citation_elements",
":",
"if",
"el",
"[",
"'typ... | 39.071429 | 13.642857 |
def set_file_limits(n):
'''
Set the limit on number of file descriptors
that this process can open.
'''
try:
resource.setrlimit(resource.RLIMIT_NOFILE, (n, n))
return True
except ValueError:
return False | [
"def",
"set_file_limits",
"(",
"n",
")",
":",
"try",
":",
"resource",
".",
"setrlimit",
"(",
"resource",
".",
"RLIMIT_NOFILE",
",",
"(",
"n",
",",
"n",
")",
")",
"return",
"True",
"except",
"ValueError",
":",
"return",
"False"
] | 20.166667 | 24 |
def polarization_vector(phi, theta, alpha, beta, p):
r"""This function returns a unitary vector describing the polarization
of plane waves. It recieves as arguments:
phi .- The spherical coordinates azimuthal angle of the wave vector k.
theta .- The spherical coordinates polar angle of the wave vecto... | [
"def",
"polarization_vector",
"(",
"phi",
",",
"theta",
",",
"alpha",
",",
"beta",
",",
"p",
")",
":",
"epsilon",
"=",
"Matrix",
"(",
"[",
"cos",
"(",
"2",
"*",
"beta",
")",
",",
"p",
"*",
"I",
"*",
"sin",
"(",
"2",
"*",
"beta",
")",
",",
"0"... | 33.396825 | 23.634921 |
def emit(self, event, *args, **kwargs):
"""Emit a server generated SocketIO event.
This function emits a SocketIO event to one or more connected clients.
A JSON blob can be attached to the event as payload. This function can
be used outside of a SocketIO event context, so it is appropri... | [
"def",
"emit",
"(",
"self",
",",
"event",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"namespace",
"=",
"kwargs",
".",
"pop",
"(",
"'namespace'",
",",
"'/'",
")",
"room",
"=",
"kwargs",
".",
"pop",
"(",
"'room'",
",",
"None",
")",
"inclu... | 55.45 | 23.625 |
def _randomize(coeffs, radixes, seed=None):
"""Applies the Owen (2017) randomization to the coefficients."""
given_dtype = coeffs.dtype
coeffs = tf.cast(coeffs, dtype=tf.int32)
num_coeffs = tf.shape(input=coeffs)[-1]
radixes = tf.reshape(tf.cast(radixes, dtype=tf.int32), shape=[-1])
stream = distributions.S... | [
"def",
"_randomize",
"(",
"coeffs",
",",
"radixes",
",",
"seed",
"=",
"None",
")",
":",
"given_dtype",
"=",
"coeffs",
".",
"dtype",
"coeffs",
"=",
"tf",
".",
"cast",
"(",
"coeffs",
",",
"dtype",
"=",
"tf",
".",
"int32",
")",
"num_coeffs",
"=",
"tf",
... | 52.466667 | 12.466667 |
def get_lists(self, **query_params):
'''
Get the lists attached to this board. Returns a list of List objects.
Returns:
list(List): The lists attached to this board
'''
lists = self.get_lists_json(self.base_uri, query_params=query_params)
lists_list = []
... | [
"def",
"get_lists",
"(",
"self",
",",
"*",
"*",
"query_params",
")",
":",
"lists",
"=",
"self",
".",
"get_lists_json",
"(",
"self",
".",
"base_uri",
",",
"query_params",
"=",
"query_params",
")",
"lists_list",
"=",
"[",
"]",
"for",
"list_json",
"in",
"li... | 30.071429 | 25.357143 |
def backing_file(self):
"""
When using linked clone this will return the path to the base image
:returns: None if it's not a linked clone, the path otherwise
"""
with open(self._path, 'rb') as f:
f.seek(self.backing_file_offset)
content = f.read(self.bac... | [
"def",
"backing_file",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"_path",
",",
"'rb'",
")",
"as",
"f",
":",
"f",
".",
"seek",
"(",
"self",
".",
"backing_file_offset",
")",
"content",
"=",
"f",
".",
"read",
"(",
"self",
".",
"backing_... | 28.333333 | 18.6 |
def _set_user_password(self, v, load=False):
"""
Setter method for user_password, mapped from YANG variable /username/user_password (user-passwd)
If this variable is read-only (config: false) in the
source YANG file, then _set_user_password is considered as a private
method. Backends looking to popu... | [
"def",
"_set_user_password",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"... | 78.545455 | 36.454545 |
def diff_prettyHtml(self, diffs):
"""Convert a diff array into a pretty HTML report.
Args:
diffs: Array of diff tuples.
Returns:
HTML representation.
"""
html = []
for (op, data) in diffs:
text = (data.replace("&", "&").replace("<", "<")
.replace(">", ... | [
"def",
"diff_prettyHtml",
"(",
"self",
",",
"diffs",
")",
":",
"html",
"=",
"[",
"]",
"for",
"(",
"op",
",",
"data",
")",
"in",
"diffs",
":",
"text",
"=",
"(",
"data",
".",
"replace",
"(",
"\"&\"",
",",
"\"&\"",
")",
".",
"replace",
"(",
"\"<... | 32.9 | 18.05 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.