text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def timed_call(self, ms, callback, *args, **kwargs):
""" Invoke a callable on the main event loop thread at a
specified time in the future.
Parameters
----------
ms : int
The time to delay, in milliseconds, before executing the
callable.
callback... | [
"def",
"timed_call",
"(",
"self",
",",
"ms",
",",
"callback",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"loop",
".",
"timed_call",
"(",
"ms",
",",
"callback",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 30.894737 | 22.210526 |
def do_it(self, dbg):
''' Converts request into python variable '''
try:
try:
# don't trace new threads created by console command
disable_trace_thread_modules()
result = pydevconsole.console_exec(self.thread_id, self.frame_id, self.expression... | [
"def",
"do_it",
"(",
"self",
",",
"dbg",
")",
":",
"try",
":",
"try",
":",
"# don't trace new threads created by console command",
"disable_trace_thread_modules",
"(",
")",
"result",
"=",
"pydevconsole",
".",
"console_exec",
"(",
"self",
".",
"thread_id",
",",
"se... | 41.913043 | 22.434783 |
def get_conn(self):
"""
Retrieves connection to Cloud Vision.
:return: Google Cloud Vision client object.
:rtype: google.cloud.vision_v1.ProductSearchClient
"""
if not self._client:
self._client = ProductSearchClient(credentials=self._get_credentials())
... | [
"def",
"get_conn",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_client",
":",
"self",
".",
"_client",
"=",
"ProductSearchClient",
"(",
"credentials",
"=",
"self",
".",
"_get_credentials",
"(",
")",
")",
"return",
"self",
".",
"_client"
] | 33.3 | 16.3 |
def stringify_device_meta(device_object):
""" Input: Portals device object.
Output: The same device object with the device meta
converted to a python string. """
try:
if isinstance(device_object['info']['description']['meta'], dict):
device_object['info']['description... | [
"def",
"stringify_device_meta",
"(",
"device_object",
")",
":",
"try",
":",
"if",
"isinstance",
"(",
"device_object",
"[",
"'info'",
"]",
"[",
"'description'",
"]",
"[",
"'meta'",
"]",
",",
"dict",
")",
":",
"device_object",
"[",
"'info'",
"]",
"[",
"'desc... | 45 | 15.181818 |
def str_to_bool(value):
"""
Converts string truthy/falsey strings to a bool
Empty strings are false
"""
if isinstance(value, basestring):
value = value.strip().lower()
if value in ['true', 't', 'yes', 'y']:
return True
elif value in ['false', 'f', 'no', 'n', '']:
... | [
"def",
"str_to_bool",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"basestring",
")",
":",
"value",
"=",
"value",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"if",
"value",
"in",
"[",
"'true'",
",",
"'t'",
",",
"'yes'",
",",
... | 28.466667 | 14.2 |
def save_or_update(self, cluster):
"""Save or update the cluster to persistent state.
:param cluster: cluster to save or update
:type cluster: :py:class:`elasticluster.cluster.Cluster`
"""
if not os.path.exists(self.storage_path):
os.makedirs(self.storage_path)
... | [
"def",
"save_or_update",
"(",
"self",
",",
"cluster",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"storage_path",
")",
":",
"os",
".",
"makedirs",
"(",
"self",
".",
"storage_path",
")",
"path",
"=",
"self",
".",
"_get_c... | 37 | 12 |
def async_process(fn):
""" Decorator function to launch a function as a separate process """
def run(*args, **kwargs):
proc = mp.Process(target=fn, args=args, kwargs=kwargs)
proc.start()
return proc
return run | [
"def",
"async_process",
"(",
"fn",
")",
":",
"def",
"run",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"proc",
"=",
"mp",
".",
"Process",
"(",
"target",
"=",
"fn",
",",
"args",
"=",
"args",
",",
"kwargs",
"=",
"kwargs",
")",
"proc",
".... | 26.555556 | 22 |
def run(self, command, variables=[], board=None, packages=[]):
"""Executes scons for building"""
# -- Check for the SConstruct file
if not isfile(util.safe_join(util.get_project_dir(), 'SConstruct')):
variables += ['-f']
variables += [util.safe_join(
util... | [
"def",
"run",
"(",
"self",
",",
"command",
",",
"variables",
"=",
"[",
"]",
",",
"board",
"=",
"None",
",",
"packages",
"=",
"[",
"]",
")",
":",
"# -- Check for the SConstruct file",
"if",
"not",
"isfile",
"(",
"util",
".",
"safe_join",
"(",
"util",
".... | 36.384615 | 16.576923 |
async def get_details(self):
"""Get machine details information.
:returns: Mapping of hardware details.
"""
data = await self._handler.details(system_id=self.system_id)
return bson.decode_all(data)[0] | [
"async",
"def",
"get_details",
"(",
"self",
")",
":",
"data",
"=",
"await",
"self",
".",
"_handler",
".",
"details",
"(",
"system_id",
"=",
"self",
".",
"system_id",
")",
"return",
"bson",
".",
"decode_all",
"(",
"data",
")",
"[",
"0",
"]"
] | 33.571429 | 12.428571 |
def new_graph(self, name, data=None, **attr):
"""Return a new instance of type Graph, initialized with the given
data if provided.
:arg name: a name for the graph
:arg data: dictionary or NetworkX graph object providing initial state
"""
self._init_graph(name, 'Graph')
... | [
"def",
"new_graph",
"(",
"self",
",",
"name",
",",
"data",
"=",
"None",
",",
"*",
"*",
"attr",
")",
":",
"self",
".",
"_init_graph",
"(",
"name",
",",
"'Graph'",
")",
"g",
"=",
"Graph",
"(",
"self",
",",
"name",
",",
"data",
",",
"*",
"*",
"att... | 33.666667 | 14.416667 |
def mountain_car_trajectories(num_traj):
'''Collect data using random hard-coded policies on MountainCar.
num_traj : int, number of trajectories to collect
Returns (trajectories, traces)
'''
domain = MountainCar()
slopes = np.random.normal(0, 0.01, size=num_traj)
v0s = np.random.normal(0, 0.005, size=nu... | [
"def",
"mountain_car_trajectories",
"(",
"num_traj",
")",
":",
"domain",
"=",
"MountainCar",
"(",
")",
"slopes",
"=",
"np",
".",
"random",
".",
"normal",
"(",
"0",
",",
"0.01",
",",
"size",
"=",
"num_traj",
")",
"v0s",
"=",
"np",
".",
"random",
".",
... | 34.4 | 17.866667 |
def git_pull(repo_dir, remote="origin", ref=None, update_head_ok=False):
"""Do a git pull of `ref` from `remote`."""
command = ['git', 'pull']
if update_head_ok:
command.append('--update-head-ok')
command.append(pipes.quote(remote))
if ref:
command.append(ref)
return execute_git_... | [
"def",
"git_pull",
"(",
"repo_dir",
",",
"remote",
"=",
"\"origin\"",
",",
"ref",
"=",
"None",
",",
"update_head_ok",
"=",
"False",
")",
":",
"command",
"=",
"[",
"'git'",
",",
"'pull'",
"]",
"if",
"update_head_ok",
":",
"command",
".",
"append",
"(",
... | 38.555556 | 13.777778 |
def task_list(task_array):
"""Return a task list.
The task_array should be 2-dimensional; the first item should be the task
text, and the second the boolean completion state.
>>> task_list([["Be born", True], ["Be dead", False]])
'- [X] Be born\\n- [ ] Be dead'
When displayed using `print`, t... | [
"def",
"task_list",
"(",
"task_array",
")",
":",
"tasks",
"=",
"[",
"]",
"for",
"item",
",",
"completed",
"in",
"task_array",
":",
"task",
"=",
"\"- [ ] \"",
"+",
"esc_format",
"(",
"item",
")",
"if",
"completed",
":",
"task",
"=",
"task",
"[",
":",
... | 28.142857 | 18.095238 |
def flush(self):
"""Flush message queue if there's an active connection running"""
self._pending_flush = False
if self.handler is None or not self.handler.active or not self.send_queue:
return
self.handler.send_pack('a[%s]' % self.send_queue)
self.send_queue = '' | [
"def",
"flush",
"(",
"self",
")",
":",
"self",
".",
"_pending_flush",
"=",
"False",
"if",
"self",
".",
"handler",
"is",
"None",
"or",
"not",
"self",
".",
"handler",
".",
"active",
"or",
"not",
"self",
".",
"send_queue",
":",
"return",
"self",
".",
"h... | 34.333333 | 22.444444 |
def _run_eos_cmds(self, commands, commands_to_log=None):
"""Execute/sends a CAPI (Command API) command to EOS.
In this method, list of commands is appended with prefix and
postfix commands - to make is understandble by EOS.
:param commands : List of command to be executed on EOS.
... | [
"def",
"_run_eos_cmds",
"(",
"self",
",",
"commands",
",",
"commands_to_log",
"=",
"None",
")",
":",
"# Always figure out who is master (starting with the last known val)",
"try",
":",
"if",
"self",
".",
"_get_eos_master",
"(",
")",
"is",
"None",
":",
"msg",
"=",
... | 40.166667 | 18.97619 |
def _RunScript(self, script):
"""Run a script and log the streamed script output.
Args:
script: string, the file location of an executable script.
"""
process = subprocess.Popen(
script, shell=True, stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
while True:
for line in iter(p... | [
"def",
"_RunScript",
"(",
"self",
",",
"script",
")",
":",
"process",
"=",
"subprocess",
".",
"Popen",
"(",
"script",
",",
"shell",
"=",
"True",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
")",
"while... | 34.461538 | 18.461538 |
def calcdelay(self, ant1, ant2, skyfreq, pol):
""" Calculates the relative delay (d1-d2) for a pair of antennas in ns.
"""
select = self.select[n.where( (self.skyfreq[self.select] == skyfreq) & (self.polarization[self.select] == pol) )[0]]
ind1 = n.where(ant1 == self.antnum[select])
... | [
"def",
"calcdelay",
"(",
"self",
",",
"ant1",
",",
"ant2",
",",
"skyfreq",
",",
"pol",
")",
":",
"select",
"=",
"self",
".",
"select",
"[",
"n",
".",
"where",
"(",
"(",
"self",
".",
"skyfreq",
"[",
"self",
".",
"select",
"]",
"==",
"skyfreq",
")"... | 37.857143 | 18.857143 |
def start(builtins=False, profile_threads=True):
"""Starts profiling all threads and all greenlets.
This function can be called from any thread at any time.
Resumes profiling if stop() was called previously.
* `builtins`: Profile builtin functions used by standart Python modules.
* `profile_thread... | [
"def",
"start",
"(",
"builtins",
"=",
"False",
",",
"profile_threads",
"=",
"True",
")",
":",
"# TODO: what about builtins False or profile_threads False?",
"_vendorized_yappi",
".",
"yappi",
".",
"set_context_id_callback",
"(",
"lambda",
":",
"greenlet",
"and",
"id",
... | 42.444444 | 23.388889 |
def recv_rpc(self, context, payload):
"""Call from any thread"""
logger.debug("Adding RPC payload to ControlBuffer queue: %s", payload)
self.buf.put(('rpc', (context, payload)))
with self.cv:
self.cv.notifyAll() | [
"def",
"recv_rpc",
"(",
"self",
",",
"context",
",",
"payload",
")",
":",
"logger",
".",
"debug",
"(",
"\"Adding RPC payload to ControlBuffer queue: %s\"",
",",
"payload",
")",
"self",
".",
"buf",
".",
"put",
"(",
"(",
"'rpc'",
",",
"(",
"context",
",",
"p... | 41.666667 | 13 |
def exit_statistics(hostname, start_time, count_sent, count_received, min_time, avg_time, max_time, deviation):
"""
Print ping exit statistics
"""
end_time = datetime.datetime.now()
duration = end_time - start_time
duration_sec = float(duration.seconds * 1000)
duration_ms = float(duration.mi... | [
"def",
"exit_statistics",
"(",
"hostname",
",",
"start_time",
",",
"count_sent",
",",
"count_received",
",",
"min_time",
",",
"avg_time",
",",
"max_time",
",",
"deviation",
")",
":",
"end_time",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"durati... | 46.217391 | 24.043478 |
def prepare(self):
"""Prepare for monitoring - install agents etc"""
# Parse config
agent_configs = []
if self.config:
agent_configs = self.config_manager.getconfig(
self.config, self.default_target)
# Creating agent for hosts
for config in a... | [
"def",
"prepare",
"(",
"self",
")",
":",
"# Parse config",
"agent_configs",
"=",
"[",
"]",
"if",
"self",
".",
"config",
":",
"agent_configs",
"=",
"self",
".",
"config_manager",
".",
"getconfig",
"(",
"self",
".",
"config",
",",
"self",
".",
"default_targe... | 43.038462 | 19 |
def sort_query(self, query, sort_info):
"""Sort query according to jsonapi 1.0
:param Query query: sqlalchemy query to sort
:param list sort_info: sort information
:return Query: the sorted query
"""
for sort_opt in sort_info:
field = sort_opt['field']
... | [
"def",
"sort_query",
"(",
"self",
",",
"query",
",",
"sort_info",
")",
":",
"for",
"sort_opt",
"in",
"sort_info",
":",
"field",
"=",
"sort_opt",
"[",
"'field'",
"]",
"if",
"not",
"hasattr",
"(",
"self",
".",
"model",
",",
"field",
")",
":",
"raise",
... | 42.846154 | 15.538462 |
def select_profile(self, index):
"""Select a given profile by index.
Slot for when profile is selected.
:param index: The selected item's index
:type index: int
"""
new_profile = self.profile_combo.itemText(index)
self.resources_list.clear()
self.minimum... | [
"def",
"select_profile",
"(",
"self",
",",
"index",
")",
":",
"new_profile",
"=",
"self",
".",
"profile_combo",
".",
"itemText",
"(",
"index",
")",
"self",
".",
"resources_list",
".",
"clear",
"(",
")",
"self",
".",
"minimum_needs",
".",
"load_profile",
"(... | 31.857143 | 11.571429 |
def calc_gradient(beta,
design,
alt_IDs,
rows_to_obs,
rows_to_alts,
choice_vector,
utility_transform,
transform_first_deriv_c,
transform_first_deriv_v,
transf... | [
"def",
"calc_gradient",
"(",
"beta",
",",
"design",
",",
"alt_IDs",
",",
"rows_to_obs",
",",
"rows_to_alts",
",",
"choice_vector",
",",
"utility_transform",
",",
"transform_first_deriv_c",
",",
"transform_first_deriv_v",
",",
"transform_deriv_alpha",
",",
"intercept_par... | 51.639594 | 23.964467 |
def listen(self, timeout=10):
"""
Listen for incoming messages. Timeout is used to check if the server must be switched off.
:param timeout: Socket Timeout in seconds
"""
self._socket.settimeout(float(timeout))
while not self.stopped.isSet():
try:
... | [
"def",
"listen",
"(",
"self",
",",
"timeout",
"=",
"10",
")",
":",
"self",
".",
"_socket",
".",
"settimeout",
"(",
"float",
"(",
"timeout",
")",
")",
"while",
"not",
"self",
".",
"stopped",
".",
"isSet",
"(",
")",
":",
"try",
":",
"data",
",",
"c... | 47.709677 | 21.096774 |
def select(self, selector):
"""
Like :meth:`find_all`, but takes a CSS selector string as input.
"""
op = operator.methodcaller('select', selector)
return self._wrap_multi(op) | [
"def",
"select",
"(",
"self",
",",
"selector",
")",
":",
"op",
"=",
"operator",
".",
"methodcaller",
"(",
"'select'",
",",
"selector",
")",
"return",
"self",
".",
"_wrap_multi",
"(",
"op",
")"
] | 35 | 10.666667 |
def get_conn(self):
"""
Retrieves connection to Cloud Speech.
:return: Google Cloud Speech client object.
:rtype: google.cloud.speech_v1.SpeechClient
"""
if not self._client:
self._client = SpeechClient(credentials=self._get_credentials())
return self... | [
"def",
"get_conn",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_client",
":",
"self",
".",
"_client",
"=",
"SpeechClient",
"(",
"credentials",
"=",
"self",
".",
"_get_credentials",
"(",
")",
")",
"return",
"self",
".",
"_client"
] | 31.9 | 14.9 |
def run_transaction(self, command_list, do_commit=True):
'''This can be used to stage multiple commands and roll back the transaction if an error occurs. This is useful
if you want to remove multiple records in multiple tables for one entity but do not want the deletion to occur
if the e... | [
"def",
"run_transaction",
"(",
"self",
",",
"command_list",
",",
"do_commit",
"=",
"True",
")",
":",
"pass",
"# I decided against creating this for now.",
"# It may be more useful to create a stored procedure like in e.g. _create_protein_deletion_stored_procedure",
"# in the DDGadmin p... | 59.285714 | 39.380952 |
def get(self, name):
"""Get variable `name` from MATLAB workspace.
Parameters
----------
name : str
Name of the variable in MATLAB workspace.
Returns
-------
array_like
Value of the variable `name`.
"""
pm = self._libeng.... | [
"def",
"get",
"(",
"self",
",",
"name",
")",
":",
"pm",
"=",
"self",
".",
"_libeng",
".",
"engGetVariable",
"(",
"self",
".",
"_ep",
",",
"name",
")",
"out",
"=",
"mxarray_to_ndarray",
"(",
"self",
".",
"_libmx",
",",
"pm",
")",
"self",
".",
"_libm... | 20.045455 | 22.772727 |
def to_python(self):
"""The string ``'True'`` (case insensitive) will be converted
to ``True``, as will any positive integers.
"""
if isinstance(self.data, str):
return self.data.strip().lower() == 'true'
if isinstance(self.data, int):
return self.data > ... | [
"def",
"to_python",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"data",
",",
"str",
")",
":",
"return",
"self",
".",
"data",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"==",
"'true'",
"if",
"isinstance",
"(",
"self",
".",
"d... | 34.3 | 10.7 |
def delete(self):
"""Remove this resource or collection (recursive).
See DAVResource.delete()
"""
if self.provider.readonly:
raise DAVError(HTTP_FORBIDDEN)
shutil.rmtree(self._file_path, ignore_errors=False)
self.remove_all_properties(True)
self.remov... | [
"def",
"delete",
"(",
"self",
")",
":",
"if",
"self",
".",
"provider",
".",
"readonly",
":",
"raise",
"DAVError",
"(",
"HTTP_FORBIDDEN",
")",
"shutil",
".",
"rmtree",
"(",
"self",
".",
"_file_path",
",",
"ignore_errors",
"=",
"False",
")",
"self",
".",
... | 32.8 | 10.3 |
def __add_query_comment(sql):
"""
Adds a comment line to the query to be executed containing the line number of the calling
function. This is useful for debugging slow queries, as the comment will show in the slow
query log
@type sql: str
@param sql: sql needing comment... | [
"def",
"__add_query_comment",
"(",
"sql",
")",
":",
"# Inspect the call stack for the originating call",
"file_name",
"=",
"''",
"line_number",
"=",
"''",
"caller_frames",
"=",
"inspect",
".",
"getouterframes",
"(",
"inspect",
".",
"currentframe",
"(",
")",
")",
"fo... | 37.181818 | 20.727273 |
async def check_ping_timeout(self):
"""Make sure the client is still sending pings.
This helps detect disconnections for long-polling clients.
"""
if self.closed:
raise exceptions.SocketIsClosedError()
if time.time() - self.last_ping > self.server.ping_interval + 5:
... | [
"async",
"def",
"check_ping_timeout",
"(",
"self",
")",
":",
"if",
"self",
".",
"closed",
":",
"raise",
"exceptions",
".",
"SocketIsClosedError",
"(",
")",
"if",
"time",
".",
"time",
"(",
")",
"-",
"self",
".",
"last_ping",
">",
"self",
".",
"server",
... | 45.1875 | 18.4375 |
def summary(self):
"""Get Crates.io summary"""
path = urijoin(CRATES_API_URL, CATEGORY_SUMMARY)
raw_content = self.fetch(path)
return raw_content | [
"def",
"summary",
"(",
"self",
")",
":",
"path",
"=",
"urijoin",
"(",
"CRATES_API_URL",
",",
"CATEGORY_SUMMARY",
")",
"raw_content",
"=",
"self",
".",
"fetch",
"(",
"path",
")",
"return",
"raw_content"
] | 24.714286 | 19.142857 |
def _get_model_cost(self, formula, model):
"""
Given a WCNF formula and a model, the method computes the MaxSAT
cost of the model, i.e. the sum of weights of soft clauses that are
unsatisfied by the model.
:param formula: an input MaxSAT formula
:para... | [
"def",
"_get_model_cost",
"(",
"self",
",",
"formula",
",",
"model",
")",
":",
"model_set",
"=",
"set",
"(",
"model",
")",
"cost",
"=",
"0",
"for",
"i",
",",
"cl",
"in",
"enumerate",
"(",
"formula",
".",
"soft",
")",
":",
"cost",
"+=",
"formula",
"... | 31.363636 | 23.181818 |
def delete_expired_requests():
"""Delete expired inclusion requests."""
InclusionRequest.query.filter_by(
InclusionRequest.expiry_date > datetime.utcnow()).delete()
db.session.commit() | [
"def",
"delete_expired_requests",
"(",
")",
":",
"InclusionRequest",
".",
"query",
".",
"filter_by",
"(",
"InclusionRequest",
".",
"expiry_date",
">",
"datetime",
".",
"utcnow",
"(",
")",
")",
".",
"delete",
"(",
")",
"db",
".",
"session",
".",
"commit",
"... | 40 | 11.2 |
def draw_capitan_stroke_images(self, symbols: List[CapitanSymbol],
destination_directory: str,
stroke_thicknesses: List[int]) -> None:
"""
Creates a visual representation of the Capitan strokes by drawing lines that connect the points... | [
"def",
"draw_capitan_stroke_images",
"(",
"self",
",",
"symbols",
":",
"List",
"[",
"CapitanSymbol",
"]",
",",
"destination_directory",
":",
"str",
",",
"stroke_thicknesses",
":",
"List",
"[",
"int",
"]",
")",
"->",
"None",
":",
"total_number_of_symbols",
"=",
... | 59.230769 | 37.435897 |
def autoconf(self):
"""Implements Munin Plugin Auto-Configuration Option.
@return: True if plugin can be auto-configured, False otherwise.
"""
serverInfo = MemcachedInfo(self._host, self._port, self._socket_file)
return (serverInfo is not None) | [
"def",
"autoconf",
"(",
"self",
")",
":",
"serverInfo",
"=",
"MemcachedInfo",
"(",
"self",
".",
"_host",
",",
"self",
".",
"_port",
",",
"self",
".",
"_socket_file",
")",
"return",
"(",
"serverInfo",
"is",
"not",
"None",
")"
] | 38.25 | 18.5 |
def signed_token_generator(private_pem, **kwargs):
"""
:param private_pem:
"""
def signed_token_generator(request):
request.claims = kwargs
return common.generate_signed_token(private_pem, request)
return signed_token_generator | [
"def",
"signed_token_generator",
"(",
"private_pem",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"signed_token_generator",
"(",
"request",
")",
":",
"request",
".",
"claims",
"=",
"kwargs",
"return",
"common",
".",
"generate_signed_token",
"(",
"private_pem",
",",... | 28.444444 | 12 |
def ChunkedAttentionSelector(x, params, selector=None, **kwargs):
"""Select which chunks to attend to in chunked attention.
Args:
x: inputs, a list of elements of the form (q, k, v), mask for each chunk.
params: parameters (unused).
selector: a function from chunk_number -> list of chunk numbers that s... | [
"def",
"ChunkedAttentionSelector",
"(",
"x",
",",
"params",
",",
"selector",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"del",
"params",
",",
"kwargs",
"selector",
"=",
"selector",
"or",
"(",
"lambda",
"x",
":",
"[",
"]",
"if",
"x",
"<",
"1",
... | 46.324324 | 22.324324 |
def impact_table_pdf_extractor(impact_report, component_metadata):
"""Extracting impact summary of the impact layer.
For PDF generations
:param impact_report: the impact report that acts as a proxy to fetch
all the data that extractor needed
:type impact_report: safe.report.impact_report.Impac... | [
"def",
"impact_table_pdf_extractor",
"(",
"impact_report",
",",
"component_metadata",
")",
":",
"# QGIS Composer needed certain context to generate the output",
"# - Map Settings",
"# - Substitution maps",
"# - Element settings, such as icon for picture file or image source",
"context",
"=... | 32 | 20.186047 |
def get_all_response(self, sort_order=None, sort_target='key',
keys_only=False):
"""Get all keys currently stored in etcd."""
range_request = self._build_get_range_request(
key=b'\0',
range_end=b'\0',
sort_order=sort_order,
sort_ta... | [
"def",
"get_all_response",
"(",
"self",
",",
"sort_order",
"=",
"None",
",",
"sort_target",
"=",
"'key'",
",",
"keys_only",
"=",
"False",
")",
":",
"range_request",
"=",
"self",
".",
"_build_get_range_request",
"(",
"key",
"=",
"b'\\0'",
",",
"range_end",
"=... | 32 | 13.882353 |
def is_expired(self, time_offset_seconds=0):
"""
Checks to see if the Session Token is expired or not. By default
it will check to see if the Session Token is expired as of the
moment the method is called. However, you can supply an
optional parameter which is the number of sec... | [
"def",
"is_expired",
"(",
"self",
",",
"time_offset_seconds",
"=",
"0",
")",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"if",
"time_offset_seconds",
":",
"now",
"=",
"now",
"+",
"datetime",
".",
"timedelta",
"(",
"seconds",
"=... | 47.5 | 17.1 |
def set_game_score(
self,
user_id: Union[int, str],
score: int,
force: bool = None,
disable_edit_message: bool = None,
chat_id: Union[int, str] = None,
message_id: int = None
):
# inline_message_id: str = None): TODO Add inline_message_id
"""U... | [
"def",
"set_game_score",
"(",
"self",
",",
"user_id",
":",
"Union",
"[",
"int",
",",
"str",
"]",
",",
"score",
":",
"int",
",",
"force",
":",
"bool",
"=",
"None",
",",
"disable_edit_message",
":",
"bool",
"=",
"None",
",",
"chat_id",
":",
"Union",
"[... | 41.742424 | 25.545455 |
def LockScanNode(self, path_spec):
"""Marks a scan node as locked.
Args:
path_spec (PathSpec): path specification.
Raises:
KeyError: if the scan node does not exists.
"""
scan_node = self._scan_nodes.get(path_spec, None)
if not scan_node:
raise KeyError('Scan node does not ex... | [
"def",
"LockScanNode",
"(",
"self",
",",
"path_spec",
")",
":",
"scan_node",
"=",
"self",
".",
"_scan_nodes",
".",
"get",
"(",
"path_spec",
",",
"None",
")",
"if",
"not",
"scan_node",
":",
"raise",
"KeyError",
"(",
"'Scan node does not exist.'",
")",
"self",... | 26.071429 | 18.071429 |
def GetMemBalloonMaxMB(self):
'''Undocumented.'''
counter = c_uint()
ret = vmGuestLib.VMGuestLib_GetMemBalloonMaxMB(self.handle.value, byref(counter))
if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret)
return counter.value | [
"def",
"GetMemBalloonMaxMB",
"(",
"self",
")",
":",
"counter",
"=",
"c_uint",
"(",
")",
"ret",
"=",
"vmGuestLib",
".",
"VMGuestLib_GetMemBalloonMaxMB",
"(",
"self",
".",
"handle",
".",
"value",
",",
"byref",
"(",
"counter",
")",
")",
"if",
"ret",
"!=",
"... | 45.5 | 22.166667 |
def _write_string(self, string, pos_x, pos_y, height, color, bold=False, align_right=False, depth=0.):
"""Write a string
Writes a string with a simple OpenGL method in the given size at the given position.
:param string: The string to draw
:param pos_x: x starting position
:par... | [
"def",
"_write_string",
"(",
"self",
",",
"string",
",",
"pos_x",
",",
"pos_y",
",",
"height",
",",
"color",
",",
"bold",
"=",
"False",
",",
"align_right",
"=",
"False",
",",
"depth",
"=",
"0.",
")",
":",
"stroke_width",
"=",
"height",
"/",
"8.",
"if... | 38.735294 | 17.911765 |
def mtxmg(m1, m2, ncol1, nr1r2, ncol2):
"""
Multiply the transpose of a matrix with
another matrix, both of arbitrary size.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/mtxmg_c.html
:param m1: nr1r2 X ncol1 double precision matrix.
:type m1: NxM-Element Array of floats
:param m2... | [
"def",
"mtxmg",
"(",
"m1",
",",
"m2",
",",
"ncol1",
",",
"nr1r2",
",",
"ncol2",
")",
":",
"m1",
"=",
"stypes",
".",
"toDoubleMatrix",
"(",
"m1",
")",
"m2",
"=",
"stypes",
".",
"toDoubleMatrix",
"(",
"m2",
")",
"mout",
"=",
"stypes",
".",
"emptyDoub... | 35.571429 | 11.142857 |
def gapsplit(args):
"""
%prog gapsplit gffile > split.gff
Read in the gff (normally generated by GMAP) and print it out after splitting
each feature into one parent and multiple child features based on alignment
information encoded in CIGAR string.
"""
p = OptionParser(gapsplit.__doc__)
... | [
"def",
"gapsplit",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"gapsplit",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"1",
":",
"sys",
".",
"exit",
"(",
... | 33.298969 | 17.360825 |
def process(self, salt_data, token, opts):
'''
Process events and publish data
'''
parts = salt_data['tag'].split('/')
if len(parts) < 2:
return
# TBD: Simplify these conditional expressions
if parts[1] == 'job':
if parts[3] == 'new':
... | [
"def",
"process",
"(",
"self",
",",
"salt_data",
",",
"token",
",",
"opts",
")",
":",
"parts",
"=",
"salt_data",
"[",
"'tag'",
"]",
".",
"split",
"(",
"'/'",
")",
"if",
"len",
"(",
"parts",
")",
"<",
"2",
":",
"return",
"# TBD: Simplify these condition... | 38 | 14.181818 |
def _set_Cpu(self, v, load=False):
"""
Setter method for Cpu, mapped from YANG variable /rbridge_id/threshold_monitor/Cpu (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_Cpu is considered as a private
method. Backends looking to populate this variable sho... | [
"def",
"_set_Cpu",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base",
"... | 79.363636 | 37.5 |
def increase_writes_in_percent(
current_provisioning, percent, max_provisioned_writes,
consumed_write_units_percent, log_tag):
""" Increase the current_provisioning with percent %
:type current_provisioning: int
:param current_provisioning: The current provisioning
:type percent: int
... | [
"def",
"increase_writes_in_percent",
"(",
"current_provisioning",
",",
"percent",
",",
"max_provisioned_writes",
",",
"consumed_write_units_percent",
",",
"log_tag",
")",
":",
"current_provisioning",
"=",
"float",
"(",
"current_provisioning",
")",
"consumed_write_units_percen... | 39.489362 | 20.361702 |
def setup_symbol_list(self, filter_text, current_path):
"""Setup list widget content for symbol list display."""
# Get optional symbol name
filter_text, symbol_text = filter_text.split('@')
# Fetch the Outline explorer data, get the icons and values
oedata = self.get_symbol_list... | [
"def",
"setup_symbol_list",
"(",
"self",
",",
"filter_text",
",",
"current_path",
")",
":",
"# Get optional symbol name",
"filter_text",
",",
"symbol_text",
"=",
"filter_text",
".",
"split",
"(",
"'@'",
")",
"# Fetch the Outline explorer data, get the icons and values",
"... | 40.269231 | 18.769231 |
def repository_data(self, repo):
"""
Grap data packages
"""
sum_pkgs, size, unsize, last_upd = 0, [], [], ""
for line in (Utils().read_file(
self.meta.lib_path + repo + "_repo/PACKAGES.TXT").splitlines()):
if line.startswith("PACKAGES.TXT;"):
... | [
"def",
"repository_data",
"(",
"self",
",",
"repo",
")",
":",
"sum_pkgs",
",",
"size",
",",
"unsize",
",",
"last_upd",
"=",
"0",
",",
"[",
"]",
",",
"[",
"]",
",",
"\"\"",
"for",
"line",
"in",
"(",
"Utils",
"(",
")",
".",
"read_file",
"(",
"self"... | 44.4 | 11.2 |
def create_subnet(network, cidr, name=None,
ip_version=4, profile=None):
'''
Creates a new subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.create_subnet network-name 192.168.1.0/24
:param network: Network ID or name this subnet belongs to
:param cidr: CIDR... | [
"def",
"create_subnet",
"(",
"network",
",",
"cidr",
",",
"name",
"=",
"None",
",",
"ip_version",
"=",
"4",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_auth",
"(",
"profile",
")",
"return",
"conn",
".",
"create_subnet",
"(",
"network",
",",
... | 32.9 | 22.7 |
def resume(self):
"""Resume process execution."""
# safety measure in case the current process has been killed in
# meantime and the kernel reused its PID
if not self.is_running():
name = self._platform_impl._process_name
raise NoSuchProcess(self.pid, name)
... | [
"def",
"resume",
"(",
"self",
")",
":",
"# safety measure in case the current process has been killed in",
"# meantime and the kernel reused its PID",
"if",
"not",
"self",
".",
"is_running",
"(",
")",
":",
"name",
"=",
"self",
".",
"_platform_impl",
".",
"_process_name",
... | 38.923077 | 14.538462 |
def initialize(self, **kwargs):
"""!
@brief Calculates initial centers using K-Means++ method.
@param[in] **kwargs: Arbitrary keyword arguments (available arguments: 'return_index').
<b>Keyword Args:</b><br>
- return_index (bool): If True then returns indexes of points from... | [
"def",
"initialize",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return_index",
"=",
"kwargs",
".",
"get",
"(",
"'return_index'",
",",
"False",
")",
"index_point",
"=",
"self",
".",
"__get_initial_center",
"(",
"True",
")",
"centers",
"=",
"[",
"ind... | 36 | 24.870968 |
def get_content_unscoped_package(self, feed_id, package_name, package_version, **kwargs):
"""GetContentUnscopedPackage.
[Preview API] Get an unscoped npm package.
:param str feed_id: Name or ID of the feed.
:param str package_name: Name of the package.
:param str package_version:... | [
"def",
"get_content_unscoped_package",
"(",
"self",
",",
"feed_id",
",",
"package_name",
",",
"package_version",
",",
"*",
"*",
"kwargs",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"feed_id",
"is",
"not",
"None",
":",
"route_values",
"[",
"'feedId'",
"]"... | 51.6 | 20.48 |
def montage(data, ref_chan=None, ref_to_avg=False, bipolar=None,
method='average'):
"""Apply linear transformation to the channels.
Parameters
----------
data : instance of DataRaw
the data to filter
ref_chan : list of str
list of channels used as reference
ref_to_av... | [
"def",
"montage",
"(",
"data",
",",
"ref_chan",
"=",
"None",
",",
"ref_to_avg",
"=",
"False",
",",
"bipolar",
"=",
"None",
",",
"method",
"=",
"'average'",
")",
":",
"if",
"ref_to_avg",
"and",
"ref_chan",
"is",
"not",
"None",
":",
"raise",
"TypeError",
... | 34.5 | 21.47561 |
def calculate_integral(self, T1, T2, method):
r'''Method to calculate the integral of a property with respect to
temperature, using a specified method. Implements the
analytical integrals of all available methods except for tabular data,
the case of multiple coefficient sets needed to ... | [
"def",
"calculate_integral",
"(",
"self",
",",
"T1",
",",
"T2",
",",
"method",
")",
":",
"if",
"method",
"==",
"ZABRANSKY_SPLINE",
":",
"return",
"self",
".",
"Zabransky_spline",
".",
"calculate_integral",
"(",
"T1",
",",
"T2",
")",
"elif",
"method",
"==",... | 46.851064 | 21.914894 |
def generate_submission_id():
"""
Executor for `globus task generate-submission-id`
"""
client = get_client()
res = client.get_submission_id()
formatted_print(res, text_format=FORMAT_TEXT_RAW, response_key="value") | [
"def",
"generate_submission_id",
"(",
")",
":",
"client",
"=",
"get_client",
"(",
")",
"res",
"=",
"client",
".",
"get_submission_id",
"(",
")",
"formatted_print",
"(",
"res",
",",
"text_format",
"=",
"FORMAT_TEXT_RAW",
",",
"response_key",
"=",
"\"value\"",
"... | 29 | 14.75 |
def printUniqueTFAM(tfam, samples, prefix):
"""Prints a new TFAM with only unique samples.
:param tfam: a representation of a TFAM file.
:param samples: the position of the samples
:param prefix: the prefix of the output file name
:type tfam: list
:type samples: dict
:type prefix: str
... | [
"def",
"printUniqueTFAM",
"(",
"tfam",
",",
"samples",
",",
"prefix",
")",
":",
"fileName",
"=",
"prefix",
"+",
"\".unique_samples.tfam\"",
"try",
":",
"with",
"open",
"(",
"fileName",
",",
"\"w\"",
")",
"as",
"outputFile",
":",
"for",
"i",
"in",
"sorted",... | 30.3 | 15.25 |
def to_list(self, csv_file):
""" 串接每日資料 舊→新
:param csv csv_file: csv files
:rtype: list
"""
tolist = []
for i in csv_file:
i = [value.strip().replace(',', '') for value in i]
try:
for value in (1, 2, 3, 4, 5, 6, 8):
... | [
"def",
"to_list",
"(",
"self",
",",
"csv_file",
")",
":",
"tolist",
"=",
"[",
"]",
"for",
"i",
"in",
"csv_file",
":",
"i",
"=",
"[",
"value",
".",
"strip",
"(",
")",
".",
"replace",
"(",
"','",
",",
"''",
")",
"for",
"value",
"in",
"i",
"]",
... | 35.266667 | 13.9 |
def cmd_rollback(context):
"""
Roll back by finding the most recent "stable" tagged version, and putting it again, so that
it's the new "current" version.
Args:
context: a populated EFVersionContext object
"""
last_stable = get_versions(context, return_stable=True)
if len(last_stable) != 1:
fail("... | [
"def",
"cmd_rollback",
"(",
"context",
")",
":",
"last_stable",
"=",
"get_versions",
"(",
"context",
",",
"return_stable",
"=",
"True",
")",
"if",
"len",
"(",
"last_stable",
")",
"!=",
"1",
":",
"fail",
"(",
"\"Didn't find a version marked stable for key: {} in en... | 39.470588 | 16.294118 |
def get_printable(iterable):
"""
Get printable characters from the specified string.
Note that str.isprintable() is not available in Python 2.
"""
if iterable:
return ''.join(i for i in iterable if i in string.printable)
return '' | [
"def",
"get_printable",
"(",
"iterable",
")",
":",
"if",
"iterable",
":",
"return",
"''",
".",
"join",
"(",
"i",
"for",
"i",
"in",
"iterable",
"if",
"i",
"in",
"string",
".",
"printable",
")",
"return",
"''"
] | 31.875 | 15.875 |
def facade(factory):
"""Declare a method as a facade factory."""
wrapper = FacadeDescriptor(factory.__name__, factory)
return update_wrapper(wrapper, factory) | [
"def",
"facade",
"(",
"factory",
")",
":",
"wrapper",
"=",
"FacadeDescriptor",
"(",
"factory",
".",
"__name__",
",",
"factory",
")",
"return",
"update_wrapper",
"(",
"wrapper",
",",
"factory",
")"
] | 41.75 | 10 |
def _print_unix(objects, sep, end, file, flush):
"""A print_() implementation which writes bytes"""
encoding = _encoding
if isinstance(sep, text_type):
sep = sep.encode(encoding, "replace")
if not isinstance(sep, bytes):
raise TypeError
if isinstance(end, text_type):
end =... | [
"def",
"_print_unix",
"(",
"objects",
",",
"sep",
",",
"end",
",",
"file",
",",
"flush",
")",
":",
"encoding",
"=",
"_encoding",
"if",
"isinstance",
"(",
"sep",
",",
"text_type",
")",
":",
"sep",
"=",
"sep",
".",
"encode",
"(",
"encoding",
",",
"\"re... | 28.892857 | 18.642857 |
def groupedby(collection, fn):
"""
same like itertools.groupby
:note: This function does not needs initial sorting like itertools.groupby
:attention: Order of pairs is not deterministic.
"""
d = {}
for item in collection:
k = fn(item)
try:
arr = d[k]
exc... | [
"def",
"groupedby",
"(",
"collection",
",",
"fn",
")",
":",
"d",
"=",
"{",
"}",
"for",
"item",
"in",
"collection",
":",
"k",
"=",
"fn",
"(",
"item",
")",
"try",
":",
"arr",
"=",
"d",
"[",
"k",
"]",
"except",
"KeyError",
":",
"arr",
"=",
"[",
... | 21.578947 | 20.210526 |
def replay_sgf(sgf_contents):
"""Wrapper for sgf files, returning go.PositionWithContext instances.
It does NOT return the very final position, as there is no follow up.
To get the final position, call pwc.position.play_move(pwc.next_move)
on the last PositionWithContext returned.
Example usage:
... | [
"def",
"replay_sgf",
"(",
"sgf_contents",
")",
":",
"root_node",
"=",
"get_sgf_root_node",
"(",
"sgf_contents",
")",
"props",
"=",
"root_node",
".",
"properties",
"assert",
"int",
"(",
"sgf_prop",
"(",
"props",
".",
"get",
"(",
"'GM'",
",",
"[",
"'1'",
"]"... | 38.37931 | 16.862069 |
def all_minutes(self):
"""
Returns a DatetimeIndex representing all the minutes in this calendar.
"""
opens_in_ns = self._opens.values.astype(
'datetime64[ns]',
).view('int64')
closes_in_ns = self._closes.values.astype(
'datetime64[ns]',
)... | [
"def",
"all_minutes",
"(",
"self",
")",
":",
"opens_in_ns",
"=",
"self",
".",
"_opens",
".",
"values",
".",
"astype",
"(",
"'datetime64[ns]'",
",",
")",
".",
"view",
"(",
"'int64'",
")",
"closes_in_ns",
"=",
"self",
".",
"_closes",
".",
"values",
".",
... | 27.5 | 18.25 |
async def edit_message_caption(self, chat_id: typing.Union[base.Integer, base.String, None] = None,
message_id: typing.Union[base.Integer, None] = None,
inline_message_id: typing.Union[base.String, None] = None,
cap... | [
"async",
"def",
"edit_message_caption",
"(",
"self",
",",
"chat_id",
":",
"typing",
".",
"Union",
"[",
"base",
".",
"Integer",
",",
"base",
".",
"String",
",",
"None",
"]",
"=",
"None",
",",
"message_id",
":",
"typing",
".",
"Union",
"[",
"base",
".",
... | 63.666667 | 33.102564 |
def get_groups(self):
"""
Returns all groups for a user pool. Returns instances of the
self.group_class.
:return: list of instances
"""
response = self.client.list_groups(UserPoolId=self.user_pool_id)
return [self.get_group_obj(group_data)
for grou... | [
"def",
"get_groups",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"client",
".",
"list_groups",
"(",
"UserPoolId",
"=",
"self",
".",
"user_pool_id",
")",
"return",
"[",
"self",
".",
"get_group_obj",
"(",
"group_data",
")",
"for",
"group_data",
"in"... | 38.333333 | 13.666667 |
def xslt(request):
"""Shows xml output transformed with standard xslt"""
foos = foobar_models.Foo.objects.all()
return render_xslt_to_response('xslt/model-to-xml.xsl', foos, mimetype='text/xml') | [
"def",
"xslt",
"(",
"request",
")",
":",
"foos",
"=",
"foobar_models",
".",
"Foo",
".",
"objects",
".",
"all",
"(",
")",
"return",
"render_xslt_to_response",
"(",
"'xslt/model-to-xml.xsl'",
",",
"foos",
",",
"mimetype",
"=",
"'text/xml'",
")"
] | 50.75 | 17.5 |
def get_file_from_cghub(job, cghub_xml, cghub_key, univ_options, write_to_jobstore=True):
"""
This function will download the file from cghub using the xml specified by cghub_xml
ARGUMENTS
1. cghub_xml: Path to an xml file for cghub.
2. cghub_key: Credentials for a cghub download operation.
3. ... | [
"def",
"get_file_from_cghub",
"(",
"job",
",",
"cghub_xml",
",",
"cghub_key",
",",
"univ_options",
",",
"write_to_jobstore",
"=",
"True",
")",
":",
"work_dir",
"=",
"job",
".",
"fileStore",
".",
"getLocalTempDir",
"(",
")",
"# Get from S3 if required",
"if",
"cg... | 49.447368 | 24.842105 |
def run_selected_clicked(self):
"""Run the selected scenario."""
# get all selected rows
rows = sorted(set(index.row() for index in
self.table.selectedIndexes()))
self.enable_busy_cursor()
# iterate over selected rows
for row in rows:
... | [
"def",
"run_selected_clicked",
"(",
"self",
")",
":",
"# get all selected rows",
"rows",
"=",
"sorted",
"(",
"set",
"(",
"index",
".",
"row",
"(",
")",
"for",
"index",
"in",
"self",
".",
"table",
".",
"selectedIndexes",
"(",
")",
")",
")",
"self",
".",
... | 39.615385 | 9.153846 |
def overlay_gateway_site_bfd_enable(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
overlay_gateway = ET.SubElement(config, "overlay-gateway", xmlns="urn:brocade.com:mgmt:brocade-tunnels")
name_key = ET.SubElement(overlay_gateway, "name")
name_ke... | [
"def",
"overlay_gateway_site_bfd_enable",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"overlay_gateway",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"overlay-gateway\"",
",",
"xmlns",
"... | 44.571429 | 14.785714 |
def getSensors(self):
""" Returns the currently visible state of the world as a numpy array
of doubles.
"""
Pd = array([b.p_demand for b in self.case.buses if b.type == PQ])
logger.info("State: %s" % list(Pd))
return Pd | [
"def",
"getSensors",
"(",
"self",
")",
":",
"Pd",
"=",
"array",
"(",
"[",
"b",
".",
"p_demand",
"for",
"b",
"in",
"self",
".",
"case",
".",
"buses",
"if",
"b",
".",
"type",
"==",
"PQ",
"]",
")",
"logger",
".",
"info",
"(",
"\"State: %s\"",
"%",
... | 37.285714 | 14.142857 |
def read_namespaced_stateful_set_scale(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_stateful_set_scale # noqa: E501
read scale of the specified StatefulSet # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request,... | [
"def",
"read_namespaced_stateful_set_scale",
"(",
"self",
",",
"name",
",",
"namespace",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
... | 52.304348 | 26.913043 |
def com_google_fonts_check_smart_dropout(ttFont):
"""Font enables smart dropout control in "prep" table instructions?
B8 01 FF PUSHW 0x01FF
85 SCANCTRL (unconditinally turn on
dropout control mode)
B0 04 PUSHB 0x04
8D SCANTYPE (enable smart dropout control)
... | [
"def",
"com_google_fonts_check_smart_dropout",
"(",
"ttFont",
")",
":",
"INSTRUCTIONS",
"=",
"b\"\\xb8\\x01\\xff\\x85\\xb0\\x04\\x8d\"",
"if",
"(",
"\"prep\"",
"in",
"ttFont",
"and",
"INSTRUCTIONS",
"in",
"ttFont",
"[",
"\"prep\"",
"]",
".",
"program",
".",
"getByteco... | 45.676471 | 18.147059 |
def add_annotator(self, doc, annotator):
"""Adds an annotator to the SPDX Document.
Annotator is an entity created by an EntityBuilder.
Raises SPDXValueError if not a valid annotator type.
"""
# Each annotator marks the start of a new annotation object.
# FIXME: this stat... | [
"def",
"add_annotator",
"(",
"self",
",",
"doc",
",",
"annotator",
")",
":",
"# Each annotator marks the start of a new annotation object.",
"# FIXME: this state does not make sense",
"self",
".",
"reset_annotations",
"(",
")",
"if",
"validations",
".",
"validate_annotator",
... | 45.153846 | 14.615385 |
def calendar_tuple(jd_float, offset=0.0):
"""Return a (year, month, day, hour, minute, second.fraction) tuple.
The `offset` is added to the time before it is split into its
components. This is useful if the user is going to round the
result before displaying it. If the result is going to be
displ... | [
"def",
"calendar_tuple",
"(",
"jd_float",
",",
"offset",
"=",
"0.0",
")",
":",
"jd_float",
"=",
"_to_array",
"(",
"jd_float",
")",
"whole",
",",
"fraction",
"=",
"divmod",
"(",
"jd_float",
"+",
"0.5",
",",
"1.0",
")",
"whole",
"=",
"whole",
".",
"astyp... | 46.052632 | 16.315789 |
def _get_repo_options(fromrepo=None, packagesite=None):
'''
Return a list of tuples to seed the "env" list, which is used to set
environment variables for any pkg_add commands that are spawned.
If ``fromrepo`` or ``packagesite`` are None, then their corresponding
config parameter will be looked up ... | [
"def",
"_get_repo_options",
"(",
"fromrepo",
"=",
"None",
",",
"packagesite",
"=",
"None",
")",
":",
"root",
"=",
"fromrepo",
"if",
"fromrepo",
"is",
"not",
"None",
"else",
"__salt__",
"[",
"'config.get'",
"]",
"(",
"'freebsdpkg.PACKAGEROOT'",
",",
"None",
"... | 41.869565 | 23.26087 |
def parse_market(self, market, split_char='_'):
"""
In comes the market identifier directly from the service. Returned is
the crypto and fiat identifier in moneywagon format.
"""
crypto, fiat = market.lower().split(split_char)
return (
self.fix_symbol(crypto, ... | [
"def",
"parse_market",
"(",
"self",
",",
"market",
",",
"split_char",
"=",
"'_'",
")",
":",
"crypto",
",",
"fiat",
"=",
"market",
".",
"lower",
"(",
")",
".",
"split",
"(",
"split_char",
")",
"return",
"(",
"self",
".",
"fix_symbol",
"(",
"crypto",
"... | 38.3 | 15.1 |
def ctc_beam_search_decoder(probs_seq,
alphabet,
beam_size,
cutoff_prob=1.0,
cutoff_top_n=40,
scorer=None):
"""Wrapper for the CTC Beam Search Decoder.
:param probs_seq: 2... | [
"def",
"ctc_beam_search_decoder",
"(",
"probs_seq",
",",
"alphabet",
",",
"beam_size",
",",
"cutoff_prob",
"=",
"1.0",
",",
"cutoff_top_n",
"=",
"40",
",",
"scorer",
"=",
"None",
")",
":",
"beam_results",
"=",
"swigwrapper",
".",
"ctc_beam_search_decoder",
"(",
... | 44.914286 | 17.257143 |
def get_available_name(self, name):
"""
Returns a filename that's free on the target storage system, and
available for new content to be written to.
"""
dir_name, file_name = os.path.split(name)
file_root, file_ext = os.path.splitext(file_name)
# If the filename a... | [
"def",
"get_available_name",
"(",
"self",
",",
"name",
")",
":",
"dir_name",
",",
"file_name",
"=",
"os",
".",
"path",
".",
"split",
"(",
"name",
")",
"file_root",
",",
"file_ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"file_name",
")",
"# If t... | 43.3125 | 17.8125 |
def splitPath( self, path ):
"""
Splits the path into its components.
:param path | <str>
:return [<str>, ..]
"""
sep = self.model().separator()
splt = nativestring(path).lstrip(sep).split(sep)
if ( splt and not splt[-1]... | [
"def",
"splitPath",
"(",
"self",
",",
"path",
")",
":",
"sep",
"=",
"self",
".",
"model",
"(",
")",
".",
"separator",
"(",
")",
"splt",
"=",
"nativestring",
"(",
"path",
")",
".",
"lstrip",
"(",
"sep",
")",
".",
"split",
"(",
"sep",
")",
"if",
... | 25.6 | 13.333333 |
def maybe_convert_ix(*args):
"""
We likely want to take the cross-product
"""
ixify = True
for arg in args:
if not isinstance(arg, (np.ndarray, list, ABCSeries, Index)):
ixify = False
if ixify:
return np.ix_(*args)
else:
return args | [
"def",
"maybe_convert_ix",
"(",
"*",
"args",
")",
":",
"ixify",
"=",
"True",
"for",
"arg",
"in",
"args",
":",
"if",
"not",
"isinstance",
"(",
"arg",
",",
"(",
"np",
".",
"ndarray",
",",
"list",
",",
"ABCSeries",
",",
"Index",
")",
")",
":",
"ixify"... | 20.357143 | 19.642857 |
def _post_json(self, instance, space=None, rel_path=None, extra_params=None):
"""
Base level method for updating data via the API
"""
model = type(instance)
# Only API.spaces and API.event should not provide
# the `space argument
if space is None and model not i... | [
"def",
"_post_json",
"(",
"self",
",",
"instance",
",",
"space",
"=",
"None",
",",
"rel_path",
"=",
"None",
",",
"extra_params",
"=",
"None",
")",
":",
"model",
"=",
"type",
"(",
"instance",
")",
"# Only API.spaces and API.event should not provide",
"# the `spac... | 30.535714 | 16.607143 |
def apply(self, node):
""" Apply transformation and return if an update happened. """
new_node = self.run(node)
return self.update, new_node | [
"def",
"apply",
"(",
"self",
",",
"node",
")",
":",
"new_node",
"=",
"self",
".",
"run",
"(",
"node",
")",
"return",
"self",
".",
"update",
",",
"new_node"
] | 40.25 | 7.25 |
def fit(self, X, y=None):
"""
The fit method is the primary drawing input for the frequency
distribution visualization. It requires vectorized lists of
documents and a list of features, which are the actual words
from the original corpus (needed to label the x-axis ticks).
... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
")",
":",
"# Compute the conditional word frequency",
"if",
"y",
"is",
"not",
"None",
":",
"# Fit the frequencies",
"self",
".",
"conditional_freqdist_",
"=",
"{",
"}",
"# Conditional frequency distributi... | 37.113636 | 19.931818 |
def get_sanitized_endpoint(url):
"""
Sanitize an endpoint, as removing unneeded parameters
"""
# sanitize esri
sanitized_url = url.rstrip()
esri_string = '/rest/services'
if esri_string in url:
match = re.search(esri_string, sanitized_url)
sanitized_url = url[0:(match.start(0... | [
"def",
"get_sanitized_endpoint",
"(",
"url",
")",
":",
"# sanitize esri",
"sanitized_url",
"=",
"url",
".",
"rstrip",
"(",
")",
"esri_string",
"=",
"'/rest/services'",
"if",
"esri_string",
"in",
"url",
":",
"match",
"=",
"re",
".",
"search",
"(",
"esri_string"... | 32.272727 | 11.545455 |
def filter_query(filter_dict, required_keys):
"""Ensure that the dict has all of the information available. If not, return what does"""
if not isinstance(filter_dict, dict):
raise TypeError("dict_list is not a list. Please try again")
if not isinstance(required_keys, list):
raise TypeError(... | [
"def",
"filter_query",
"(",
"filter_dict",
",",
"required_keys",
")",
":",
"if",
"not",
"isinstance",
"(",
"filter_dict",
",",
"dict",
")",
":",
"raise",
"TypeError",
"(",
"\"dict_list is not a list. Please try again\"",
")",
"if",
"not",
"isinstance",
"(",
"requi... | 36.642857 | 16.428571 |
def update(self, byts):
'''
Update all the hashes in the set with the given bytes.
'''
self.size += len(byts)
[h[1].update(byts) for h in self.hashes] | [
"def",
"update",
"(",
"self",
",",
"byts",
")",
":",
"self",
".",
"size",
"+=",
"len",
"(",
"byts",
")",
"[",
"h",
"[",
"1",
"]",
".",
"update",
"(",
"byts",
")",
"for",
"h",
"in",
"self",
".",
"hashes",
"]"
] | 30.833333 | 19.166667 |
def get_file_to_path(self, share_name, directory_name, file_name, file_path,
open_mode='wb', start_range=None, end_range=None,
range_get_content_md5=None, progress_callback=None,
max_connections=1, max_retries=5, retry_wait=1.0, timeout=None):
... | [
"def",
"get_file_to_path",
"(",
"self",
",",
"share_name",
",",
"directory_name",
",",
"file_name",
",",
"file_path",
",",
"open_mode",
"=",
"'wb'",
",",
"start_range",
"=",
"None",
",",
"end_range",
"=",
"None",
",",
"range_get_content_md5",
"=",
"None",
",",... | 52.092308 | 22.461538 |
def bucket_dict_to_policy(args, bucket_name, d):
"""
Create a bucket policy document from a permissions dict.
The dictionary d maps (user, prefix) to 'R' or 'W'.
:param bucket_name:
:param d:
:return:
"""
import json
iam = get_resource(args, 'iam')
statements = make_bucket_p... | [
"def",
"bucket_dict_to_policy",
"(",
"args",
",",
"bucket_name",
",",
"d",
")",
":",
"import",
"json",
"iam",
"=",
"get_resource",
"(",
"args",
",",
"'iam'",
")",
"statements",
"=",
"make_bucket_policy_statements",
"(",
"bucket_name",
")",
"user_stats",
"=",
"... | 27.56 | 20.88 |
def update(self, password=values.unset):
"""
Update the CredentialInstance
:param unicode password: The password will not be returned in the response
:returns: Updated CredentialInstance
:rtype: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialInstance
... | [
"def",
"update",
"(",
"self",
",",
"password",
"=",
"values",
".",
"unset",
")",
":",
"return",
"self",
".",
"_proxy",
".",
"update",
"(",
"password",
"=",
"password",
",",
")"
] | 37.4 | 19.8 |
def longest_run_1d(arr):
"""Return the length of the longest consecutive run of identical values.
Parameters
----------
arr : bool array
Input array
Returns
-------
int
Length of longest run.
"""
v, rl = rle_1d(arr)[:2]
return np.where(v, rl, 0).max() | [
"def",
"longest_run_1d",
"(",
"arr",
")",
":",
"v",
",",
"rl",
"=",
"rle_1d",
"(",
"arr",
")",
"[",
":",
"2",
"]",
"return",
"np",
".",
"where",
"(",
"v",
",",
"rl",
",",
"0",
")",
".",
"max",
"(",
")"
] | 19.4 | 20.8 |
def throw_random_private( lengths, regions, save_interval_func, allow_overlap=False, three_args=True ):
"""
(Internal function; we expect calls only through the interface functions
above)
`lengths`: A list containing the length of each interval to be generated.
`regions`: A list of regions in ... | [
"def",
"throw_random_private",
"(",
"lengths",
",",
"regions",
",",
"save_interval_func",
",",
"allow_overlap",
"=",
"False",
",",
"three_args",
"=",
"True",
")",
":",
"# Implementation:",
"# We keep a list of the regions, sorted from largest to smallest. We then",
"# pl... | 47.46087 | 24.052174 |
def path_split(self, path):
"""
Splits a path into the part matching this middleware and the part remaining.
If path does not exist, it returns a pair of None values.
If the regex matches the entire pair, the second item in returned tuple is None.
Args:
path (str): T... | [
"def",
"path_split",
"(",
"self",
",",
"path",
")",
":",
"match",
"=",
"self",
".",
"path",
".",
"match",
"(",
"path",
")",
"if",
"match",
"is",
"None",
":",
"return",
"None",
",",
"None",
"# split string at position",
"the_rest",
"=",
"path",
"[",
"ma... | 31.083333 | 21.583333 |
def runPlink(options):
"""Runs Plink with the geno option.
:param options: the options.
:type options: argparse.Namespace
"""
# The plink command
plinkCommand = ["plink", "--noweb", "--bfile", options.bfile, "--geno",
str(options.geno), "--make-bed", "--out", options.out]
... | [
"def",
"runPlink",
"(",
"options",
")",
":",
"# The plink command",
"plinkCommand",
"=",
"[",
"\"plink\"",
",",
"\"--noweb\"",
",",
"\"--bfile\"",
",",
"options",
".",
"bfile",
",",
"\"--geno\"",
",",
"str",
"(",
"options",
".",
"geno",
")",
",",
"\"--make-b... | 30.526316 | 20.736842 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.