content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import numpy
def gauss_ellip(x: numpy.ndarray, y: numpy.ndarray, p: numpy.ndarray) \
-> numpy.ndarray:
"""
Elliptical Gaussian PSF
:param x: array of X coordinates
:param y: array of Y coordinates
:param p: 7-element array of parameters: (x0, y0, baseline, amplitude,
sigma_x, sigm... | 2883783d76f7178e96e950bddec40d1a4c6e874c | 627,847 |
def create_extra_dimensions_stats(customer_records_by_extra_dim):
"""Groups entry records by customer_id and extra_dimension.
Args:
customer_records_by_extra_dim: Tuple containing a tuple of customer_id
and extra_dimension and a list of transaction records related to
that combin... | a616d084496c980ed7dc2a465b84b18be853e701 | 627,848 |
def o_minimum(listy):
"""
Input: A list of numbers.
Output: The lowest number in the list, using min function.
"""
if listy != []:
return (min(listy)) | ba8de0de95406cb2d4636b5942cbb566e6474c83 | 627,849 |
def db2lin(value):
"""Convert logarithimic units to linear
>>> round(db2lin(10.0), 2)
10.0
>>> round(db2lin(20.0), 2)
100.0
>>> round(db2lin(1.0), 2)
1.26
>>> round(db2lin(0.0), 2)
1.0
>>> round(db2lin(-10.0), 2)
0.1
"""
return 10**(value / 10) | 8840989dc365eee46e7836749d3fc8fff14dc048 | 627,850 |
from shutil import copyfile
def make_bakup(directory: str, filename: str) -> None:
"""Make a bakup of the file."""
copyfile(f"{directory}{filename}", f"{directory}{filename}.bak")
return None | 010577d8c4960f15e5a6cca40fb2132f234c6213 | 627,851 |
import re
def isValidModelname(name):
"""Returns if a name contains characters other than alphanumeric, '_' and '-'.
Also, empyt strings are not valid model names.
Args:
name (str): potential name for a model
Returns:
bool -- True if the name is a valid model name according to conven... | 1d061d3b29d393dd093f5b5f862ecfb503b65d6e | 627,852 |
def Line2Float(line):
"""Convert a string into a list of Float"""
return map(float,line.split()) | 2f2fa2f1f8bc905a8a3a52f4bbab558dcfe8f2d7 | 627,853 |
def read_whitelist(input_file, global_whitelist):
"""global_whitelist contains lines for many files.
Return a collection of suppressed warnings for input_file"""
res = list()
with open(global_whitelist) as f:
for line in f:
# To make it compatible with cppsa's own output, ignore l... | 9af57d5ffb29e34e78e6a6fa1e98df998fba25e1 | 627,854 |
import sys
def get_best_matches(csvfile):
"""Find the best match for each transcript"""
FIRST_ID = 0
SECOND_ID = 1
best = []
prevbest = next(csvfile)
for row in csvfile:
if row[FIRST_ID] == row[SECOND_ID]:
pass
else:
if row[FIRST_ID] != prevbest[FIRST_... | 1916e50f2a49b1a5731d36d77021ca960318ef6b | 627,855 |
import socket
def get_current_hostname() -> str:
"""Returns the hostname of current machine
Returns:
str: current hostname
"""
return socket.gethostname() | b231dd9acf507b76f64890b7843f6165fcb9b630 | 627,857 |
def rr(n: int) -> float:
"""
Calcula el resultado de la serie.
:param n: número entero positivo mayor o igual a 1.
:return: resultado de la serie.
"""
if n == 1:
return 1
else:
return 1 / (n**2) + rr(n - 1) | 523e61f59d4637a2f66e58b56458716f1ab0d073 | 627,858 |
from typing import Iterable
from pathlib import Path
from typing import Optional
def searchcandidates(candidates: Iterable[Path]) -> Optional[Path]:
""" Searches for the first filename in `candidates` which exists. Returns `None` if none of the paths are valid.
Parameters
----------
candidates: List[Path]
T... | d5efeafda07e7b5ef8e3e111ce16df15b3b33f5d | 627,859 |
def determine_color(number):
"""
In number ranges from 1 to 10 and 19 to 28, odd numbers are red and even are black.
In ranges from 11 to 18 and 29 to 36, odd numbers are black and even are red.
"""
if number >= 1 and number <= 10:
return "black" if number % 2 == 0 else "red"
elif number... | ab27cc7f40c497d5710645d393f909f176bbde28 | 627,860 |
from typing import List
import functools
def count_arrangements_bf(joltages: List[int]) -> int:
"""recursive brute force: works (for the test cases), but takes way too
long for the "real" thing.
"""
@functools.lru_cache
def recursion(start):
if start == len(joltages) - 1:
retu... | 41ab1b571adfbdde40c42fba44424cbc7fc83200 | 627,862 |
def extract(query_dict, prefix=""):
"""
Extract the *order_by*, *per_page*, and *page* parameters from
`query_dict` (a Django QueryDict), and return a dict suitable for
instantiating a preconfigured Table object.
"""
strs = ['order_by']
ints = ['per_page', 'page']
extracted = { }
... | 4deb8f09e3b6185a389736b3eb7fdadb4b82ecfe | 627,863 |
def top_contributors_aoa(start=None, end=None, locale=None, count=10, page=1, use_cache=True):
"""Get the top Army of Awesome contributors."""
# AoA is deprecated, return 0 until we remove all related code.
return ([], 0) | 515d631a6208df928161061499006ee86d1b806c | 627,864 |
def filterOdometry(solutions, odometry):
"""Filter the solutions by odometry.
Removes solutions from the list if there are not within range
of the odometry.
Args:
solutions: A set of points candidates to the final solution.
odometry: Odometry instance.
Returns:
A list of c... | 707c6716f9baf6b5ee6be6adb91ec264aad4e67f | 627,865 |
def get_pending_vgroup(module, array):
""" Get Deleted Volume Group"""
vgroup = None
for vgrp in array.list_vgroups(pending=True):
if vgrp["name"] == module.params['vgroup'] and vgrp['time_remaining']:
vgroup = vgrp
break
return vgroup | 9396f78b6c23411c3e4e9d29b6050eef98885a61 | 627,867 |
import socket
import sys
def get_sock_char_line(sock, timeout=10.):
"""
Retrieves one newline terminated string from input open socket
"""
sock.settimeout(timeout)
chunks = []
indat = b'^'
try:
while indat[-1:] != b'\n':
# see https://github.com/obspy/obspy/issues/383
... | 434d561ff24065d02eb1f2f5e32fc72fea98d7a6 | 627,868 |
import torch
def learnable_p_choose(
energy,
noise_mean: float = 0.0,
noise_var: float = 0.0,
training: bool = True
):
"""
Calculating step wise prob for reading and writing
1 to read, 0 to write
energy: bsz, tgt_len, src_len
"""
noise = 0
if training:
# add noise ... | e274a68f2adfce070fcd93f35f3061038e260723 | 627,869 |
def _generate_initial_states(matrices):
"""Reads a list of matrices and outputs a list of tuples of initial states
each element in the list will be a tuple ([flavours hadron 1, flavours hadron 2])
for each matrix
"""
initial_flavours = []
for matrix in matrices:
initials = matrix.initial... | ad4ed6d04ab32e69d3dc9f5c0cf6ed376a2bd8fc | 627,870 |
def mod_Goodman_Fos(sa, sm, Se, Sut):
"""
Computes the mod Goodman relation factor of safety
:param sa: alternating stress
:param sm: midrange stress
:param Se: Endurance strength
:param Sut: Ultimate tensile strength
:return: factor of safety
"""
n_inv = sa/Se + sm / Sut
retur... | b98e8335929a8ef40569f25fd46dc7035090a20a | 627,871 |
def autoserialize(dali_pipeline):
"""
Decorator, that marks a DALI pipeline (represented by :meth:`nvidia.dali.pipeline_def`) for
autoserialization in [DALI Backend's](https://github.com/triton-inference-server/dali_backend#dali-triton-backend) model repository.
For details about the autoserialization ... | 621bfd2ddd4d6e3e50d9823a086ffc05987e1418 | 627,872 |
def flip_left_right(image):
"""Flips an image left and right.
# Arguments
image: Numpy array.
"""
return image[:, ::-1] | aaca0201572ab9fa2df857d82919db0b3f5a102c | 627,873 |
def get_average_solution_length(population):
"""
Calculate the average distance of the instances within a population
Args:
population: list of indices with format {"feasible":[], "infeasible":[]}
Returns: avg distance of instances in the population
"""
sum_length = 0
nr_instances ... | 347fe771302b75765f71a1ba7c96e3bf3e6f5058 | 627,875 |
def updateAlias(old_alias: str, new_alias: str) -> str:
"""Return a query to update a character's alias."""
return (f"UPDATE alias "
f"SET aname='{new_alias}' "
f"WHERE aname='{old_alias}';"
) | 6db124254e42b88017cd4b6b8d82a84c08eb4101 | 627,877 |
def gm_symbol_to_jq(gm_symbol: str) -> str:
"""掘金代码转聚宽代码
:param gm_symbol: 掘金代码
:return: jq_symbol
"""
exchange, code = gm_symbol.split(".")
if exchange == 'SHSE':
jq_symbol = code + ".XSHG"
elif exchange == 'SZSE':
jq_symbol = code + ".XSHE"
else:
raise ValueErr... | dd8bb0702872bc5a461e7764a07a5c7229d94e68 | 627,878 |
def sortbyMUMlength(form):
"""sort MUMs by length
Args:
form: pandas dataframe
Returns:
The sorted pandas dataframe
"""
form['length'] = form.index.str.len()
form.sort_values('length', ascending=False, inplace=True)
return(form.drop(["length"], axis=1)) | 519015124fd3ce314484f2515e9b429668f2b93c | 627,879 |
def get_trailing_edge_dist(ds):
"""
the lowest elevation at which the signal strength of the waveform is half of the maximum signal above the background noise value
lowest elevation = largest distance from satellite
"""
energy_threshold = (ds.rec_wf.max(dim="rec_bin") - ds.noise_mean) / 2.0
retu... | 4e7ce2a8cc2cceac3d093d31dd8aa4abb4965f9e | 627,880 |
import json
def matdesc_to_unicode(matdesc):
"""Convert Material Descriptor to Unicode String."""
return str(
json.dumps(
{
"queryId": matdesc.query_id,
"smkId": str(matdesc.smk_id),
"keySize": str(matdesc.key_size),
},
... | a8ff0cdc4cb625adcea39154af60d4c1b239cf7a | 627,881 |
def pig_it(string):
"""Function creates string with simple pig latin words."""
pyg = "ay"
final_output = ""
for word in string.split():
if not word.isalpha():
final_output += word + " "
break
else:
first = word[0]
new_word = word + first + ... | bcd46b5ff9b49153ea8410ae03d8d0edebcd8e8b | 627,882 |
def bilinear_interp(x1, x2, y1, y2, x, y, q11, q12, q21, q22):
"""
Perform a bilinear interpolation at the point x,y from the rectangular grid
defined by x1,y1 and x2,y2 with values at the four corners equal to Q11, Q12,
Q21 and Q22.
"""
assert x1 <= x <= x2
assert y1 <= y <= y2
asser... | b692c7c48e3c93b491e5ff56ab9c08159bc08f23 | 627,883 |
def is_same_module_or_submodule(orig, incoming):
"""
Returns true if the incoming module is the same module as the original,
or is a submodule of the original module
"""
if incoming is None:
return False
if orig == incoming:
return True
if incoming.__name__.startswith(orig._... | a3ecf3f1d9d1546a9f8a30f9ef6609ae9e94cc6e | 627,884 |
def merge_or(base, to_merge, exclusive):
"""
Merge json schemas assuming a 'oneOf' or 'anyOf' command
The idea is to find out the differences between 'base' and 'to_merge'.
If a property is in 'base' and not in 'to_merge', it is added to all the alternative
properties except 'to_merge'.
If a pr... | 6838cfa4c029555ca82225babbcdf08179005e88 | 627,885 |
import re
def strip_internal_comments(text):
"""Removes internal comments from a string and normalizes whitespace
around them.
Comments are in the format [[comment]]. For example, the string 'Lorem
ispum [[dolor sit]] amet.' will be transformed to 'Lorem ipsum amet.'
Further examples: https://www... | 3cf00fc44f0aa2614f275f54f4c1d22f190fba3a | 627,886 |
def count_in_layer(layer, number):
"""Count occurrences of number in layer."""
return sum(row.count(number) for row in layer) | 1d70ef128a4688343911b01cd4022493dcd2f19e | 627,887 |
def shift_position(pos, x_shift, y_shift) -> dict:
"""
Moves nodes' position by (x_shift, y_shift)
"""
return {n: (x + x_shift, y + y_shift) for n, (x, y) in pos.items()} | c354c713a6a620b0691aeea940f1f14314580c95 | 627,888 |
import argparse
def parse_args(args):
"""Take care of all the argparse stuff.
:returns: the args
"""
parser = argparse.ArgumentParser(description='Do iam simulations on stars.')
parser.add_argument('star', help='Star names', default=None)
parser.add_argument('--suffix', help='Suffix to add to... | 2e395b5de0ca6abc437db0d5c9f7d9aeadafabbd | 627,889 |
def chop_list(lst, chop_length, filler=None):
"""Chops a list into a list of lists. Used to generate a plate map
corresponding to microplate layouts.
Parameters
----------
lst: list
The original list that needs to be chopped up
chop_length: Int
The length of the pieces to chop t... | 2d68ef7a5bb58b3ce5453ce8ff4ce5d5fbf80d9c | 627,890 |
from typing import Optional
import aiohttp
async def getResponseBody(url: str) -> Optional[dict]:
"""
Gets a resource at url and parses the json body to a dict,
returns None on failed utils.
@param url:
@return:
"""
async with aiohttp.ClientSession() as session:
async with session.... | e6f5e3080e0ba1650d37d2e150f02da8db5e1550 | 627,891 |
def process_internet_gateway(account, region, ec2):
"""
describes one or more of your internet gateways
:param account:
:param region:
:param ec2 (child session):
:return list of internet gateways:
"""
list = []
result = []
response = ec2.describe_internet_gateways()
for item... | ee81b91125e388836f8fa5922ea008a0f1b9bdec | 627,894 |
import sympy
def op_mirror():
"""Jones matrix operator for a perfect mirror."""
return sympy.Matrix([[1, 0], [0, -1]]) | 025a01e30f1626f044e406253f0910112d52f742 | 627,895 |
def forward_step(x, parameters):
"""get prediction"""
y_hat = parameters['w'] * x + parameters['b']
return y_hat | 43d3cf4ff6f42615c5026b23b3d0a010e793b83e | 627,896 |
def create_data_model():
"""Stores the data for the problem."""
data = {}
# Special location don't consume token, while regular one consume one
data['tokens'] = [
0, # 0 depot
0, # 1 special node
0, # 2 special node
0, # 3 special node
0, # 4 special node
... | 42a8696ef1f9216e759036df02f6e93bff24ead5 | 627,897 |
import re
def normalize(s):
"""
Normalizes a string:
- replaces any sequence of whitespace characters (including non-breaking space) with a single space character
"""
if s == None:
return None
else:
return re.sub(r'\s+', ' ', s) | 6bb8267a0bc465ce4c0eba22b7311058562c39d5 | 627,898 |
def remove_whitespace(string):
"""Remove whitespace from string"""
return "".join(string.split()) | 60e5396a53f66b94e5b162fec1c90511c268f6e6 | 627,899 |
import os
def scrape_indices_WD(directory_path, control = False):
"""
Function to get valid patient IDs from a directory containing preprocessed files
based off filenames of form:
Fixed_Dim_HBs_Idx[C]###.npy
:param directory_path: String, path to directory
:returns: [list[string]] corresponding patient IDs
"""... | edfb54c5344eb844c2cf0e63ac77cb3a8864e627 | 627,900 |
from google.protobuf.descriptor_pb2 import FileDescriptorProto
from google.protobuf.descriptor_pb2 import FileDescriptorSet
def build_fds_for_msg(msg):
"""
Given a Protobuf message `msg` (or message class), build a
`FileDescriptorSet` that can be used with `DynamicMessageFactory` below (or
`protobag::DynamicM... | 34a61e67566de87a16ddf11d0788d207b80f5839 | 627,902 |
import os
def get_deployment_dir():
"""
Assumes there is a deployment folder in the project root that contains the needed ansible files.
:return: The absolute path to the deployment folder.
"""
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
return os.path.join(proje... | dfd52e70b4005e520061a834f1741a5646dc58cb | 627,903 |
def reversed_enumerate(seq):
"""Like reversed(list(enumerate(seq))) without copying the whole seq."""
return zip(reversed(range(len(seq))), reversed(seq)) | d9623d6557b94b70ee5f73b241e8fd985e5e85a6 | 627,904 |
import re
def strip_prefix(line):
"""Remove the [filename:lineno] prefix in a Log line, if present."""
m = re.match(r"^(\[.+:\d+\]\s*)(.*)", line)
if m:
return m.group(2)
else:
return line | 57bb10f8c1b405087c69ecc2f6538e1728a39307 | 627,905 |
def proper(s):
"""Strips then capitalizes each word in a string."""
s = s.replace("-", " ").title()
s = s.replace("_", " ").title()
return s | 78fa0f28bfdb77fdc572eb851f4021daabdc1a2b | 627,906 |
def clip(input, conf):
"""
Clip the generating instance with each feature to make sure it is valid
:param input: generating instance
:param conf: the configuration of dataset
:return: a valid generating instance
"""
for i in range(len(input)):
input[i] = max(input[i], conf.input_boun... | a18fb851d76df3b80fe5ac88d6d07291955ce499 | 627,907 |
import yaml
def _parse_yaml(path):
"""Parse the global variables, return as dict"""
with open(path, "r") as stream:
data = yaml.safe_load(stream)
return data | 87239b7ebf74b9439a1b97e27a67be6cb90b0d7b | 627,908 |
import os
def checkPath(path):
"""Check if path exists"""
return os.path.exists(path) | 5998383940f6e3bd6a723fd9c18282ad3132aeb7 | 627,909 |
def check_models_have(models, key):
"""Check models have deserialized the provided key."""
n_err_models = 0
for m in models:
if not m.is_deserialized(key):
n_err_models += 1
if n_err_models:
return "errors: {}/{} models {} don't have key {}".format(
n_err_models, ... | b20cb64f386dba6d3a7100e14c76040af2d700f6 | 627,910 |
def _val2col(val):
"""
Helper function to convert input value into a red hue RGBA
"""
nonred = abs(0.5-val)*2.0
return (1.0,nonred,nonred,1.) | 68adb104a7812f0992ec79864a1b8d5d3103e023 | 627,911 |
def get_non_zero_objects(obj_list):
"""
Filters out images where no lines were found.
Parametrs:
------------------
obj_list: list
List of elements of class matchingObjects
"""
new_obj_list = []
count_lines = 0
for obj in obj_list:
if obj.lines is not None:
... | faac7f783d734379a77bd8162c9751178e0473ac | 627,912 |
import re
def is_snake_case(id_name):
"""Check if id_name is written in snake case.
Actually, it is restricted to a certain subset of snake case, so that
we can guarantee camel->snake->camel roundtrip.
>>> is_snake_case('')
False
>>> is_snake_case('_')
False
>>> is_snake_case('h')
... | 2558d1bebdf8405a86b213f7892932616558f3c6 | 627,913 |
def _title(profile):
"""Process a title of a fig."""
if profile['operation'] == 'differential':
p1, p2 = profile['profiles']
return 'differential ({}, {})'.format(_title(p1), _title(p2))
elif profile['operation'] == 'local feature':
p = profile['profile']
return 'local featur... | 8ad0190f5295f095eb9a08a7ce9c4f4aa05a4135 | 627,914 |
from __main__ import gearsConfigGet as redisGearsConfigGet
def gearsConfigGet(key: str, default=None) -> str:
"""Fetches the current value of a RedisGears configuration option and returns a
default value if that key does not exist.
Args:
key (str):
The configuration option key.
... | a6532b528b033160a21c8eeb7ce8952b3c3481fc | 627,915 |
from datetime import datetime
def get_pub_articles(queryset):
"""Get All Avaiable Articles
"""
now = datetime.now()
STATUS = 'pub'
return queryset.filter(
pub_status=STATUS,
pub_start_date__lte=now,
pub_end_date__gt=now,
) | b530ad385c06bed3e55632e1d699271ea835fad8 | 627,916 |
import torch
def normalized_mean_square_error(output, target, reduction='mean'):
"""Return the TensorFlow expression of normalized mean-square-error of two distributions.
Parameters
----------
output : Tensor
2D, 3D or 4D tensor i.e. [batch_size, n_feature], [batch_size, height, width] or [ba... | d0ece920da6b1c26f18390ceb51bfb81e7cae188 | 627,917 |
import random
def choose_from_string(string: str, n: int):
""" Choose a card from a string. Returns the choice and what remains after choosing. """
assert len(string) >= n
choices = []
for _ in range(n):
char = random.choice(string)
string = string.replace(char, '', 1)
choice... | e8605428d046456311333f73c66465319803dc13 | 627,918 |
def get_aggregate_function(attribute):
"""Get actual computed function from aggregate function field."""
afn = attribute.attribute_definition.attribute_type.aggregate_function
function_name = afn.split()[2]
if function_name == "max":
def max_(aggregate_values, rel_map):
"""Get maximum value and id fro... | fd9ebdce5777b81397b8223f7105453e72f68b1a | 627,919 |
import os
import torch
def load_model(model, path, name):
"""
Loading a model from a pre-saved state dictionary
Args:
-----
model: torch Module
model skeleton initialized with random weights
path: string
path to the directory where model is stored
name: string
name... | 01cc1dde041e8049df2013f1a0782590475930ab | 627,920 |
import re
def find_value(pattern, string, default=None, flags=0):
"""
根据正则表达式在字符串中搜索值,若未找到,返回 default
"""
m = re.search(pattern, string, flags)
if m:
return m.group(1)
else:
return default | 37a199e080e7221c52681a45dc3c6264019d6248 | 627,922 |
import requests
def get_image() -> bytes:
"""Get a person that does not exist."""
data = requests.get(
"https://thispersondoesnotexist.com/image",
headers={"User-Agent": "My User Agent 1.0"},
).content
return data | 88861bb689ddf17e378fb196cfc8fe4d47fd7dec | 627,923 |
def transfer_weights(model, weights=None):
"""
Always trains from scratch; never transfers weights
:param model:
:param weights:
:return:
"""
print('ICNet has found no compatible pretrained weights! Skipping weight transfer...')
return model | 4c34ef1c6126106c878e36b31fdd477ea6d21340 | 627,924 |
def is_available():
"""Torchscript available.
Returns:
bool: Always True.
"""
return True | 18e4ca0fa46f592b2270fbb23fe6e8d7d17f5760 | 627,925 |
def digitsum(s: str) -> int:
"""
>>> all(digitsum(str(i)) == (1 if i == 1 else 0) for i in range(100))
True
"""
i = sum(pow(int(c), 5) for c in s)
return i if i == int(s) else 0 | 1c312734f328314694217f842ca3d0148eb21b97 | 627,926 |
def potential(r, r_c, r_e, r_a):
"""Potential (Eq. 4)
Args:
r: distance between agent i and j
r_c: hard-core repulsion distance
r_e: equilibrium (preferred) distance
r_a: maximum interaction range
Returns:
potential: attractive/repulsive potential
"""
if r < r... | 0cf253ec694c27b43728af5bac77e3dd7e1f7969 | 627,927 |
def loadMCLSamplingMap(name):
"""Returns MCL map with given name from directory. Weight value is cut off
to the 15th decimal.
precondition: name is a string with correct extension"""
assert type(name) == str, "name isn't a string"
Map = []
text = open(name)
for line in text:
comma1 =... | b31b3ad05575f3fd97979732c01e28122de68fb2 | 627,928 |
def clean_pdb(list_pdb_ids, querymode=None):
"""Cleans up the string returned by search()
Args:
list_pdb_ids: string, output from search()
querymode: Type of search being performed
Returns: A list of 4-letter PDB codes
"""
if querymode == 'Lig':
list_pdb_ids = list_pdb_ids... | 3a9763d18d3c55dbc39ed20090033bc8431b674d | 627,929 |
def get_sender(tx: dict) -> str:
"""
Returns the tx sender's address
:param tx: transaction dictionary
:return: str
"""
return tx["events"][0]["sub"][0]["sender"][0]["account"]["id"] | d4bc293a9b92c335ff09fa82f9f7f4f82862a491 | 627,930 |
def is_valid_game(game_str, num_players):
""" Check whether game_str represents a valid game
Args:
game_str: the string representing the game
num_players: the number of players (between 1 and 5)
Returns:
True if the game is valid or False otherwise
"""
gates = {"H": 1, "I... | a93187620f47e427a77331c038e360615c2a0888 | 627,932 |
def next_power_of_two(x):
# type: (int) -> int
"""
Compute the next power of two that is greater than `x`:
>>> next_power_of_two(0)
1
>>> next_power_of_two(1)
2
>>> next_power_of_two(2)
4
>>> next_power_of_two(3)
4
>>> next_power_of_two... | bc9275767fc863951b91fcc83f8e811aeb77d581 | 627,933 |
import os
def listdir(dirname):
"""Returns a list of filenames contained in the named directory."""
return os.listdir(dirname) | ff948b9def868eb92d7edb95e1a28549b446527c | 627,934 |
from typing import List
from typing import Union
def numeros_al_final_recursivo(lista: List[Union[float, str]]) -> List[Union[float, str]]:
"""CHALLENGE OPCIONAL - Re-escribir de forma recursiva."""
if len(lista) == 0:
return []
primero, *resto = lista
if type(primero) == str:
return... | b9f17410e6c4ddcedb92be698232dc1119d7d2d7 | 627,935 |
import re
def remove_ansi_escape_seq(text):
"""
This method removes ANSI escape sequences (such as a colorama color
code) from a string so that they aren't spoken.
:param text: The text that may contain ANSI escape sequences.
:return: The text with ANSI escape sequences removed.
"""
if tex... | 6dcea78fcbce0fd6631d2940639a550d8513e9b6 | 627,936 |
def harmonic_mean(series: list) -> float:
"""
return the harmonic mean of series
>>> harmonic_mean([1, 4, 4])
2.0
>>> harmonic_mean([3, 6, 9, 12])
5.759999999999999
>>> harmonic_mean(4)
Traceback (most recent call last):
...
ValueError: Input series is not valid, valid serie... | 5e88f193f887b064fe190d8d45d9db84a88a3801 | 627,937 |
def _weight(role):
"""Return an integer weight for the given role for sorting purposes."""
if role == "CEO":
return 0
return 100 | 505d761bdcc820c425ff8d85374556cbbad93b48 | 627,938 |
def schedule_composition(row):
"""Takes in a series with $id and \*_ScheduleDay_Name values and return an
array of dict of the form {'$ref': ref}
Args:
row (pandas.Series): a row
Returns:
list: list of dicts
"""
# Assumes 7 days
day_schedules = []
days = [
"Mond... | 6c92c3d1c0a82e20bab01202880dc8fa80d7f826 | 627,939 |
def faxen_factor(height, radius, lateral=True):
"""
Return the relative change of the stokes drag according to Faxen's law.
References
----------
Schäffer, E., et al.
Surface forces and drag coefficients of microspheres near a plane
surface measured with optical tweezers.
La... | 41bff2f39cf11bdda5453397986841b1c717d974 | 627,940 |
import subprocess
def run_command(cmd):
"""
Run a command directly
"""
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
if process.returncode == 0:
return stdout.decode("utf-8"), stderr.decode("utf-8")
else:
... | 6a72a72ca5a5ec464fd802009e62a12fcc352e67 | 627,941 |
from typing import Iterable
from typing import Callable
from typing import Any
def delegate_factory(cls: type, delegate_attrs: Iterable[str]) -> Callable[[Any], Any]:
"""
Create factory function that searches object `o` for `delegate_attrs`
and check is any of these attributes have `cls` type. If no such
... | 227fd327fd86edfe577fbbf787869a8bab2a2564 | 627,942 |
import optparse
def build_cli_parser(description, args):
"""
:param description:
:return:
"""
parser = optparse.OptionParser(usage="%prog [options]", description=description)
for arg in args:
parser.add_option(arg[0],
arg[1],
action... | 3b5b0dff3b22f66866bf411e2303582194822008 | 627,943 |
from typing import Optional
def column_name_to_metric_target(col_name: str) -> tuple[str, Optional[str]]:
"""
Return (metric_name, column_name) from column name that build by this class.
"""
parts = col_name.split("__")
if parts[0] == "table_metric":
return parts[1], None
if parts[0] =... | a93359ee09dfe4e01c52cb981d2106aae9d8962b | 627,944 |
def license():
"""Return the License file."""
with open('LICENSE.md') as f:
return f.read() | 87265b750c59160df27d62aa9985da8f82a9e754 | 627,945 |
import re
def html_description_to_human_readable(breach_description):
"""
Args:
breach_description: Description of breach from hibp response
Returns: Description string that altered HTML urls to clickable urls
for better readability in war-room
"""
html_link_pattern = re.compile('<a... | cab5a37e77da239bdf347d44cea43778a6861c53 | 627,946 |
def strip_leading_output_cell(lyx_string):
"""Return `string` with any leading output cell stripped off."""
lyx_string_lines = lyx_string.splitlines()
saved_lines = []
max_search_lines = 3
found_cell = False
inside_cell = False
for count, line in enumerate(lyx_string_lines):
if not f... | 037c7d37d931fd12b6424ff059b78e745084ae71 | 627,948 |
def stack_pivot_from_kernel_to_user_rop():
"""
This function creates a ROP chain to stack pivot to user space from kernel space
!!!!To be implemented
@return: ROP chain
"""
rop = ''
return rop | 15803bdd5fe9485b780b29ad538288d2d449bfce | 627,949 |
def lookup_dict_from_url_params(url_params):
"""Convert a url_params dict in a mapping suitable for ORM querying."""
lookup_dict = {}
for k, v in url_params.items():
values = v.split(",")
if len(values) > 1:
lookup_dict[k] = values
else:
lookup_dict[k] = v
... | f8cb93a924d01aa45fb0ae926b688a1b640a5e61 | 627,952 |
import functools
def classdecorator(func):
"""Class decorator that can be used with or without parameters."""
@functools.wraps(func)
def wrapper(cls=None, **kwargs):
def wrap(klass):
return func(klass, **kwargs)
# Check if called as @decorator or @decorator(...).
if cl... | 48ba5076962746cce374e610c01b7e491cf793af | 627,953 |
import subprocess
def run(command):
"""Runs a test command and returns the return code.
:param command: Command to run.
"""
print("Running '{}':".format(command))
rc = subprocess.call(command, shell=True)
print("'{command}' returned {rc}.".format(command=command,
... | 9c545e4e53998162aeac7bf00c9906cd8c80b0aa | 627,954 |
from typing import List
def cast_trailing_nulls(series: List) -> List:
"""
Cast trailing None's in a list series to 0's
"""
for i, x in reversed(list(enumerate(series))):
if x is None:
series[i] = 0
else:
return series
return series | 3a7f7d53dcb7ed9b892b9b423c3650a339af26e2 | 627,957 |
def merge_lists(l, r):
"""Merges the left and the right lists, returns the simple concatenation"""
new_list = l.copy()
temp_r = r.copy()
for i in range(len(temp_r)):
new_list.append(temp_r.popleft())
return new_list | 612e584e2f03c85e4f834a41a69c4d6c6818c8d4 | 627,958 |
def _is_multiple_records(mem_addr, num_recs):
"""Return true if we are searching for multiple records."""
return (mem_addr == 0x00 and num_recs == 0) or num_recs > 1 | 4422ae8563fff77d24026fe431bdedb7f60f44b0 | 627,959 |
def _encode_structure_parts(local_target):
"""
Encodes the design task, to distinguish between struture and wequence domains.
Args:
A sequence that may contain structure or sequence parts.
Returns:
A list representation of the sequence with all structure sites and None else.
"""
... | deb185b439f7b75b6081ca61e57547bdb87aa981 | 627,960 |
def validate_vni_ranges(ranges):
"""
Validate VNI ranges provided are valid and properly formatted
:param ranges: list
:return: list
"""
errors = []
for vni_range in ranges:
if not isinstance(vni_range, list):
errors.append("Invalid range: must be a list")
elif l... | aa83d60d881683ac771a7ffaf6dae503c4ece81f | 627,961 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.