text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def _process_in_collection_filter_directive(filter_operation_info, location, context, parameters):
"""Return a Filter basic block that checks for a value's existence in a collection.
Args:
filter_operation_info: FilterOperationInfo object, containing the directive and field info
... | [
"def",
"_process_in_collection_filter_directive",
"(",
"filter_operation_info",
",",
"location",
",",
"context",
",",
"parameters",
")",
":",
"filtered_field_type",
"=",
"filter_operation_info",
".",
"field_type",
"filtered_field_name",
"=",
"filter_operation_info",
".",
"f... | 54.870968 | 31.129032 |
def click_window_multiple(self, window, button, repeat=2, delay=100000):
"""
Send a one or more clicks for a specific mouse button at the
current mouse location.
:param window:
The window you want to send the event to or CURRENTWINDOW
:param button:
The m... | [
"def",
"click_window_multiple",
"(",
"self",
",",
"window",
",",
"button",
",",
"repeat",
"=",
"2",
",",
"delay",
"=",
"100000",
")",
":",
"_libxdo",
".",
"xdo_click_window_multiple",
"(",
"self",
".",
"_xdo",
",",
"window",
",",
"button",
",",
"repeat",
... | 43.466667 | 18.666667 |
def execute(cmd, cwd=None):
""" Execute a command and return it's output. """
try:
lines = subprocess \
.check_output(cmd, cwd=cwd, stderr=DEVNULL) \
.splitlines()
except subprocess.CalledProcessError:
return None
else:
if lines:
retu... | [
"def",
"execute",
"(",
"cmd",
",",
"cwd",
"=",
"None",
")",
":",
"try",
":",
"lines",
"=",
"subprocess",
"",
".",
"check_output",
"(",
"cmd",
",",
"cwd",
"=",
"cwd",
",",
"stderr",
"=",
"DEVNULL",
")",
".",
"splitlines",
"(",
")",
"except",
"subpro... | 28.846154 | 15.923077 |
def acquire_resources(self, source):
"""
Store the resources returned by ``source()``. If ``source`` has
been acquired before, it will not be called a second time.
Args:
source (callable): A function that returns a resource or a
list of resources.
Re... | [
"def",
"acquire_resources",
"(",
"self",
",",
"source",
")",
":",
"if",
"source",
"not",
"in",
"self",
".",
"consulted",
":",
"self",
".",
"consulted",
".",
"add",
"(",
"source",
")",
"if",
"isinstance",
"(",
"source",
",",
"Tag",
")",
":",
"res",
"=... | 30.88 | 14.4 |
def atEpoch(self, epoch=2000):
'''
Return SkyCoords of the objects, propagated to a (single) given epoch.
Parameters
----------
epoch : Time, or float
Either an astropy time, or a decimal year of the desired epoch.
Returns
-------
coordinates... | [
"def",
"atEpoch",
"(",
"self",
",",
"epoch",
"=",
"2000",
")",
":",
"projected",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"standardized",
")",
"# calculate the time offset from the epochs of the orignal coordinates",
"try",
":",
"epoch",
".",
"year",
"newob... | 33.294118 | 20.27451 |
def set_lowest_numeric_score(self, score):
"""Sets the lowest numeric score.
arg: score (decimal): the lowest numeric score
raise: InvalidArgument - ``score`` is invalid
raise: NoAccess - ``score`` cannot be modified
*compliance: mandatory -- This method must be implemented... | [
"def",
"set_lowest_numeric_score",
"(",
"self",
",",
"score",
")",
":",
"# Implemented from template for osid.grading.GradeSystemForm.set_lowest_numeric_score",
"if",
"self",
".",
"get_lowest_numeric_score_metadata",
"(",
")",
".",
"is_read_only",
"(",
")",
":",
"raise",
"e... | 42.789474 | 18.473684 |
def start_element(self, name, attrs):
"""
Callback for start of an XML element. Checks to see if we are
about to start a table that matches the ignore pattern.
@param name: the name of the tag being opened
@type name: string
@param attrs: a dictionary of the attributes for the tag being opened... | [
"def",
"start_element",
"(",
"self",
",",
"name",
",",
"attrs",
")",
":",
"if",
"name",
".",
"lower",
"(",
")",
"==",
"\"table\"",
":",
"for",
"attr",
"in",
"attrs",
".",
"keys",
"(",
")",
":",
"if",
"attr",
".",
"lower",
"(",
")",
"==",
"\"name\... | 32.75 | 15.25 |
def iterative_encoder_decoder(encoder_input,
encoder_self_attention_bias,
encoder_decoder_attention_bias,
query,
hparams):
"""Iterative encoder decoder."""
for _ in range(hparams.num_rec_steps):
... | [
"def",
"iterative_encoder_decoder",
"(",
"encoder_input",
",",
"encoder_self_attention_bias",
",",
"encoder_decoder_attention_bias",
",",
"query",
",",
"hparams",
")",
":",
"for",
"_",
"in",
"range",
"(",
"hparams",
".",
"num_rec_steps",
")",
":",
"with",
"tf",
".... | 29.88 | 15.16 |
def group_default_invalidator(self, obj):
"""Invalidated cached items when the Group changes."""
user_pks = User.objects.values_list('pk', flat=True)
return [('User', pk, False) for pk in user_pks] | [
"def",
"group_default_invalidator",
"(",
"self",
",",
"obj",
")",
":",
"user_pks",
"=",
"User",
".",
"objects",
".",
"values_list",
"(",
"'pk'",
",",
"flat",
"=",
"True",
")",
"return",
"[",
"(",
"'User'",
",",
"pk",
",",
"False",
")",
"for",
"pk",
"... | 54.5 | 9 |
def to_html(text, config, search_path):
""" Convert Markdown text to HTML """
processor = misaka.Markdown(HtmlRenderer(config, search_path),
extensions=ENABLED_EXTENSIONS)
text = processor(text)
if not config.get('no_smartquotes'):
text = misaka.smartypants(text)... | [
"def",
"to_html",
"(",
"text",
",",
"config",
",",
"search_path",
")",
":",
"processor",
"=",
"misaka",
".",
"Markdown",
"(",
"HtmlRenderer",
"(",
"config",
",",
"search_path",
")",
",",
"extensions",
"=",
"ENABLED_EXTENSIONS",
")",
"text",
"=",
"processor",... | 34.2 | 15.5 |
def _leave(ins):
""" Return from a function popping N bytes from the stack
Use '__fastcall__' as 1st parameter, to just return
"""
global FLAG_use_function_exit
output = []
if ins.quad[1] == '__fastcall__':
output.append('ret')
return output
nbytes = int(ins.quad[1]) # Nu... | [
"def",
"_leave",
"(",
"ins",
")",
":",
"global",
"FLAG_use_function_exit",
"output",
"=",
"[",
"]",
"if",
"ins",
".",
"quad",
"[",
"1",
"]",
"==",
"'__fastcall__'",
":",
"output",
".",
"append",
"(",
"'ret'",
")",
"return",
"output",
"nbytes",
"=",
"in... | 28.753846 | 19.215385 |
def publish_results(self, view, submitters, commenters):
"""Submit the results to the subreddit. Has no return value (None)."""
def timef(timestamp, date_only=False):
"""Return a suitable string representaation of the timestamp."""
dtime = datetime.fromtimestamp(timestamp)
... | [
"def",
"publish_results",
"(",
"self",
",",
"view",
",",
"submitters",
",",
"commenters",
")",
":",
"def",
"timef",
"(",
"timestamp",
",",
"date_only",
"=",
"False",
")",
":",
"\"\"\"Return a suitable string representaation of the timestamp.\"\"\"",
"dtime",
"=",
"d... | 44.176471 | 18.176471 |
def update(self, friendly_name=values.unset, api_version=values.unset,
sms_url=values.unset, sms_method=values.unset,
sms_fallback_url=values.unset, sms_fallback_method=values.unset):
"""
Update the ShortCodeInstance
:param unicode friendly_name: A string to descri... | [
"def",
"update",
"(",
"self",
",",
"friendly_name",
"=",
"values",
".",
"unset",
",",
"api_version",
"=",
"values",
".",
"unset",
",",
"sms_url",
"=",
"values",
".",
"unset",
",",
"sms_method",
"=",
"values",
".",
"unset",
",",
"sms_fallback_url",
"=",
"... | 49.041667 | 23.375 |
def process_bool_arg(arg):
""" Determine True/False from argument """
if isinstance(arg, bool):
return arg
elif isinstance(arg, basestring):
if arg.lower() in ["true", "1"]:
return True
elif arg.lower() in ["false", "0"]:
return False | [
"def",
"process_bool_arg",
"(",
"arg",
")",
":",
"if",
"isinstance",
"(",
"arg",
",",
"bool",
")",
":",
"return",
"arg",
"elif",
"isinstance",
"(",
"arg",
",",
"basestring",
")",
":",
"if",
"arg",
".",
"lower",
"(",
")",
"in",
"[",
"\"true\"",
",",
... | 31.777778 | 9.555556 |
def _get_remote_video_url(self, remote_node, session_id):
"""Get grid-extras url to download videos
:param remote_node: remote node name
:param session_id: test session id
:returns: grid-extras url to download videos
"""
url = '{}/video'.format(self._get_remote_node_url(... | [
"def",
"_get_remote_video_url",
"(",
"self",
",",
"remote_node",
",",
"session_id",
")",
":",
"url",
"=",
"'{}/video'",
".",
"format",
"(",
"self",
".",
"_get_remote_node_url",
"(",
"remote_node",
")",
")",
"timeout",
"=",
"time",
".",
"time",
"(",
")",
"+... | 38 | 17.2 |
def in_constraint(self, node1, node2):
"""Checks if node1 is in node2's constraints
For instance, if node1 = 010 and node2 = 110:
010 & 110 = 010 -> has the element."""
constraint = constraint_table[node2]
if constraint == 0b0:
return False
try:
v... | [
"def",
"in_constraint",
"(",
"self",
",",
"node1",
",",
"node2",
")",
":",
"constraint",
"=",
"constraint_table",
"[",
"node2",
"]",
"if",
"constraint",
"==",
"0b0",
":",
"return",
"False",
"try",
":",
"value",
"=",
"self",
".",
"el2bv",
"[",
"node1",
... | 30.071429 | 13.642857 |
def _FlagIsRegistered(self, flag_obj):
"""Checks whether a Flag object is registered under long name or short name.
Args:
flag_obj: A Flag object.
Returns:
A boolean: True iff flag_obj is registered under long name or short name.
"""
flag_dict = self.FlagDict()
# Check whether flag... | [
"def",
"_FlagIsRegistered",
"(",
"self",
",",
"flag_obj",
")",
":",
"flag_dict",
"=",
"self",
".",
"FlagDict",
"(",
")",
"# Check whether flag_obj is registered under its long name.",
"name",
"=",
"flag_obj",
".",
"name",
"if",
"flag_dict",
".",
"get",
"(",
"name"... | 32.75 | 18 |
def filter(self, callback=None):
"""
Run a filter over each of the items.
:param callback: The filter callback
:type callback: callable or None
:rtype: Collection
"""
if callback:
return self.__class__(list(filter(callback, self.items)))
ret... | [
"def",
"filter",
"(",
"self",
",",
"callback",
"=",
"None",
")",
":",
"if",
"callback",
":",
"return",
"self",
".",
"__class__",
"(",
"list",
"(",
"filter",
"(",
"callback",
",",
"self",
".",
"items",
")",
")",
")",
"return",
"self",
".",
"__class__"... | 27.538462 | 16.923077 |
def __split_genomic_interval_filename(fn):
"""
Split a filename of the format chrom:start-end.ext or chrom.ext (full chrom).
:return: tuple of (chrom, start, end) -- 'start' and 'end' are None if not
present in the filename.
"""
if fn is None or fn == "":
raise ValueError("invalid filename: " ... | [
"def",
"__split_genomic_interval_filename",
"(",
"fn",
")",
":",
"if",
"fn",
"is",
"None",
"or",
"fn",
"==",
"\"\"",
":",
"raise",
"ValueError",
"(",
"\"invalid filename: \"",
"+",
"str",
"(",
"fn",
")",
")",
"fn",
"=",
"\".\"",
".",
"join",
"(",
"fn",
... | 34.666667 | 15.555556 |
def from_attribute(attr):
"""
Converts an attribute into a shadow attribute.
:param attr: :class:`MispAttribute` instance to be converted
:returns: Converted :class:`MispShadowAttribute`
:example:
>>> server = MispServer()
>>> event = server.events.get(12)
... | [
"def",
"from_attribute",
"(",
"attr",
")",
":",
"assert",
"attr",
"is",
"not",
"MispAttribute",
"prop",
"=",
"MispShadowAttribute",
"(",
")",
"prop",
".",
"distribution",
"=",
"attr",
".",
"distribution",
"prop",
".",
"type",
"=",
"attr",
".",
"type",
"pro... | 31.217391 | 13.478261 |
def apply_zappa_settings(zappa_obj, zappa_settings, environment):
'''Load Zappa settings, set defaults if needed, and apply to the Zappa object'''
settings_all = json.load(zappa_settings)
settings = settings_all[environment]
# load defaults for missing options
for key,value in DEFAULT_SETTINGS.ite... | [
"def",
"apply_zappa_settings",
"(",
"zappa_obj",
",",
"zappa_settings",
",",
"environment",
")",
":",
"settings_all",
"=",
"json",
".",
"load",
"(",
"zappa_settings",
")",
"settings",
"=",
"settings_all",
"[",
"environment",
"]",
"# load defaults for missing options",... | 40.380952 | 22.857143 |
def _get_alphanumeric_index(query_string):
""" Given an input string of either int or char, returns what index in the alphabet and case it is
:param query_string: str, query string
:return: (int, str), list of the index and type
"""
# TODO: could probably rework this. it works, ... | [
"def",
"_get_alphanumeric_index",
"(",
"query_string",
")",
":",
"# TODO: could probably rework this. it works, but it's ugly as hell.",
"try",
":",
"return",
"[",
"int",
"(",
"query_string",
")",
",",
"'int'",
"]",
"except",
"ValueError",
":",
"if",
"len",
"(",
"quer... | 47.294118 | 17.705882 |
def get_results(self):
'''
:return: result from running the task
'''
self._event.wait()
if self._exception is not None:
#
# Well... rethrownig the exception caught in execute
# but on the caller thread
#
raise self._exce... | [
"def",
"get_results",
"(",
"self",
")",
":",
"self",
".",
"_event",
".",
"wait",
"(",
")",
"if",
"self",
".",
"_exception",
"is",
"not",
"None",
":",
"#",
"# Well... rethrownig the exception caught in execute",
"# but on the caller thread",
"#",
"raise",
"self",
... | 30.583333 | 17.25 |
def get_files(cls, folder):
""" Retrieve the list of files the plugin can work on.
Find this list based on the files name, files extension or even
actually by reading in the file.
:arg folder: the path to the folder containing the files to
check. This folder may contain sub-... | [
"def",
"get_files",
"(",
"cls",
",",
"folder",
")",
":",
"filelist",
"=",
"[",
"]",
"if",
"folder",
"is",
"None",
"or",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"folder",
")",
":",
"return",
"filelist",
"for",
"root",
",",
"dirs",
",",
"files",... | 37.944444 | 14.777778 |
def route_present(name, address_prefix, next_hop_type, route_table, resource_group, next_hop_ip_address=None,
connection_auth=None, **kwargs):
'''
.. versionadded:: 2019.2.0
Ensure a route exists within a route table.
:param name:
Name of the route.
:param address_prefix... | [
"def",
"route_present",
"(",
"name",
",",
"address_prefix",
",",
"next_hop_type",
",",
"route_table",
",",
"resource_group",
",",
"next_hop_ip_address",
"=",
"None",
",",
"connection_auth",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'n... | 30.923664 | 23.091603 |
def parity_even_p(state, marked_qubits):
"""
Calculates the parity of elements at indexes in marked_qubits
Parity is relative to the binary representation of the integer state.
:param state: The wavefunction index that corresponds to this state.
:param marked_qubits: The indexes to be considered i... | [
"def",
"parity_even_p",
"(",
"state",
",",
"marked_qubits",
")",
":",
"assert",
"isinstance",
"(",
"state",
",",
"int",
")",
",",
"f\"{state} is not an integer. Must call parity_even_p with an integer state.\"",
"mask",
"=",
"0",
"for",
"q",
"in",
"marked_qubits",
":"... | 38.625 | 20.625 |
def solve(self):
'''First EOS-generic method; should be called by all specific EOSs.
For solving for `T`, the EOS must provide the method `solve_T`.
For all cases, the EOS must provide `a_alpha_and_derivatives`.
Calls `set_from_PT` once done.
'''
self.check_sufficient_inp... | [
"def",
"solve",
"(",
"self",
")",
":",
"self",
".",
"check_sufficient_inputs",
"(",
")",
"if",
"self",
".",
"V",
":",
"if",
"self",
".",
"P",
":",
"self",
".",
"T",
"=",
"self",
".",
"solve_T",
"(",
"self",
".",
"P",
",",
"self",
".",
"V",
")",... | 51.95 | 31.75 |
def com_google_fonts_check_family_equal_font_versions(ttFonts):
"""Make sure all font files have the same version value."""
all_detected_versions = []
fontfile_versions = {}
for ttFont in ttFonts:
v = ttFont['head'].fontRevision
fontfile_versions[ttFont] = v
if v not in all_detected_versions:
... | [
"def",
"com_google_fonts_check_family_equal_font_versions",
"(",
"ttFonts",
")",
":",
"all_detected_versions",
"=",
"[",
"]",
"fontfile_versions",
"=",
"{",
"}",
"for",
"ttFont",
"in",
"ttFonts",
":",
"v",
"=",
"ttFont",
"[",
"'head'",
"]",
".",
"fontRevision",
... | 39.619048 | 13.571429 |
def targeted_einsum(gate: np.ndarray,
wf: np.ndarray,
wf_target_inds: List[int]
) -> np.ndarray:
"""Left-multiplies the given axes of the wf tensor by the given gate matrix.
Note that the matrix must have a compatible tensor structure.
For example... | [
"def",
"targeted_einsum",
"(",
"gate",
":",
"np",
".",
"ndarray",
",",
"wf",
":",
"np",
".",
"ndarray",
",",
"wf_target_inds",
":",
"List",
"[",
"int",
"]",
")",
"->",
"np",
".",
"ndarray",
":",
"k",
"=",
"len",
"(",
"wf_target_inds",
")",
"d",
"="... | 46.956522 | 23.23913 |
def cs20(msg):
"""Aircraft callsign
Args:
msg (String): 28 bytes hexadecimal message (BDS40) string
Returns:
string: callsign, max. 8 chars
"""
chars = '#ABCDEFGHIJKLMNOPQRSTUVWXYZ#####_###############0123456789######'
d = hex2bin(data(msg))
cs = ''
cs += chars[bin2in... | [
"def",
"cs20",
"(",
"msg",
")",
":",
"chars",
"=",
"'#ABCDEFGHIJKLMNOPQRSTUVWXYZ#####_###############0123456789######'",
"d",
"=",
"hex2bin",
"(",
"data",
"(",
"msg",
")",
")",
"cs",
"=",
"''",
"cs",
"+=",
"chars",
"[",
"bin2int",
"(",
"d",
"[",
"8",
":",
... | 23.666667 | 19.541667 |
def _fit_tfa_inner(
self,
data,
R,
template_centers,
template_widths,
template_centers_mean_cov,
template_widths_mean_var_reci):
"""Fit TFA model, the inner loop part
Parameters
----------
data: 2D arra... | [
"def",
"_fit_tfa_inner",
"(",
"self",
",",
"data",
",",
"R",
",",
"template_centers",
",",
"template_widths",
",",
"template_centers_mean_cov",
",",
"template_widths_mean_var_reci",
")",
":",
"nfeature",
"=",
"data",
".",
"shape",
"[",
"0",
"]",
"nsample",
"=",
... | 33.548387 | 18.967742 |
def calc_h_v1(self):
"""Approximate the water stage resulting in a certain reference discarge
with the Pegasus iteration method.
Required control parameters:
|QTol|
|HTol|
Required flux sequence:
|QRef|
Modified aide sequences:
|HMin|
|HMax|
|QMin|
|QMax|... | [
"def",
"calc_h_v1",
"(",
"self",
")",
":",
"con",
"=",
"self",
".",
"parameters",
".",
"control",
".",
"fastaccess",
"flu",
"=",
"self",
".",
"sequences",
".",
"fluxes",
".",
"fastaccess",
"aid",
"=",
"self",
".",
"sequences",
".",
"aides",
".",
"fasta... | 29.858921 | 21.929461 |
def _terminate_procs(procs):
"""
Terminate all processes in the process dictionary
"""
logging.warn("Stopping all remaining processes")
for proc, g in procs.values():
logging.debug("[%s] SIGTERM", proc.pid)
try:
proc.terminate()
except OSError as e:
# ... | [
"def",
"_terminate_procs",
"(",
"procs",
")",
":",
"logging",
".",
"warn",
"(",
"\"Stopping all remaining processes\"",
")",
"for",
"proc",
",",
"g",
"in",
"procs",
".",
"values",
"(",
")",
":",
"logging",
".",
"debug",
"(",
"\"[%s] SIGTERM\"",
",",
"proc",
... | 31.642857 | 12.928571 |
def _no_duplicates_constructor(loader, node, deep=False):
"""Check for duplicate keys."""
mapping = {}
for key_node, value_node in node.value:
key = loader.construct_object(key_node, deep=deep)
value = loader.construct_object(value_node, deep=deep)
if key in mapping:
rai... | [
"def",
"_no_duplicates_constructor",
"(",
"loader",
",",
"node",
",",
"deep",
"=",
"False",
")",
":",
"mapping",
"=",
"{",
"}",
"for",
"key_node",
",",
"value_node",
"in",
"node",
".",
"value",
":",
"key",
"=",
"loader",
".",
"construct_object",
"(",
"ke... | 40.8 | 18.466667 |
def get_blocked(self):
"""Return a UserList of Redditors with whom the user has blocked."""
url = self.reddit_session.config['blocked']
return self.reddit_session.request_json(url) | [
"def",
"get_blocked",
"(",
"self",
")",
":",
"url",
"=",
"self",
".",
"reddit_session",
".",
"config",
"[",
"'blocked'",
"]",
"return",
"self",
".",
"reddit_session",
".",
"request_json",
"(",
"url",
")"
] | 50.25 | 10.25 |
def _evaluatelinearPotentials(Pot,x,t=0.):
"""Raw, undecorated function for internal use"""
if isinstance(Pot,list):
sum= 0.
for pot in Pot:
sum+= pot._call_nodecorator(x,t=t)
return sum
elif isinstance(Pot,linearPotential):
return Pot._call_nodecorator(x,t=t)
... | [
"def",
"_evaluatelinearPotentials",
"(",
"Pot",
",",
"x",
",",
"t",
"=",
"0.",
")",
":",
"if",
"isinstance",
"(",
"Pot",
",",
"list",
")",
":",
"sum",
"=",
"0.",
"for",
"pot",
"in",
"Pot",
":",
"sum",
"+=",
"pot",
".",
"_call_nodecorator",
"(",
"x"... | 42.545455 | 17.636364 |
def largest_connected_submatrix(C, directed=True, lcc=None):
r"""Compute the count matrix on the largest connected set.
Parameters
----------
C : scipy.sparse matrix
Count matrix specifying edge weights.
directed : bool, optional
Whether to compute connected components for a directed... | [
"def",
"largest_connected_submatrix",
"(",
"C",
",",
"directed",
"=",
"True",
",",
"lcc",
"=",
"None",
")",
":",
"if",
"isdense",
"(",
"C",
")",
":",
"return",
"sparse",
".",
"connectivity",
".",
"largest_connected_submatrix",
"(",
"csr_matrix",
"(",
"C",
... | 30.576271 | 24.254237 |
def parent_frame_arguments():
"""Returns parent frame arguments.
When called inside a function, returns a dictionary with the caller's function
arguments. These are positional arguments and keyword arguments (**kwargs),
while variable arguments (*varargs) are excluded.
When called at global scope, this will... | [
"def",
"parent_frame_arguments",
"(",
")",
":",
"# All arguments and the names used for *varargs, and **kwargs",
"arg_names",
",",
"variable_arg_name",
",",
"keyword_arg_name",
",",
"local_vars",
"=",
"(",
"tf_inspect",
".",
"_inspect",
".",
"getargvalues",
"(",
"# pylint: ... | 41.142857 | 24.428571 |
def forward(self, x):
"""
Transforms from the packed to unpacked representations (numpy)
:param x: packed numpy array. Must have shape `self.num_matrices x triangular_number
:return: Reconstructed numpy array y of shape self.num_matrices x N x N
"""
fwd = np.zero... | [
"def",
"forward",
"(",
"self",
",",
"x",
")",
":",
"fwd",
"=",
"np",
".",
"zeros",
"(",
"(",
"self",
".",
"num_matrices",
",",
"self",
".",
"N",
",",
"self",
".",
"N",
")",
",",
"settings",
".",
"float_type",
")",
"indices",
"=",
"np",
".",
"tr... | 47 | 19.307692 |
def integrity(integrity_func, retry_errors=(ResponseNotValid,)):
"""
Args:
:param integrity_func: couldb callable or string contains name of
method to call
"""
def build_decorator(func):
@functools.wraps(func)
def func_wrapper(self, grab, task):
if isinsta... | [
"def",
"integrity",
"(",
"integrity_func",
",",
"retry_errors",
"=",
"(",
"ResponseNotValid",
",",
")",
")",
":",
"def",
"build_decorator",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"func_wrapper",
"(",
"self",
",",
... | 38.548387 | 12.806452 |
def nvmlDeviceGetSupportedMemoryClocks(handle):
r"""
/**
* Retrieves the list of possible memory clocks that can be used as an argument for \ref nvmlDeviceSetApplicationsClocks.
*
* For Kepler &tm; or newer fully supported devices.
*
* @param device The ide... | [
"def",
"nvmlDeviceGetSupportedMemoryClocks",
"(",
"handle",
")",
":",
"# first call to get the size",
"c_count",
"=",
"c_uint",
"(",
"0",
")",
"fn",
"=",
"_nvmlGetFunctionPointer",
"(",
"\"nvmlDeviceGetSupportedMemoryClocks\"",
")",
"ret",
"=",
"fn",
"(",
"handle",
",... | 43.442308 | 28.192308 |
def createNorthPointer(self):
'''Creates the north pointer relative to current heading.'''
self.headingNorthTri = patches.RegularPolygon((0.0,0.80),3,0.05,color='k',zorder=4)
self.axes.add_patch(self.headingNorthTri)
self.headingNorthText = self.axes.text(0.0,0.675,'N',color='k',size=sel... | [
"def",
"createNorthPointer",
"(",
"self",
")",
":",
"self",
".",
"headingNorthTri",
"=",
"patches",
".",
"RegularPolygon",
"(",
"(",
"0.0",
",",
"0.80",
")",
",",
"3",
",",
"0.05",
",",
"color",
"=",
"'k'",
",",
"zorder",
"=",
"4",
")",
"self",
".",
... | 78.4 | 42.8 |
def build_walker(concurrency):
"""This will return a function suitable for passing to
:class:`stacker.plan.Plan` for walking the graph.
If concurrency is 1 (no parallelism) this will return a simple topological
walker that doesn't use any multithreading.
If concurrency is 0, this will return a wal... | [
"def",
"build_walker",
"(",
"concurrency",
")",
":",
"if",
"concurrency",
"==",
"1",
":",
"return",
"walk",
"semaphore",
"=",
"UnlimitedSemaphore",
"(",
")",
"if",
"concurrency",
">",
"1",
":",
"semaphore",
"=",
"threading",
".",
"Semaphore",
"(",
"concurren... | 33.375 | 22.166667 |
def request_instance(vm_=None, call=None):
'''
Put together all of the information necessary to request an instance
through Novaclient and then fire off the request the instance.
Returns data about the instance
'''
if call == 'function':
# Technically this function may be called other w... | [
"def",
"request_instance",
"(",
"vm_",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'function'",
":",
"# Technically this function may be called other ways too, but it",
"# definitely cannot be called with --function.",
"raise",
"SaltCloudSystemExit",... | 37.598131 | 21.981308 |
def get_array(self, rowBased=True):
"""Return a two dimensional list with the values of the :py:obj:`self`.
:param boolean rowBased: Indicates wether the returned list should be
row or column based. Has to be True if list[i] should be the i'th
row, False if list[i] should be the... | [
"def",
"get_array",
"(",
"self",
",",
"rowBased",
"=",
"True",
")",
":",
"if",
"rowBased",
":",
"array",
"=",
"[",
"]",
"for",
"row",
"in",
"xrange",
"(",
"self",
".",
"_rows",
")",
":",
"newRow",
"=",
"[",
"]",
"for",
"col",
"in",
"xrange",
"(",... | 40.85 | 17.95 |
def bit_count(self, start=None, end=None):
"""
Count the set bits in a string. Note that the `start` and `end`
parameters are offsets in **bytes**.
"""
return self.database.bitcount(self.key, start, end) | [
"def",
"bit_count",
"(",
"self",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
")",
":",
"return",
"self",
".",
"database",
".",
"bitcount",
"(",
"self",
".",
"key",
",",
"start",
",",
"end",
")"
] | 39.666667 | 9.333333 |
def construct_start_message(self):
"""Collect preliminary run info at the start of the DFK.
Returns :
- Message dict dumped as json string, ready for UDP
"""
uname = getpass.getuser().encode('latin1')
hashed_username = hashlib.sha256(uname).hexdigest()[0:10]
... | [
"def",
"construct_start_message",
"(",
"self",
")",
":",
"uname",
"=",
"getpass",
".",
"getuser",
"(",
")",
".",
"encode",
"(",
"'latin1'",
")",
"hashed_username",
"=",
"hashlib",
".",
"sha256",
"(",
"uname",
")",
".",
"hexdigest",
"(",
")",
"[",
"0",
... | 40.666667 | 12.142857 |
def cmd_tool(args=None):
""" Command line utility for creating HDF5 blimpy files. """
from argparse import ArgumentParser
parser = ArgumentParser(description="Command line utility for creating HDF5 Filterbank files.")
parser.add_argument('dirname', type=str, help='Name of directory to read')
args = ... | [
"def",
"cmd_tool",
"(",
"args",
"=",
"None",
")",
":",
"from",
"argparse",
"import",
"ArgumentParser",
"parser",
"=",
"ArgumentParser",
"(",
"description",
"=",
"\"Command line utility for creating HDF5 Filterbank files.\"",
")",
"parser",
".",
"add_argument",
"(",
"'... | 40.287671 | 22.315068 |
def download(config, account, day, region, output):
"""Download a traildb file for a given account/day/region"""
with open(config) as fh:
config = yaml.safe_load(fh.read())
jsonschema.validate(config, CONFIG_SCHEMA)
found = None
for info in config['accounts']:
if info['name'] == a... | [
"def",
"download",
"(",
"config",
",",
"account",
",",
"day",
",",
"region",
",",
"output",
")",
":",
"with",
"open",
"(",
"config",
")",
"as",
"fh",
":",
"config",
"=",
"yaml",
".",
"safe_load",
"(",
"fh",
".",
"read",
"(",
")",
")",
"jsonschema",... | 27.137931 | 18.586207 |
def insert_child(self, child_pid, index=-1):
"""Insert a Version child PID."""
if child_pid.status != PIDStatus.REGISTERED:
raise PIDRelationConsistencyError(
"Version PIDs should have status 'REGISTERED'. Use "
"insert_draft_child to insert 'RESERVED' draft P... | [
"def",
"insert_child",
"(",
"self",
",",
"child_pid",
",",
"index",
"=",
"-",
"1",
")",
":",
"if",
"child_pid",
".",
"status",
"!=",
"PIDStatus",
".",
"REGISTERED",
":",
"raise",
"PIDRelationConsistencyError",
"(",
"\"Version PIDs should have status 'REGISTERED'. Us... | 51.214286 | 13.142857 |
def plotit(self):
'''
Produce the plots requested in the Dynac input file. This makes the same
plots as produced by the Dynac ``plotit`` command.
'''
[self._plot(i) for i in range(len(self.plots))] | [
"def",
"plotit",
"(",
"self",
")",
":",
"[",
"self",
".",
"_plot",
"(",
"i",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"plots",
")",
")",
"]"
] | 38.833333 | 25.833333 |
def verify_claims(app_req, issuer=None):
"""
Verify JWT claims.
All times must be UTC unix timestamps.
These claims will be verified:
- iat: issued at time. If JWT was issued more than an hour ago it is
rejected.
- exp: expiration time.
All exceptions are derived from
:class:`m... | [
"def",
"verify_claims",
"(",
"app_req",
",",
"issuer",
"=",
"None",
")",
":",
"if",
"not",
"issuer",
":",
"issuer",
"=",
"_get_issuer",
"(",
"app_req",
"=",
"app_req",
")",
"try",
":",
"float",
"(",
"str",
"(",
"app_req",
".",
"get",
"(",
"'exp'",
")... | 28.107143 | 15.678571 |
def parse_region(self):
"""Pull region/auth url information from context."""
try:
auth_url = self.job_args['os_auth_url']
if 'tokens' not in auth_url:
if not auth_url.endswith('/'):
auth_url = '%s/' % auth_url
auth_url = urlpar... | [
"def",
"parse_region",
"(",
"self",
")",
":",
"try",
":",
"auth_url",
"=",
"self",
".",
"job_args",
"[",
"'os_auth_url'",
"]",
"if",
"'tokens'",
"not",
"in",
"auth_url",
":",
"if",
"not",
"auth_url",
".",
"endswith",
"(",
"'/'",
")",
":",
"auth_url",
"... | 38 | 16.714286 |
def print_results(cls, stdout, stderr):
"""Print linter results and exits with an error if there's any."""
for line in stderr:
print(line, file=sys.stderr)
if stdout:
if stderr: # blank line to separate stdout from stderr
print(file=sys.stderr)
... | [
"def",
"print_results",
"(",
"cls",
",",
"stdout",
",",
"stderr",
")",
":",
"for",
"line",
"in",
"stderr",
":",
"print",
"(",
"line",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"if",
"stdout",
":",
"if",
"stderr",
":",
"# blank line to separate stdout ... | 39.3 | 9.5 |
def auto_toc_tree(self, node): # pylint: disable=too-many-branches
"""Try to convert a list block to toctree in rst.
This function detects if the matches the condition and return
a converted toc tree node. The matching condition:
The list only contains one level, and only contains refe... | [
"def",
"auto_toc_tree",
"(",
"self",
",",
"node",
")",
":",
"# pylint: disable=too-many-branches",
"if",
"not",
"self",
".",
"config",
"[",
"'enable_auto_toc_tree'",
"]",
":",
"return",
"None",
"# when auto_toc_tree_section is set",
"# only auto generate toctree under the s... | 37.644737 | 15.671053 |
def output_keys(self, source_keys):
"""
Given input chunk keys, compute what keys will be needed to put
the result into the result array.
As an example of where this gets used - when we aggregate on a
particular axis, the source keys may be ``(0:2, None:None)``, but for
... | [
"def",
"output_keys",
"(",
"self",
",",
"source_keys",
")",
":",
"keys",
"=",
"list",
"(",
"source_keys",
")",
"# Remove the aggregated axis from the keys.",
"del",
"keys",
"[",
"self",
".",
"axis",
"]",
"return",
"tuple",
"(",
"keys",
")"
] | 38.466667 | 18.333333 |
def first_delayed(self):
"""
Return the first entry in the delayed zset (a tuple with the job's pk
and the score of the zset, which it's delayed time as a timestamp)
Returns None if no delayed jobs
"""
entries = self.delayed.zrange(0, 0, withscores=True)
return en... | [
"def",
"first_delayed",
"(",
"self",
")",
":",
"entries",
"=",
"self",
".",
"delayed",
".",
"zrange",
"(",
"0",
",",
"0",
",",
"withscores",
"=",
"True",
")",
"return",
"entries",
"[",
"0",
"]",
"if",
"entries",
"else",
"None"
] | 42.75 | 14.25 |
def show_version(a_device):
"""Execute show version command using Netmiko."""
remote_conn = ConnectHandler(**a_device)
print()
print("#" * 80)
print(remote_conn.send_command("show version"))
print("#" * 80)
print() | [
"def",
"show_version",
"(",
"a_device",
")",
":",
"remote_conn",
"=",
"ConnectHandler",
"(",
"*",
"*",
"a_device",
")",
"print",
"(",
")",
"print",
"(",
"\"#\"",
"*",
"80",
")",
"print",
"(",
"remote_conn",
".",
"send_command",
"(",
"\"show version\"",
")"... | 29.375 | 16 |
def isMine(self, scriptname):
"""Primitive queuing system detection; only looks at suffix at the moment."""
suffix = os.path.splitext(scriptname)[1].lower()
if suffix.startswith('.'):
suffix = suffix[1:]
return self.suffix == suffix | [
"def",
"isMine",
"(",
"self",
",",
"scriptname",
")",
":",
"suffix",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"scriptname",
")",
"[",
"1",
"]",
".",
"lower",
"(",
")",
"if",
"suffix",
".",
"startswith",
"(",
"'.'",
")",
":",
"suffix",
"=",
"... | 45.166667 | 7.666667 |
def update_user_auth_stat(self, user, success=True):
"""
Update authentication successful to user.
:param user:
The authenticated user model
:param success:
Default to true, if false increments fail_login_count on user model
"""
... | [
"def",
"update_user_auth_stat",
"(",
"self",
",",
"user",
",",
"success",
"=",
"True",
")",
":",
"if",
"not",
"user",
".",
"login_count",
":",
"user",
".",
"login_count",
"=",
"0",
"if",
"not",
"user",
".",
"fail_login_count",
":",
"user",
".",
"fail_log... | 33.1 | 12.1 |
def __set_ethernet_uris(self, ethernet_names, operation="add"):
"""Updates network uris."""
if not isinstance(ethernet_names, list):
ethernet_names = [ethernet_names]
associated_enets = self.data.get('networkUris', [])
ethernet_uris = []
for i, enet in enumerate(eth... | [
"def",
"__set_ethernet_uris",
"(",
"self",
",",
"ethernet_names",
",",
"operation",
"=",
"\"add\"",
")",
":",
"if",
"not",
"isinstance",
"(",
"ethernet_names",
",",
"list",
")",
":",
"ethernet_names",
"=",
"[",
"ethernet_names",
"]",
"associated_enets",
"=",
"... | 44.68 | 25.04 |
def getUpperDetectionLimit(self):
"""Returns the Upper Detection Limit (UDL) that applies to this
analysis in particular. If no value set or the analysis service
doesn't allow manual input of detection limits, returns the value set
by default in the Analysis Service
"""
i... | [
"def",
"getUpperDetectionLimit",
"(",
"self",
")",
":",
"if",
"self",
".",
"isUpperDetectionLimit",
"(",
")",
":",
"result",
"=",
"self",
".",
"getResult",
"(",
")",
"try",
":",
"# in this case, the result itself is the LDL.",
"return",
"float",
"(",
"result",
"... | 50 | 14.352941 |
def __execute_cmd(name, cmd):
'''
Execute Riak commands
'''
return __salt__['cmd.run_all'](
'{0} {1}'.format(salt.utils.path.which(name), cmd)
) | [
"def",
"__execute_cmd",
"(",
"name",
",",
"cmd",
")",
":",
"return",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"'{0} {1}'",
".",
"format",
"(",
"salt",
".",
"utils",
".",
"path",
".",
"which",
"(",
"name",
")",
",",
"cmd",
")",
")"
] | 23.714286 | 21.428571 |
def _get_auth(self, force_console=False):
"""Try to get login auth from known sources."""
if not self.target:
raise ValueError("Unspecified target ({!r})".format(self.target))
elif not force_console and self.URL_RE.match(self.target):
auth_url = urlparse(self.target)
... | [
"def",
"_get_auth",
"(",
"self",
",",
"force_console",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"target",
":",
"raise",
"ValueError",
"(",
"\"Unspecified target ({!r})\"",
".",
"format",
"(",
"self",
".",
"target",
")",
")",
"elif",
"not",
"force_... | 42.272727 | 13.954545 |
def time_seconds(tc_array, year):
"""Return the time object from the timecodes
"""
tc_array = np.array(tc_array, copy=True)
word = tc_array[:, 0]
day = word >> 1
word = tc_array[:, 1].astype(np.uint64)
msecs = ((127) & word) * 1024
word = tc_array[:, 2]
msecs += word & 1023
msecs... | [
"def",
"time_seconds",
"(",
"tc_array",
",",
"year",
")",
":",
"tc_array",
"=",
"np",
".",
"array",
"(",
"tc_array",
",",
"copy",
"=",
"True",
")",
"word",
"=",
"tc_array",
"[",
":",
",",
"0",
"]",
"day",
"=",
"word",
">>",
"1",
"word",
"=",
"tc_... | 31.117647 | 10.117647 |
def system_info(url, auth, verify_ssl):
"""Retrieve SDC system information.
Args:
url (str): the host url.
auth (tuple): a tuple of username, and password.
"""
sysinfo_response = requests.get(url + '/info', headers=X_REQ_BY, auth=auth, verify=verify_ssl)
sysinfo_response.raise_for_... | [
"def",
"system_info",
"(",
"url",
",",
"auth",
",",
"verify_ssl",
")",
":",
"sysinfo_response",
"=",
"requests",
".",
"get",
"(",
"url",
"+",
"'/info'",
",",
"headers",
"=",
"X_REQ_BY",
",",
"auth",
"=",
"auth",
",",
"verify",
"=",
"verify_ssl",
")",
"... | 32.090909 | 18.272727 |
def get_accounts_from_file(filename):
"""
Reads a list of user/password combinations from the given file
and returns a list of Account instances. The file content
has the following format::
[account-pool]
user1 = cGFzc3dvcmQ=
user2 = cGFzc3dvcmQ=
Note that "cGFzc3dvcmQ=" is... | [
"def",
"get_accounts_from_file",
"(",
"filename",
")",
":",
"accounts",
"=",
"[",
"]",
"cfgparser",
"=",
"__import__",
"(",
"'configparser'",
",",
"{",
"}",
",",
"{",
"}",
",",
"[",
"''",
"]",
")",
"parser",
"=",
"cfgparser",
".",
"RawConfigParser",
"(",... | 36.59375 | 18.46875 |
async def helo(
self, hostname: str = None, timeout: DefaultNumType = _default
) -> SMTPResponse:
"""
Send the SMTP HELO command.
Hostname to send for this command defaults to the FQDN of the local
host.
:raises SMTPHeloError: on unexpected server response code
... | [
"async",
"def",
"helo",
"(",
"self",
",",
"hostname",
":",
"str",
"=",
"None",
",",
"timeout",
":",
"DefaultNumType",
"=",
"_default",
")",
"->",
"SMTPResponse",
":",
"if",
"hostname",
"is",
"None",
":",
"hostname",
"=",
"self",
".",
"source_address",
"a... | 33.272727 | 18.909091 |
def _generic_action_parser(self):
"""Generic parser for Actions."""
actions = []
while True:
action_code = unpack_ui8(self._src)
if action_code == 0:
break
action_name = ACTION_NAMES[action_code]
if action_code > 128:
... | [
"def",
"_generic_action_parser",
"(",
"self",
")",
":",
"actions",
"=",
"[",
"]",
"while",
"True",
":",
"action_code",
"=",
"unpack_ui8",
"(",
"self",
".",
"_src",
")",
"if",
"action_code",
"==",
"0",
":",
"break",
"action_name",
"=",
"ACTION_NAMES",
"[",
... | 41.761905 | 15.690476 |
def _on_github_user(self, future, access_token, response):
"""Invoked as a callback when self.github_request returns the response
to the request for user data.
:param method future: The callback method to pass along
:param str access_token: The access token for the user's use
:p... | [
"def",
"_on_github_user",
"(",
"self",
",",
"future",
",",
"access_token",
",",
"response",
")",
":",
"response",
"[",
"'access_token'",
"]",
"=",
"access_token",
"future",
".",
"set_result",
"(",
"response",
")"
] | 41.818182 | 17 |
def main(args=None):
"""Call the CLI interface and wait for the result."""
retcode = 0
try:
ci = CliInterface()
args = ci.parser.parse_args()
result = args.func(args)
if result is not None:
print(result)
retcode = 0
except Exception:
retcode = ... | [
"def",
"main",
"(",
"args",
"=",
"None",
")",
":",
"retcode",
"=",
"0",
"try",
":",
"ci",
"=",
"CliInterface",
"(",
")",
"args",
"=",
"ci",
".",
"parser",
".",
"parse_args",
"(",
")",
"result",
"=",
"args",
".",
"func",
"(",
"args",
")",
"if",
... | 25.714286 | 15.5 |
def _home_assistant_config(self):
""" Creates home assistant configuration for the known devices """
devices = {}
for scs_id, dev in self._devices.items():
devices[dev['ha_id']] = {
'name': dev['name'],
'scs_id': scs_id}
return {'devices': dev... | [
"def",
"_home_assistant_config",
"(",
"self",
")",
":",
"devices",
"=",
"{",
"}",
"for",
"scs_id",
",",
"dev",
"in",
"self",
".",
"_devices",
".",
"items",
"(",
")",
":",
"devices",
"[",
"dev",
"[",
"'ha_id'",
"]",
"]",
"=",
"{",
"'name'",
":",
"de... | 35.222222 | 10.555556 |
def also_restrict_to(self, restriction):
"""
Works like restict_to but offers an additional restriction. Playbooks use this
to implement serial behavior.
"""
if type(restriction) != list:
restriction = [ restriction ]
self._also_restriction = restriction | [
"def",
"also_restrict_to",
"(",
"self",
",",
"restriction",
")",
":",
"if",
"type",
"(",
"restriction",
")",
"!=",
"list",
":",
"restriction",
"=",
"[",
"restriction",
"]",
"self",
".",
"_also_restriction",
"=",
"restriction"
] | 38.5 | 7.25 |
def round_array(array_in):
"""
arr_out = round_array(array_in)
Rounds an array and recasts it to int. Also works on scalars.
"""
if isinstance(array_in, ndarray):
return np.round(array_in).astype(int)
else:
return int(np.round(array_in)) | [
"def",
"round_array",
"(",
"array_in",
")",
":",
"if",
"isinstance",
"(",
"array_in",
",",
"ndarray",
")",
":",
"return",
"np",
".",
"round",
"(",
"array_in",
")",
".",
"astype",
"(",
"int",
")",
"else",
":",
"return",
"int",
"(",
"np",
".",
"round",... | 26.9 | 12.5 |
def get_ports(device_owners=None, vnic_type=None, port_id=None, active=True):
"""Returns list of all ports in neutron the db"""
session = db.get_reader_session()
with session.begin():
port_model = models_v2.Port
ports = (session
.query(port_model)
.filter_un... | [
"def",
"get_ports",
"(",
"device_owners",
"=",
"None",
",",
"vnic_type",
"=",
"None",
",",
"port_id",
"=",
"None",
",",
"active",
"=",
"True",
")",
":",
"session",
"=",
"db",
".",
"get_reader_session",
"(",
")",
"with",
"session",
".",
"begin",
"(",
")... | 42 | 15.909091 |
def process(self):
"""Execute the grep command"""
for _, path in self.state.input:
log_file_path = os.path.join(self._output_path, 'grepper.log')
print('Log file: {0:s}'.format(log_file_path))
print('Walking through dir (absolute) = ' + os.path.abspath(path))
try:
for root, _, ... | [
"def",
"process",
"(",
"self",
")",
":",
"for",
"_",
",",
"path",
"in",
"self",
".",
"state",
".",
"input",
":",
"log_file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_output_path",
",",
"'grepper.log'",
")",
"print",
"(",
"'Log fi... | 41.4 | 18.028571 |
def list_group_members(self, group_url, max_results=0):
''' a method to retrieve a list of members for a meetup group
:param group_url: string with meetup urlname for group
:param max_results: [optional] integer with number of members to include
:return: dictionary with list of m... | [
"def",
"list_group_members",
"(",
"self",
",",
"group_url",
",",
"max_results",
"=",
"0",
")",
":",
"# https://www.meetup.com/meetup_api/docs/:urlname/members/#list\r",
"title",
"=",
"'%s.list_group_members'",
"%",
"self",
".",
"__class__",
".",
"__name__",
"# validate in... | 35.06383 | 24.510638 |
def heightmap_add_voronoi(
hm: np.ndarray,
nbPoints: Any,
nbCoef: int,
coef: Sequence[float],
rnd: Optional[tcod.random.Random] = None,
) -> None:
"""Add values from a Voronoi diagram to the heightmap.
Args:
hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
... | [
"def",
"heightmap_add_voronoi",
"(",
"hm",
":",
"np",
".",
"ndarray",
",",
"nbPoints",
":",
"Any",
",",
"nbCoef",
":",
"int",
",",
"coef",
":",
"Sequence",
"[",
"float",
"]",
",",
"rnd",
":",
"Optional",
"[",
"tcod",
".",
"random",
".",
"Random",
"]"... | 34.034483 | 18.344828 |
def use(**kwargs):
"""
Updates the active resource configuration to the passed
keyword arguments.
Invoking this method without passing arguments will just return the
active resource configuration.
@returns
The previous configuration.
"""
config = dict(use.config)
use.config... | [
"def",
"use",
"(",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"dict",
"(",
"use",
".",
"config",
")",
"use",
".",
"config",
".",
"update",
"(",
"kwargs",
")",
"return",
"config"
] | 24.285714 | 18.142857 |
def translate_pname(self, pname: PrefName, mid: ModuleId) -> QualName:
"""Translate a prefixed name to a qualified name.
Args:
pname: Name with an optional prefix.
mid: Identifier of the module in which `pname` appears.
Raises:
ModuleNotRegistered: If `mid` is... | [
"def",
"translate_pname",
"(",
"self",
",",
"pname",
":",
"PrefName",
",",
"mid",
":",
"ModuleId",
")",
"->",
"QualName",
":",
"loc",
",",
"nid",
"=",
"self",
".",
"resolve_pname",
"(",
"pname",
",",
"mid",
")",
"return",
"(",
"loc",
",",
"self",
"."... | 47.909091 | 18.454545 |
def set_servo_speed(self, goalspeed, led):
""" Set the Herkulex in continuous rotation mode
Args:
goalspeed (int): the speed , range -1023 to 1023
led (int): the LED color
0x00 LED off
0x04 GREEN
0x08 BLUE
... | [
"def",
"set_servo_speed",
"(",
"self",
",",
"goalspeed",
",",
"led",
")",
":",
"if",
"goalspeed",
">",
"0",
":",
"goalspeed_msb",
"=",
"(",
"int",
"(",
"goalspeed",
")",
"&",
"0xFF00",
")",
">>",
"8",
"goalspeed_lsb",
"=",
"int",
"(",
"goalspeed",
")",... | 30.645161 | 14.741935 |
def closest_common_ancestor(self, other):
"""
Find the common ancestor between this history node and 'other'.
:param other: the PathHistory to find a common ancestor with.
:return: the common ancestor SimStateHistory, or None if there isn't one
"""
our_history_... | [
"def",
"closest_common_ancestor",
"(",
"self",
",",
"other",
")",
":",
"our_history_iter",
"=",
"reversed",
"(",
"HistoryIter",
"(",
"self",
")",
")",
"their_history_iter",
"=",
"reversed",
"(",
"HistoryIter",
"(",
"other",
")",
")",
"sofar",
"=",
"set",
"("... | 34.131579 | 15.973684 |
def has_hardware_breakpoint(self, dwThreadId, address):
"""
Checks if a hardware breakpoint is defined at the given address.
@see:
L{define_hardware_breakpoint},
L{get_hardware_breakpoint},
L{erase_hardware_breakpoint},
L{enable_hardware_breakpoin... | [
"def",
"has_hardware_breakpoint",
"(",
"self",
",",
"dwThreadId",
",",
"address",
")",
":",
"if",
"dwThreadId",
"in",
"self",
".",
"__hardwareBP",
":",
"bpSet",
"=",
"self",
".",
"__hardwareBP",
"[",
"dwThreadId",
"]",
"for",
"bp",
"in",
"bpSet",
":",
"if"... | 32.814815 | 15.037037 |
def cmd_repeat(self, args):
'''repeat a command at regular intervals'''
if len(args) == 0:
if len(self.repeats) == 0:
print("No repeats")
return
for i in range(len(self.repeats)):
print("%u: %s" % (i, self.repeats[i]))
r... | [
"def",
"cmd_repeat",
"(",
"self",
",",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"0",
":",
"if",
"len",
"(",
"self",
".",
"repeats",
")",
"==",
"0",
":",
"print",
"(",
"\"No repeats\"",
")",
"return",
"for",
"i",
"in",
"range",
"(",
... | 35.142857 | 13.571429 |
async def _do_tp(self, pip, mount) -> top_types.Point:
""" Execute the work of tip probe.
This is a separate function so that it can be encapsulated in
a context manager that ensures the state of the pipette tip tracking
is reset properly. It should not be called outside of
:py:... | [
"async",
"def",
"_do_tp",
"(",
"self",
",",
"pip",
",",
"mount",
")",
"->",
"top_types",
".",
"Point",
":",
"# Clear the old offset during calibration",
"pip",
".",
"update_instrument_offset",
"(",
"top_types",
".",
"Point",
"(",
")",
")",
"# Hotspots based on our... | 47.96 | 16.533333 |
def _runargs(argstring):
""" Entrypoint for debugging
"""
import shlex
parser = cli.make_arg_parser()
args = parser.parse_args(shlex.split(argstring))
run(args) | [
"def",
"_runargs",
"(",
"argstring",
")",
":",
"import",
"shlex",
"parser",
"=",
"cli",
".",
"make_arg_parser",
"(",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
"shlex",
".",
"split",
"(",
"argstring",
")",
")",
"run",
"(",
"args",
")"
] | 25.428571 | 12.142857 |
def parse_attribute(tokens, is_merc):
""" Parse a token stream from inside an attribute selector.
Enter this function after a left-bracket is found:
http://www.w3.org/TR/CSS2/selector.html#attribute-selectors
"""
#
# Local helper functions
#
def next_scalar(tokens, op):
... | [
"def",
"parse_attribute",
"(",
"tokens",
",",
"is_merc",
")",
":",
"#",
"# Local helper functions",
"#",
"def",
"next_scalar",
"(",
"tokens",
",",
"op",
")",
":",
"\"\"\" Look for a scalar value just after an attribute selector operator.\n \"\"\"",
"while",
"True",
... | 38.931034 | 19.232759 |
def traverse(obj, *path, **kwargs):
"""
Traverse the object we receive with the given path. Path
items can be either strings or lists of strings (or any
nested combination thereof). Behavior in given cases is
laid out line by line below.
"""
if path:
if isinstance(obj, list) or isins... | [
"def",
"traverse",
"(",
"obj",
",",
"*",
"path",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"path",
":",
"if",
"isinstance",
"(",
"obj",
",",
"list",
")",
"or",
"isinstance",
"(",
"obj",
",",
"tuple",
")",
":",
"#If the current state of the object received... | 48.448276 | 16.793103 |
def write_single_coil(slave_id, address, value):
""" Return ADU for Modbus function code 05: Write Single Coil.
:param slave_id: Number of slave.
:return: Byte array with ADU.
"""
function = WriteSingleCoil()
function.address = address
function.value = value
return _create_request_adu(... | [
"def",
"write_single_coil",
"(",
"slave_id",
",",
"address",
",",
"value",
")",
":",
"function",
"=",
"WriteSingleCoil",
"(",
")",
"function",
".",
"address",
"=",
"address",
"function",
".",
"value",
"=",
"value",
"return",
"_create_request_adu",
"(",
"slave_... | 31 | 13.818182 |
def _gen_headers(self, bearer, url):
'''
Generate headders, adding in Oauth2 bearer token if present
'''
headers = {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": ("en;q=1, fr;q=0.9, de;q=0.8, ja;q=0.7, " +
... | [
"def",
"_gen_headers",
"(",
"self",
",",
"bearer",
",",
"url",
")",
":",
"headers",
"=",
"{",
"\"Accept\"",
":",
"\"*/*\"",
",",
"\"Accept-Encoding\"",
":",
"\"gzip, deflate\"",
",",
"\"Accept-Language\"",
":",
"(",
"\"en;q=1, fr;q=0.9, de;q=0.8, ja;q=0.7, \"",
"+",... | 42.578947 | 24.263158 |
def turbulent_Petukhov_Kirillov_Popov(Re=None, Pr=None, fd=None):
r'''Calculates internal convection Nusselt number for turbulent flows
in pipe according to [2]_ and [3]_ as in [1]_.
.. math::
Nu = \frac{(f/8)RePr}{C+12.7(f/8)^{1/2}(Pr^{2/3}-1)}\\
C = 1.07 + 900/Re - [0.63/(1+10Pr)]
Pa... | [
"def",
"turbulent_Petukhov_Kirillov_Popov",
"(",
"Re",
"=",
"None",
",",
"Pr",
"=",
"None",
",",
"fd",
"=",
"None",
")",
":",
"C",
"=",
"1.07",
"+",
"900.",
"/",
"Re",
"-",
"(",
"0.63",
"/",
"(",
"1.",
"+",
"10.",
"*",
"Pr",
")",
")",
"return",
... | 31.704545 | 26.431818 |
def requires_roles(roles):
"""
Decorator for :class:`ModelView` views that limits access to the specified
roles.
"""
def inner(f):
def is_available_here(context):
return bool(roles.intersection(context.obj.current_roles))
def is_available(context):
result = i... | [
"def",
"requires_roles",
"(",
"roles",
")",
":",
"def",
"inner",
"(",
"f",
")",
":",
"def",
"is_available_here",
"(",
"context",
")",
":",
"return",
"bool",
"(",
"roles",
".",
"intersection",
"(",
"context",
".",
"obj",
".",
"current_roles",
")",
")",
... | 32.814815 | 16.740741 |
def additions_remove(**kwargs):
'''
Remove VirtualBox Guest Additions.
Firstly it tries to uninstall itself by executing
'/opt/VBoxGuestAdditions-VERSION/uninstall.run uninstall'.
It uses the CD, connected by VirtualBox if it failes.
CLI Example:
.. code-block:: bash
salt '*' vbo... | [
"def",
"additions_remove",
"(",
"*",
"*",
"kwargs",
")",
":",
"kernel",
"=",
"__grains__",
".",
"get",
"(",
"'kernel'",
",",
"''",
")",
"if",
"kernel",
"==",
"'Linux'",
":",
"ret",
"=",
"_additions_remove_linux",
"(",
")",
"if",
"not",
"ret",
":",
"ret... | 28.461538 | 22.538462 |
def create(cls, session, attributes=None, relationships=None):
"""Create a resource of the resource.
This should only be called from sub-classes
Args:
session(Session): The session to create the resource in.
attributes(dict): Any attributes that are valid for the
... | [
"def",
"create",
"(",
"cls",
",",
"session",
",",
"attributes",
"=",
"None",
",",
"relationships",
"=",
"None",
")",
":",
"resource_type",
"=",
"cls",
".",
"_resource_type",
"(",
")",
"resource_path",
"=",
"cls",
".",
"_resource_path",
"(",
")",
"url",
"... | 33.035714 | 21.392857 |
def data(self, *args):
'''Add or retrieve data values for this :class:`Html`.'''
data = self._data
if not args:
return data or {}
result, adding = self._attrdata('data', *args)
if adding:
if data is None:
self._extra['data'] = {}
... | [
"def",
"data",
"(",
"self",
",",
"*",
"args",
")",
":",
"data",
"=",
"self",
".",
"_data",
"if",
"not",
"args",
":",
"return",
"data",
"or",
"{",
"}",
"result",
",",
"adding",
"=",
"self",
".",
"_attrdata",
"(",
"'data'",
",",
"*",
"args",
")",
... | 32.266667 | 13.6 |
def get_logger(self):
"""
Returns the standard logger
"""
if Global.LOGGER:
Global.LOGGER.debug('configuring a logger')
if self._logger_instance is not None:
return self._logger_instance
self._logger_instance = logging.getLogger("flowsLogger")
... | [
"def",
"get_logger",
"(",
"self",
")",
":",
"if",
"Global",
".",
"LOGGER",
":",
"Global",
".",
"LOGGER",
".",
"debug",
"(",
"'configuring a logger'",
")",
"if",
"self",
".",
"_logger_instance",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_logger_inst... | 35.217391 | 18.869565 |
def diff_move(self,v,new_comm):
""" Calculate the difference in the quality function if node ``v`` is
moved to community ``new_comm``.
Parameters
----------
v
The node to move.
new_comm
The community to move to.
Returns
-------
float
Difference in quality functio... | [
"def",
"diff_move",
"(",
"self",
",",
"v",
",",
"new_comm",
")",
":",
"return",
"_c_louvain",
".",
"_MutableVertexPartition_diff_move",
"(",
"self",
".",
"_partition",
",",
"v",
",",
"new_comm",
")"
] | 30.552632 | 24.552632 |
def svg_to_path(file_obj, file_type=None):
"""
Load an SVG file into a Path2D object.
Parameters
-----------
file_obj : open file object
Contains SVG data
file_type: None
Not used
Returns
-----------
loaded : dict
With kwargs for Path2D constructor
"""
de... | [
"def",
"svg_to_path",
"(",
"file_obj",
",",
"file_type",
"=",
"None",
")",
":",
"def",
"element_transform",
"(",
"e",
",",
"max_depth",
"=",
"100",
")",
":",
"\"\"\"\n Find a transformation matrix for an XML element.\n \"\"\"",
"matrices",
"=",
"[",
"]",... | 25.076923 | 15.846154 |
def from_keras(cls, model, bounds, input_shape=None,
channel_axis=3, preprocessing=(0, 1)):
"""Alternative constructor for a TensorFlowModel that
accepts a `tf.keras.Model` instance.
Parameters
----------
model : `tensorflow.keras.Model`
A `tensorf... | [
"def",
"from_keras",
"(",
"cls",
",",
"model",
",",
"bounds",
",",
"input_shape",
"=",
"None",
",",
"channel_axis",
"=",
"3",
",",
"preprocessing",
"=",
"(",
"0",
",",
"1",
")",
")",
":",
"import",
"tensorflow",
"as",
"tf",
"if",
"input_shape",
"is",
... | 45.263158 | 18.684211 |
def parse_args(self):
"""Parse CLI args."""
Args(self.tcex.parser)
self.args = self.tcex.args | [
"def",
"parse_args",
"(",
"self",
")",
":",
"Args",
"(",
"self",
".",
"tcex",
".",
"parser",
")",
"self",
".",
"args",
"=",
"self",
".",
"tcex",
".",
"args"
] | 28.5 | 8.75 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.