content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def underline_to_hump(underline_str):
"""
Transfer underline to hump
Args:
underline_str(string): underline code string
"""
sub = re.sub(r'(_\w)', lambda x: x.group(1)[1].upper(), underline_str)
return sub | 74,200 |
def get_query_workload(duration_sec, rate):
"""
Returns an array of query tuples (see get_next_query()) for the given duration and rate
"""
cur_time = 0.0
workload = []
while cur_time < duration_sec:
q = get_next_query(rate, duration_sec)
cur_time += q["dt"]
workload.appe... | 74,201 |
def _is_sound_file(name):
"""Returns: True if name is the name of an font file.
Parameter name: A file name
Precondition: NONE"""
if type(name) != str:
return False
return os.path.exists(SOUND_PATH+'/'+name) | 74,202 |
def test_startofweek_offset():
"""startofweek works correctly for a column arg."""
db = FakeDatabase("help", "Samples")
tbl = TableExpr("tbl", database=db, columns={"foo": datetime})
query = tbl.project(weekstart=F.startofweek(tbl.foo, 1))
assert "weekstart" in query.columns
assert "foo" not in ... | 74,203 |
def successor(node):
""" 4.6 Successor: Write an algorithm to find the "next" node
(i.e., in-order successor) of a given node in a binary search tree.
You may assume that each node has a link to its parent.
"""
def get_min(node):
if node.left != None:
return get_min(node.left)
... | 74,204 |
def get_length_audio(audiopath, extension):
"""
Returns length of audio in seconds.
Returns None if format isn't supported or in case of error.
"""
try:
audio = AudioSegment.from_file(audiopath, extension.replace(".", ""))
except Exception:
print(f"Error in get_length_audio(): {t... | 74,205 |
def load_schema(data):
"""
Load Schema/Example data depending on its type (JSON, XML).
If error in parsing as JSON and XML, just returns unloaded data.
:param str data: schema/example data
"""
try:
return json.loads(data)
except Exception: # POKEMON!
pass
try:
... | 74,206 |
def netcdf_file_handler(index):
"""
Returns file info and phenomena information of a NETCDF file.
"""
fname = "file_%02d" % index
fmeta = get_file_doc(fname)
#fphen = get_file_phenomena()
fphen = get_file_phenomena_i(index)
return (fmeta, fphen) | 74,207 |
def get_reference_number_from_object_name(object_name_string):
""" Given s3 object name: 'e23413582523--QUIDP.json' or 'e23413582523P.json':
return just 'e23413582523'
"""
logger.debug(f"Received: {object_name_string}")
if '--' in object_name_string:
reference_number = object_name_st... | 74,208 |
def test__missingcols__validate():
"""Test missing columns"""
assay_info_df = pd.DataFrame()
test_dict = copy.deepcopy(GDC_DATA_DICT)
with patch.object(process_functions, "get_gdc_data_dictionary",
return_value=test_dict) as patch_get_gdc:
error, warning = ASSAY_INFO._valid... | 74,209 |
def test_Axis_to_numpy():
"""Check that '.to_numpy' returns a numpy array"""
axis = Axis.from_array(())
assert isinstance(axis.to_numpy(), np.ndarray) | 74,210 |
def multi_find_threshold(models, dataloaders, metric, device=None, num_thresholds=1000):
"""Searches for the best single and per-class decision thresholds for each model
Wrapper function around ``find_single_threshold```and ``find_class_threshold``
built to handle multiple models and return the single and ... | 74,211 |
def calculate_transform(src, dst, model_class=AffineTransform):
"""Calculate transformation matrix from matched coordinate pairs.
Parameters
----------
src : ndarray
Matched row, column coordinates from source image.
dst : ndarray
Matched row, column coordinates from destination ima... | 74,212 |
def after_attack_all(skills: Iterable[Skill], arena: ActiveArena, data: AfterAttackData) -> List[Dict]:
"""
Executes the after_attack_effect for all the given skills, if such exists, returning a list
of their cumulative output, if applicable
:param skills: an iterable containing Skills whose after_attac... | 74,213 |
def update(dxm_state, jobname, envname, rulesetname, email, feedback_size,
max_memory, min_memory, jobdesc, num_streams, profilename,
multi_tenant):
"""
Update an existing proflejob on Masking engine
Return non zero code if there was problem with updating a job
"""
params = {
... | 74,214 |
def _get_laplace_matrix_2d(bcs) -> Tuple[Any, Any]:
"""get sparse matrix for laplace operator on a 2d Cartesian grid
Args:
bcs (:class:`~pde.grids.boundaries.axes.Boundaries`):
{ARG_BOUNDARIES_INSTANCE}
Returns:
tuple: A sparse matrix and a sparse vector that can be used to eva... | 74,215 |
def change_part2_function(ranking_file, c_nameplayer, c_pet, c_age,
c_total_score, c_position, c_value,
c_number, c_new):
"""Deze functie stuurt alle variabelen die nodig zijn
voor het nieuwe ranking bestand door naar een nieuwe functie.
Tenzij de pos... | 74,216 |
def build_zooma_query(trait_name: str, filters: dict, zooma_host: str) -> str:
"""
Given a trait name, filters and hostname, create a url with which to query Zooma. Return this
url.
:param trait_name: A string containing a trait name from a ClinVar record.
:param filters: A dictionary containing fi... | 74,217 |
async def test_flow_entry_already_exists(hass):
"""Test user input for config_entry that already exists."""
first_entry = MockConfigEntry(
domain="tibber", data={CONF_ACCESS_TOKEN: "valid"}, unique_id="tibber",
)
first_entry.add_to_hass(hass)
test_data = {
CONF_ACCESS_TOKEN: "valid"... | 74,218 |
def _flatten_nested_jacobian(jacobian, state_shape):
"""Flattens a nested Jacobian into a matrix.
The flattening and concatenation follows the interpretation of the structure
as being a leading 'axis', meaning that if the input has 'shape':
[input_structure, A, B], and the output has 'shape':
[output_structu... | 74,219 |
def calc_mean_squared_error(options):
"""
Calculate mean squared error between the original and decompressed reads.
"""
std_err_file = open('mse.log', 'w')
for compression_method in options.compressed_dirs:
for reads_filename in options.reads_filenames:
MSE_CMD = "python src/e... | 74,220 |
def figletbulbhead(txt):
""" FigletBulbLook Text """
f = Figlet(font='bulbhead')
return f'{f.renderText(txt)}' | 74,221 |
def write_dat(data, output_dir='./'):
"""Write dispersion profiles into a file"""
datasets = dict()
for data_point in data:
experiment_name = data_point.par['experiment_name']
datasets.setdefault(experiment_name, list()).append(data_point)
for experiment_name, data in datasets.items()... | 74,222 |
def run_delete_old_groups():
"""
Run workflow to delete old groups.
First get all old project ids from remaining groups.
Then delete all groups for the given project_ids.
"""
projects = get_old_groups()
for project_id in projects:
delete_old_groups(project_id)
logger.info(f"... | 74,223 |
def bytes_to_element(type, bytes, byteorder = 'little'):
"""Returns a python object parsed from bytes
:param type: the type of the object to parse
:param bytes: the bytes to read
:param byteorder: little or big endian
"""
if type == 'char':
return ord(struct.unpack('<b', bytes)[0])
... | 74,224 |
def pickle_load(cwd,file_Name):
"""
Load pickled data from current working directory.
INPUT: cwd - Current working directory.
file_name - Name of pickled data to be loaded.
OUTPUT: filePickle - Loaded pickle data.
"""
print('\nLoading data...\n')
os.chdir(cwd)
fileObject = ... | 74,225 |
def extract_predictions(data, predictions):
"""' Joins a dataframe containing match data with one
containing predictions, returning a dataframe with
team names, predicted values, and if available, the
actual outcome (in points).
"""
probs = _team_test_prob(predictions)
teams0 = []
teams1... | 74,226 |
def naturalnumber(value: int | float, *, caps: bool = True, digits=1) -> str:
"""
Makes a number to a human-readable string.
Examples:
naturalnumber(1000) -> "1k"
naturalnumber(100000) -> "100k"
naturalnumber(1000000) -> "1m"
naturalnumber(1000000000) -> "1b"
naturalnumber(1000000000, c... | 74,227 |
def request_analysis(user, analysis_func, subject, *other_args, **kwargs):
"""Request an analysis for a given user.
:param user: User instance, user who want to see this analysis
:param subject: instance which will be used as first argument to analysis function
:param analysis_func: AnalysisFunc instan... | 74,228 |
def sequences_to_one_hot(sequences, chars='ACGTN'):
"""
:param sequences:
:param chars:
:return:
"""
seqlen = len(sequences[0])
char_to_int = dict((c, i) for i, c in enumerate(chars))
one_hot_encoded = []
for seq in sequences:
onehot_seq = []
integer_encoded = [ch... | 74,229 |
def __virtual__():
"""Only load keystonev3 if requirements are available."""
if REQUIREMENTS_MET:
return 'keystonev3'
else:
return False, ("The keystonev3 execution module cannot be loaded: "
"os_client_config or keystoneauth are unavailable.") | 74,230 |
def thread_create(request, forum_slug):
"""
"""
raise NotImplementedError(
"TODO: Implement 'thread-create' endpoint (%s)"
% reverse('forum:thread-create', kwargs = { 'forum_slug': forum_slug })
) | 74,231 |
def combined_equal_all_basic_types() -> tuple:
"""Combined tuple of all basic types"""
combined_types: tuple = tuple(
(value, value) for value in _ALL_BASIC_TYPES_1.values()
)
return combined_types | 74,232 |
def n_cyber_object_to_node(graph):
"""
Initial function to create the blank nodes for each of the file's facet nodes
:param graph: rdflib graph object for adding nodes to
:return: The four blank nodes for each fo the other functions to fill
"""
cyber_object_facet = rdflib.BNode()
n_raster_fa... | 74,233 |
def freeze_module_until(module, name):
"""
Freeze all submodules inplace before and including `name`. If `isintance(name, list)`,
submodules before and including every `name` will be frozen.
Args:
module (nn.Module): torch.nn.Module
name (list(str)): submodule name
"""
def _is_c... | 74,234 |
def run_unittests_for_setup(file_or_folder, skip_function=None, setup_params=None,
only_setup_hook=False, coverage_options=None, coverage_exclude_lines=None,
additional_ut_path=None, covtoken=None, hook_print=True, stdout=None,
stderr=N... | 74,235 |
def create_archived_attendance(user_id: UserID, party_id: PartyID) -> None:
"""Create an archived attendance of the user at the party."""
table = DbArchivedAttendance.__table__
query = insert(table) \
.values({
'user_id': str(user_id),
'party_id': str(party_id),
}) \... | 74,236 |
def pad_to_batch(dataset, batch_size):
"""Pad Tensors to specified batch size.
Args:
dataset: An instance of tf.data.Dataset.
batch_size: The number of samples per batch of input requested.
Returns:
An instance of tf.data.Dataset that yields the same Tensors with the same
structure as the origin... | 74,237 |
def apply_ast_transformations(source):
"""Used to convert the source code into an AST tree and applying
all AST transformer specified in the source code. It returns
a (potentially transformed) AST tree.
"AST transformers" are modules which must contain a function
transform_ast(tree... | 74,238 |
def plot_prediction(step, net, batch):
"""
plot mel prediction
"""
eval_net = jax.tree_map(lambda x: x[0], net.eval())
gt_mel, predicted_mel = gta_prediction(eval_net, batch)
fig, ax = plt.subplots(2, 1, figsize=(10, 6))
gt_mel = gt_mel[0].astype(jnp.float32).T
ax[0].imshow(gt_mel, aspec... | 74,239 |
def main() -> None:
"""
Main entry point
"""
try:
asyncio.run(_main())
except KeyboardInterrupt:
return | 74,240 |
def vlines_ranges(X, aggr=('min', 'median', 'max'), axis=0, **kwargs):
"""vlines plot statistics of X matrix data"""
if isinstance(aggr, int):
if aggr == 2:
aggr = ('min', 'max')
elif aggr == 3:
aggr = ('min', 'median', 'max')
assert len(aggr) >= 2, 'aggr must have at... | 74,241 |
def create_full_name_without_space_fields(romanize_method, given_name,
family_name):
"""
Creates fields with the full name without white spaces.
Returns:
fullname fields, romanized_name_list: (for check)
"""
fields = []
romanized_name_list = []
... | 74,242 |
def test_encorr_schema():
"""Test creating an instance of EnCorr"""
supported_elements = ['H', 'C', 'N', 'O', 'S', 'P']
aec = {'H': -0.502155915123, 'C': -37.8574709934, 'N': -54.6007233609,
'O': -75.0909131284, 'P': -341.281730319, 'S': -398.134489850}
bac = {'C-H': 0.25, 'C-C': -1.89, 'C=C'... | 74,243 |
def scale_up_dynos(app):
"""Scale up the Heroku dynos."""
dyno_type = dlgr.config.server_parameters.dyno_type
num_dynos = {
"web": dlgr.config.server_parameters.num_dynos_web,
"worker": dlgr.config.server_parameters.num_dynos_worker
}
for process in ["web", "worker"]:
subpr... | 74,244 |
def test_memoization_with_invalid_timeout_value():
"""
This test should raise and exception for timeout None or any other value than int or float"
:return:
"""
test_result = 5
test_function = lambda key: test_result
# timeout = 0 should raise exception
with pytest.raises(TypeError, matc... | 74,245 |
def read_wdnr_monthly_water_use(wu_file, wu_points, model,
active_area=None,
drop_ids=None,
minimum_layer_thickness=2
):
"""Read water use data from a master file generated from
WDNR_w... | 74,246 |
def test_update_panel_maintainer(mock_app):
"""Tests the CLI that updates a panel with maintainers"""
runner = mock_app.test_cli_runner()
assert runner
# Test adding a non-existing user
result = runner.invoke(
cli, ["update", "panel", "-p", "panel1", "-a", "noone@nowhere.no"]
)
ass... | 74,247 |
def create_coupon(auth_token: str, mavenseed_url: str, args: Args) -> None:
"""Creates a coupon with the given coupon code on the Mavenseed platform."""
def generate_random_coupon_code() -> str:
"""Generates a random coupon code with 8 characters."""
import random
import string
... | 74,248 |
def validate_clockwise_points(points):
"""
Validates that the points that the 4 points that dlimite a polygon are in clockwise order.
"""
if len(points) != 8:
raise Exception("Points list not valid." + str(len(points)))
point = [
[int(points[0]) , int(points[1])],
... | 74,249 |
def get_available_recipes():
""" Returns a dict of the available user-recipes """
recipes = {}
for name, data in custom_recipes.items():
recipes[name] = {
'name': name,
'parameters': data['parameters']
}
return recipes | 74,250 |
def wait_for_workflows(client, namespace, names,
timeout=datetime.timedelta(minutes=30),
polling_interval=datetime.timedelta(seconds=30),
status_callback=None):
"""Wait for multiple workflows to finish.
Args:
client: K8s api client.
namespac... | 74,251 |
def test_success_with_pre_signed_distribution(upload_settings, stub_repository):
"""Add GPG signature provided by user to uploaded package."""
# Upload a pre-signed distribution
result = upload.upload(
upload_settings, [helpers.WHEEL_FIXTURE, helpers.WHEEL_FIXTURE + ".asc"]
)
assert result i... | 74,252 |
def passwd(filename: str, alt_schema: bool) -> None:
"""Find all the valid passwords within a file according to the defined policy.
Example passwords:
1-3 a: abcde
1-3 b: cdefg
2-9 c: ccccccccc
1st Policy:
Each line gives the password policy and then the password. The password policy
indicates the l... | 74,253 |
def _uncomment_magic(line):
"""Reverts the comments applied to magics (line level)
"""
if line.startswith(_PREFIX):
return line[_PREFIX_LEN:]
parts = _is_commented_line_magic(line)
if parts:
code, magic = parts
return f'{magic} {code}'
else:
return line | 74,254 |
def get_context(entity):
"""Returns the operating context of the given object.
If the object is a subclass of Context, returns the top most context (or
containing instance) of the object.
If the object is a builtin object, returns the operating module (if available).
Otherwise, returns the object... | 74,255 |
def ret(d: dict, key: str) -> Any:
""" Unwrap nested dictionaries in a recursive way.
Parameters
----------
d: dict
Python dictionary
key: str or Any
Key or chain of keys. See example below to
access nested levels.
Returns
----------
out: Any
Value from ... | 74,256 |
def distribute_product(immutability, product_name, source_path,
packaging_path, parms, user, group):
"""
Determines if the distribution method is set to local or remote and
calls the correct distribution method.
Args:
immutability: Whether or not to set the immutability f... | 74,257 |
def decrypt_config(file_path: str):
"""
Decrypts the configuration from REvil
:param file_path: Unpacked payload
:return: JSON config
"""
if not os.path.isfile(file_path):
print("[-] Invalid file path")
return None
# Loads the PE file
pe = pefile.PE(file_path)
# Che... | 74,258 |
def _conical_frustum_to_gaussian(z_vals: f32['... num_samples 1'],
rays: types.Rays):
"""Approximate a conical frustum as a Gaussian distribution (mean+cov).
Assumes the ray is originating from the origin, and rays.base_radius is the
radius at dist=1. Doesn't assume rays.directio... | 74,259 |
def train_arguments():
"""Used only for training"""
parser = argparse.ArgumentParser(parents=[generic_arguments()])
parser.description = 'Train the network'
# General parameters
parser.add_argument('--lr', default=3e-4, type=float, help='Learning rate during training')
parser.add_argument('--gr... | 74,260 |
def MLE_NQB_sim(n, measurements, paulis, variances, density_matrix,
tolerance, random_initialization, max_iter_num, nlvl=2,
plot_convergence=False, verbose=False, directory_path=""):
"""Maximum likelihood estimation for n_qubit n_level qubit state tomography.
For illustrativ... | 74,261 |
def run_interp_back(kdat, tm, params):
"""Interpolates kdat to on-grid coordinates.
Args:
kdat (tensor): The off-grid frequency data.
tm (tensor): Normalized frequency coordinates.
params (dict): Dictionary with elements 'dims', 'table', 'numpoints',
'Jlist', and 'table_over... | 74,262 |
def portmap_portstat_route(port):
"""generate port statistics fragment"""
stats = db.session.query(Service.proto, func.count(Service.id)).join(Host) \
.filter(Service.port == port) \
.group_by(Service.proto).order_by(Service.proto)
infos = db.session.query(Service.info, func.count(Service.... | 74,263 |
def main():
"""docstring for main"""
from settings import global_settings
restore(global_settings.ISSUES_ROOT) | 74,264 |
def ensure_dir(directory):
"""
Ensure a directory exists
Parameters
----------
directory : str
Name of the directory to check
Returns
-------
None
nil
"""
if not os.path.exists(directory):
os.makedirs(directory) | 74,265 |
def authenticate(data):
"""Admin broadcast channel authentication"""
if "token" in data:
current_user = User.verify_auth_token(data["token"])
if current_user is not None and current_user.can(Permission.ADMIN):
room = Channel.get_room()
join_room(room)
emit("au... | 74,266 |
def main(quote, **kwargs):
"""
Creates a PIL Image with 'quote' printed on it.
:param quote: The message to be printed on the image
:keyword shadow: Whether to add shadow to the text or not.
:keyword noise: The amount of graphics to be overlaid on the image
:keyword text_color: The colour of the text as a hex ... | 74,267 |
def closet_common_manager(ceo: Employee, first_employee: Employee, second_employee: Employee)->Employee:
""" 得到our boss
:param ceo: 起始节点,Employee
:param first_employee: 第一个雇员, Employee
:param second_employee: 第二个雇员, Employee
:return: 一般会返回一个正确的结果,
异常情况:Employee.EmployeeNotIn -> 雇员不在ceo管辖范围
... | 74,268 |
def instance_destroy(context, instance_uuid, constraint=None,
update_cells=True):
"""Destroy the instance or raise if it does not exist."""
rv = IMPL.instance_destroy(context, instance_uuid, constraint)
if update_cells:
try:
cells_rpcapi.CellsAPI().instance_destroy_at_top(context... | 74,269 |
def central_difference_order(f, x, h, n):
"""
Evaluates the n-th derivative at x, with step size h, using a central
difference scheme (of degree 1).
@type f: function
@param f: function to differentiate
@type x: number
@param x: position at which to evaluate
@type h: number
@para... | 74,270 |
def get_traceback(exc=None):
"""
Returns the string with the traceback for the specifiec exc
object, or for the current exception exc is not specified.
"""
if exc is None:
exc = sys.exc_info()
if not exc:
return None
tb = exc[2]
sio = StringIO()
traceback.print_tb(tb... | 74,271 |
def group_excessive_points(gdf: gpd.geodataframe.GeoDataFrame, cell_size: float):
"""
Creates groupings of collocated points exceeding a threshold.
By default, a grouping is defined as three times the average
cell size of the input file.
:param gdf:
:param cell_size:
:return:
"""... | 74,272 |
def local_conv2d(inputs,
kernel,
kernel_size,
strides,
output_shape,
data_format="channels_last"):
"""Apply 2D conv with un-shared weights.
Arguments:
inputs: 4D tensor with shape:
(batch_size, filters, new_rows... | 74,273 |
def convex_hull(points, return_copy=False):
"""Computes the convex hull of a set of 2D points.
Input: an iterable sequence of (x, y) pairs representing the points.
Output: a list of vertices of the convex hull in counter-clockwise order,
starting from the vertex with the lexicographically... | 74,274 |
def unit_to_altaz(x, y):
"""Convert coordinates on the projected skydome to alt,az coordinates
Args:
x, y: float coordinates, normalised to the unit circle
Returns:
Tuple[float, float]: alt, az coordinates in degrees
"""
R = min(sqrt(x**2 + y**2), 1)
alt = degrees(a... | 74,275 |
def fields_in_create(obj: Any):
"""Build dictionary for data insert by adding createdAt field"""
if isinstance(obj, BaseModel):
return { **obj.dict(), "createdAt": datetime.utcnow(), "updatedAt": None}
else:
return { **obj, "createdAt": datetime.utcnow(), "updatedAt": None}
pass | 74,276 |
def build_matrix(node, m, k, D, beta):
"""Compute k-tree algorithm matrices for each node of the tree.
Args:
node (KTreeNode): the top node of the tree.
m (int): the alphabet size.
k (int): the number of trees requested.
D (int): the depth of the tree.
Returns:
... | 74,277 |
def mesh_select_face(mesh, message="Select a face."):
"""Select a single face of a mesh.
Parameters
----------
mesh: :class:`compas.datastructures.Mesh`
message: str, optional
Returns
-------
int or None
"""
guid = rs.GetObject(message, preselect=True, filter=rs.filter.mesh | r... | 74,278 |
def simpleMergeMotifs(motifs, window=0):
"""
aggregates the motifs if they overlap, into one motif file
Args:
----
motifs: df bed-like of motifs locations
window: int maxsize around motif for which to still merge
Returns:
--------
df bedlike of merged motif:
df bedlike of motifs that were not merged as ... | 74,279 |
def to_minutes(hour, minute):
"""
converts hours to minutes and adds extra minutes in the time...
returns the sum
"""
return (hour * 60) + minute | 74,280 |
def plot_map_region(lon,lat,var,name,title='',lb=20,ub=30,spacing=0.25):
"""
This function plots a map of the variable you specify.
Arguments are:
lon, lat, variable to plot, name of file to be saved to, title (optional).
A large range is used for the variable and the spacing.
This applies to eg global maps... | 74,281 |
async def test_tz_aware(client: Prisma) -> None:
"""Modifying timezone still finds the record"""
record = await client.types.create(data={})
found = await client.types.find_first(
where={
'datetime': {
'lt': (
record.datetime + datetime.timedelta(hours... | 74,282 |
def _copy_to_tail_args(args: Namespace, as_router: bool = True) -> Namespace:
"""Set the incoming args of the tail router
"""
_tail_args = copy.deepcopy(args)
_tail_args.port_in = random_port()
_tail_args.port_ctrl = random_port()
_tail_args.socket_in = SocketType.PULL_BIND
_tail_args.uses =... | 74,283 |
def autolabel(rects, ax, xpos='center'):
"""
Attach a text label above each bar in *rects*, displaying its height.
*xpos* indicates which side to place the text w.r.t. the center of
the bar. It can be one of the following {'center', 'right', 'left'}.
"""
ha = {'center': 'center', 'right': 'lef... | 74,284 |
def test_list_gpg_keys_info(info_gpg_key):
"""
Test list_gpg_keys with extra information
"""
info_gpg_key.side_effect = lambda x, root: {"Description": "key for {}".format(x)}
mock = MagicMock(return_value="\n".join(["gpg-pubkey-1", "gpg-pubkey-2"]))
with patch.dict(rpm.__salt__, {"cmd.run_stdou... | 74,285 |
def encodeAsMarket(data):
"""
Hide data inside a url commonly used for email personalization
Parameters:
data - the data to encode
Returns: a dictionary with the key 'url' referencing a string
holding the url and the key 'cookie' holding an array of 0 or more
cookies.
Note: Cookies will be used to st... | 74,286 |
def is_identity(u):
"""Checks if the unit is equivalent to 1"""
return u.unitSI == 1 and u.unitDimension == (0,0,0,0,0,0,0) | 74,287 |
def m_seq_inx_to_int(seq, args=0):
"""
将列表中单个列表中元素转成int,返回新的列表
:param seq: 列表形成的列表
:param args: 列表的次序
:return: 转换后的列表
example:
:seq [['30', 0], ['5', 1]]
:args 0
:return [[30, 0], [5, 1]]
"""
for i in seq:
... | 74,288 |
def convert_df_dates_to_str_or_none(df, cols):
"""Convert dataframe dates to str or None.
Parameters:
df (pd.DataFrame): The input dataframe
cols (sqlalchemy table columns): The colums for the associated table
Returns:
df (pd.DataFrame): DataFrame with idntified date columns as str... | 74,289 |
def find_nearest(df, value, value_col="Insertion Loss (dB)", index_col="Frequency (Hz)"):
"""Given a pandas dataframe, find value corresponding to nearest index"""
index = (np.abs(df[index_col]-value)).argmin()
return df[value_col][index] | 74,290 |
def source_df() -> pd.DataFrame:
"""
Produces a dataframe containing source coordinates for testing. Contains
ra and dec.
Returns:
Dataframe with coordinates.
"""
source_df = pd.DataFrame(
data={
'ra': [
12.59305887,
12.68310734,
... | 74,291 |
def txt(msg):
"""Will first make the msg a string, then make storage.text equal the msg as well as speak the msg"""
msg = str(msg)
spk(msg)
storage.text = msg | 74,292 |
def gen_files_from_zipfiles(
zipfilenames_or_files: Iterable[Union[str, BinaryIO]],
filespec: str,
on_disk: bool = False) -> Generator[BinaryIO, None, None]:
"""
Args:
zipfilenames_or_files: iterable of filenames or :class:`BinaryIO`
file-like objects, giving the ``.... | 74,293 |
def get_dzi_path(filepath):
"""
Get a path for the DZI relative to a rendered output file.
"""
return "%s/dzi/%s.dzi" % (os.path.dirname(filepath),
os.path.splitext(os.path.basename(filepath))[0]) | 74,294 |
async def test_create_instance_missing_schema(jp_fetch, schemaspace_location):
"""Attempt to create an instance using an invalid schema """
missing_schema = copy.deepcopy(valid_metadata_json)
missing_schema['name'] = 'missing_schema'
missing_schema['schema_name'] = 'missing_schema'
missing_schema.p... | 74,295 |
def read_from_csv(path):
"""read data from csv"""
if not Path(path).exists():
return None
if not path.endswith('.csv'):
return None
with open(path, 'r') as file:
data = pd.read_csv(file, header=0)
return data | 74,296 |
def compute_moments(features, input_channels=3):
"""
Computes means and standard deviation for 3 dimensional input for normalization.
"""
means = np.zeros(input_channels, dtype=np.float32)
stddevs = np.zeros(input_channels, dtype=np.float32)
for i in range(input_channels):
# very specifi... | 74,297 |
def _normalizeGlifContourFormat2(element):
"""
- Don't write unknown subelements.
"""
# INVALID DATA POSSIBILITY: unknown child element
# INVALID DATA POSSIBILITY: unknown point type
points = []
for subElement in element:
tag = subElement.tag
if tag != "point":
co... | 74,298 |
def _compile_fragment_ast(schema, current_schema_type, ast, location, context):
"""Return a list of basic blocks corresponding to the inline fragment at this AST node.
Args:
schema: GraphQL schema object, obtained from the graphql library
current_schema_type: GraphQLType, the schema type at the... | 74,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.