text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def call_async(self, func: Callable, *args, **kwargs):
"""
Call the given callable in the event loop thread.
This method lets you call asynchronous code from a worker thread.
Do not use it from within the event loop thread.
If the callable returns an awaitable, it is resolved b... | [
"def",
"call_async",
"(",
"self",
",",
"func",
":",
"Callable",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"asyncio_extras",
".",
"call_async",
"(",
"self",
".",
"loop",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")... | 41.8125 | 25.4375 |
def _ic_decode(self, msg):
"""IC: Send Valid Or Invalid User Code Format."""
code = msg[4:16]
if re.match(r'(0\d){6}', code):
code = re.sub(r'0(\d)', r'\1', code)
return {'code': code, 'user': int(msg[16:19])-1,
'keypad': int(msg[19:21])-1} | [
"def",
"_ic_decode",
"(",
"self",
",",
"msg",
")",
":",
"code",
"=",
"msg",
"[",
"4",
":",
"16",
"]",
"if",
"re",
".",
"match",
"(",
"r'(0\\d){6}'",
",",
"code",
")",
":",
"code",
"=",
"re",
".",
"sub",
"(",
"r'0(\\d)'",
",",
"r'\\1'",
",",
"co... | 42 | 8.428571 |
def fits(self, current_count, current_size, max_size, new_span):
"""Checks if the new span fits in the max payload size."""
return current_size + len(new_span) <= max_size | [
"def",
"fits",
"(",
"self",
",",
"current_count",
",",
"current_size",
",",
"max_size",
",",
"new_span",
")",
":",
"return",
"current_size",
"+",
"len",
"(",
"new_span",
")",
"<=",
"max_size"
] | 61.666667 | 13 |
def report(self, output_file=sys.stdout):
"""Report analysis outcome in human readable form."""
max_perf = self.results['max_perf']
if self._args and self._args.verbose >= 3:
print('{}'.format(pformat(self.results)), file=output_file)
if self._args and self._args.verbose >=... | [
"def",
"report",
"(",
"self",
",",
"output_file",
"=",
"sys",
".",
"stdout",
")",
":",
"max_perf",
"=",
"self",
".",
"results",
"[",
"'max_perf'",
"]",
"if",
"self",
".",
"_args",
"and",
"self",
".",
"_args",
".",
"verbose",
">=",
"3",
":",
"print",
... | 52.205128 | 23.923077 |
def compile(self, values):
""" Compiles the tagset and returns a str containing the result
"""
def is_international(tag):
return tag.endswith('_')
def get_country_code(tag):
return tag[-2:]
def strip_country_code(tag):
return tag[:-2]
... | [
"def",
"compile",
"(",
"self",
",",
"values",
")",
":",
"def",
"is_international",
"(",
"tag",
")",
":",
"return",
"tag",
".",
"endswith",
"(",
"'_'",
")",
"def",
"get_country_code",
"(",
"tag",
")",
":",
"return",
"tag",
"[",
"-",
"2",
":",
"]",
"... | 32.714286 | 18.142857 |
def ns(self, value):
"""The ns property.
Args:
value (string). the property value.
"""
if value == self._defaults['ns'] and 'ns' in self._values:
del self._values['ns']
else:
self._values['ns'] = value | [
"def",
"ns",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"==",
"self",
".",
"_defaults",
"[",
"'ns'",
"]",
"and",
"'ns'",
"in",
"self",
".",
"_values",
":",
"del",
"self",
".",
"_values",
"[",
"'ns'",
"]",
"else",
":",
"self",
".",
"_valu... | 27.7 | 14.7 |
def random_subset(self, relative_size, balance_labels=False, label_list_ids=None):
"""
Create a subview of random utterances with a approximate size relative to the full corpus.
By default x random utterances are selected with x equal to ``relative_size * corpus.num_utterances``.
Args:
... | [
"def",
"random_subset",
"(",
"self",
",",
"relative_size",
",",
"balance_labels",
"=",
"False",
",",
"label_list_ids",
"=",
"None",
")",
":",
"num_utterances_in_subset",
"=",
"round",
"(",
"relative_size",
"*",
"self",
".",
"corpus",
".",
"num_utterances",
")",
... | 57.973684 | 41.184211 |
def singleCalc(self,
m={'Al2O3': 13.01, 'Alpha': 0.6, 'Ba': 188.0, 'Be': 0.85, 'CaO': 8.35, 'Ce': 28.2, 'Co': 45.2,
'Cr': 117.0, 'Cs': 0.83, 'Cu': 53.5, 'Dy': 5.58, 'Er': 2.96, 'Eu': 1.79, 'Fe2O3': 14.47,
'FeO': 5.51, 'Ga': 19.4, 'Gd': 5.24, 'Hf': 3.38, 'Ho... | [
"def",
"singleCalc",
"(",
"self",
",",
"m",
"=",
"{",
"'Al2O3'",
":",
"13.01",
",",
"'Alpha'",
":",
"0.6",
",",
"'Ba'",
":",
"188.0",
",",
"'Be'",
":",
"0.85",
",",
"'CaO'",
":",
"8.35",
",",
"'Ce'",
":",
"28.2",
",",
"'Co'",
":",
"45.2",
",",
... | 37.005059 | 24.504216 |
def _convert_hdxobjects(self, hdxobjects):
# type: (List[HDXObjectUpperBound]) -> List[HDXObjectUpperBound]
"""Helper function to convert supplied list of HDX objects to a list of dict
Args:
hdxobjects (List[T <= HDXObject]): List of HDX objects to convert
Returns:
... | [
"def",
"_convert_hdxobjects",
"(",
"self",
",",
"hdxobjects",
")",
":",
"# type: (List[HDXObjectUpperBound]) -> List[HDXObjectUpperBound]",
"newhdxobjects",
"=",
"list",
"(",
")",
"for",
"hdxobject",
"in",
"hdxobjects",
":",
"newhdxobjects",
".",
"append",
"(",
"hdxobje... | 38.071429 | 19.428571 |
def from_dict(d):
"""
Re-create the Specs from a dictionary representation.
:param Dict[str, Any] d: The dictionary representation.
:return: The restored Specs.
:rtype: Specs
"""
return Specs(
qubits_specs=sorted([QubitSpecs(id=int(q),
... | [
"def",
"from_dict",
"(",
"d",
")",
":",
"return",
"Specs",
"(",
"qubits_specs",
"=",
"sorted",
"(",
"[",
"QubitSpecs",
"(",
"id",
"=",
"int",
"(",
"q",
")",
",",
"fRO",
"=",
"qspecs",
".",
"get",
"(",
"'fRO'",
")",
",",
"f1QRB",
"=",
"qspecs",
".... | 52.2 | 25.4 |
def insult(rest):
"Generate a random insult from datahamster"
# not supplying any style will automatically redirect to a random
url = 'http://autoinsult.datahamster.com/'
ins_type = random.randrange(4)
ins_url = url + "?style={ins_type}".format(**locals())
insre = re.compile('<div class="insult" id="insult">(.*?)... | [
"def",
"insult",
"(",
"rest",
")",
":",
"# not supplying any style will automatically redirect to a random",
"url",
"=",
"'http://autoinsult.datahamster.com/'",
"ins_type",
"=",
"random",
".",
"randrange",
"(",
"4",
")",
"ins_url",
"=",
"url",
"+",
"\"?style={ins_type}\""... | 33.541667 | 14.791667 |
def build_reduce_code(self, result, select, reduce):
"""
Builds a reduce operation on the selected target range.
"""
select = select.replace('/', '.')
select = select.replace(' ', '')
if reduce == 'add':
reduce_op = '+'
acc_start = 0
else:... | [
"def",
"build_reduce_code",
"(",
"self",
",",
"result",
",",
"select",
",",
"reduce",
")",
":",
"select",
"=",
"select",
".",
"replace",
"(",
"'/'",
",",
"'.'",
")",
"select",
"=",
"select",
".",
"replace",
"(",
"' '",
",",
"''",
")",
"if",
"reduce",... | 36.2 | 21.633333 |
def update(self, group_id, name=None, order=None, collapsed=None):
"""Update a Component Group
:param int group_id: Component Group ID
:param str name: Name of the component group
:param int order: Order of the group
:param int collapsed: Collapse the group?
:return: Upd... | [
"def",
"update",
"(",
"self",
",",
"group_id",
",",
"name",
"=",
"None",
",",
"order",
"=",
"None",
",",
"collapsed",
"=",
"None",
")",
":",
"data",
"=",
"ApiParams",
"(",
")",
"data",
"[",
"'group'",
"]",
"=",
"group_id",
"data",
"[",
"'name'",
"]... | 39.352941 | 16.529412 |
def _invoke_submit(self, iterobj, is_dict, is_itmcoll, mres, global_kw):
"""
Internal function to invoke the actual submit_single function
:param iterobj: The raw object returned as the next item of the iterator
:param is_dict: True if iterator is a dictionary
:param is_itmcoll: ... | [
"def",
"_invoke_submit",
"(",
"self",
",",
"iterobj",
",",
"is_dict",
",",
"is_itmcoll",
",",
"mres",
",",
"global_kw",
")",
":",
"if",
"is_itmcoll",
":",
"item",
",",
"key_options",
"=",
"next",
"(",
"iterobj",
")",
"key",
"=",
"item",
".",
"key",
"va... | 36.26087 | 18.565217 |
def to_string_short(self):
"""
see also :meth:`to_string`
:return: a shorter abreviated string reprentation of the parameter
"""
opt = np.get_printoptions()
np.set_printoptions(threshold=8, edgeitems=3, linewidth=opt['linewidth']-len(self.uniquetwig)-2)
str_ = su... | [
"def",
"to_string_short",
"(",
"self",
")",
":",
"opt",
"=",
"np",
".",
"get_printoptions",
"(",
")",
"np",
".",
"set_printoptions",
"(",
"threshold",
"=",
"8",
",",
"edgeitems",
"=",
"3",
",",
"linewidth",
"=",
"opt",
"[",
"'linewidth'",
"]",
"-",
"le... | 37.545455 | 19.545455 |
def njsd(network, ref_gene_expression_dict, query_gene_expression_dict, gene_set):
"""Calculate Jensen-Shannon divergence between query and reference gene expression profile.
"""
gene_jsd_dict = dict()
reference_genes = ref_gene_expression_dict.keys()
assert len(reference_genes) != 'Reference g... | [
"def",
"njsd",
"(",
"network",
",",
"ref_gene_expression_dict",
",",
"query_gene_expression_dict",
",",
"gene_set",
")",
":",
"gene_jsd_dict",
"=",
"dict",
"(",
")",
"reference_genes",
"=",
"ref_gene_expression_dict",
".",
"keys",
"(",
")",
"assert",
"len",
"(",
... | 45.111111 | 29.407407 |
def generate(str, alg):
"""Generates an PIL image avatar based on the given
input String. Acts as the main accessor to pagan."""
img = Image.new(IMAGE_MODE, IMAGE_SIZE, BACKGROUND_COLOR)
hashcode = hash_input(str, alg)
pixelmap = setup_pixelmap(hashcode)
draw_image(pixelmap, img)
return img | [
"def",
"generate",
"(",
"str",
",",
"alg",
")",
":",
"img",
"=",
"Image",
".",
"new",
"(",
"IMAGE_MODE",
",",
"IMAGE_SIZE",
",",
"BACKGROUND_COLOR",
")",
"hashcode",
"=",
"hash_input",
"(",
"str",
",",
"alg",
")",
"pixelmap",
"=",
"setup_pixelmap",
"(",
... | 39 | 10.125 |
def add_reverse_arcs(graph, capac=None):
"""Utility function for flow algorithms that need for every arc (u,v),
the existence of an (v,u) arc, by default with zero capacity.
graph can be in adjacency list, possibly with capacity matrix capac.
or graph can be in adjacency dictionary, then capac parameter... | [
"def",
"add_reverse_arcs",
"(",
"graph",
",",
"capac",
"=",
"None",
")",
":",
"for",
"u",
"in",
"range",
"(",
"len",
"(",
"graph",
")",
")",
":",
"for",
"v",
"in",
"graph",
"[",
"u",
"]",
":",
"if",
"u",
"not",
"in",
"graph",
"[",
"v",
"]",
"... | 42.285714 | 14.428571 |
def process_user_input(self):
"""
Gets the next single character and decides what to do with it
"""
user_input = self.get_input()
try:
num = int(user_input)
except Exception:
return
if 0 < num < len(self.items) + 1:
self.curren... | [
"def",
"process_user_input",
"(",
"self",
")",
":",
"user_input",
"=",
"self",
".",
"get_input",
"(",
")",
"try",
":",
"num",
"=",
"int",
"(",
"user_input",
")",
"except",
"Exception",
":",
"return",
"if",
"0",
"<",
"num",
"<",
"len",
"(",
"self",
".... | 25.133333 | 15.133333 |
def assert_has_permission(self, scope_required):
"""
Warn that the required scope is not found in the scopes
granted to the currently authenticated user.
::
# The admin user should have client admin permissions
uaa.assert_has_permission('admin', 'clients.admin')... | [
"def",
"assert_has_permission",
"(",
"self",
",",
"scope_required",
")",
":",
"if",
"not",
"self",
".",
"authenticated",
":",
"raise",
"ValueError",
"(",
"\"Must first authenticate()\"",
")",
"if",
"scope_required",
"not",
"in",
"self",
".",
"get_scopes",
"(",
"... | 35.818182 | 25.454545 |
def tags(cls, filename, namespace=None):
"""Extract tags from file."""
return cls._raster_opener(filename).tags(ns=namespace) | [
"def",
"tags",
"(",
"cls",
",",
"filename",
",",
"namespace",
"=",
"None",
")",
":",
"return",
"cls",
".",
"_raster_opener",
"(",
"filename",
")",
".",
"tags",
"(",
"ns",
"=",
"namespace",
")"
] | 46.333333 | 7.333333 |
def zremrangebyscore(self, name, min, max):
"""
Remove a range of element by between score ``min_value`` and
``max_value`` both included.
:param name: str the name of the redis key
:param min:
:param max:
:return: Future()
"""
with self.pipe a... | [
"def",
"zremrangebyscore",
"(",
"self",
",",
"name",
",",
"min",
",",
"max",
")",
":",
"with",
"self",
".",
"pipe",
"as",
"pipe",
":",
"return",
"pipe",
".",
"zremrangebyscore",
"(",
"self",
".",
"redis_key",
"(",
"name",
")",
",",
"min",
",",
"max",... | 32.416667 | 15.583333 |
def playToneList(self, playList = None):
"""!
\~english
Play tone from a tone list
@param playList a array of tones
\~chinese
播放音调列表
@param playList: 音调数组
\~english @note <b>playList</b> format:\n
\~chinese @note <b>playList</b> 格... | [
"def",
"playToneList",
"(",
"self",
",",
"playList",
"=",
"None",
")",
":",
"if",
"playList",
"==",
"None",
":",
"return",
"False",
"for",
"t",
"in",
"playList",
":",
"self",
".",
"playTone",
"(",
"t",
"[",
"\"freq\"",
"]",
",",
"t",
"[",
"\"reps\"",... | 32.666667 | 21.181818 |
def wait(*coros_or_futures, limit=0, timeout=None, loop=None,
return_exceptions=False, return_when='ALL_COMPLETED'):
"""
Wait for the Futures and coroutine objects given by the sequence
futures to complete, with optional concurrency limit.
Coroutines will be wrapped in Tasks.
``timeout`` c... | [
"def",
"wait",
"(",
"*",
"coros_or_futures",
",",
"limit",
"=",
"0",
",",
"timeout",
"=",
"None",
",",
"loop",
"=",
"None",
",",
"return_exceptions",
"=",
"False",
",",
"return_when",
"=",
"'ALL_COMPLETED'",
")",
":",
"# Support iterable as first argument for be... | 37.753247 | 21.961039 |
def verify_is(self, first, second, msg=None):
"""
Soft assert for whether the parameters evaluate to the same object
:params want: the object to compare against
:params second: the object to compare with
:params msg: (Optional) msg explaining the difference
"""
t... | [
"def",
"verify_is",
"(",
"self",
",",
"first",
",",
"second",
",",
"msg",
"=",
"None",
")",
":",
"try",
":",
"self",
".",
"assert_is",
"(",
"first",
",",
"second",
",",
"msg",
")",
"except",
"AssertionError",
",",
"e",
":",
"if",
"msg",
":",
"m",
... | 34.1875 | 14.4375 |
def sources(self):
"""
Get the sources for a given experience_id, which is tied to a specific language
:param experience_id: int; video content id
:return: sources dict
"""
api_url = self.sources_api_url.format(experience_id=self.experience_id)
res = self.get(api_... | [
"def",
"sources",
"(",
"self",
")",
":",
"api_url",
"=",
"self",
".",
"sources_api_url",
".",
"format",
"(",
"experience_id",
"=",
"self",
".",
"experience_id",
")",
"res",
"=",
"self",
".",
"get",
"(",
"api_url",
",",
"params",
"=",
"{",
"\"pinst_id\"",... | 43.888889 | 17.666667 |
def intelligently_find_filenames(line, TeX=False, ext=False,
commas_okay=False):
"""Intelligently find filenames.
Find the filename in the line. We don't support all filenames! Just eps
and ps for now.
:param: line (string): the line we want to get a filename out of
... | [
"def",
"intelligently_find_filenames",
"(",
"line",
",",
"TeX",
"=",
"False",
",",
"ext",
"=",
"False",
",",
"commas_okay",
"=",
"False",
")",
":",
"files_included",
"=",
"[",
"'ERROR'",
"]",
"if",
"commas_okay",
":",
"valid_for_filename",
"=",
"'\\\\s*[A-Za-z... | 36.15625 | 20.083333 |
def nlmsg_type(self, value):
"""Message content setter."""
self.bytearray[self._get_slicers(1)] = bytearray(c_uint16(value or 0)) | [
"def",
"nlmsg_type",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"bytearray",
"[",
"self",
".",
"_get_slicers",
"(",
"1",
")",
"]",
"=",
"bytearray",
"(",
"c_uint16",
"(",
"value",
"or",
"0",
")",
")"
] | 47.666667 | 16.666667 |
def _dynamic_operation(self, map_obj):
"""
Generate function to dynamically apply the operation.
Wraps an existing HoloMap or DynamicMap.
"""
if not isinstance(map_obj, DynamicMap):
def dynamic_operation(*key, **kwargs):
kwargs = dict(self._eval_kwargs... | [
"def",
"_dynamic_operation",
"(",
"self",
",",
"map_obj",
")",
":",
"if",
"not",
"isinstance",
"(",
"map_obj",
",",
"DynamicMap",
")",
":",
"def",
"dynamic_operation",
"(",
"*",
"key",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"=",
"dict",
"(",
"sel... | 49.380952 | 17.47619 |
def get_batch_by_transaction(self, transaction_id):
"""
Check to see if the requested transaction_id is in the current chain.
If so, find the batch that has the transaction referenced by the
transaction_id and return the batch. This is done by finding the block
and searching for ... | [
"def",
"get_batch_by_transaction",
"(",
"self",
",",
"transaction_id",
")",
":",
"payload",
"=",
"self",
".",
"_get_data_by_id",
"(",
"transaction_id",
",",
"'commit_store_get_batch_by_transaction'",
")",
"batch",
"=",
"Batch",
"(",
")",
"batch",
".",
"ParseFromStri... | 36 | 20.736842 |
def mouse_move_event(self, event):
"""
Forward mouse cursor position events to the example
"""
self.example.mouse_position_event(event.x(), event.y()) | [
"def",
"mouse_move_event",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"example",
".",
"mouse_position_event",
"(",
"event",
".",
"x",
"(",
")",
",",
"event",
".",
"y",
"(",
")",
")"
] | 36.4 | 9.6 |
def fork(self):
"""Fork this gist.
:returns: :class:`Gist <Gist>` if successful, ``None`` otherwise
"""
url = self._build_url('forks', base_url=self._api)
json = self._json(self._post(url), 201)
return Gist(json, self) if json else None | [
"def",
"fork",
"(",
"self",
")",
":",
"url",
"=",
"self",
".",
"_build_url",
"(",
"'forks'",
",",
"base_url",
"=",
"self",
".",
"_api",
")",
"json",
"=",
"self",
".",
"_json",
"(",
"self",
".",
"_post",
"(",
"url",
")",
",",
"201",
")",
"return",... | 30.888889 | 19 |
def parse(self,type_regex=None):
"""
Each line of the frame cache file is like the following:
/frames/E13/LHO/frames/hoftMon_H1/H-H1_DMT_C00_L2-9246,H,H1_DMT_C00_L2,1,16 1240664820 6231 {924600000 924646720 924646784 924647472 924647712 924700000}
The description is as follows:
1.1) Directory pat... | [
"def",
"parse",
"(",
"self",
",",
"type_regex",
"=",
"None",
")",
":",
"path",
"=",
"self",
".",
"__path",
"cache",
"=",
"self",
".",
"cache",
"if",
"type_regex",
":",
"type_filter",
"=",
"re",
".",
"compile",
"(",
"type_regex",
")",
"else",
":",
"ty... | 32.589744 | 23.717949 |
def add_dependency(self, p_from_todo, p_to_todo):
""" Adds a dependency from task 1 to task 2. """
def find_next_id():
"""
Find a new unused ID.
Unused means that no task has it as an 'id' value or as a 'p'
value.
"""
def id_exists(... | [
"def",
"add_dependency",
"(",
"self",
",",
"p_from_todo",
",",
"p_to_todo",
")",
":",
"def",
"find_next_id",
"(",
")",
":",
"\"\"\"\n Find a new unused ID.\n Unused means that no task has it as an 'id' value or as a 'p'\n value.\n \"\"\"",
... | 35.448276 | 15.862069 |
def process_data(self, data, cloud_cover='total_clouds', **kwargs):
"""
Defines the steps needed to convert raw forecast data
into processed forecast data.
Parameters
----------
data: DataFrame
Raw forecast data
cloud_cover: str, default 'total_clouds... | [
"def",
"process_data",
"(",
"self",
",",
"data",
",",
"cloud_cover",
"=",
"'total_clouds'",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"super",
"(",
"GFS",
",",
"self",
")",
".",
"process_data",
"(",
"data",
",",
"*",
"*",
"kwargs",
")",
"data",... | 35.565217 | 17.73913 |
def check_base_suggested_attributes(self, dataset):
'''
Check the global suggested attributes for 2.0 templates. These go an extra step besides
just checking that they exist.
:param netCDF4.Dataset dataset: An open netCDF dataset
:creator_type = "" ; //............................ | [
"def",
"check_base_suggested_attributes",
"(",
"self",
",",
"dataset",
")",
":",
"suggested_ctx",
"=",
"TestCtx",
"(",
"BaseCheck",
".",
"LOW",
",",
"'Suggested global attributes'",
")",
"# Do any of the variables define platform ?",
"platform_name",
"=",
"getattr",
"(",
... | 109.030769 | 82.938462 |
def send_video_note(self, chat_id, data, duration=None, length=None, reply_to_message_id=None, reply_markup=None,
disable_notification=None, timeout=None):
"""
Use this method to send video files, Telegram clients support mp4 videos.
:param chat_id: Integer : Unique ident... | [
"def",
"send_video_note",
"(",
"self",
",",
"chat_id",
",",
"data",
",",
"duration",
"=",
"None",
",",
"length",
"=",
"None",
",",
"reply_to_message_id",
"=",
"None",
",",
"reply_markup",
"=",
"None",
",",
"disable_notification",
"=",
"None",
",",
"timeout",... | 67.666667 | 37.4 |
def read_feather(cls, path, columns=None, use_threads=True):
"""Read a pandas.DataFrame from Feather format.
Ray DataFrame only supports pyarrow engine for now.
Args:
path: The filepath of the feather file.
We only support local files for now.
mu... | [
"def",
"read_feather",
"(",
"cls",
",",
"path",
",",
"columns",
"=",
"None",
",",
"use_threads",
"=",
"True",
")",
":",
"if",
"cls",
".",
"read_feather_remote_task",
"is",
"None",
":",
"return",
"super",
"(",
"RayIO",
",",
"cls",
")",
".",
"read_feather"... | 38.694915 | 20.423729 |
def add_perfdata(self, *args, **kwargs):
"""
add a perfdata to the internal perfdata list
arguments:
the same arguments as for Perfdata()
"""
self._perfdata.append(Perfdata(*args, **kwargs)) | [
"def",
"add_perfdata",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_perfdata",
".",
"append",
"(",
"Perfdata",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | 29.5 | 12.25 |
def get_gene2binvec(self):
"""Return a boolean vector for each gene representing GO section membership."""
_sec2chr = self.sec2chr
return {g:[s in s2gos for s in _sec2chr] for g, s2gos in self.gene2section2gos.items()} | [
"def",
"get_gene2binvec",
"(",
"self",
")",
":",
"_sec2chr",
"=",
"self",
".",
"sec2chr",
"return",
"{",
"g",
":",
"[",
"s",
"in",
"s2gos",
"for",
"s",
"in",
"_sec2chr",
"]",
"for",
"g",
",",
"s2gos",
"in",
"self",
".",
"gene2section2gos",
".",
"item... | 59.75 | 19.5 |
def get_bits( self, count ):
"""Get an integer containing the next [count] bits from the source."""
result = 0
for i in range( count ):
if self.bits_remaining <= 0:
self._fill_buffer()
if self.bits_reverse:
bit = (1 if (self.current_bits & ... | [
"def",
"get_bits",
"(",
"self",
",",
"count",
")",
":",
"result",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"count",
")",
":",
"if",
"self",
".",
"bits_remaining",
"<=",
"0",
":",
"self",
".",
"_fill_buffer",
"(",
")",
"if",
"self",
".",
"bits_reve... | 33.545455 | 13.545455 |
def _filenames_to_modulenames(filenames: Iterable[str], modulename_prefix: str, filename_prefix: str = '') -> Iterable[str]:
'''Convert given filenames to module names.
Any filename that does not have a corresponding module name will be dropped
from the result (i.e. __init__.py).
Parameters
------... | [
"def",
"_filenames_to_modulenames",
"(",
"filenames",
":",
"Iterable",
"[",
"str",
"]",
",",
"modulename_prefix",
":",
"str",
",",
"filename_prefix",
":",
"str",
"=",
"''",
")",
"->",
"Iterable",
"[",
"str",
"]",
":",
"modulenames",
"=",
"[",
"]",
"# type:... | 28.54902 | 26.27451 |
def isCollapsed( self ):
"""
Returns whether or not this group box is collapsed.
:return <bool>
"""
if not self.isCollapsible():
return False
if self._inverted:
return self.isChecked()
return not self.isChec... | [
"def",
"isCollapsed",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"isCollapsible",
"(",
")",
":",
"return",
"False",
"if",
"self",
".",
"_inverted",
":",
"return",
"self",
".",
"isChecked",
"(",
")",
"return",
"not",
"self",
".",
"isChecked",
"(",... | 26.166667 | 12.5 |
def size(col):
"""
Collection function: returns the length of the array or map stored in the column.
:param col: name of column or expression
>>> df = spark.createDataFrame([([1, 2, 3],),([1],),([],)], ['data'])
>>> df.select(size(df.data)).collect()
[Row(size(data)=3), Row(size(data)=1), Row(... | [
"def",
"size",
"(",
"col",
")",
":",
"sc",
"=",
"SparkContext",
".",
"_active_spark_context",
"return",
"Column",
"(",
"sc",
".",
"_jvm",
".",
"functions",
".",
"size",
"(",
"_to_java_column",
"(",
"col",
")",
")",
")"
] | 36.583333 | 19.75 |
def absolute(value):
"""Return the absolute value."""
try:
return abs(valid_numeric(value))
except (ValueError, TypeError):
try:
return abs(value)
except Exception:
return '' | [
"def",
"absolute",
"(",
"value",
")",
":",
"try",
":",
"return",
"abs",
"(",
"valid_numeric",
"(",
"value",
")",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"try",
":",
"return",
"abs",
"(",
"value",
")",
"except",
"Exception",
":",
... | 25.111111 | 14.444444 |
def parse_from_string(
root_processor, # type: RootProcessor
xml_string # type: Text
):
# type: (...) -> Any
"""
Parse the XML string using the processor starting from the root of the document.
:param xml_string: XML string to parse.
See also :func:`declxml.parse_from_file`
"... | [
"def",
"parse_from_string",
"(",
"root_processor",
",",
"# type: RootProcessor",
"xml_string",
"# type: Text",
")",
":",
"# type: (...) -> Any",
"if",
"not",
"_is_valid_root_processor",
"(",
"root_processor",
")",
":",
"raise",
"InvalidRootProcessor",
"(",
"'Invalid root pr... | 31.96 | 18.68 |
def guess_type(self, path, allow_directory=True):
"""
Guess the type of a file.
If allow_directory is False, don't consider the possibility that the
file is a directory.
"""
if path.endswith('.ipynb'):
return 'notebook'
elif allow_directory and self.d... | [
"def",
"guess_type",
"(",
"self",
",",
"path",
",",
"allow_directory",
"=",
"True",
")",
":",
"if",
"path",
".",
"endswith",
"(",
"'.ipynb'",
")",
":",
"return",
"'notebook'",
"elif",
"allow_directory",
"and",
"self",
".",
"dir_exists",
"(",
"path",
")",
... | 30.384615 | 14.384615 |
def is_parent_of_log(self, id_, log_id):
"""Tests if an ``Id`` is a direct parent of a log.
arg: id (osid.id.Id): an ``Id``
arg: log_id (osid.id.Id): the ``Id`` of a log
return: (boolean) - ``true`` if this ``id`` is a parent of
``log_id,`` ``false`` otherwise
... | [
"def",
"is_parent_of_log",
"(",
"self",
",",
"id_",
",",
"log_id",
")",
":",
"# Implemented from template for",
"# osid.resource.BinHierarchySession.is_parent_of_bin",
"if",
"self",
".",
"_catalog_session",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_catalog_sess... | 49.7 | 18.35 |
def _getLayer(self, name, **kwargs):
"""
This is the environment implementation of
:meth:`BaseFont.getLayer`. **name** will
be a :ref:`type-string`. It will have been
normalized with :func:`normalizers.normalizeLayerName`
and it will have been verified as an existing laye... | [
"def",
"_getLayer",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"layer",
"in",
"self",
".",
"layers",
":",
"if",
"layer",
".",
"name",
"==",
"name",
":",
"return",
"layer"
] | 37.5 | 11.5 |
def enkf(self):
"""
Loop over time windows and apply da
:return:
"""
for cycle_index, time_point in enumerate(self.timeline):
if cycle_index >= len(self.timeline) - 1:
# Logging : Last Update cycle has finished
break
print... | [
"def",
"enkf",
"(",
"self",
")",
":",
"for",
"cycle_index",
",",
"time_point",
"in",
"enumerate",
"(",
"self",
".",
"timeline",
")",
":",
"if",
"cycle_index",
">=",
"len",
"(",
"self",
".",
"timeline",
")",
"-",
"1",
":",
"# Logging : Last Update cycle has... | 39.206897 | 24.034483 |
def split_all_edges_between_two_vertices(self, vertex1, vertex2, guidance=None, sorted_guidance=False,
account_for_colors_multiplicity_in_guidance=True):
""" Splits all edges between two supplied vertices in current :class:`BreakpointGraph` instance with respect to t... | [
"def",
"split_all_edges_between_two_vertices",
"(",
"self",
",",
"vertex1",
",",
"vertex2",
",",
"guidance",
"=",
"None",
",",
"sorted_guidance",
"=",
"False",
",",
"account_for_colors_multiplicity_in_guidance",
"=",
"True",
")",
":",
"self",
".",
"__split_all_edges_b... | 81.235294 | 46.352941 |
def debugTreePrint(node,pfx="->"):
"""Purely a debugging aid: Ascii-art picture of a tree descended from node"""
print pfx,node.item
for c in node.children:
debugTreePrint(c," "+pfx) | [
"def",
"debugTreePrint",
"(",
"node",
",",
"pfx",
"=",
"\"->\"",
")",
":",
"print",
"pfx",
",",
"node",
".",
"item",
"for",
"c",
"in",
"node",
".",
"children",
":",
"debugTreePrint",
"(",
"c",
",",
"\" \"",
"+",
"pfx",
")"
] | 37.8 | 10 |
def disconnect_entry_signals():
"""
Disconnect all the signals on Entry model.
"""
post_save.disconnect(
sender=Entry,
dispatch_uid=ENTRY_PS_PING_DIRECTORIES)
post_save.disconnect(
sender=Entry,
dispatch_uid=ENTRY_PS_PING_EXTERNAL_URLS)
post_save.disconnect(
... | [
"def",
"disconnect_entry_signals",
"(",
")",
":",
"post_save",
".",
"disconnect",
"(",
"sender",
"=",
"Entry",
",",
"dispatch_uid",
"=",
"ENTRY_PS_PING_DIRECTORIES",
")",
"post_save",
".",
"disconnect",
"(",
"sender",
"=",
"Entry",
",",
"dispatch_uid",
"=",
"ENT... | 29.5625 | 11.5625 |
def modifier_id(self, modifier_id):
"""
Sets the modifier_id of this CatalogModifierOverride.
The ID of the [CatalogModifier](#type-catalogmodifier) whose default behavior is being overridden.
:param modifier_id: The modifier_id of this CatalogModifierOverride.
:type: str
... | [
"def",
"modifier_id",
"(",
"self",
",",
"modifier_id",
")",
":",
"if",
"modifier_id",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Invalid value for `modifier_id`, must not be `None`\"",
")",
"if",
"len",
"(",
"modifier_id",
")",
"<",
"1",
":",
"raise",
"Va... | 40.733333 | 26.6 |
def _replies(self, *args, **kwargs):
"""Overridable method."""
reply_msg = make_reply(*args, **kwargs)
if self._server:
self._server._log('\t%d\t<-- %r' % (self.client_port, reply_msg))
reply_bytes = reply_msg.reply_bytes(self)
self._client.sendall(reply_bytes) | [
"def",
"_replies",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"reply_msg",
"=",
"make_reply",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"self",
".",
"_server",
":",
"self",
".",
"_server",
".",
"_log",
"(",
"'\\... | 43.857143 | 10.571429 |
def INDEX_OF_CP(string_expression, substring_expression, start=None, end=None):
"""
Searches a string for an occurence of a substring and returns the UTF-8 code point index (zero-based) of the first occurence.
If the substring is not found, returns -1.
https://docs.mongodb.com/manual/reference/operator/... | [
"def",
"INDEX_OF_CP",
"(",
"string_expression",
",",
"substring_expression",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
")",
":",
"res",
"=",
"[",
"string_expression",
",",
"substring_expression",
"]",
"if",
"start",
"is",
"not",
"None",
":",
"res",... | 54.5 | 29.388889 |
def remove_child_book(self, book_id, child_id):
"""Removes a child from a book.
arg: book_id (osid.id.Id): the ``Id`` of a book
arg: child_id (osid.id.Id): the ``Id`` of the new child
raise: NotFound - ``book_id`` not a parent of ``child_id``
raise: NullArgument - ``book... | [
"def",
"remove_child_book",
"(",
"self",
",",
"book_id",
",",
"child_id",
")",
":",
"# Implemented from template for",
"# osid.resource.BinHierarchyDesignSession.remove_child_bin_template",
"if",
"self",
".",
"_catalog_session",
"is",
"not",
"None",
":",
"return",
"self",
... | 51.941176 | 23.235294 |
def reindex_like_indexers(target, other):
"""Extract indexers to align target with other.
Not public API.
Parameters
----------
target : Dataset or DataArray
Object to be aligned.
other : Dataset or DataArray
Object to be aligned with.
Returns
-------
Dict[Any, pan... | [
"def",
"reindex_like_indexers",
"(",
"target",
",",
"other",
")",
":",
"indexers",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"other",
".",
"indexes",
".",
"items",
"(",
")",
"if",
"k",
"in",
"target",
".",
"dims",
"}",
"for",
"dim",
"i... | 30.1875 | 21.125 |
def snmp_server_engineID_drop_engineID_local(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
snmp_server = ET.SubElement(config, "snmp-server", xmlns="urn:brocade.com:mgmt:brocade-snmp")
engineID_drop = ET.SubElement(snmp_server, "engineID-drop")
... | [
"def",
"snmp_server_engineID_drop_engineID_local",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"snmp_server",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"snmp-server\"",
",",
"xmlns",
... | 45.166667 | 17.083333 |
def delete_editor(userid):
"""
:param userid: a string representing the user's UW NetID
:return: True if request is successful, False otherwise.
raise DataFailureException or a corresponding TrumbaException
if the request failed or an error code has been returned.
"""
url = _make_del_account... | [
"def",
"delete_editor",
"(",
"userid",
")",
":",
"url",
"=",
"_make_del_account_url",
"(",
"userid",
")",
"return",
"_process_resp",
"(",
"url",
",",
"get_sea_resource",
"(",
"url",
")",
",",
"_is_editor_deleted",
")"
] | 39.166667 | 11.333333 |
def machine_usage(self, hall_no):
"""Returns the average usage of laundry machines every hour
for a given hall.
The usages are returned in a dictionary, with the key being
the day of the week, and the value being an array listing the usages
per hour.
:param hall_no:
... | [
"def",
"machine_usage",
"(",
"self",
",",
"hall_no",
")",
":",
"try",
":",
"num",
"=",
"int",
"(",
"hall_no",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"\"Room Number must be integer\"",
")",
"r",
"=",
"requests",
".",
"get",
"(",
"USAG... | 35.870968 | 18.516129 |
def _get_files(self):
"""
Walk the project directory for tests and returns a list.
:return: list
"""
excludes = [
'.git',
'.tox',
'.vagrant',
'.venv',
os.path.basename(self._config.verifier.directory),
]
... | [
"def",
"_get_files",
"(",
"self",
")",
":",
"excludes",
"=",
"[",
"'.git'",
",",
"'.tox'",
",",
"'.vagrant'",
",",
"'.venv'",
",",
"os",
".",
"path",
".",
"basename",
"(",
"self",
".",
"_config",
".",
"verifier",
".",
"directory",
")",
",",
"]",
"gen... | 28.052632 | 22.368421 |
def rm(i):
"""
Input: {
(repo_uoa) - repo UOA (where to delete entry about repository)
uoa - data UOA
(force) - if 'yes', force removal
(with_files) or (all) - if 'yes', remove files as well
}
Ou... | [
"def",
"rm",
"(",
"i",
")",
":",
"# Check if global writing is allowed",
"r",
"=",
"ck",
".",
"check_writing",
"(",
"{",
"}",
")",
"if",
"r",
"[",
"'return'",
"]",
">",
"0",
":",
"return",
"r",
"global",
"cache_repo_uoa",
",",
"cache_repo_info",
"ruoa",
... | 30.585106 | 21.138298 |
def find_kernel_specs(self):
"""Returns a dict mapping kernel names to resource directories."""
# let real installed kernels overwrite envs with the same name:
# this is the same order as the get_kernel_spec way, which also prefers
# kernels from the jupyter dir over env kernels.
... | [
"def",
"find_kernel_specs",
"(",
"self",
")",
":",
"# let real installed kernels overwrite envs with the same name:",
"# this is the same order as the get_kernel_spec way, which also prefers",
"# kernels from the jupyter dir over env kernels.",
"specs",
"=",
"self",
".",
"find_kernel_specs... | 54 | 17.333333 |
def are_imaging_dicoms(dicom_input):
"""
This function will check the dicom headers to see which type of series it is
Possibilities are fMRI, DTI, Anatomical (if no clear type is found anatomical is used)
:param dicom_input: directory with dicom files or a list of dicom objects
"""
# if it is ... | [
"def",
"are_imaging_dicoms",
"(",
"dicom_input",
")",
":",
"# if it is philips and multiframe dicom then we assume it is ok",
"if",
"common",
".",
"is_philips",
"(",
"dicom_input",
")",
":",
"if",
"common",
".",
"is_multiframe_dicom",
"(",
"dicom_input",
")",
":",
"retu... | 38.5625 | 22.1875 |
def make_digest_file(data_file, digest_file):
'''Create a file containing the hex digest string of a data file.'''
hexdigest = get_file_hexdigest(data_file)
fd = open(digest_file, 'w')
fd.write(hexdigest)
fd.close() | [
"def",
"make_digest_file",
"(",
"data_file",
",",
"digest_file",
")",
":",
"hexdigest",
"=",
"get_file_hexdigest",
"(",
"data_file",
")",
"fd",
"=",
"open",
"(",
"digest_file",
",",
"'w'",
")",
"fd",
".",
"write",
"(",
"hexdigest",
")",
"fd",
".",
"close",... | 32.857143 | 19.142857 |
def people_per_project(self, project_id, company_id):
"""
This will return all of the people in the given company that can
access the given project.
"""
path = '/projects/%u/contacts/people/%u' % (project_id, company_id)
return self._request(path) | [
"def",
"people_per_project",
"(",
"self",
",",
"project_id",
",",
"company_id",
")",
":",
"path",
"=",
"'/projects/%u/contacts/people/%u'",
"%",
"(",
"project_id",
",",
"company_id",
")",
"return",
"self",
".",
"_request",
"(",
"path",
")"
] | 41.285714 | 13.285714 |
def get_project_config_path(path=None):
"""Return project configuration folder if exist."""
project_path = Path(path or '.').absolute().joinpath(RENKU_HOME)
if project_path.exists() and project_path.is_dir():
return str(project_path) | [
"def",
"get_project_config_path",
"(",
"path",
"=",
"None",
")",
":",
"project_path",
"=",
"Path",
"(",
"path",
"or",
"'.'",
")",
".",
"absolute",
"(",
")",
".",
"joinpath",
"(",
"RENKU_HOME",
")",
"if",
"project_path",
".",
"exists",
"(",
")",
"and",
... | 49.8 | 10.4 |
def build_loss(model_logits, sparse_targets):
"""Compute the log loss given predictions and targets."""
time_major_shape = [FLAGS.unroll_steps, FLAGS.batch_size]
flat_batch_shape = [FLAGS.unroll_steps * FLAGS.batch_size, -1]
xent = tf.nn.sparse_softmax_cross_entropy_with_logits(
logits=tf.reshape(model_lo... | [
"def",
"build_loss",
"(",
"model_logits",
",",
"sparse_targets",
")",
":",
"time_major_shape",
"=",
"[",
"FLAGS",
".",
"unroll_steps",
",",
"FLAGS",
".",
"batch_size",
"]",
"flat_batch_shape",
"=",
"[",
"FLAGS",
".",
"unroll_steps",
"*",
"FLAGS",
".",
"batch_s... | 50.416667 | 13.333333 |
def smoothMLS3D(actors, neighbours=10):
"""
A time sequence of actors is being smoothed in 4D
using a `MLS (Moving Least Squares)` variant.
The time associated to an actor must be specified in advance with ``actor.time()`` method.
Data itself can suggest a meaningful time separation based on the spa... | [
"def",
"smoothMLS3D",
"(",
"actors",
",",
"neighbours",
"=",
"10",
")",
":",
"from",
"scipy",
".",
"spatial",
"import",
"KDTree",
"coords4d",
"=",
"[",
"]",
"for",
"a",
"in",
"actors",
":",
"# build the list of 4d coordinates",
"coords3d",
"=",
"a",
".",
"... | 36.901639 | 20.180328 |
def editFolder(self, description, webEncrypted=False):
"""
This operation allows you to change the description of an existing
folder or change the web encrypted property.
The web encrypted property indicates if all the services contained
in the folder are only accessible over a s... | [
"def",
"editFolder",
"(",
"self",
",",
"description",
",",
"webEncrypted",
"=",
"False",
")",
":",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/editFolder\"",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
",",
"\"webEncrypted\"",
":",
"webEncrypted",
",",
"\"... | 43.6 | 17.36 |
def acquire_authorization_header(self):
"""Acquire tokens from AAD."""
try:
return self._acquire_authorization_header()
except AdalError as error:
if self._authentication_method is AuthenticationMethod.aad_username_password:
kwargs = {"username": self._use... | [
"def",
"acquire_authorization_header",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_acquire_authorization_header",
"(",
")",
"except",
"AdalError",
"as",
"error",
":",
"if",
"self",
".",
"_authentication_method",
"is",
"AuthenticationMethod",
".",
"... | 53.75 | 28.95 |
def get_file_version_info(cls, filename):
"""
Get the program version from an executable file, if available.
@type filename: str
@param filename: Pathname to the executable file to query.
@rtype: tuple(str, str, bool, bool, str, str)
@return: Tuple with version informa... | [
"def",
"get_file_version_info",
"(",
"cls",
",",
"filename",
")",
":",
"# Get the file version info structure.",
"pBlock",
"=",
"win32",
".",
"GetFileVersionInfo",
"(",
"filename",
")",
"pBuffer",
",",
"dwLen",
"=",
"win32",
".",
"VerQueryValue",
"(",
"pBlock",
",... | 39.07767 | 16.84466 |
def fit_theta(self):
"""use least squares to fit all default curves parameter seperately
Returns
-------
None
"""
x = range(1, self.point_num + 1)
y = self.trial_history
for i in range(NUM_OF_FUNCTIONS):
model = curve_combination_model... | [
"def",
"fit_theta",
"(",
"self",
")",
":",
"x",
"=",
"range",
"(",
"1",
",",
"self",
".",
"point_num",
"+",
"1",
")",
"y",
"=",
"self",
".",
"trial_history",
"for",
"i",
"in",
"range",
"(",
"NUM_OF_FUNCTIONS",
")",
":",
"model",
"=",
"curve_combinati... | 45.393939 | 16.363636 |
def run_netsh_command(netsh_args):
"""Execute a netsh command and return the output."""
devnull = open(os.devnull, 'w')
command_raw = 'netsh interface ipv4 ' + netsh_args
return int(subprocess.call(command_raw, stdout=devnull)) | [
"def",
"run_netsh_command",
"(",
"netsh_args",
")",
":",
"devnull",
"=",
"open",
"(",
"os",
".",
"devnull",
",",
"'w'",
")",
"command_raw",
"=",
"'netsh interface ipv4 '",
"+",
"netsh_args",
"return",
"int",
"(",
"subprocess",
".",
"call",
"(",
"command_raw",
... | 47.8 | 9 |
def make_carrier_tone(freq, db, dur, samplerate, caldb=100, calv=0.1):
"""
Produce a pure tone signal
:param freq: Frequency of the tone to be produced (Hz)
:type freq: int
:param db: Intensity of the tone in dB SPL
:type db: int
:param dur: duration (seconds)
:type dur: float
:para... | [
"def",
"make_carrier_tone",
"(",
"freq",
",",
"db",
",",
"dur",
",",
"samplerate",
",",
"caldb",
"=",
"100",
",",
"calv",
"=",
"0.1",
")",
":",
"if",
"samplerate",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"\"Samplerate must be greater than 0\"",
")",
"i... | 37.447368 | 26.710526 |
def mapReduce(mapFunc, reductionFunc, *iterables, **kwargs):
"""Exectues the :meth:`~scoop.futures.map` function and then applies a
reduction function to its result. The reduction function will cumulatively
merge the results of the map function in order to get a single final value.
This call is blocking... | [
"def",
"mapReduce",
"(",
"mapFunc",
",",
"reductionFunc",
",",
"*",
"iterables",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"submit",
"(",
"_recursiveReduce",
",",
"mapFunc",
",",
"reductionFunc",
",",
"False",
",",
"*",
"iterables",
")",
".",
"result",
... | 45.407407 | 24.888889 |
def search_call_sets(self, variant_set_id, name=None, biosample_id=None):
"""
Returns an iterator over the CallSets fulfilling the specified
conditions from the specified VariantSet.
:param str variant_set_id: Find callsets belonging to the
provided variant set.
:par... | [
"def",
"search_call_sets",
"(",
"self",
",",
"variant_set_id",
",",
"name",
"=",
"None",
",",
"biosample_id",
"=",
"None",
")",
":",
"request",
"=",
"protocol",
".",
"SearchCallSetsRequest",
"(",
")",
"request",
".",
"variant_set_id",
"=",
"variant_set_id",
"r... | 45.952381 | 16.428571 |
def fgm(self, x, labels, targeted=False):
"""
TensorFlow Eager implementation of the Fast Gradient Method.
:param x: the input variable
:param targeted: Is the attack targeted or untargeted? Untargeted, the
default, will try to make the label incorrect.
Targeted... | [
"def",
"fgm",
"(",
"self",
",",
"x",
",",
"labels",
",",
"targeted",
"=",
"False",
")",
":",
"# Compute loss",
"with",
"tf",
".",
"GradientTape",
"(",
")",
"as",
"tape",
":",
"# input should be watched because it may be",
"# combination of trainable and non-trainabl... | 39.40625 | 18.15625 |
def recursive_processing(self, base_dir, target_dir, it):
"""Method to recursivly process the notebooks in the `base_dir`
Parameters
----------
base_dir: str
Path to the base example directory (see the `examples_dir`
parameter for the :class:`Gallery` class)
... | [
"def",
"recursive_processing",
"(",
"self",
",",
"base_dir",
",",
"target_dir",
",",
"it",
")",
":",
"try",
":",
"file_dir",
",",
"dirs",
",",
"files",
"=",
"next",
"(",
"it",
")",
"except",
"StopIteration",
":",
"return",
"''",
",",
"[",
"]",
"readme_... | 42.622222 | 18.3 |
def sample(self, ctrs, rstate=None, return_q=False, kdtree=None):
"""
Sample a point uniformly distributed within the *union* of cubes.
Uses a K-D Tree to perform the search if provided.
Returns
-------
x : `~numpy.ndarray` with shape (ndim,)
A coordinate wit... | [
"def",
"sample",
"(",
"self",
",",
"ctrs",
",",
"rstate",
"=",
"None",
",",
"return_q",
"=",
"False",
",",
"kdtree",
"=",
"None",
")",
":",
"if",
"rstate",
"is",
"None",
":",
"rstate",
"=",
"np",
".",
"random",
"nctrs",
"=",
"len",
"(",
"ctrs",
"... | 32.148148 | 19.592593 |
def cnst_A1T(self, Y1):
r"""Compute :math:`A_1^T \mathbf{y}_1` component of
:math:`A^T \mathbf{y}`. In this case :math:`A_1^T \mathbf{y}_1 =
(\Gamma_0^T \;\; \Gamma_1^T \;\; \ldots) \mathbf{y}_1`.
"""
Y1f = sl.rfftn(Y1, None, axes=self.cri.axisN)
return sl.irfftn(np.conj... | [
"def",
"cnst_A1T",
"(",
"self",
",",
"Y1",
")",
":",
"Y1f",
"=",
"sl",
".",
"rfftn",
"(",
"Y1",
",",
"None",
",",
"axes",
"=",
"self",
".",
"cri",
".",
"axisN",
")",
"return",
"sl",
".",
"irfftn",
"(",
"np",
".",
"conj",
"(",
"self",
".",
"GD... | 42.555556 | 16.333333 |
def generate_dataset(self, cdl_path):
'''
Use ncgen to generate a netCDF file from a .cdl file
Returns the path to the generated netcdf file
:param str cdl_path: Absolute path to cdl file that is used to generate netCDF file
'''
if '.cdl' in cdl_path: # it's possible th... | [
"def",
"generate_dataset",
"(",
"self",
",",
"cdl_path",
")",
":",
"if",
"'.cdl'",
"in",
"cdl_path",
":",
"# it's possible the filename doesn't have the .cdl extension",
"ds_str",
"=",
"cdl_path",
".",
"replace",
"(",
"'.cdl'",
",",
"'.nc'",
")",
"else",
":",
"ds_... | 41.230769 | 24.307692 |
def get_handler(self, *args, **options):
"""
Entry point to plug the LiveReload feature.
"""
handler = super(Command, self).get_handler(*args, **options)
if options['use_livereload']:
threading.Timer(1, self.livereload_request, kwargs=options).start()
return h... | [
"def",
"get_handler",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"options",
")",
":",
"handler",
"=",
"super",
"(",
"Command",
",",
"self",
")",
".",
"get_handler",
"(",
"*",
"args",
",",
"*",
"*",
"options",
")",
"if",
"options",
"[",
"'use_liv... | 39.875 | 12.375 |
def swo_enable(self, cpu_speed, swo_speed=9600, port_mask=0x01):
"""Enables SWO output on the target device.
Configures the output protocol, the SWO output speed, and enables any
ITM & stimulus ports.
This is equivalent to calling ``.swo_start()``.
Note:
If SWO is al... | [
"def",
"swo_enable",
"(",
"self",
",",
"cpu_speed",
",",
"swo_speed",
"=",
"9600",
",",
"port_mask",
"=",
"0x01",
")",
":",
"if",
"self",
".",
"swo_enabled",
"(",
")",
":",
"self",
".",
"swo_stop",
"(",
")",
"res",
"=",
"self",
".",
"_dll",
".",
"J... | 31.972973 | 24.783784 |
def convert_value(self, v):
""" convert the expression that is in the term to something that is
accepted by pytables """
def stringify(value):
if self.encoding is not None:
encoder = partial(pprint_thing_encoded,
encoding=self.encodi... | [
"def",
"convert_value",
"(",
"self",
",",
"v",
")",
":",
"def",
"stringify",
"(",
"value",
")",
":",
"if",
"self",
".",
"encoding",
"is",
"not",
"None",
":",
"encoder",
"=",
"partial",
"(",
"pprint_thing_encoded",
",",
"encoding",
"=",
"self",
".",
"en... | 39.703704 | 13.277778 |
def backup(self, paths=None):
"""Backup method driver."""
if not paths:
paths = self._get_paths()
try:
self._backup_compresslevel(paths)
except TypeError:
try:
self._backup_pb_gui(paths)
except ImportError:
... | [
"def",
"backup",
"(",
"self",
",",
"paths",
"=",
"None",
")",
":",
"if",
"not",
"paths",
":",
"paths",
"=",
"self",
".",
"_get_paths",
"(",
")",
"try",
":",
"self",
".",
"_backup_compresslevel",
"(",
"paths",
")",
"except",
"TypeError",
":",
"try",
"... | 27.764706 | 13.117647 |
def postinit(self, func=None, args=None, keywords=None):
"""Do some setup after initialisation.
:param func: What is being called.
:type func: NodeNG or None
:param args: The positional arguments being given to the call.
:type args: list(NodeNG) or None
:param keywords... | [
"def",
"postinit",
"(",
"self",
",",
"func",
"=",
"None",
",",
"args",
"=",
"None",
",",
"keywords",
"=",
"None",
")",
":",
"self",
".",
"func",
"=",
"func",
"self",
".",
"args",
"=",
"args",
"self",
".",
"keywords",
"=",
"keywords"
] | 32.933333 | 16.6 |
def updateRPYText(self):
'Updates the displayed Roll, Pitch, Yaw Text'
self.rollText.set_text('Roll: %.2f' % self.roll)
self.pitchText.set_text('Pitch: %.2f' % self.pitch)
self.yawText.set_text('Yaw: %.2f' % self.yaw) | [
"def",
"updateRPYText",
"(",
"self",
")",
":",
"self",
".",
"rollText",
".",
"set_text",
"(",
"'Roll: %.2f'",
"%",
"self",
".",
"roll",
")",
"self",
".",
"pitchText",
".",
"set_text",
"(",
"'Pitch: %.2f'",
"%",
"self",
".",
"pitch",
")",
"self",
".",
... | 49.8 | 16.2 |
def eigenvalues_rev(T, k, ncv=None, mu=None):
r"""Compute the eigenvalues of a reversible, sparse transition matrix.
Parameters
----------
T : (M, M) scipy.sparse matrix
Transition matrix
k : int
Number of eigenvalues to compute.
ncv : int, optional
The number of Lanczos... | [
"def",
"eigenvalues_rev",
"(",
"T",
",",
"k",
",",
"ncv",
"=",
"None",
",",
"mu",
"=",
"None",
")",
":",
"\"\"\"compute stationary distribution if not given\"\"\"",
"if",
"mu",
"is",
"None",
":",
"mu",
"=",
"stationary_distribution",
"(",
"T",
")",
"if",
"np... | 27.590909 | 20.272727 |
def sa_indices(num_states, num_actions):
"""
Generate `s_indices` and `a_indices` for `DiscreteDP`, for the case
where all the actions are feasible at every state.
Parameters
----------
num_states : scalar(int)
Number of states.
num_actions : scalar(int)
Number of actions.
... | [
"def",
"sa_indices",
"(",
"num_states",
",",
"num_actions",
")",
":",
"L",
"=",
"num_states",
"*",
"num_actions",
"dtype",
"=",
"np",
".",
"int_",
"s_indices",
"=",
"np",
".",
"empty",
"(",
"L",
",",
"dtype",
"=",
"dtype",
")",
"a_indices",
"=",
"np",
... | 23.651163 | 18.674419 |
def merge_from_list(self, list_args):
"""find any matching parser_args from list_args and merge them into this
instance
list_args -- list -- an array of (args, kwargs) tuples
"""
def xs(name, parser_args, list_args):
"""build the generator of matching list_args"""
... | [
"def",
"merge_from_list",
"(",
"self",
",",
"list_args",
")",
":",
"def",
"xs",
"(",
"name",
",",
"parser_args",
",",
"list_args",
")",
":",
"\"\"\"build the generator of matching list_args\"\"\"",
"for",
"args",
",",
"kwargs",
"in",
"list_args",
":",
"if",
"len... | 37 | 13.3 |
def uploadFile(uploadfunc, fileindex, existing, uf, skip_broken=False):
"""Update a file object so that the location is a reference to the toil file
store, writing it to the file store if necessary.
"""
if uf["location"].startswith("toilfs:") or uf["location"].startswith("_:"):
return
if u... | [
"def",
"uploadFile",
"(",
"uploadfunc",
",",
"fileindex",
",",
"existing",
",",
"uf",
",",
"skip_broken",
"=",
"False",
")",
":",
"if",
"uf",
"[",
"\"location\"",
"]",
".",
"startswith",
"(",
"\"toilfs:\"",
")",
"or",
"uf",
"[",
"\"location\"",
"]",
".",... | 40.47619 | 20.238095 |
def get_dates(raw_table) -> "list of dates":
"""
Goes through the first column of input table and
returns the first sequence of dates it finds.
"""
dates = []
found_first = False
for i, dstr in enumerate([raw_table[i][0] for i in range(0, len(raw_table))])... | [
"def",
"get_dates",
"(",
"raw_table",
")",
"->",
"\"list of dates\"",
":",
"dates",
"=",
"[",
"]",
"found_first",
"=",
"False",
"for",
"i",
",",
"dstr",
"in",
"enumerate",
"(",
"[",
"raw_table",
"[",
"i",
"]",
"[",
"0",
"]",
"for",
"i",
"in",
"range"... | 43.36 | 17.84 |
def export_gpx_file(self):
"""Generate GPX element tree from ``Trackpoints``.
Returns:
etree.ElementTree: GPX element tree depicting ``Trackpoints``
objects
"""
gpx = create_elem('gpx', GPX_ELEM_ATTRIB)
if not self.metadata.bounds:
self.me... | [
"def",
"export_gpx_file",
"(",
"self",
")",
":",
"gpx",
"=",
"create_elem",
"(",
"'gpx'",
",",
"GPX_ELEM_ATTRIB",
")",
"if",
"not",
"self",
".",
"metadata",
".",
"bounds",
":",
"self",
".",
"metadata",
".",
"bounds",
"=",
"[",
"j",
"for",
"i",
"in",
... | 33.4 | 13.05 |
def update_video(video_data):
"""
Called on to update Video objects in the database
update_video is used to update Video objects by the given edx_video_id in the video_data.
Args:
video_data (dict):
{
url: api url to the video
edx_video_id: ID of the vi... | [
"def",
"update_video",
"(",
"video_data",
")",
":",
"try",
":",
"video",
"=",
"_get_video",
"(",
"video_data",
".",
"get",
"(",
"\"edx_video_id\"",
")",
")",
"except",
"Video",
".",
"DoesNotExist",
":",
"error_message",
"=",
"u\"Video not found when trying to upda... | 35.564103 | 22.076923 |
def write_csv(path, data):
"""This function writes comma-separated <data> to
<path>. Parameter <path> is either a pathname or a file-like
object that supports the |write()| method."""
fd = _try_open_file(path, 'w',
'The first argument must be a pathname or an object that support... | [
"def",
"write_csv",
"(",
"path",
",",
"data",
")",
":",
"fd",
"=",
"_try_open_file",
"(",
"path",
",",
"'w'",
",",
"'The first argument must be a pathname or an object that supports write() method'",
")",
"for",
"v",
"in",
"data",
":",
"fd",
".",
"write",
"(",
"... | 40.727273 | 18.909091 |
def calc_transform(src, dst_crs=None, resolution=None, dimensions=None,
src_bounds=None, dst_bounds=None, target_aligned_pixels=False):
"""Output dimensions and transform for a reprojection.
Parameters
------------
src: rasterio.io.DatasetReader
Data source.
dst_crs: rast... | [
"def",
"calc_transform",
"(",
"src",
",",
"dst_crs",
"=",
"None",
",",
"resolution",
"=",
"None",
",",
"dimensions",
"=",
"None",
",",
"src_bounds",
"=",
"None",
",",
"dst_bounds",
"=",
"None",
",",
"target_aligned_pixels",
"=",
"False",
")",
":",
"if",
... | 37.132353 | 20.125 |
def add(A, b, offset=0):
"""
Add b to the view of A in place (!).
Returns modified A.
Broadcasting is allowed, thus b can be scalar.
if offset is not zero, make sure b is of right shape!
:param ndarray A: 2 dimensional array
:param ndarray-like b: either one dimensional or scalar
:para... | [
"def",
"add",
"(",
"A",
",",
"b",
",",
"offset",
"=",
"0",
")",
":",
"return",
"_diag_ufunc",
"(",
"A",
",",
"b",
",",
"offset",
",",
"np",
".",
"add",
")"
] | 31.357143 | 12.357143 |
def computeFunctional(x, cooP):
'''
Compute value of functional J(X) = ||PX - PA||^2_F,
where P is projector into index subspace of known elements,
X is our approximation,
A is original tensor.
Parameters:
:tt.vector: x
current approximation [X]
... | [
"def",
"computeFunctional",
"(",
"x",
",",
"cooP",
")",
":",
"indices",
"=",
"cooP",
"[",
"'indices'",
"]",
"values",
"=",
"cooP",
"[",
"'values'",
"]",
"[",
"P",
",",
"d",
"]",
"=",
"indices",
".",
"shape",
"assert",
"P",
"==",
"len",
"(",
"values... | 28.382353 | 17.617647 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.