content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def add_arrays(arr1, arr2):
"""
Function to adds two arrays element-wise
Returns the a new array with the result
"""
if len(arr1) == len(arr2):
return [arr1[i] + arr2[i] for i in range(len(arr1))]
return None | d16adfb33fb0c1a30277f7250485cddea60b1fe9 | 691,048 |
def strip_commands(commands):
""" Strips a sequence of commands.
Strips down the sequence of commands by removing comments and
surrounding whitespace around each individual command and then
removing blank commands.
Parameters
----------
commands : iterable of strings
Iterable of co... | d2260c157de8b791af59fadaba380bbc06c6a30d | 691,049 |
def __merge2sorted__(arr1, arr2):
"""
Takes two sorted subarrays and returns a sorted array
"""
m, n = len(arr1), len(arr2)
aux_arr = [None] * (m + n)
p1 = 0
p2 = 0
c = 0
while p1 < m and p2 < n:
if arr1[p1] < arr2[p2]:
aux_arr[c] = arr1[p1]
p1 += 1
... | 292521702ba5b9f9237ca988c1e3f6091b0f142e | 691,051 |
def args_idx(x):
"""Get the idx of "?" in the string"""
return x.rfind('?') if '?' in x else None | 65a59f63ccad4e755731814850870f914968a060 | 691,052 |
from typing import Dict
from typing import Any
def userinfo_token(
token_subject: str,
token_idp: str,
token_ssn: str,
) -> Dict[str, Any]:
"""
Mocked userinfo-token from Identity Provider (unencoded).
"""
return {
'iss': 'https://pp.netseidbroker.dk/op',
'nbf':... | 976cadad107d5a167f169405e62d56e64b3f865e | 691,055 |
def homo_line(a, b):
"""
Return the homogenous equation of a line passing through a and b,
i.e. [ax, ay, 1] cross [bx, by, 1]
"""
return (a[1] - b[1], b[0] - a[0], a[0] * b[1] - a[1] * b[0]) | 44888650c16d2a48b2a60adaf9e9bd89e0a0de67 | 691,056 |
from unittest.mock import call
def get_local_jitter(sound, min_time=0., max_time=0., pitch_floor=75., pitch_ceiling=600.,
period_floor=0.0001, period_ceiling=0.02, max_period_factor=1.3):
"""
Function to calculate (local) jitter from a periodic PointProcess.
:param (parselmouth.Sound... | ba9302f7593f9d324193ba8be6b64982b515e878 | 691,057 |
def anchor_ctr_inside_region_flags(anchors, stride, region):
"""Get the flag indicate whether anchor centers are inside regions."""
x1, y1, x2, y2 = region
f_anchors = anchors / stride
x = (f_anchors[:, 0] + f_anchors[:, 2]) * 0.5
y = (f_anchors[:, 1] + f_anchors[:, 3]) * 0.5
flags = (x >= x1) &... | 5f1e3b764145a9ee8abb709cd43f7f99c8515eb7 | 691,059 |
def position_is_escaped(string, position=None):
"""
Checks whether a char at a specific position of the string is preceded by
an odd number of backslashes.
:param string: Arbitrary string
:param position: Position of character in string that should be checked
:return: True if the char... | 8fbaa26a6fb56f56819e5937a921efa3a6882627 | 691,062 |
def select_column_values(df, col_name="totale_casi", groupby=["data"], group_by_criterion="sum"):
"""
:param df: pandas dataFrame
:param col_name: column of interest
:param groupby: column to group by (optional) data.
:param group_by_criterion: how to merge the values of grouped elements in col_nam... | cb0d63fa3c29447353163ae8336eb42f6f454ced | 691,063 |
def normalize_min_max(x, x_min, x_max):
"""Normalized data using it's maximum and minimum values
# Arguments
x: array
x_min: minimum value of x
x_max: maximum value of x
# Returns
min-max normalized data
"""
return (x - x_min) / (x_max - x_min) | e31028c84603d0fc6d1ad00b768fb6373aee975c | 691,069 |
def get_orientation_from(pose):
""" Extract and convert the pose's orientation into a list.
Args:
pose (PoseStamped): the pose to extract the position from
Returns:
the orientation quaternion list [x, y, z, w]
"""
return [pose.pose.orientation.x,
pose.pose.orientation.y... | 2c3116c4070779511df54f0aafd488d22bc1c94b | 691,072 |
import string
def index_to_column(index):
"""
0ベース序数をカラムを示すアルファベットに変換する。
Params:
index(int): 0ベース座標
Returns:
str: A, B, C, ... Z, AA, AB, ...
"""
m = index + 1 # 1ベースにする
k = 26
digits = []
while True:
q = (m-1) // k
d = m - q * k
digit = stri... | 2d1b1018e91e3408aee7e8adbe51ea2e9867bd45 | 691,073 |
def _listen_count(opp):
"""Return number of event listeners."""
return sum(opp.bus.async_listeners().values()) | b342b040292ab846206d46210f834fef042af3b4 | 691,076 |
import math
def distance(point1, point2):
""" Calculates distance between two points.
:param point1: tuple (x, y) with coordinates of the first point
:param point2: tuple (x, y) with coordinates of the second point
:return: distance between two points in pixels
"""
return math.sqrt(math.pow(po... | e38be3e5cc3418ab8c5edefb560e95e583dede21 | 691,082 |
from typing import List
from typing import Set
def scan_polarimeter_names(group_names: List[str]) -> Set[str]:
"""Scan a list of group names and return the set of polarimeters in it.
Example::
>>> group_names(["BOARD_G", "COMMANDS", "LOG", "POL_G0", "POL_G6"])
set("G0", "G6")
"""
res... | d4ae998041401beb40df7746ec0afc2b98c9d6b1 | 691,084 |
def get_project_folders(window):
"""Get project folder."""
data = window.project_data()
if data is None:
data = {'folders': [{'path': f} for f in window.folders()]}
return data.get('folders', []) | d3bc83067e4acdf0df1a29891cebcb60422fe5e6 | 691,088 |
import textwrap
def dedented_lines(description):
"""
Each line of the provided string with leading whitespace stripped.
"""
if not description:
return []
return textwrap.dedent(description).split('\n') | 8a398b0afe6aa1f9cdf5f4ae386ecebef06bdd2b | 691,090 |
def behavior_get_required_inputs(self):
"""Return all required Parameters of type input for this Behavior
Note: assumes that type is all either in or out
Returns
-------
Iterator over Parameters
"""
return (p for p in self.get_inputs() if p.property_value.lower_value.value > 0) | 13063f7708d518928aed7556ca9da7a851de6622 | 691,091 |
def _AddNGrad(op, grad):
"""Copies the gradient to all inputs."""
# Not broadcasting.
return [grad] * len(op.inputs) | 9cbeee4a863b44e45475b4161fdc7b94f576005a | 691,097 |
def oneof(*args):
"""Returns true iff one of the parameters is true.
Args:
*args: arguments to check
Returns:
bool: true iff one of the parameters is true.
"""
return len([x for x in args if x]) == 1 | 14731b54f19658d25ca3e62af439d7d2000c1872 | 691,100 |
import warnings
from typing import Optional
from typing import Union
from typing import Type
from typing import cast
def _is_unexpected_warning(
actual_warning: warnings.WarningMessage,
expected_warning: Optional[Union[Type[Warning], bool]],
) -> bool:
"""Check if the actual warning issued is unexpected."... | 7b4be666af4f963ef94758d5061224e2806b60ca | 691,101 |
import torch
def get_pose_loss(gt_pose, pred_pose, vis, loss_type):
"""
gt_pose: [B, J*2]
pred_pose: [B, J*2]
vis: [B, J]
Loss: L2 (MSE), or L1
"""
vis = torch.repeat_interleave(vis, 2, dim=-1) # [B, 1122...JJ]
if loss_type == "L2":
loss = torch.sum((gt_pose - pred_pose) ** ... | 2cedc132ec5e6fc9870ba3439b756d7b421486d6 | 691,102 |
def wrap_cdata(s: str) -> str:
"""Wraps a string into CDATA sections"""
s = str(s).replace("]]>", "]]]]><![CDATA[>")
return "<![CDATA[" + s + "]]>" | 861d086e77b02c354815da11278fc0c3b6297a68 | 691,103 |
def get_spacing_groups(font):
"""
Return a dictionary containing the ``left`` and ``right`` spacing groups in the font.
"""
_groups = {}
_groups['left'] = {}
_groups['right'] = {}
for _group in list(font.groups.keys()):
if _group[:1] == '_':
if _group[1:5] == 'left':
... | 778a27b49ce9d869d7867774df8dfe22a3cd6140 | 691,106 |
def _get_gate_span(qregs, instruction):
"""Get the list of qubits drawing this gate would cover"""
min_index = len(qregs)
max_index = 0
for qreg in instruction.qargs:
index = qregs.index(qreg)
if index < min_index:
min_index = index
if index > max_index:
... | b85b1a0e5dd6691e9b460dea90cb205ce46227e9 | 691,107 |
def get_AP_parameters(exp):
"""
This function is connect with'Advanced Parameter' button.
Parameters
------
exp: the Ui_Experiment object
Return
------
AP_parameters: list contains all the advanced parameters
"""
conv_fact = float(exp.experiment_conversion_factor.text(... | 079759600626e3c7cbb4fee882d1b9623a1f4a43 | 691,109 |
import requests
def read_data_json(typename, api, body):
"""
read_data_json directly accesses the C3.ai COVID-19 Data Lake APIs using the requests library,
and returns the response as a JSON, raising an error if the call fails for any reason.
------
typename: The type you want to access, i.e. 'Ou... | b0aed423512408efa97e0f5cf406bb442b876a3d | 691,110 |
def matrix_from_vectors(op, v):
"""
Given vector v, build matrix
[[op(v1, v1), ..., op(v1, vn)],
...
[op(v2, v1), ..., op(vn, vn)]].
Note that if op is commutative, this is redundant: the matrix will be equal to its transpose.
The matrix is represented as a list of lists.
... | cfefaf9e66db33e993044b2cc609f25f89e103ea | 691,114 |
def create_user(connection, body, username, fields=None):
"""Create a new user. The response includes the user ID, which other
endpoints use as a request parameter to specify the user to perform an
action on.
Args:
connection(object): MicroStrategy connection object returned by
`con... | c4f11b3b39ba2a84417ca667ab1d66e978d33bd3 | 691,120 |
def plus_all(tem, sum):
"""
:param tem:int, the temperature user entered.
:param sum:int, the sum of temperatures user entered.
This function plus all temperatures user entered.
"""
return sum+tem | 187d81f2bbebc2a21e6a23a297c56550216141fa | 691,122 |
def check_input(saved_input):
"""Checks for yes and no awnsers from the user."""
if saved_input.lower() == "!yes":
return True
if saved_input.lower() == "!no":
return False | 8e0cb2613434a2e7dc00a758dd0df03cb8b06d36 | 691,124 |
def _get_fk_relations_helper(unvisited_tables, visited_tables,
fk_relations_map):
"""Returns a ForeignKeyRelation connecting to an unvisited table, or None."""
for table_to_visit in unvisited_tables:
for table in visited_tables:
if (table, table_to_visit) in fk_relations_map:
... | fb2458437d16d94341f037ddf65347dc6d6169e4 | 691,127 |
import math
def phaseNearTargetPhase(phase,phase_trgt):
"""
Adds or subtracts 2*math.pi to get the phase near the target phase.
"""
pi2 = 2*math.pi
delta = pi2*int((phase_trgt - phase)/(pi2))
phase += delta
if(phase_trgt - phase > math.pi):
phase += pi2
return phase
if(phase_trgt - phase < -math.pi):
... | dbd1a7c291b47703fa64756c986815d2cf706677 | 691,132 |
def coding_problem_28(word_list, max_line_length):
"""
Write an algorithm to justify text. Given a sequence of words and an integer line length k, return a list of
strings which represents each line, fully justified. More specifically, you should have as many words as possible
in each line. There should... | 59beff7b181730ab094f7f797128de9bfc83ef8b | 691,135 |
def truncate(value):
"""
Takes a float and truncates it to two decimal points.
"""
return float('{0:.2f}'.format(value)) | b47412443fa55e0fd9158879b3c0d85c5ecc7aad | 691,137 |
def open_file(filename, mode='r'):
"""
常用文件操作,可在python2和python3间切换.
mode: 'r' or 'w' for read or write
"""
return open(filename, mode, encoding='utf-8', errors='ignore') | 100179e22f140c4e8d25a1ccab94f9ca3831b5f3 | 691,138 |
def get_pubmed_ids_from_csv(ids_txt_filepath):
"""
Function retrieves PubMed ids from a csv file
:param ids_txt_filepath: String - Full file path including file name to txt file containing PubMed IDs
:return lines: List of PubMed article IDs
"""
with open(ids_txt_filepath, 'r') as file:
... | 4f6f53eee0d14bb3beae27ac6f15f7c14b33dbe5 | 691,139 |
from typing import Dict
def parse_wspecifier(wspecifier: str) -> Dict[str, str]:
"""Parse wspecifier to dict
Examples:
>>> parse_wspecifier('ark,scp:out.ark,out.scp')
{'ark': 'out.ark', 'scp': 'out.scp'}
"""
ark_scp, filepath = wspecifier.split(":", maxsplit=1)
if ark_scp not in ... | cdd28f17387c43d475abdcf463dcd58bee2ede5c | 691,144 |
def get_nodes(graph, metanode):
"""
Return a list of nodes for a given metanode, in sorted order.
"""
metanode = graph.metagraph.get_metanode(metanode)
metanode_to_nodes = graph.get_metanode_to_nodes()
nodes = sorted(metanode_to_nodes[metanode])
return nodes | 1decea0c15425bdba58d8ab2a8735aaff8d44b98 | 691,145 |
def create_state_action_dictionary(env, policy: dict) -> dict:
"""
return initial Q (state-action) matrix storing 0 as reward for each action in each state
:param env:
:param policy: 2D dictionary of {state_index: {action_index: action_probability}}
:return: Q matrix dictionary of {state_index: {act... | cfa546add31b8668ba065a4635c041679bbe319a | 691,146 |
async def check_win(ctx, player_id, game):
"""Checks if the player has won the game"""
player = game.players[player_id]
if len(player.hand) == 0:
await ctx.send(f"Game over! {player.player_name} has won!")
return True
return False | cb3fb54f499f9127ebecbbed5cbfb0be518697cf | 691,147 |
def price_to_profit(lst):
"""
Given a list of stock prices like the one above,
return a list of of the change in value each day.
The list of the profit returned from this function will be our input in max_profit.
>>> price_to_profit([100, 105, 97, 200, 150])
[0, 5, -8, 103, -50]
>>> price_t... | 5539c7c22f10c06199855e8c495221b111f67377 | 691,148 |
def upgrade(request):
"""Specify if upgrade test is to be executed."""
return request.config.getoption('--upgrade') | e52e3cd3af930f6867e6807bd7fa1402e1993b8c | 691,149 |
def _inlining_threshold(optlevel, sizelevel=0):
"""
Compute the inlining threshold for the desired optimisation level
Refer to http://llvm.org/docs/doxygen/html/InlineSimple_8cpp_source.html
"""
if optlevel > 2:
return 275
# -Os
if sizelevel == 1:
return 75
# -Oz
i... | dd4a2ac54fc9dea53bf667095e41ca6d768a4627 | 691,151 |
def get_resampling_period(target_dts, cmip_dt):
"""Return 30-year time bounds of the resampling period.
This is the period for which the target model delta T
matches the cmip delta T for a specific year.
Uses a 30-year rolling window to get the best match.
"""
target_dts = target_dts.rolling(ti... | d335fe1300703bc11ac3210d5ffce4b8c0ffd0f7 | 691,154 |
import struct
def read_data(file, endian, num=1):
"""
Read a given number of 32-bits unsigned integers from the given file
with the given endianness.
"""
res = struct.unpack(endian + "L" * num, file.read(num * 4))
if len(res) == 1:
return res[0]
return res | 74b58ea11d3818ce6bdd56ba04ee1d1d34e9913a | 691,156 |
def raw_values(y_true, y):
"""
Returns input value y. Used for numerical diagnostics.
"""
return y | 5ca341e6ed14899df6a51564ee2d8f8b90dae04b | 691,159 |
def default_filter(src,dst):
"""The default progress/filter callback; returns True for all files"""
return dst | 8b76498b6c740ec0a3c882fd42cdabbc6608ac25 | 691,161 |
def retrieve_channel(Client, UseNameOrId, Identifier):
"""Returns a channel object based or either name or Id.
"""
text_channel_object = None
for channel in Client.get_all_channels():
if UseNameOrId == 'id':
if channel.id == Identifier:
text_channel_object = channel
... | 0a70268583f87dc088f3a3154d43b70830bb2680 | 691,162 |
def with_subfolder(location: str, subfolder: str):
"""
Wrapper to appends a subfolder to a location.
:param location:
:param subfolder:
:return:
"""
if subfolder:
location += subfolder + '/'
return location | 9c5c50e08ff6e2b250ac25bc317df834c359a1f3 | 691,163 |
from typing import Callable
def pow_util(gamma: float) -> Callable[[float], float]:
"""
べき乗関数的な効用関数を返します。
Parameters
----------
gamma: float
実指数
Returns
-------
Callable[[float], float]
x >= 0 について、u(x) = x^{1 - gamma} / (1 - gamma) を満たす効用関数u
"""
def u(x: flo... | 39a1e134f5fc22c406c823387a7b51e8370b79b4 | 691,169 |
def get_ports(svc_group, db):
"""Gets the ports and protocols defined in a service group.
Args:
svc_group: a list of strings for each service group
db: network and service definitions
Returns:
results: a list of tuples for each service defined, in the format:
(service name, "<po... | 04502215d32742465a9b22c8630997f00016b236 | 691,171 |
def run(capsys, mocker):
"""CLI run method fixture
To use:
run(meth, *args, input_side_effect=['first', 'second', 'last'])
run(meth, *args, input_return_value='42')
This would run the method `meth` with arguments `*args`.
In the first every time `builtins.input()` is called by `meth`, ... | f82905e8a8cca0fedbb64c896efd52e3a8c0add3 | 691,174 |
def add_spaces(x):
"""Add four spaces to every line in x
This is needed to make html raw blocks in rst format correctly
"""
y = ''
if isinstance(x, str):
x = x.split('\n')
for q in x:
y += ' ' + q
return y | 8443f4d019022b1e4705abbeca5bbd54bc94699d | 691,179 |
def tsorted(a):
"""Sort a tuple"""
return tuple(sorted(a)) | 8b2f4946453759447258fb3c437a9babd2c3e92a | 691,180 |
def ignores_leakcheck(func):
"""
Ignore the given object during leakchecks.
Can be applied to a method, in which case the method will run, but
will not be subject to leak checks.
If applied to a class, the entire class will be skipped during leakchecks. This
is intended to be used for classes ... | 7947a760db8f065fcf6a6d980db57cb1aa5fd2d2 | 691,183 |
def or_condition(field, op, seq):
""" Return an 'or' condition of the format:
((field, ('op seq[0]', 'op seq[1]'...), )
Example
-------
>>> or_condition('tag', 'has', ('Web', 'Case Study', 'Testing'))
>>> ('tag', ('has Web', 'has Case Study', 'has Testing'),
"""
return ((field, tuple(["... | dac40cec3ddac98d59676a6b713be59ea7ca1af7 | 691,184 |
def generate_projwfc_node(generate_calc_job_node, fixture_localhost, tmpdir):
"""Fixture to constructure a ``projwfc.x`` calcjob node for a specified test."""
def _generate_projwfc_node(test_name):
"""Generate a mock ``ProjwfcCalculation`` node for testing the parsing.
:param test_name: The na... | 9e167013a320e6b69d0121a820ea62efc9fc9f92 | 691,185 |
def to_fixed_point(val: float, precision: int) -> int:
"""
Converts the given value to fixed point representation with the provided precision.
"""
return int(val * (1 << precision)) | 182cd3b94679dab3c0247c2478029750f1fd6753 | 691,186 |
from typing import Any
from typing import Optional
def try_int(value: Any) -> Optional[int]:
"""Convert a value to an int, if possible, otherwise ``None``"""
return int(str(value)) if str(value).isnumeric() else None | ced219e25a66286df327dd41a85f328c5bc28ec4 | 691,187 |
def pre_process_tags(paragraph_element):
"""
Convert initial italics-tagged text to markdown bold
and convert the rest of a paragraph's I tags to markdown italics.
"""
first_tag = paragraph_element.find("I")
if first_tag:
bold_content = first_tag.text
first_tag.replaceWith("**{}*... | 2db70456626a50111c664959a5c6591770567bd2 | 691,189 |
def limit_versions(language, limit, operator):
"""
Limits given languages with the given operator:
:param language:
A `Language` instance.
:param limit:
A number to limit the versions.
:param operator:
The operator to use for the limiting.
:return:
A new `Languag... | 77a7780ca5b6b9e706ebb39c1b39239fae8269be | 691,190 |
import threading
def threaded_fn(func):
"""
A decorator for any function that needs to be run on a separate thread
"""
def wrapper(*args, **kwargs):
thread = threading.Thread(target=func, args=args, kwargs=kwargs)
thread.start()
return thread
return wrapper | de72cc698cbbb2404e853930fcf848f2b05bff20 | 691,196 |
import re
def replace_links(text, link_patterns):
"""
A little function that will replace string patterns in text with
supplied hyperlinks. 'text' is just a string, most often a field
in a django or flask model. link_pattern is a list of two element
dictionaries. Each dicationary must have keys... | 087bfc736d2c859fdd6828255993de52af935e45 | 691,199 |
def input_action(i, _):
"""Returns the input that matched the transition"""
return i | fff447c9d049f335e485f35ab4925879b72ee585 | 691,200 |
def byteToHex( byteStr ):
"""
Convert a byte string to it's hex string representation e.g. for output.
"""
# Uses list comprehension which is a fractionally faster implementation than
# the alternative, more readable, implementation below
#
# hex = []
# for aChar in byteStr:
# hex.append... | b599eb3e24495c8f2dc76c4b83c1d71c0919c599 | 691,201 |
def split(p):
"""Split a pathname. Returns tuple "(head, tail)" where "tail" is
everything after the final slash. Either part may be empty."""
i = p.rfind('/') + 1
head, tail = p[:i], p[i:]
if head and head != '/'*len(head):
head = head.rstrip('/')
return head, tail | ae48332005fe4fe490702bd0f514190dbf856c93 | 691,203 |
def isvalid(ctx, a):
""" Test if an identifier is known.
Returns a string '1' if valid, '0' otherwise.
"""
plotid = a.plotid()
return "%d" % (1 if ctx.isvalid(plotid) else 0) | c2b433bd4f0a4e4d0ce9443d55e659b1dc96321a | 691,214 |
def listbox_identify(listbox, y):
"""Returns the index of the listbox item at the supplied (relative) y
coordinate"""
item = listbox.nearest(y)
if item != -1 and listbox.bbox(item)[1] + listbox.bbox(item)[3] > y:
return item
return None | a378f792b9274a03895e4a646a9418e594e5537f | 691,218 |
def _s_(n: int) -> str:
"""Return spaces."""
return " " * n | 028098a8971f690b55dd60ffb8e235a8b4244c63 | 691,223 |
import math
def taylor_exp(x, accuracy=20):
"""
A function to get e^x.
It uses the taylor expansion of e^x.
## https://en.wikipedia.org/wiki/Exponential_function ##
Be aware that this loses accuracy fairly quickly.
Accuracy can be somewhat increased, but there is a limit
to how large... | 68db3f3164fee700c76fafcd312eae0bd4012744 | 691,226 |
def get_true_graph(env):
"""Given an environment, unwrap it until there is an attribute .true_graph."""
if hasattr(env, 'true_graph'):
g = env.true_graph
assert hasattr(g, 'As')
return g
elif hasattr(env, 'env'):
return get_true_graph(env.env)
else:
return None | efbd530f2aa460af1d649d286678ac2dce7954e2 | 691,229 |
def register(dmm, typecls):
"""Used as decorator to simplify datamodel registration.
Returns the object being decorated so that chaining is possible.
"""
def wraps(fn):
dmm.register(typecls, fn)
return fn
return wraps | c8ee7372ee4f651015f26bc67e93d529c6a580c0 | 691,230 |
def build_source_url(username, repository):
"""
Create valid GitHub url for a user's repository.
:param str username: username of the repository owner
:param str repository: name of the target repository
"""
base_url = 'https://github.com/{username}/{repository}'
return base_url.format(user... | 511a29a9bf7625e3b580880d264df78f80bef8c6 | 691,232 |
def _type_name(obj: object) -> str:
"""Get type name."""
return type(obj).__qualname__ | 0ced2627eaf459c09daaa4e92d4686a58188b5a3 | 691,233 |
def log_function(func):
"""
A decorator to log arguments of function
"""
fname = func.__code__.co_name
arg_names = func.__code__.co_varnames
def echo_func(*args, **kwargs):
"""
Echoes the function arguments
"""
print("[!]", fname + ": ", ", ".join("%s=%r" % entry... | 5fb1657209f5fe105a315ecd08b909b157eef1db | 691,239 |
def clamp(minValue, maxValue, value):
"""Make sure value is between minValue and maxValue"""
if value < minValue:
return minValue
if value > maxValue:
return maxValue
return value | 17a7d58f441143ec77c965b1c8cd9eb5a70f1372 | 691,240 |
def reconstruct_pod(coeffs, R):
"""
Reconstruct grid from POD coefficients and transormation matrix R.
Args:
coeffs (np.array): POD coefficients
R (np.array): Transformation matrix R
Returns:
np.array: Reconstructed grid
"""
return R @ coeffs | d13dd1aca6f7ffee6a805d50e94883d6ec58b0bc | 691,244 |
def cube_to_axial(c):
"""
Converts a cube coord to an axial coord.
:param c: A cube coord x, z, y.
:return: An axial coord q, r.
"""
x, z, _ = c
return x, z | 39c614c072b4e886e3ae3f6a2c8ecd40918cff8d | 691,245 |
from typing import Dict
from typing import Union
def _are_agent_locations_equal(
ap0: Dict[str, Union[float, int, bool]],
ap1: Dict[str, Union[float, int, bool]],
ignore_standing: bool,
tol=1e-2,
ignore_y: bool = True,
):
"""Determines if two agent locations are equal up to some tolerance."""
... | 0bcdf03a128a6df1f3be653c74355c00c0097692 | 691,246 |
import time
def retry_function(function, action_name, err_msg,
max_retries=4, retry_delay=60):
"""Common utility to retry calling a function with exponential backoff.
:param function: The function to call.
:type function: function
:param action_name: The name of the action being pe... | b9c628f4940e204187771996e676975f90f782e7 | 691,250 |
import json
from io import StringIO
def generate_validation_error_report(e, json_object, lines_before=7, lines_after=7):
"""
Generate a detailed report of a schema validation error.
'e' is a jsonschema.ValidationError exception that errored on
'json_object'.
Steps to discover the location of the... | ccba131c6e524ee0a990bdd6dc440248d3684ac2 | 691,253 |
def set_first_line(img, pixels):
"""Set the first line of an image with the given pixel values."""
for index, pixel in enumerate(pixels):
img.set_pixel(index, 0, pixel)
return img | c87f5cf42591443c06b6b352c9f65cb898cfccf2 | 691,254 |
def istype(obj, allowed_types):
"""isinstance() without subclasses"""
if isinstance(allowed_types, (tuple, list, set)):
return type(obj) in allowed_types
return type(obj) is allowed_types | 5c441a69030be82e4d11c54ea366ee3463d388c8 | 691,257 |
def scale3D(v,scale):
"""Returns a scaled 3D vector"""
return (v[0] * scale, v[1] * scale, v[2] * scale) | 61ce41b706d1f9aadb9241c87ebd6c0757def159 | 691,259 |
def tokenize(chars):
"""Convert a string of characters into a list of tokens."""
# Idea from http://norvig.com/lispy.html
line = chars.replace(
'[', ' [ ').replace(']', ' ] ').replace(',', ' ').split()
for i, v in enumerate(line):
if v != '[' and v != ']':
line[i] = int(v)
... | 742b3594ca94cc8ea163a5879074a686f3bc7769 | 691,262 |
from typing import Tuple
def clean_version(package) -> Tuple[str, str, str]:
""" Splits the module from requirments to the tuple: (pkg, cmp_op, ver) """
separators = ["==", ">=", "<=", "!="]
for s in separators:
if s in package:
return package.partition(s)
return (package, "", ""... | 4606a5b976ca2bfe6eca9e54e40564f42e451b1e | 691,264 |
def get_gate_info(gate):
"""
gate: str, string gate. ie H(0), or "cx(1, 0)".
returns: tuple, (gate_name (str), gate_args (tuple)).
"""
gate = gate.strip().lower().replace("cnot", "cx")
i = gate.index("(")
gate_name, gate_args = gate[:i], eval(gate[i:])
try: len(gate_args)
except Type... | 48f75c184c441d8884ae691db2af3a90684d574c | 691,266 |
import random
def PickFromPool(n, pool, a_as_set):
"""Returns n items from the pool which do not appear in a_as_set.
Args:
n: number of items to return.
pool: an sequence of elements to choose from.
a_as_set: a set of elements which should not appear in the result.
Returns:
List of n items fro... | e856772b02232fefe84366d0399900e79fd07adb | 691,267 |
def query_for_message_ids(service, search_query):
"""searching for an e-mail (Supports the same query format as the Gmail search box.
For example, "from:someuser@example.com rfc822msgid:<somemsgid@example.com>
is:unread")
"""
result = service.messages().list(userId='me', q=search_query).execute()
... | a973708e211feb5f77a3b8dfcf65df43535a9f44 | 691,268 |
def trim(s):
"""Trim string to fit on terminal (assuming 80-column display)"""
return s if len(s) <= 80 else s[:77] + "..." | b3c2236b902bf20e0f2e4e7c97cfb57487ec1031 | 691,271 |
def euler(Tn, dTndt, tStep):
"""
Performs Euler integration to obtain T_{n+1}.
Arguments:
Tn: Array-like representing Temperature at time t_n.
dTndt: Array-like representing dT/dt at time t_n.
tStep: Float determining the time to step over.
Returns T_{n+1} as an array-like.
""... | 12a89ba6c777880ab20cfe04ecd13a6ab2ecc601 | 691,273 |
def get_opts(options):
"""
Args:
options: options object.
Returns:
args (tuple): positional options.
kwargs (map): keyword arguments.
"""
if isinstance(options, tuple):
if len(options) == 2 and isinstance(options[-1], dict):
args, kwargs = options
... | 3bc8f06e66b9c3d8b8b7cbc3e67087bcfe9fd7da | 691,278 |
from pathlib import Path
def count_files(path, glob=None) -> int:
"""Return the number of files in a given directory."""
path = Path(path)
files = path.glob(glob) if glob else path.iterdir()
return sum(1 for file in files if file.is_file()) | 39d10368c8e6a073a0dca290b74520a177244a2b | 691,279 |
def arkToInfo(ark):
"""
Turn an ark id into an info: uri
"""
parts = ark.split("ark:", 1)
if len(parts) != 2:
return ark
return "info:ark%s" % parts[1] | 38295232ea4bc649d28e6bd35e9ff4eee1dc4045 | 691,280 |
import torch
def create_rectified_fundamental_matrix(batch_size):
"""Creates a batch of rectified fundamental matrices of shape Bx3x3"""
F_rect = torch.tensor([[0.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]]).view(1, 3, 3)
F_repeat = F_rect.repeat(batch_size, 1, 1)
return F_repeat | f641d914a6d0cf91e7e07ffc619b70dc1e4381a0 | 691,284 |
def get_midpoint(origin, destination):
""" Return the midpoint between two points on cartesian plane.
:param origin: (x, y)
:param destination: (x, y)
:return: (x, y)
"""
x_dist = destination[0] + origin[0]
y_dist = destination[1] + origin[1]
return x_dist / 2.0, y_dist / 2.0 | d1a0f2a476efe66688d2a686febc0a3d0a94caaa | 691,287 |
def _ReplaceNameByUuidProcessLine(
node_name, _key, line_identifier, line_key, found, node_uuid=None):
"""Replaces a node's name with its UUID on a matching line in the key file.
This is an auxiliary function for C{_ManipulatePublicKeyFile} which processes
a line of the ganeti public key file. If the line in... | eb4bc4d320cbbde7d0d56032f0c071629cdb81c3 | 691,291 |
def quality_index(dat, colname):
"""Return the index for `colname` in `dat`"""
colname = colname.split(':')[0]
return list(dat.dtype.names).index(colname) | d13f89bd6da6ea09637433d2ed7c6378a738a6cf | 691,293 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.