text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def _handle_waited_log(self, event: dict):
""" A subroutine of handle_log
Increment self.event_count, forget about waiting, and call the callback if any.
"""
txn_hash = event['transactionHash']
event_name = event['event']
assert event_name in self.event_waiting
as... | [
"def",
"_handle_waited_log",
"(",
"self",
",",
"event",
":",
"dict",
")",
":",
"txn_hash",
"=",
"event",
"[",
"'transactionHash'",
"]",
"event_name",
"=",
"event",
"[",
"'event'",
"]",
"assert",
"event_name",
"in",
"self",
".",
"event_waiting",
"assert",
"tx... | 39.666667 | 16.277778 |
def write_output(self):
"""Write the Playbook output variables.
This method should be overridden with the output variables defined in the install.json
configuration file.
"""
self.tcex.log.info('Writing Output')
self.tcex.playbook.create_output('json.pretty', self.pretty... | [
"def",
"write_output",
"(",
"self",
")",
":",
"self",
".",
"tcex",
".",
"log",
".",
"info",
"(",
"'Writing Output'",
")",
"self",
".",
"tcex",
".",
"playbook",
".",
"create_output",
"(",
"'json.pretty'",
",",
"self",
".",
"pretty_json",
")"
] | 39.875 | 20.125 |
def add(self, child):
"""
Adds a typed child object to the component type.
@param child: Child object to be added.
"""
if isinstance(child, FatComponent):
self.add_child_component(child)
else:
Fat.add(self, child) | [
"def",
"add",
"(",
"self",
",",
"child",
")",
":",
"if",
"isinstance",
"(",
"child",
",",
"FatComponent",
")",
":",
"self",
".",
"add_child_component",
"(",
"child",
")",
"else",
":",
"Fat",
".",
"add",
"(",
"self",
",",
"child",
")"
] | 25.181818 | 14.818182 |
def get_cpu_vendor(cls, family, arch='x86'):
"""
Get CPU vendor, if vendor is not available will return 'generic'
Args:
family(str): CPU family
arch(str): CPU arch
Returns:
str: CPU vendor if found otherwise 'generic'
"""
props = cls... | [
"def",
"get_cpu_vendor",
"(",
"cls",
",",
"family",
",",
"arch",
"=",
"'x86'",
")",
":",
"props",
"=",
"cls",
".",
"get_cpu_props",
"(",
"family",
",",
"arch",
")",
"vendor",
"=",
"'generic'",
"try",
":",
"vendor",
"=",
"props",
".",
"xpath",
"(",
"'... | 25.684211 | 18.631579 |
def random_split(self, weights):
"""
Random split imageframes according to weights
:param weights: weights for each ImageFrame
:return:
"""
jvalues = self.image_frame.random_split(weights)
return [ImageFrame(jvalue) for jvalue in jvalues] | [
"def",
"random_split",
"(",
"self",
",",
"weights",
")",
":",
"jvalues",
"=",
"self",
".",
"image_frame",
".",
"random_split",
"(",
"weights",
")",
"return",
"[",
"ImageFrame",
"(",
"jvalue",
")",
"for",
"jvalue",
"in",
"jvalues",
"]"
] | 36.125 | 11.125 |
def get_data(self, pivotrequest):
"""The method is getting data by pivot request"""
path = '/api/1.0/data/pivot/'
return self._api_post(definition.PivotResponse, path, pivotrequest) | [
"def",
"get_data",
"(",
"self",
",",
"pivotrequest",
")",
":",
"path",
"=",
"'/api/1.0/data/pivot/'",
"return",
"self",
".",
"_api_post",
"(",
"definition",
".",
"PivotResponse",
",",
"path",
",",
"pivotrequest",
")"
] | 41.2 | 16.4 |
def write(self, output_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Write the data encoding the GetAttributes response payload to a
stream.
Args:
output_buffer (stream): A data stream in which to encode object
data, supporting a write method; usually... | [
"def",
"write",
"(",
"self",
",",
"output_buffer",
",",
"kmip_version",
"=",
"enums",
".",
"KMIPVersion",
".",
"KMIP_1_0",
")",
":",
"local_buffer",
"=",
"utils",
".",
"BytearrayStream",
"(",
")",
"if",
"self",
".",
"_unique_identifier",
":",
"self",
".",
... | 38.54902 | 19.803922 |
def plot_multi(func:Callable[[int,int,plt.Axes],None], r:int=1, c:int=1, figsize:Tuple=(12,6)):
"Call `func` for every combination of `r,c` on a subplot"
axes = plt.subplots(r, c, figsize=figsize)[1]
for i in range(r):
for j in range(c): func(i,j,axes[i,j]) | [
"def",
"plot_multi",
"(",
"func",
":",
"Callable",
"[",
"[",
"int",
",",
"int",
",",
"plt",
".",
"Axes",
"]",
",",
"None",
"]",
",",
"r",
":",
"int",
"=",
"1",
",",
"c",
":",
"int",
"=",
"1",
",",
"figsize",
":",
"Tuple",
"=",
"(",
"12",
",... | 54.6 | 21.8 |
def _type_check_pointers(utype):
"""Checks the user-derived type for non-nullified pointer array declarations
in its base definition.
Returns (list of offending members).
"""
result = []
for mname, member in utype.members.items():
if ("pointer" in member.modifiers and member.D > 0 and
... | [
"def",
"_type_check_pointers",
"(",
"utype",
")",
":",
"result",
"=",
"[",
"]",
"for",
"mname",
",",
"member",
"in",
"utype",
".",
"members",
".",
"items",
"(",
")",
":",
"if",
"(",
"\"pointer\"",
"in",
"member",
".",
"modifiers",
"and",
"member",
".",... | 33.076923 | 16.538462 |
def set_burnstages_upgrade_massive(self):
'''
Outputs burnign stages as done in burningstages_upgrade (nugridse)
'''
burn_info=[]
burn_mini=[]
for i in range(len(self.runs_H5_surf)):
sefiles=se(self.runs_H5_out[i])
burn_info.append(sefiles.burnstage_upgrade())
... | [
"def",
"set_burnstages_upgrade_massive",
"(",
"self",
")",
":",
"burn_info",
"=",
"[",
"]",
"burn_mini",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"runs_H5_surf",
")",
")",
":",
"sefiles",
"=",
"se",
"(",
"self",
".",
"r... | 38.470588 | 16.823529 |
def nltk_tokenize_words(string, attached_period=False, language=None):
"""Wrap NLTK's tokenizer PunktLanguageVars(), but make final period
its own token.
>>> nltk_tokenize_words("Sentence 1. Sentence 2.")
['Sentence', '1', '.', 'Sentence', '2', '.']
>>> #Optionally keep the NLTK's output:
>>>... | [
"def",
"nltk_tokenize_words",
"(",
"string",
",",
"attached_period",
"=",
"False",
",",
"language",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"string",
",",
"str",
")",
",",
"\"Incoming string must be type str.\"",
"if",
"language",
"==",
"'sanskrit'",
... | 35.027778 | 18.361111 |
def stdin(self, line, prompt=True, timeout=3):
"""
Send line to stdin, optionally expect a prompt.
:param line: line to be send to stdin
:type line: str
:param prompt: boolean indicating whether a prompt is expected, if True absorbs \
all of stdout before ... | [
"def",
"stdin",
"(",
"self",
",",
"line",
",",
"prompt",
"=",
"True",
",",
"timeout",
"=",
"3",
")",
":",
"if",
"line",
"==",
"EOF",
":",
"log",
"(",
"\"sending EOF...\"",
")",
"else",
":",
"log",
"(",
"_",
"(",
"\"sending input {}...\"",
")",
".",
... | 35.942857 | 19.885714 |
def get_top_artists(self, limit=None, cacheable=True):
"""Returns a sequence of the most played artists."""
params = self._get_params()
if limit:
params["limit"] = limit
doc = self._request("geo.getTopArtists", cacheable, params)
return _extract_top_artists(doc, sel... | [
"def",
"get_top_artists",
"(",
"self",
",",
"limit",
"=",
"None",
",",
"cacheable",
"=",
"True",
")",
":",
"params",
"=",
"self",
".",
"_get_params",
"(",
")",
"if",
"limit",
":",
"params",
"[",
"\"limit\"",
"]",
"=",
"limit",
"doc",
"=",
"self",
"."... | 34.888889 | 17.777778 |
def get_nfd_quick_check_property(value, is_bytes=False):
"""Get `NFD QUICK CHECK` property."""
obj = unidata.ascii_nfd_quick_check if is_bytes else unidata.unicode_nfd_quick_check
if value.startswith('^'):
negated = value[1:]
value = '^' + unidata.unicode_alias['nfdquickcheck'].get(negated... | [
"def",
"get_nfd_quick_check_property",
"(",
"value",
",",
"is_bytes",
"=",
"False",
")",
":",
"obj",
"=",
"unidata",
".",
"ascii_nfd_quick_check",
"if",
"is_bytes",
"else",
"unidata",
".",
"unicode_nfd_quick_check",
"if",
"value",
".",
"startswith",
"(",
"'^'",
... | 35.416667 | 27.666667 |
def add_record(self, record):
"""Add a record to the OAISet.
:param record: Record to be added.
:type record: `invenio_records.api.Record` or derivative.
"""
record.setdefault('_oai', {}).setdefault('sets', [])
assert not self.has_record(record)
record['_oai'][... | [
"def",
"add_record",
"(",
"self",
",",
"record",
")",
":",
"record",
".",
"setdefault",
"(",
"'_oai'",
",",
"{",
"}",
")",
".",
"setdefault",
"(",
"'sets'",
",",
"[",
"]",
")",
"assert",
"not",
"self",
".",
"has_record",
"(",
"record",
")",
"record",... | 30.454545 | 17.090909 |
def spectrum_loglike(self, specType, params, scale=1E3):
""" return the log-likelihood for a particular spectrum
Parameters
----------
specTypes : str
The type of spectrum to try
params : array-like
The spectral parameters
scale : float
... | [
"def",
"spectrum_loglike",
"(",
"self",
",",
"specType",
",",
"params",
",",
"scale",
"=",
"1E3",
")",
":",
"sfn",
"=",
"self",
".",
"create_functor",
"(",
"specType",
",",
"scale",
")",
"[",
"0",
"]",
"return",
"self",
".",
"__call__",
"(",
"sfn",
"... | 28.25 | 15.875 |
def summary(self, CorpNum, JobID, TradeType, TradeUsage, UserID=None):
""" 수집 결과 요약정보 조회
args
CorpNum : 팝빌회원 사업자번호
JobID : 작업아이디
TradeType : 문서형태 배열, N-일반 현금영수증, C-취소 현금영수증
TradeUsage : 거래구분 배열, P-소등공제용, C-지출증빙용
UserID :... | [
"def",
"summary",
"(",
"self",
",",
"CorpNum",
",",
"JobID",
",",
"TradeType",
",",
"TradeUsage",
",",
"UserID",
"=",
"None",
")",
":",
"if",
"JobID",
"==",
"None",
"or",
"len",
"(",
"JobID",
")",
"!=",
"18",
":",
"raise",
"PopbillException",
"(",
"-... | 35.761905 | 16.238095 |
def get_real_time_locate(ipAddress):
"""
function takes the ipAddress of a specific host and issues a RESTFUL call to get the device and interface that the
target host is currently connected to.
:param ipAddress: str value valid IPv4 IP address
:return: dictionary containing hostIp, devId, deviceIP,... | [
"def",
"get_real_time_locate",
"(",
"ipAddress",
")",
":",
"if",
"auth",
"is",
"None",
"or",
"url",
"is",
"None",
":",
"# checks to see if the imc credentials are already available",
"set_imc_creds",
"(",
")",
"real_time_locate_url",
"=",
"\"/imcrs/res/access/realtimeLocate... | 48.722222 | 25.833333 |
def watch_thread(self):
'''watch for settings changes from child'''
from mp_settings import MPSetting
while True:
setting = self.child_pipe.recv()
if not isinstance(setting, MPSetting):
break
try:
self.settings.set(setting.name,... | [
"def",
"watch_thread",
"(",
"self",
")",
":",
"from",
"mp_settings",
"import",
"MPSetting",
"while",
"True",
":",
"setting",
"=",
"self",
".",
"child_pipe",
".",
"recv",
"(",
")",
"if",
"not",
"isinstance",
"(",
"setting",
",",
"MPSetting",
")",
":",
"br... | 39.545455 | 16.272727 |
def generate_help():
"""Generates help text with alphabetically sorted recipes."""
help_text = '\nAvailable recipes:\n\n'
recipes = config.Config.get_registered_recipes()
for contents, _, _ in sorted(recipes, key=lambda k: k[0]['name']):
help_text += ' {0:<35s}{1:s}\n'.format(
contents['name'], cont... | [
"def",
"generate_help",
"(",
")",
":",
"help_text",
"=",
"'\\nAvailable recipes:\\n\\n'",
"recipes",
"=",
"config",
".",
"Config",
".",
"get_registered_recipes",
"(",
")",
"for",
"contents",
",",
"_",
",",
"_",
"in",
"sorted",
"(",
"recipes",
",",
"key",
"="... | 47.5 | 15.125 |
def update(self, of):
"""Update a file from another file, for copying"""
# The other values should be set when the file object is created with dataset.bsfile()
for p in ('mime_type', 'preference', 'state', 'hash', 'modified', 'size', 'contents', 'source_hash', 'data'):
setattr(self,... | [
"def",
"update",
"(",
"self",
",",
"of",
")",
":",
"# The other values should be set when the file object is created with dataset.bsfile()",
"for",
"p",
"in",
"(",
"'mime_type'",
",",
"'preference'",
",",
"'state'",
",",
"'hash'",
",",
"'modified'",
",",
"'size'",
","... | 44.125 | 31.875 |
def slice_query(self, slice_id):
"""
This method exposes an API endpoint to
get the database query string for this slice
"""
viz_obj = get_viz(slice_id)
security_manager.assert_datasource_permission(viz_obj.datasource)
return self.get_query_string_response(viz_obj... | [
"def",
"slice_query",
"(",
"self",
",",
"slice_id",
")",
":",
"viz_obj",
"=",
"get_viz",
"(",
"slice_id",
")",
"security_manager",
".",
"assert_datasource_permission",
"(",
"viz_obj",
".",
"datasource",
")",
"return",
"self",
".",
"get_query_string_response",
"(",... | 39.25 | 9.75 |
def can_lookup_objective_prerequisites(self):
"""Tests if this user can perform Objective lookups.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known all methods in this
session will result in a PermissionDenied. This is intended a... | [
"def",
"can_lookup_objective_prerequisites",
"(",
"self",
")",
":",
"url_path",
"=",
"construct_url",
"(",
"'authorization'",
",",
"bank_id",
"=",
"self",
".",
"_catalog_idstr",
")",
"return",
"self",
".",
"_get_request",
"(",
"url_path",
")",
"[",
"'objectiveRequ... | 46.470588 | 22.294118 |
def update(self, **fields):
"""Updates all rows that match the filter."""
# build up the query to execute
self._for_write = True
if django.VERSION >= (2, 0):
query = self.query.chain(UpdateQuery)
else:
query = self.query.clone(UpdateQuery)
query._... | [
"def",
"update",
"(",
"self",
",",
"*",
"*",
"fields",
")",
":",
"# build up the query to execute",
"self",
".",
"_for_write",
"=",
"True",
"if",
"django",
".",
"VERSION",
">=",
"(",
"2",
",",
"0",
")",
":",
"query",
"=",
"self",
".",
"query",
".",
"... | 34.035714 | 16.285714 |
def bind(self, data_shapes, label_shapes=None, for_training=True,
inputs_need_grad=False, force_rebind=False, shared_module=None,
grad_req='write'):
"""Binds the symbols to construct executors. This is necessary before one
can perform computation with the module.
Param... | [
"def",
"bind",
"(",
"self",
",",
"data_shapes",
",",
"label_shapes",
"=",
"None",
",",
"for_training",
"=",
"True",
",",
"inputs_need_grad",
"=",
"False",
",",
"force_rebind",
"=",
"False",
",",
"shared_module",
"=",
"None",
",",
"grad_req",
"=",
"'write'",
... | 49.265306 | 23.265306 |
def user_list(self, userid, cur_p=''):
'''
List the entities of the user.
'''
current_page_number = int(cur_p) if cur_p else 1
current_page_number = 1 if current_page_number < 1 else current_page_number
kwd = {
'current_page': current_page_number
}
... | [
"def",
"user_list",
"(",
"self",
",",
"userid",
",",
"cur_p",
"=",
"''",
")",
":",
"current_page_number",
"=",
"int",
"(",
"cur_p",
")",
"if",
"cur_p",
"else",
"1",
"current_page_number",
"=",
"1",
"if",
"current_page_number",
"<",
"1",
"else",
"current_pa... | 34.277778 | 23.277778 |
def get_tree(root=None):
"""
This is a helper function to get a multipath configuration component for
your local machine or an archive. It's for use in interactive sessions.
"""
from insights import run
return run(MultipathConfTree, root=root).get(MultipathConfTree) | [
"def",
"get_tree",
"(",
"root",
"=",
"None",
")",
":",
"from",
"insights",
"import",
"run",
"return",
"run",
"(",
"MultipathConfTree",
",",
"root",
"=",
"root",
")",
".",
"get",
"(",
"MultipathConfTree",
")"
] | 40.571429 | 18 |
def addLayer(layer, loadInLegend=True):
"""
Add one or several layers to the QGIS session and layer registry.
:param layer: The layer object or list with layers to add the QGIS layer registry and session.
:param loadInLegend: True if this layer should be added to the legend.
:return: The added laye... | [
"def",
"addLayer",
"(",
"layer",
",",
"loadInLegend",
"=",
"True",
")",
":",
"if",
"not",
"hasattr",
"(",
"layer",
",",
"\"__iter__\"",
")",
":",
"layer",
"=",
"[",
"layer",
"]",
"_layerreg",
".",
"addMapLayers",
"(",
"layer",
",",
"loadInLegend",
")",
... | 40.636364 | 16.818182 |
def _get_indices(values, selected, tolerance):
"""Get indices based on user-selected values.
Parameters
----------
values : ndarray (any dtype)
values present in the axis.
selected : ndarray (any dtype) or tuple or list
values selected by the user
tolerance : float
avoid... | [
"def",
"_get_indices",
"(",
"values",
",",
"selected",
",",
"tolerance",
")",
":",
"idx_data",
"=",
"[",
"]",
"idx_output",
"=",
"[",
"]",
"for",
"idx_of_selected",
",",
"one_selected",
"in",
"enumerate",
"(",
"selected",
")",
":",
"if",
"tolerance",
"is",... | 31.044444 | 22.377778 |
def flush(self):
"""Erases queue and set `end-of-queue` message."""
while not self._queue.empty():
self._queue.get()
self._queue.task_done()
self.close() | [
"def",
"flush",
"(",
"self",
")",
":",
"while",
"not",
"self",
".",
"_queue",
".",
"empty",
"(",
")",
":",
"self",
".",
"_queue",
".",
"get",
"(",
")",
"self",
".",
"_queue",
".",
"task_done",
"(",
")",
"self",
".",
"close",
"(",
")"
] | 32.666667 | 10.333333 |
def _cmd_create(self):
"""Create a migration in the current or new revision folder
"""
assert self._message, "need to supply a message for the \"create\" command"
if not self._revisions:
self._revisions.append("1")
# get the migration folder
rev_folder = self... | [
"def",
"_cmd_create",
"(",
"self",
")",
":",
"assert",
"self",
".",
"_message",
",",
"\"need to supply a message for the \\\"create\\\" command\"",
"if",
"not",
"self",
".",
"_revisions",
":",
"self",
".",
"_revisions",
".",
"append",
"(",
"\"1\"",
")",
"# get the... | 44.710526 | 17.078947 |
def check_input_and_output_types(operator, good_input_types=None, good_output_types=None):
'''
Check if the type(s) of input(s)/output(s) is(are) correct
:param operator: A Operator object
:param good_input_types: A list of allowed input types (e.g., [FloatTensorType, Int64TensorType]) or None. None
... | [
"def",
"check_input_and_output_types",
"(",
"operator",
",",
"good_input_types",
"=",
"None",
",",
"good_output_types",
"=",
"None",
")",
":",
"if",
"good_input_types",
"is",
"not",
"None",
":",
"for",
"variable",
"in",
"operator",
".",
"inputs",
":",
"if",
"t... | 60 | 34.090909 |
def consume_keys(self):
"""
Work through the keys to look up sequentially
"""
print("\nLooking up " + self.input_queue.qsize().__str__() + " keys from " + self.source_name + "\n")
self.data_worker(**self.worker_args) | [
"def",
"consume_keys",
"(",
"self",
")",
":",
"print",
"(",
"\"\\nLooking up \"",
"+",
"self",
".",
"input_queue",
".",
"qsize",
"(",
")",
".",
"__str__",
"(",
")",
"+",
"\" keys from \"",
"+",
"self",
".",
"source_name",
"+",
"\"\\n\"",
")",
"self",
"."... | 41.833333 | 17.166667 |
def list_recipes(full=False):
"""Method that iterates over all available recipes and prints their
information to the standard output
Parameters
----------
full : bool
If true, it will provide the pipeline string along with the recipe name
"""
logger.info(colored_print(
"\n=... | [
"def",
"list_recipes",
"(",
"full",
"=",
"False",
")",
":",
"logger",
".",
"info",
"(",
"colored_print",
"(",
"\"\\n===== L I S T O F R E C I P E S =====\\n\"",
",",
"\"green_bold\"",
")",
")",
"# This will iterate over all modules included in the recipes subpackage",
"# ... | 37.175 | 25.625 |
def start_zap_daemon(zap_helper, start_options):
"""Helper to start the daemon using the current config."""
console.info('Starting ZAP daemon')
with helpers.zap_error_handler():
zap_helper.start(options=start_options) | [
"def",
"start_zap_daemon",
"(",
"zap_helper",
",",
"start_options",
")",
":",
"console",
".",
"info",
"(",
"'Starting ZAP daemon'",
")",
"with",
"helpers",
".",
"zap_error_handler",
"(",
")",
":",
"zap_helper",
".",
"start",
"(",
"options",
"=",
"start_options",... | 46.6 | 3.8 |
def _process_mor_objects_queue(self, instance):
"""
Pops `batch_morlist_size` items from the mor objects queue and run asynchronously
the _process_mor_objects_queue_async method to fill the Mor cache.
"""
i_key = self._instance_key(instance)
self.mor_cache.init_instance(i... | [
"def",
"_process_mor_objects_queue",
"(",
"self",
",",
"instance",
")",
":",
"i_key",
"=",
"self",
".",
"_instance_key",
"(",
"instance",
")",
"self",
".",
"mor_cache",
".",
"init_instance",
"(",
"i_key",
")",
"if",
"not",
"self",
".",
"mor_objects_queue",
"... | 55.292683 | 30.609756 |
def editpropset(self):
'''
:foo=10
'''
self.ignore(whitespace)
if not self.nextstr(':'):
self._raiseSyntaxExpects(':')
relp = self.relprop()
self.ignore(whitespace)
self.nextmust('=')
self.ignore(whitespace)
valu = self.va... | [
"def",
"editpropset",
"(",
"self",
")",
":",
"self",
".",
"ignore",
"(",
"whitespace",
")",
"if",
"not",
"self",
".",
"nextstr",
"(",
"':'",
")",
":",
"self",
".",
"_raiseSyntaxExpects",
"(",
"':'",
")",
"relp",
"=",
"self",
".",
"relprop",
"(",
")",... | 18.842105 | 22.421053 |
def njsd_all(network, ref, query, file, verbose=True):
"""Compute transcriptome-wide nJSD between reference and query expression profiles.
Attribute:
network (str): File path to a network file.
ref (str): File path to a reference expression file.
query (str): File path to a query express... | [
"def",
"njsd_all",
"(",
"network",
",",
"ref",
",",
"query",
",",
"file",
",",
"verbose",
"=",
"True",
")",
":",
"graph",
",",
"gene_set_total",
"=",
"util",
".",
"parse_network",
"(",
"network",
")",
"ref_gene_expression_dict",
"=",
"util",
".",
"parse_ge... | 58 | 30.466667 |
def check_length_of_initial_values(self, init_values):
"""
Ensures that `init_values` is of the correct length. Raises a helpful
ValueError if otherwise.
Parameters
----------
init_values : 1D ndarray.
The initial values to start the optimizatin process with.... | [
"def",
"check_length_of_initial_values",
"(",
"self",
",",
"init_values",
")",
":",
"# Calculate the expected number of shape and index parameters",
"# Note the uneven logit model has one shape parameter per alternative.",
"num_alts",
"=",
"self",
".",
"rows_to_alts",
".",
"shape",
... | 38.914286 | 22.742857 |
def run_server(conn, command, sock_path, debug, timeout):
"""Common code for run_agent and run_git below."""
ret = 0
try:
handler = protocol.Handler(conn=conn, debug=debug)
with serve(handler=handler, sock_path=sock_path,
timeout=timeout) as env:
if command:
... | [
"def",
"run_server",
"(",
"conn",
",",
"command",
",",
"sock_path",
",",
"debug",
",",
"timeout",
")",
":",
"ret",
"=",
"0",
"try",
":",
"handler",
"=",
"protocol",
".",
"Handler",
"(",
"conn",
"=",
"conn",
",",
"debug",
"=",
"debug",
")",
"with",
... | 38.357143 | 17.928571 |
def rsa_pss_verify(certificate_or_public_key, signature, data, hash_algorithm):
"""
Verifies an RSASSA-PSS signature. For the PSS padding the mask gen algorithm
will be mgf1 using the same hash algorithm as the signature. The salt length
with be the length of the hash algorithm, and the trailer field wi... | [
"def",
"rsa_pss_verify",
"(",
"certificate_or_public_key",
",",
"signature",
",",
"data",
",",
"hash_algorithm",
")",
":",
"if",
"not",
"isinstance",
"(",
"certificate_or_public_key",
",",
"(",
"Certificate",
",",
"PublicKey",
")",
")",
":",
"raise",
"TypeError",
... | 34.371429 | 23.657143 |
def _AddOutput(self, variable):
"""
Add one more variable as an output of the block
:param variable: variable (or signal as it is also a variable)
"""
if isinstance(variable, Variable):
self.outputs.append(variable)
else:
print(variable)
... | [
"def",
"_AddOutput",
"(",
"self",
",",
"variable",
")",
":",
"if",
"isinstance",
"(",
"variable",
",",
"Variable",
")",
":",
"self",
".",
"outputs",
".",
"append",
"(",
"variable",
")",
"else",
":",
"print",
"(",
"variable",
")",
"raise",
"TypeError"
] | 30.545455 | 14.363636 |
def shuffle(args):
"""
%prog shuffle p1.fastq p2.fastq
Shuffle pairs into interleaved format.
"""
p = OptionParser(shuffle.__doc__)
p.set_tag()
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
p1, p2 = args
pairsfastq = pairspf((p1, p2)) ... | [
"def",
"shuffle",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"shuffle",
".",
"__doc__",
")",
"p",
".",
"set_tag",
"(",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"2",
... | 22.860465 | 18.162791 |
def get_ii_text(node):
"""
Get the text for IndicatorItem node.
:param node: IndicatorItem node.
:return:
"""
if node.tag != 'IndicatorItem':
raise IOCParseError('Invalid tag: {}'.format(node.tag))
condition = node.attrib.get('condition')
pres... | [
"def",
"get_ii_text",
"(",
"node",
")",
":",
"if",
"node",
".",
"tag",
"!=",
"'IndicatorItem'",
":",
"raise",
"IOCParseError",
"(",
"'Invalid tag: {}'",
".",
"format",
"(",
"node",
".",
"tag",
")",
")",
"condition",
"=",
"node",
".",
"attrib",
".",
"get"... | 43.607143 | 20.321429 |
def update_frame_attributes(self, attrib):
""" For positioning update the frame """
if "align" in self.user_defined:
align = self.user_defined["align"]
if "top" in align:
attrib["style:vertical-pos"] = "top"
if "right" in align:
attrib... | [
"def",
"update_frame_attributes",
"(",
"self",
",",
"attrib",
")",
":",
"if",
"\"align\"",
"in",
"self",
".",
"user_defined",
":",
"align",
"=",
"self",
".",
"user_defined",
"[",
"\"align\"",
"]",
"if",
"\"top\"",
"in",
"align",
":",
"attrib",
"[",
"\"styl... | 36.7 | 11.3 |
def _check_cols(df, col_names):
""" Raise an AttributeError if `df` does not have a column named as an item of
the list of strings `col_names`.
"""
for col in col_names:
if not hasattr(df, col):
raise AttributeError("DataFrame does not have a '{}' column, got {}.".format(col,
... | [
"def",
"_check_cols",
"(",
"df",
",",
"col_names",
")",
":",
"for",
"col",
"in",
"col_names",
":",
"if",
"not",
"hasattr",
"(",
"df",
",",
"col",
")",
":",
"raise",
"AttributeError",
"(",
"\"DataFrame does not have a '{}' column, got {}.\"",
".",
"format",
"("... | 50.875 | 18.75 |
def browser_attach_timeout(self, value):
"""
Sets the options Browser Attach Timeout
:Args:
- value: Timeout in milliseconds
"""
if not isinstance(value, int):
raise ValueError('Browser Attach Timeout must be an integer.')
self._options[self.BROWSER... | [
"def",
"browser_attach_timeout",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"int",
")",
":",
"raise",
"ValueError",
"(",
"'Browser Attach Timeout must be an integer.'",
")",
"self",
".",
"_options",
"[",
"self",
".",
"BR... | 30.363636 | 15.272727 |
def close(self):
"""
Close the stream. This performs a proper stream shutdown, except if the
stream is currently performing a TLS handshake. In that case, calling
:meth:`close` is equivalent to calling :meth:`abort`.
Otherwise, the transport waits until all buffers are transmitt... | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_state",
"==",
"_State",
".",
"CLOSED",
":",
"self",
".",
"_invalid_state",
"(",
"\"close() called\"",
")",
"return",
"if",
"self",
".",
"_state",
"==",
"_State",
".",
"TLS_HANDSHAKING",
":",
"# ... | 37.357143 | 19.357143 |
def triple_reference_of(label: ShExJ.tripleExprLabel, cntxt: Context) -> Optional[ShExJ.tripleExpr]:
""" Search for the label in a Schema """
te: Optional[ShExJ.tripleExpr] = None
if cntxt.schema.start is not None:
te = triple_in_shape(cntxt.schema.start, label, cntxt)
if te is None:
for... | [
"def",
"triple_reference_of",
"(",
"label",
":",
"ShExJ",
".",
"tripleExprLabel",
",",
"cntxt",
":",
"Context",
")",
"->",
"Optional",
"[",
"ShExJ",
".",
"tripleExpr",
"]",
":",
"te",
":",
"Optional",
"[",
"ShExJ",
".",
"tripleExpr",
"]",
"=",
"None",
"i... | 41.545455 | 17.909091 |
def bpp2newick(bppnewick):
"converts bpp newick format to normal newick"
regex1 = re.compile(r" #[-+]?[0-9]*\.?[0-9]*[:]")
regex2 = re.compile(r" #[-+]?[0-9]*\.?[0-9]*[;]")
regex3 = re.compile(r": ")
new = regex1.sub(":", bppnewick)
new = regex2.sub(";", new)
new = regex3.sub(":", new)
r... | [
"def",
"bpp2newick",
"(",
"bppnewick",
")",
":",
"regex1",
"=",
"re",
".",
"compile",
"(",
"r\" #[-+]?[0-9]*\\.?[0-9]*[:]\"",
")",
"regex2",
"=",
"re",
".",
"compile",
"(",
"r\" #[-+]?[0-9]*\\.?[0-9]*[;]\"",
")",
"regex3",
"=",
"re",
".",
"compile",
"(",
"r\":... | 35.666667 | 12.111111 |
def _register_token_network_without_limits(
self,
token_registry_abi: Dict,
token_registry_address: str,
token_address: str,
channel_participant_deposit_limit: Optional[int],
token_network_deposit_limit: Optional[int],
):
"""Register to... | [
"def",
"_register_token_network_without_limits",
"(",
"self",
",",
"token_registry_abi",
":",
"Dict",
",",
"token_registry_address",
":",
"str",
",",
"token_address",
":",
"str",
",",
"channel_participant_deposit_limit",
":",
"Optional",
"[",
"int",
"]",
",",
"token_n... | 39.888889 | 22.044444 |
def get_hashes(path, exclude=None):
'''
Get a dictionary of file paths and timestamps.
Paths matching `exclude` regex will be excluded.
'''
out = {}
for f in Path(path).rglob('*'):
if f.is_dir():
# We want to watch files, not directories.
continue
if excl... | [
"def",
"get_hashes",
"(",
"path",
",",
"exclude",
"=",
"None",
")",
":",
"out",
"=",
"{",
"}",
"for",
"f",
"in",
"Path",
"(",
"path",
")",
".",
"rglob",
"(",
"'*'",
")",
":",
"if",
"f",
".",
"is_dir",
"(",
")",
":",
"# We want to watch files, not d... | 30.411765 | 18.647059 |
def grp_by_src(self):
"""
:returns: a new CompositeSourceModel with one group per source
"""
smodels = []
grp_id = 0
for sm in self.source_models:
src_groups = []
smodel = sm.__class__(sm.names, sm.weight, sm.path, src_groups,
... | [
"def",
"grp_by_src",
"(",
"self",
")",
":",
"smodels",
"=",
"[",
"]",
"grp_id",
"=",
"0",
"for",
"sm",
"in",
"self",
".",
"source_models",
":",
"src_groups",
"=",
"[",
"]",
"smodel",
"=",
"sm",
".",
"__class__",
"(",
"sm",
".",
"names",
",",
"sm",
... | 42 | 14.9 |
def _create_api_call(self, method, _url, kwargs):
"""
This will create an APICall object and return it
:param method: str of the html method ['GET','POST','PUT','DELETE']
:param _url: str of the sub url of the api call (ex. g/device/list)
:param kwargs: dict of additional ar... | [
"def",
"_create_api_call",
"(",
"self",
",",
"method",
",",
"_url",
",",
"kwargs",
")",
":",
"api_call",
"=",
"self",
".",
"ApiCall",
"(",
"name",
"=",
"'%s.%s'",
"%",
"(",
"_url",
",",
"method",
")",
",",
"label",
"=",
"'ID_%s'",
"%",
"self",
".",
... | 48.409091 | 15.045455 |
def dropbox_editor_factory(request):
""" this factory also requires the editor token"""
dropbox = dropbox_factory(request)
if is_equal(dropbox.editor_token, request.matchdict['editor_token'].encode('utf-8')):
return dropbox
else:
raise HTTPNotFound('invalid editor token') | [
"def",
"dropbox_editor_factory",
"(",
"request",
")",
":",
"dropbox",
"=",
"dropbox_factory",
"(",
"request",
")",
"if",
"is_equal",
"(",
"dropbox",
".",
"editor_token",
",",
"request",
".",
"matchdict",
"[",
"'editor_token'",
"]",
".",
"encode",
"(",
"'utf-8'... | 42.571429 | 16.285714 |
def preprocessRequest(self, service_request, *args, **kwargs):
"""
Preprocesses a request.
"""
processor = self.getPreprocessor(service_request)
if processor is None:
return
args = (service_request,) + args
if hasattr(processor, '_pyamf_expose_reque... | [
"def",
"preprocessRequest",
"(",
"self",
",",
"service_request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"processor",
"=",
"self",
".",
"getPreprocessor",
"(",
"service_request",
")",
"if",
"processor",
"is",
"None",
":",
"return",
"args",
"="... | 27.8125 | 17.8125 |
def create_routertype(self, context, routertype):
"""Creates a router type.
Also binds it to the specified hosting device template.
"""
LOG.debug("create_routertype() called. Contents %s", routertype)
rt = routertype['routertype']
with context.session.begin(subtransactio... | [
"def",
"create_routertype",
"(",
"self",
",",
"context",
",",
"routertype",
")",
":",
"LOG",
".",
"debug",
"(",
"\"create_routertype() called. Contents %s\"",
",",
"routertype",
")",
"rt",
"=",
"routertype",
"[",
"'routertype'",
"]",
"with",
"context",
".",
"ses... | 44.565217 | 11.608696 |
def pci_contents(self, use_dict=None, as_class=dict):
"""Return the contents of an object as a dict."""
if _debug: PCI._debug("pci_contents use_dict=%r as_class=%r", use_dict, as_class)
# make/extend the dictionary of content
if use_dict is None:
use_dict = as_class()
... | [
"def",
"pci_contents",
"(",
"self",
",",
"use_dict",
"=",
"None",
",",
"as_class",
"=",
"dict",
")",
":",
"if",
"_debug",
":",
"PCI",
".",
"_debug",
"(",
"\"pci_contents use_dict=%r as_class=%r\"",
",",
"use_dict",
",",
"as_class",
")",
"# make/extend the dictio... | 37.352941 | 22.470588 |
def colorize(text='', opts=(), **kwargs):
"""
Returns your text, enclosed in ANSI graphics codes.
Depends on the keyword arguments 'fg' and 'bg', and the contents of
the opts tuple/list.
Returns the RESET code if no parameters are given.
Valid colors:
'black', 'red', 'green', 'yellow'... | [
"def",
"colorize",
"(",
"text",
"=",
"''",
",",
"opts",
"=",
"(",
")",
",",
"*",
"*",
"kwargs",
")",
":",
"color_names",
"=",
"(",
"'black'",
",",
"'red'",
",",
"'green'",
",",
"'yellow'",
",",
"'blue'",
",",
"'magenta'",
",",
"'cyan'",
",",
"'whit... | 31.571429 | 18.642857 |
def create_local_module_dir(cache_dir, module_name):
"""Creates and returns the name of directory where to cache a module."""
tf_v1.gfile.MakeDirs(cache_dir)
return os.path.join(cache_dir, module_name) | [
"def",
"create_local_module_dir",
"(",
"cache_dir",
",",
"module_name",
")",
":",
"tf_v1",
".",
"gfile",
".",
"MakeDirs",
"(",
"cache_dir",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"cache_dir",
",",
"module_name",
")"
] | 51 | 6 |
def generate_bio_assembly(data_api, struct_inflator):
"""Generate the bioassembly data.
:param data_api the interface to the decoded data
:param struct_inflator the interface to put the data into the client object"""
bioassembly_count = 0
for bioassembly in data_api.bio_assembly:
bioassembly... | [
"def",
"generate_bio_assembly",
"(",
"data_api",
",",
"struct_inflator",
")",
":",
"bioassembly_count",
"=",
"0",
"for",
"bioassembly",
"in",
"data_api",
".",
"bio_assembly",
":",
"bioassembly_count",
"+=",
"1",
"for",
"transform",
"in",
"bioassembly",
"[",
"\"tra... | 54.363636 | 15.363636 |
def concretize_store_idx(self, idx, strategies=None):
"""
Concretizes a store index.
:param idx: An expression for the index.
:param strategies: A list of concretization strategies (to override the default).
:param min_idx: Minimum value for a concretize... | [
"def",
"concretize_store_idx",
"(",
"self",
",",
"idx",
",",
"strategies",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"idx",
",",
"int",
")",
":",
"return",
"[",
"idx",
"]",
"elif",
"not",
"self",
".",
"state",
".",
"solver",
".",
"symbolic",
"(... | 46.882353 | 23.235294 |
def prior_const(C, alpha=0.001):
"""Constant prior of strength alpha.
Prior is defined via
b_ij=alpha for all i,j
Parameters
----------
C : (M, M) ndarray or scipy.sparse matrix
Count matrix
alpha : float (optional)
Value of prior counts
Returns
-------
B ... | [
"def",
"prior_const",
"(",
"C",
",",
"alpha",
"=",
"0.001",
")",
":",
"B",
"=",
"alpha",
"*",
"np",
".",
"ones",
"(",
"C",
".",
"shape",
")",
"return",
"B"
] | 18.045455 | 20.909091 |
def __getHyperSearchJobIDFilePath(cls, permWorkDir, outputLabel):
"""Returns filepath where to store HyperSearch JobID
Parameters:
----------------------------------------------------------------------
permWorkDir: Directory path for saved jobID file
outputLabel: Label string for incorporating into... | [
"def",
"__getHyperSearchJobIDFilePath",
"(",
"cls",
",",
"permWorkDir",
",",
"outputLabel",
")",
":",
"# Get the base path and figure out the path of the report file.",
"basePath",
"=",
"permWorkDir",
"# Form the name of the output csv file that will contain all the results",
"filename... | 41 | 23.176471 |
def STRB(self, params):
"""
STRB Ra, [Rb, Rc]
STRB Ra, [Rb, #imm5]
Store Ra into memory as a byte
Ra, Rb, and Rc must be low registers
"""
Ra, Rb, Rc = self.get_three_parameters(self.THREE_PARAMETER_WITH_BRACKETS, params)
if self.is_immediate(Rc):
... | [
"def",
"STRB",
"(",
"self",
",",
"params",
")",
":",
"Ra",
",",
"Rb",
",",
"Rc",
"=",
"self",
".",
"get_three_parameters",
"(",
"self",
".",
"THREE_PARAMETER_WITH_BRACKETS",
",",
"params",
")",
"if",
"self",
".",
"is_immediate",
"(",
"Rc",
")",
":",
"s... | 33.090909 | 24.818182 |
def _set_sflow_profile(self, v, load=False):
"""
Setter method for sflow_profile, mapped from YANG variable /sflow_profile (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_sflow_profile is considered as a private
method. Backends looking to populate this variab... | [
"def",
"_set_sflow_profile",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"... | 128.727273 | 61.545455 |
def bool(self, name):
"""parse a boolean frame"""
self._assert_is_string(name)
frame = self._next_frame()
if len(frame) != 1:
raise MessageParserError("Expected exacty 1 byte for boolean value")
val = frame != b"\x00"
self.results.__dict__[name] = val
... | [
"def",
"bool",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"_assert_is_string",
"(",
"name",
")",
"frame",
"=",
"self",
".",
"_next_frame",
"(",
")",
"if",
"len",
"(",
"frame",
")",
"!=",
"1",
":",
"raise",
"MessageParserError",
"(",
"\"Expected e... | 35.888889 | 12.666667 |
def _segmentation_guts(root, file_paths, max_partition_size):
"""Segment a series of file paths into TarPartition values
These TarPartitions are disjoint and roughly below the prescribed
size.
"""
# Canonicalize root to include the trailing slash, since root is
# intended to be a directory anyw... | [
"def",
"_segmentation_guts",
"(",
"root",
",",
"file_paths",
",",
"max_partition_size",
")",
":",
"# Canonicalize root to include the trailing slash, since root is",
"# intended to be a directory anyway.",
"if",
"not",
"root",
".",
"endswith",
"(",
"os",
".",
"path",
".",
... | 38.946809 | 20.106383 |
def evaluate(ref_time, ref_freq, est_time, est_freq, **kwargs):
"""Evaluate two melody (predominant f0) transcriptions, where the first is
treated as the reference (ground truth) and the second as the estimate to
be evaluated (prediction).
Examples
--------
>>> ref_time, ref_freq = mir_eval.io.... | [
"def",
"evaluate",
"(",
"ref_time",
",",
"ref_freq",
",",
"est_time",
",",
"est_freq",
",",
"*",
"*",
"kwargs",
")",
":",
"# Convert to reference/estimated voicing/frequency (cent) arrays",
"(",
"ref_voicing",
",",
"ref_cent",
",",
"est_voicing",
",",
"est_cent",
")... | 41.57377 | 24.967213 |
def _set_auth(self, user, password):
"""
Set authentication parameters
"""
if user is None or len(user.strip()) == 0:
self._user = None
self._password = None
self._auth = None
else:
self._user = user.strip()
if password:... | [
"def",
"_set_auth",
"(",
"self",
",",
"user",
",",
"password",
")",
":",
"if",
"user",
"is",
"None",
"or",
"len",
"(",
"user",
".",
"strip",
"(",
")",
")",
"==",
"0",
":",
"self",
".",
"_user",
"=",
"None",
"self",
".",
"_password",
"=",
"None",
... | 34.631579 | 11.578947 |
def visit_FromImport(self, node, frame):
"""Visit named imports."""
self.newline(node)
self.write('included_template = environment.get_template(')
self.visit(node.template, frame)
self.write(', %r).' % self.name)
if node.with_context:
self.write('make_module(c... | [
"def",
"visit_FromImport",
"(",
"self",
",",
"node",
",",
"frame",
")",
":",
"self",
".",
"newline",
"(",
"node",
")",
"self",
".",
"write",
"(",
"'included_template = environment.get_template('",
")",
"self",
".",
"visit",
"(",
"node",
".",
"template",
",",... | 41.096154 | 15.673077 |
def fitted(self):
"""
Whether all models in the group have been fitted.
"""
return (all(m.fitted for m in self.models.values())
if self.models else False) | [
"def",
"fitted",
"(",
"self",
")",
":",
"return",
"(",
"all",
"(",
"m",
".",
"fitted",
"for",
"m",
"in",
"self",
".",
"models",
".",
"values",
"(",
")",
")",
"if",
"self",
".",
"models",
"else",
"False",
")"
] | 28.142857 | 14.428571 |
def distribute_work(f, inputs, outputs=None, nprocs=1, out_key='output'):
"""
For each input i (a dict) in list **inputs**, evaluate f(**i)
using multiprocessing if nprocs>1
The result has the same format as the inputs: a list of dicts,
taken from outputs, and updated with f(**i).
If outputs is... | [
"def",
"distribute_work",
"(",
"f",
",",
"inputs",
",",
"outputs",
"=",
"None",
",",
"nprocs",
"=",
"1",
",",
"out_key",
"=",
"'output'",
")",
":",
"if",
"outputs",
"is",
"None",
":",
"outputs",
"=",
"[",
"ip",
".",
"copy",
"(",
")",
"for",
"ip",
... | 34.181818 | 16.121212 |
def expectation(T, a, mu=None):
r"""Equilibrium expectation value of a given observable.
Parameters
----------
T : (M, M) ndarray or scipy.sparse matrix
Transition matrix
a : (M,) ndarray
Observable vector
mu : (M,) ndarray (optional)
The stationary distribution of T. I... | [
"def",
"expectation",
"(",
"T",
",",
"a",
",",
"mu",
"=",
"None",
")",
":",
"# check if square matrix and remember size",
"T",
"=",
"_types",
".",
"ensure_ndarray_or_sparse",
"(",
"T",
",",
"ndim",
"=",
"2",
",",
"uniform",
"=",
"True",
",",
"kind",
"=",
... | 28.02 | 24.28 |
def set_checked(self, state):
"""
Sets the Widget checked state.
:param state: New check state.
:type state: bool
:return: Method success.
:rtype: bool
"""
if not self.__checkable:
return False
if state:
self.__checked = ... | [
"def",
"set_checked",
"(",
"self",
",",
"state",
")",
":",
"if",
"not",
"self",
".",
"__checkable",
":",
"return",
"False",
"if",
"state",
":",
"self",
".",
"__checked",
"=",
"True",
"self",
".",
"setPixmap",
"(",
"self",
".",
"__active_pixmap",
")",
"... | 24.047619 | 14.809524 |
def _islinklike(dir_path):
'''
Parameters
----------
dir_path : str
Directory path.
Returns
-------
bool
``True`` if :data:`dir_path` is a link *or* junction.
'''
dir_path = ph.path(dir_path)
if platform.system() == 'Windows':
if dir_path.isjunction():
... | [
"def",
"_islinklike",
"(",
"dir_path",
")",
":",
"dir_path",
"=",
"ph",
".",
"path",
"(",
"dir_path",
")",
"if",
"platform",
".",
"system",
"(",
")",
"==",
"'Windows'",
":",
"if",
"dir_path",
".",
"isjunction",
"(",
")",
":",
"return",
"True",
"elif",
... | 20.421053 | 21.789474 |
def mad(var, constant=1):
"""
Median Absolute Deviation: a "robust" version of standard deviation.
Parameters
----------
var : list or ndarray
Value array.
constant : float
Scale factor. Use 1.4826 for results similar to default R.
Returns
----------
mad : float
... | [
"def",
"mad",
"(",
"var",
",",
"constant",
"=",
"1",
")",
":",
"median",
"=",
"np",
".",
"median",
"(",
"var",
")",
"mad",
"=",
"np",
".",
"median",
"(",
"np",
".",
"abs",
"(",
"var",
"-",
"median",
")",
")",
"mad",
"=",
"mad",
"*",
"constant... | 19.307692 | 24.794872 |
def pause(path, service_names=None):
'''
Pause running containers in the docker-compose file, service_names is a python
list, if omitted pause all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will pause only the specified serv... | [
"def",
"pause",
"(",
"path",
",",
"service_names",
"=",
"None",
")",
":",
"project",
"=",
"__load_project",
"(",
"path",
")",
"debug_ret",
"=",
"{",
"}",
"result",
"=",
"{",
"}",
"if",
"isinstance",
"(",
"project",
",",
"dict",
")",
":",
"return",
"p... | 35.542857 | 25.714286 |
def join(self, other, on=None, how=None):
"""Joins with another :class:`DataFrame`, using the given join expression.
:param other: Right side of the join
:param on: a string for the join column name, a list of column names,
a join expression (Column), or a list of Columns.
... | [
"def",
"join",
"(",
"self",
",",
"other",
",",
"on",
"=",
"None",
",",
"how",
"=",
"None",
")",
":",
"if",
"on",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"on",
",",
"list",
")",
":",
"on",
"=",
"[",
"on",
"]",
"if",
"on",
"is",
... | 45.849057 | 26.584906 |
def explainParam(self, param):
"""
Explains a single param and returns its name, doc, and optional
default value and user-supplied value in a string.
"""
param = self._resolveParam(param)
values = []
if self.isDefined(param):
if param in self._defaultP... | [
"def",
"explainParam",
"(",
"self",
",",
"param",
")",
":",
"param",
"=",
"self",
".",
"_resolveParam",
"(",
"param",
")",
"values",
"=",
"[",
"]",
"if",
"self",
".",
"isDefined",
"(",
"param",
")",
":",
"if",
"param",
"in",
"self",
".",
"_defaultPar... | 41.4375 | 13.5625 |
def filter_value(old: float, new: float, factor: float) -> float:
""" Linearly interpolate between two float values. """
r_factor: float = 1 - factor
return old * r_factor + new * factor | [
"def",
"filter_value",
"(",
"old",
":",
"float",
",",
"new",
":",
"float",
",",
"factor",
":",
"float",
")",
"->",
"float",
":",
"r_factor",
":",
"float",
"=",
"1",
"-",
"factor",
"return",
"old",
"*",
"r_factor",
"+",
"new",
"*",
"factor"
] | 48.75 | 8.25 |
def makeWidget(self):
"""
Return a single widget that should be placed in the second tree column.
The widget must be given three attributes:
========== ============================================================
sigChanged a signal that is emitted when the widget's value is c... | [
"def",
"makeWidget",
"(",
"self",
")",
":",
"opts",
"=",
"self",
".",
"param",
".",
"opts",
"t",
"=",
"opts",
"[",
"'type'",
"]",
"if",
"t",
"==",
"'int'",
":",
"defs",
"=",
"{",
"'value'",
":",
"0",
",",
"'min'",
":",
"None",
",",
"'max'",
":"... | 38.773333 | 13.76 |
def _generate_report(ret, show_tasks):
'''
Generate a report of the Salt function
:param ret: The Salt return
:param show_tasks: Flag to show the name of the changed and failed states
:return: The report
'''
returns = ret.get('return')
sorted_data = sorted(
returns.items(),
... | [
"def",
"_generate_report",
"(",
"ret",
",",
"show_tasks",
")",
":",
"returns",
"=",
"ret",
".",
"get",
"(",
"'return'",
")",
"sorted_data",
"=",
"sorted",
"(",
"returns",
".",
"items",
"(",
")",
",",
"key",
"=",
"lambda",
"s",
":",
"s",
"[",
"1",
"... | 25.90411 | 20.232877 |
def _update_route(dcidr, router_ip, old_router_ip,
vpc_info, con, route_table_id, update_reason):
"""
Update an existing route entry in the route table.
"""
instance = eni = None
try:
instance, eni = find_instance_and_eni_by_ip(vpc_info, router_ip)
logging.info("-... | [
"def",
"_update_route",
"(",
"dcidr",
",",
"router_ip",
",",
"old_router_ip",
",",
"vpc_info",
",",
"con",
",",
"route_table_id",
",",
"update_reason",
")",
":",
"instance",
"=",
"eni",
"=",
"None",
"try",
":",
"instance",
",",
"eni",
"=",
"find_instance_and... | 42.714286 | 20.828571 |
def is_registration_possible(self, user_info):
""" Returns true if users can register for this course """
return self.get_accessibility().is_open() and self._registration.is_open() and self.is_user_accepted_by_access_control(user_info) | [
"def",
"is_registration_possible",
"(",
"self",
",",
"user_info",
")",
":",
"return",
"self",
".",
"get_accessibility",
"(",
")",
".",
"is_open",
"(",
")",
"and",
"self",
".",
"_registration",
".",
"is_open",
"(",
")",
"and",
"self",
".",
"is_user_accepted_b... | 83 | 34.333333 |
def resize_to_shape(data, shape, zoom=None, mode="nearest", order=0):
"""
Function resize input data to specific shape.
:param data: input 3d array-like data
:param shape: shape of output data
:param zoom: zoom is used for back compatibility
:mode: default is 'nearest'
"""
# @TODO remove... | [
"def",
"resize_to_shape",
"(",
"data",
",",
"shape",
",",
"zoom",
"=",
"None",
",",
"mode",
"=",
"\"nearest\"",
",",
"order",
"=",
"0",
")",
":",
"# @TODO remove old code in except part",
"# TODO use function from library in future",
"try",
":",
"# rint 'pred vyjimkou... | 33.305556 | 18.305556 |
def update_article(self, article_id, article_dict):
"""
Updates an article
:param article_id: the article id
:param article_dict: dict
:return: dict
"""
return self._create_put_request(resource=ARTICLES, billomat_id=article_id, send_data=article_dict) | [
"def",
"update_article",
"(",
"self",
",",
"article_id",
",",
"article_dict",
")",
":",
"return",
"self",
".",
"_create_put_request",
"(",
"resource",
"=",
"ARTICLES",
",",
"billomat_id",
"=",
"article_id",
",",
"send_data",
"=",
"article_dict",
")"
] | 33.333333 | 17.555556 |
def list_public_repos(profile='github'):
'''
List public repositories within the organization.
.. versionadded:: 2016.11.0
profile
The name of the profile configuration to use. Defaults to ``github``.
CLI Example:
.. code-block:: bash
salt myminion github.list_public_repos
... | [
"def",
"list_public_repos",
"(",
"profile",
"=",
"'github'",
")",
":",
"repos",
"=",
"[",
"]",
"for",
"repo",
"in",
"_get_repos",
"(",
"profile",
")",
":",
"if",
"repo",
".",
"private",
"is",
"False",
":",
"repos",
".",
"append",
"(",
"repo",
".",
"n... | 24.761905 | 23.809524 |
def _get_package_data(root, file_patterns=None):
"""Expand file patterns to a list of `package_data` paths.
Parameters
-----------
root: str
The relative path to the package root from `HERE`.
file_patterns: list or str, optional
A list of glob patterns for the data file locations.
... | [
"def",
"_get_package_data",
"(",
"root",
",",
"file_patterns",
"=",
"None",
")",
":",
"if",
"file_patterns",
"is",
"None",
":",
"file_patterns",
"=",
"[",
"'*'",
"]",
"return",
"_get_files",
"(",
"file_patterns",
",",
"pjoin",
"(",
"HERE",
",",
"root",
")"... | 34.368421 | 17.157895 |
def zero_weight_obs_names(self):
""" get the zero-weighted observation names
Returns
-------
zero_weight_obs_names : list
a list of zero-weighted observation names
"""
self.observation_data.index = self.observation_data.obsnme
groups = self.observa... | [
"def",
"zero_weight_obs_names",
"(",
"self",
")",
":",
"self",
".",
"observation_data",
".",
"index",
"=",
"self",
".",
"observation_data",
".",
"obsnme",
"groups",
"=",
"self",
".",
"observation_data",
".",
"groupby",
"(",
"self",
".",
"observation_data",
"."... | 33.5625 | 19.8125 |
def slider_position(self):
"""The current position of the slider on the tool,
normalized to the range [-1, 1] and whether it has changed in this
event.
The logical zero is the neutral position of the slider, or
the logical center of the axis. This axis is available on e.g.
the Wacom Airbrush.
If this ax... | [
"def",
"slider_position",
"(",
"self",
")",
":",
"position",
"=",
"self",
".",
"_libinput",
".",
"libinput_event_tablet_tool_get_slider_position",
"(",
"self",
".",
"_handle",
")",
"changed",
"=",
"self",
".",
"_libinput",
".",
"libinput_event_tablet_tool_slider_has_c... | 31.47619 | 23.333333 |
def sine_wave(params, frequency=400, amplitude=1, offset=0):
'''
Generate a sine wave
Convenience function, table_wave generates a sine wave by default
:param params: buffer parameters, controls length of signal created
:param frequency: wave frequency (array or value)
:param amplitude: wave amp... | [
"def",
"sine_wave",
"(",
"params",
",",
"frequency",
"=",
"400",
",",
"amplitude",
"=",
"1",
",",
"offset",
"=",
"0",
")",
":",
"return",
"table_wave",
"(",
"params",
",",
"frequency",
",",
"amplitude",
",",
"offset",
")"
] | 46 | 21.272727 |
def update(self):
""" Update will try to update the target directory
w.r.t source directory. Only files that are common
to both directories will be updated, no new files
or directories are created """
self._copyfiles = False
self._updatefiles = True
self._purge =... | [
"def",
"update",
"(",
"self",
")",
":",
"self",
".",
"_copyfiles",
"=",
"False",
"self",
".",
"_updatefiles",
"=",
"True",
"self",
".",
"_purge",
"=",
"False",
"self",
".",
"_creatdirs",
"=",
"False",
"if",
"self",
".",
"_verbose",
":",
"self",
".",
... | 35.333333 | 15.2 |
def map(self, callback):
"""
Run a map over each of the item.
:param callback: The map function
:type callback: callable
:rtype: Collection
"""
return self.__class__(list(map(callback, self.items))) | [
"def",
"map",
"(",
"self",
",",
"callback",
")",
":",
"return",
"self",
".",
"__class__",
"(",
"list",
"(",
"map",
"(",
"callback",
",",
"self",
".",
"items",
")",
")",
")"
] | 24.7 | 14.1 |
def _pot_month_counts(self, pot_dataset):
"""
Return a list of 12 sets. Each sets contains the years included in the POT record period.
:param pot_dataset: POT dataset (records and meta data)
:type pot_dataset: :class:`floodestimation.entities.PotDataset`
"""
periods = p... | [
"def",
"_pot_month_counts",
"(",
"self",
",",
"pot_dataset",
")",
":",
"periods",
"=",
"pot_dataset",
".",
"continuous_periods",
"(",
")",
"result",
"=",
"[",
"set",
"(",
")",
"for",
"x",
"in",
"range",
"(",
"12",
")",
"]",
"for",
"period",
"in",
"peri... | 39.791667 | 14.375 |
def parse_cluster(self, global_params, region, cluster):
"""
Parse a single ElastiCache cluster
:param global_params: Parameters shared for all regions
:param region: Name of the AWS region
:param cluster: ElastiCache cluster
""... | [
"def",
"parse_cluster",
"(",
"self",
",",
"global_params",
",",
"region",
",",
"cluster",
")",
":",
"cluster_name",
"=",
"cluster",
".",
"pop",
"(",
"'CacheClusterId'",
")",
"cluster",
"[",
"'name'",
"]",
"=",
"cluster_name",
"# Must fetch info about the subnet gr... | 50.190476 | 22.666667 |
def update(self, modifier, dest_dir=None, **kwargs):
"""
Update the contents of a wheel in a generic way. The modifier should
be a callable which expects a dictionary argument: its keys are
archive-entry paths, and its values are absolute filesystem paths
where the contents the c... | [
"def",
"update",
"(",
"self",
",",
"modifier",
",",
"dest_dir",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"get_version",
"(",
"path_map",
",",
"info_dir",
")",
":",
"version",
"=",
"path",
"=",
"None",
"key",
"=",
"'%s/%s'",
"%",
"(",
... | 48.02 | 17.62 |
def OpenAssociatorInstancePaths(self, InstanceName, AssocClass=None,
ResultClass=None, Role=None,
ResultRole=None,
FilterQueryLanguage=None, FilterQuery=None,
OperationTimeout=... | [
"def",
"OpenAssociatorInstancePaths",
"(",
"self",
",",
"InstanceName",
",",
"AssocClass",
"=",
"None",
",",
"ResultClass",
"=",
"None",
",",
"Role",
"=",
"None",
",",
"ResultRole",
"=",
"None",
",",
"FilterQueryLanguage",
"=",
"None",
",",
"FilterQuery",
"=",... | 44.329218 | 23.99177 |
def put(self, task):
"""
Inserts a Task into the queue
:param task: :class:`~redisqueue.AbstractTask` instance
:return: Boolean insert success state
:exception: ConnectionError if queue is not connected
"""
if not self.connected:
raise QueueNotConnec... | [
"def",
"put",
"(",
"self",
",",
"task",
")",
":",
"if",
"not",
"self",
".",
"connected",
":",
"raise",
"QueueNotConnectedError",
"(",
"\"Queue is not Connected\"",
")",
"if",
"task",
".",
"unique",
":",
"# first lets check if we have this hash already in our queue",
... | 34.375 | 21.291667 |
def _make_attachment(self, attachment, str_encoding=None):
"""Returns EmailMessage.attachments item formatted for sending with Mailjet
Returns mailjet_dict, is_inline_image
"""
is_inline_image = False
if isinstance(attachment, MIMEBase):
name = attachment.get_filenam... | [
"def",
"_make_attachment",
"(",
"self",
",",
"attachment",
",",
"str_encoding",
"=",
"None",
")",
":",
"is_inline_image",
"=",
"False",
"if",
"isinstance",
"(",
"attachment",
",",
"MIMEBase",
")",
":",
"name",
"=",
"attachment",
".",
"get_filename",
"(",
")"... | 38.883721 | 16.55814 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.