content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_genUniqueDigits(base=10, maxBasePow=4):
"""
Run fairly comprehensive test on genUniqueDigits(), digitsToInt(),
digitsToStr(), and intToStr() in specified base
Test involves incrementing digits from 0 to base**maxBasePow
"""
maxNum = base**maxBasePow
genDigitsAll = genUniqueDigits(base=base, exc... | 24,300 |
def find_edges(mesh, key):
""" Temp replacement for mesh.findEdges().
This is painfully slow.
"""
for edge in mesh.edges:
v = edge.vertices
if key[0] == v[0] and key[1] == v[1]:
return edge.index | 24,301 |
def thumbnail(link):
"""
Returns the URL to a thumbnail for a given identifier.
"""
targetid, service = _targetid(link), _service(link)
if targetid:
if service in _OEMBED_MAP:
try:
return _embed_json(service, targetid)["thumbnail_url"]
except (ValueEr... | 24,302 |
def valve_gas_cv(m_dot, p_1, p_2, m_molar, T):
"""Find the required valve Cv for a given mass flow and pressure drop.
Assumes that a compressible gas is flowing through the valve.
Arguments:
m_dot (scalar): Mass flow rate [units: kilogram second**-1].
p_1 (scalar): Inlet pressure [units: p... | 24,303 |
def frequency_based_dissim(record, modes):
"""
Frequency-based dissimilarity function
inspired by "Improving K-Modes Algorithm Considering Frequencies of Attribute Values in Mode" by He et al.
"""
list_dissim = []
for cluster_mode in modes:
sum_dissim = 0
for i in range(len(recor... | 24,304 |
def _process_create_group(event: dict) -> list:
""" Process CreateGroup event. This function doesn't set tags. """
return [event['responseElements']['group']['groupName']] | 24,305 |
def tree_labels(t: Node):
"""Collect all labels of a tree into a list."""
def f(label: Any, folded_subtrees: List) -> List:
return [label] + folded_subtrees
def g(folded_first: List, folded_rest: List) -> List:
return folded_first + folded_rest
return foldtree(f, g, [], t) | 24,306 |
def find_best_split(rows):
"""Find the best question to ask by iterating over every feature / value
and calculating the information gain."""
best_gain = 0 # keep track of the best information gain
best_question = None # keep train of the feature / value that produced it
current_uncertainty = gini(... | 24,307 |
def pad_data(data, context_size, target_size, pad_at_begin= False):
"""
Performs data padding for both target and aggregate consumption
:param data: The aggregate power
:type data: np.array
:param context_size: The input sequence length
:type context_size: int
:param target_size: The target... | 24,308 |
def create_callbacks(path):
"""
Creates the callbacks to use during training.
Args
training_model: The model that is used for training.
prediction_model: The model that should be used for validation.
validation_generator: The generator for creating validation data.
args: par... | 24,309 |
def SaveAsImageFile(preferences, image):
"""Save the current image as a PNG picture."""
extension_map = {"png": wx.BITMAP_TYPE_PNG}
extensions = extension_map.keys()
wildcard = create_wildcard("Image files", extensions)
dialog = wx.FileDialog(None, message="Export to Image",
... | 24,310 |
def egg_translator(cell):
"""If the cell has the DNA for harboring its offspring inside it, granting it additional food
and protection at the risk of the parent cell, it is an egg.
Active DNA: x,A,(C/D),x,x,x
"""
dna = cell.dna.split(',')
if dna[1] == 'A' and dna[2] == 'C':
return True
... | 24,311 |
def all_different_cst(xs, cst):
"""
all_different_cst(xs, cst)
Ensure that all elements in xs + cst are distinct
"""
return [AllDifferent([(x + c) for (x,c) in zip(xs,cst)])] | 24,312 |
def test_no_remaining_worker():
"""Runner stops if we have not more trials to run"""
idle_timeout = 2
pop_time = 1
runner = new_runner(idle_timeout)
runner.pending_trials[0] = None
def no_more_trials():
time.sleep(pop_time)
runner.pending_trials = dict()
runner.trials =... | 24,313 |
def processing(task, region: dict, raster: str, parameters: dict):
"""
Cuts the raster according to given region and applies some filters
in order to find the district heating potentials and
related indicators.
Inputs :
* region : selected zone where the district heating potential is studi... | 24,314 |
def disconnect(event):
"""Attempts to disconnect from the remote server"""
elements.TOOLBAR.connect_button.SetLabel('Connect')
elements.TOOLBAR.send_button.Disable()
elements.TOOLBAR.run_button.Disable()
elements.TOOLBAR.shutdown_button.Disable()
elements.TOOLBAR.restart_button.Disable()
... | 24,315 |
def test_questionnaire_10(base_settings):
"""No. 10 tests collection for Questionnaire.
Test File: elementdefinition-de-questionnaire.json
"""
filename = (
base_settings["unittest_data_dir"] / "elementdefinition-de-questionnaire.json"
)
inst = questionnaire.Questionnaire.parse_file(
... | 24,316 |
def randbit():
"""Returns a random bit."""
return random.randrange(2) | 24,317 |
def calc_points(goals, assists):
"""
Calculate the total traditional and weighted points for all
players, grouped by player id.
Author: Rasmus Säfvenberg
Parameters
----------
goals : pandas.DataFrame
A data frame with total goals and weighted assists per player.
assist... | 24,318 |
def get_links(browser, elemento):
"""
Pega todos os links dentro de um elemento
- browser = a instância do navegador
- element = ['aside', main, body, ul, ol]
"""
resultado = {}
element = browser.find_element_by_tag_name(elemento)
ancoras = element.find_elements_by_tag_name... | 24,319 |
def file_to_base64(path):
"""
Convert specified file to base64 string
Args:
path (string): path to file
Return:
string: base64 encoded file content
"""
with io.open(path, 'rb') as file_to_convert:
return base64.b64encode(file_to_convert.read()) | 24,320 |
def get_simverb(subset=None):
"""
Get SimVerb-3500 data
:return: (pairs, scores)
"""
simverb = []
if subset == 'dev':
name = '500-dev'
elif subset == 'test':
name = '3000-test'
else:
name = '3500'
with open('../data/SimVerb-3500/SimVerb-{}.txt'.format(name)) a... | 24,321 |
def sample_image(size, min_r, max_r, circles, squares, pixel_value):
"""Generate image with geometrical shapes (circles and squares).
"""
img = np.zeros((size, size, 2))
loc = []
if pixel_value is None:
vals = np.random.randint(0, 256, circles + squares)
else:
vals = [pixel_value... | 24,322 |
def stage_input_file(workdir_path, files):
"""Stage an input file into the working directory whose path
is in workdir_path. Uses the basename if given. Recursively
stages secondary files.
Adds a 'path' key with the path to the File objects in files.
Args:
workdir_path (str): Path to the wo... | 24,323 |
def host_allocations(auth):
"""Retrieve host allocations"""
response = API.get(auth, '/os-hosts/allocations')
return response.json()['allocations'] | 24,324 |
def rosenbrock_grad(x, y):
"""Gradient of Rosenbrock function."""
return (-400 * x * (-(x ** 2) + y) + 2 * x - 2, -200 * x ** 2 + 200 * y) | 24,325 |
def vic2nc(options, global_atts, domain_dict, fields):
""" Convert ascii VIC files to netCDF format"""
# determine run mode
if (options['memory_mode'] == 'standard') \
and (options['chunksize'] in ['all', 'All', 'ALL', 0]):
memory_mode = 'big_memory'
else:
memory_mode = opti... | 24,326 |
def get_file(
fname,
origin,
untar=False,
cache_subdir="datasets",
extract=False,
archive_format="auto",
cache_dir=None,
):
"""Downloads a file from a URL if it not already in the cache.
By default the file at the url `origin` is downloaded to the
cache_dir `~/.keras`, placed in ... | 24,327 |
def extractYoujinsite(item):
"""
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if '[God & Devil World]' in item['tags'] and (chp or vol):
return buildReleaseMessageWithType(item, 'Shenmo Xitong', vol, chp, frag=frag, postfix=postfix)
if '[LBD&A]' in item['tags'] and (chp or vol):... | 24,328 |
def test_deprecated_properties(
obs_st: dict[str, Any], caplog: LogCaptureFixture
) -> None:
"""Test a warning is loggeed for deprecated properties."""
device = TempestDevice(serial_number=TEMPEST_SERIAL_NUMBER, data=obs_st)
assert device.model == "Tempest"
assert device.serial_number == TEMPEST_SER... | 24,329 |
def make_executable(p):
"""
Make file in given path executable
Source:
http://stackoverflow.com/a/33179977/3023841
"""
st = os.stat(p)
os.chmod(p, st.st_mode | 0o111) | 24,330 |
def get_patient_dirs(root_dir):
"""
Function used to get the root director for all patients
:param root_dir: root director of all image data
:return patient_paths: list of all patient paths, one for each patient
"""
search_path = os.path.join(root_dir, '[0-1]', '*')
patient_paths = glob.glob... | 24,331 |
def _download(path: str, url: str):
"""
Gets a file from cache or downloads it
Args:
path: path to the file in cache
url: url to the file
Returns:
path: path to the file in cache
"""
if url is None:
return None
if not os.path.exists(path):
master_dev... | 24,332 |
def get_logger() -> Logger:
""" This function returns the logger for this project """
return getLogger(LOGGER_NAME) | 24,333 |
def eagle(ctx, alloc, walltime, feature, stdout_path):
"""Eagle submission tool for PLEXOS aggregation."""
name = ctx.obj['NAME']
plexos_table = ctx.obj['PLEXOS_TABLE']
sc_table = ctx.obj['SC_TABLE']
cf_fpath = ctx.obj['CF_FPATH']
out_dir = ctx.obj['OUT_DIR']
dist_percentile = ctx.obj['DIST... | 24,334 |
def test_space_features_operations(space_object):
"""Test for get, add, update and delete features operations."""
gdf = space_object.get_features(feature_ids=["DEU", "ITA"], geo_dataframe=True)
assert isinstance(gdf, gpd.GeoDataFrame)
# get two features
data = space_object.get_features(feature_ids=[... | 24,335 |
def write_guess_json(guesser, filename, fold, run_length=200, censor_features=["id", "label"], num_guesses=5):
"""
Returns the vocab, which is a list of all features.
"""
vocab = [kBIAS]
print("Writing guesses to %s" % filename)
num = 0
with open(filename, 'w') as outfile:
tot... | 24,336 |
def _remove_overloaded_functions(asts):
"""Cython cannot handle overloaded functions, we will take the first one."""
functions = [n for ast in asts for n in ast.nodes
if isinstance(n, Function)]
function_names = []
removed_functions = []
for f in functions:
if f.name in func... | 24,337 |
def upgrade_to_4g(region, strategy, costs, global_parameters,
core_lut, country_parameters):
"""
Reflects the baseline scenario of needing to build a single dedicated
network.
"""
backhaul = '{}_backhaul'.format(strategy.split('_')[2])
sharing = strategy.split('_')[3]
geotype = region['... | 24,338 |
def get_url(request):
"""
Use devId and key and some hashing thing to get the url, needs /v3/api as input
"""
devId = DEV_ID
key = KEY
request = request + ('&' if ('?' in request) else '?')
raw = request + f"devid={devId}"
raw = raw.encode()
hashed = hmac.new(key, raw, sha1)
... | 24,339 |
def test_atom_order_in_mol_copy(toolkit, smiles):
"""Test that atom orders do not change when copying molecule"""
import copy
mol = utils.load_molecule(smiles, toolkit=toolkit)
if not utils.has_explicit_hydrogen(mol):
mol = utils.add_explicit_hydrogen(mol)
molcopy = copy.deepcopy(mol)
fo... | 24,340 |
def _is_mapped_class(cls):
"""Return True if the given object is a mapped class,
:class:`.Mapper`, or :class:`.AliasedClass`."""
if isinstance(cls, (AliasedClass, mapperlib.Mapper)):
return True
if isinstance(cls, expression.ClauseElement):
return False
if isinstance(cls, type):
... | 24,341 |
def get_all_links_in_catalog(html) -> list:
"""Получает список всех ссылок на пункты из каталога."""
_soup = BeautifulSoup(html, 'html.parser')
_items = _soup.find('div', class_='catalog_section_list').find_all('li', class_='name')
links_list = []
for item in _items:
links_list.append(item.f... | 24,342 |
def digitize(n):
"""Convert a number to a reversed array of digits."""
l = list(str(n))
n_l = []
for d in l:
n_l.append(int(d))
n_l.reverse()
return n_l | 24,343 |
def run_example(device_id, do_plot=False):
"""
Run the example: Connect to the device specified by device_id and obtain
impedance data using ziDAQServer's blocking (synchronous) poll() command.
Requirements:
Hardware configuration: Connect signal output 1 to signal input 1 with a
BNC cable... | 24,344 |
def _available_algorithms():
"""Verify which algorithms are supported on the current machine.
This is done by verifying that the required modules and solvers are available.
"""
available = []
for algorithm in ALGORITHM_NAMES:
if "gurobi" in algorithm and not abcrules_gurobi.gb:
... | 24,345 |
def lock(
server_url: str,
semaphore: str,
count: int = 1,
timeout: Optional[timedelta] = None,
) -> Iterator[Peer]:
"""
Acquires a lock to a semaphore
## Keyword arguments:
* `count`: Lock count. May not exceed the full count of the semaphore
* `timeout`: Leaving this at None, le... | 24,346 |
def symbols(*names, **kwargs):
"""
Emulates the behaviour of sympy.symbols.
"""
shape=kwargs.pop('shape', ())
s = names[0]
if not isinstance(s, list):
import re
s = re.split('\s|,', s)
res = []
for t in s:
# skip empty strings
if not t:
conti... | 24,347 |
def cpuPercent():
"""
START Test Results
For 10 times:
Current CPU Usage: 0.0
Current CPU Usage: 0.0
Current CPU Usage: 0.0
Current CPU Usage: 0.8
Current CPU Usage: 0.0
Current CPU Usage: 0.1
Current CPU Usage: 1.5
Current CPU Usage: 0.0
Current CPU Usage: 0.0
Current CPU Usage: 0.8
END Test Results
... | 24,348 |
def create_intent(intent, project_id, language_code):
"""Create intent in dialogflow
:param intent: dict, intent for api
:param project_id: str, secret project id
:param language_code: event with update tg object
:return:
"""
client = dialogflow.IntentsClient()
parent = client.project_ag... | 24,349 |
def construct_object_types(list_of_oids: List[str]) -> List[hlapi.ObjectType]:
"""Builds and returns a list of special 'ObjectType'
from pysnmp"""
object_types: List[hlapi.ObjectType] = []
for oid in list_of_oids:
object_types.append(hlapi.ObjectType(hlapi.ObjectIdentity(oid)))
return object... | 24,350 |
def test_resolve_private_address(peripheral, central):
"""Ensure that if the central privacy policy is set to resolve and filter
and the device has no bond then resolved private addresses are not filtered"""
advertising_types = [
"ADV_CONNECTABLE_UNDIRECTED",
# "ADV_CONNECTABLE_DIRECTED",
... | 24,351 |
def base_sampler(models, nevents, floating_params=None):
"""
Creates samplers from models.
Args:
models (list(model)): models to sample
nevents (list(int)): number of in each sampler
floating_params (list(parameter), optionnal): floating parameter in the samplers
Returns:
... | 24,352 |
def menu_maker():
"""Top Menu Maker In each html page
"""
result = "<center>"
for i,item in enumerate(page_name):
if item == "Home":
targets_blank = ""
else:
targets_blank = 'target="blank"'
# Hyper Link To Each Page In HTML File
result += '\t... | 24,353 |
def test_gamma_map():
"""Test Gamma MAP inverse."""
forward = read_forward_solution(fname_fwd)
forward = convert_forward_solution(forward, surf_ori=True)
forward = pick_types_forward(forward, meg=False, eeg=True)
evoked = read_evokeds(fname_evoked, condition=0, baseline=(None, 0),
... | 24,354 |
def project_generate_private_link_post(auth, node, **kwargs):
""" creata a new private link object and add it to the node and its selected children"""
node_ids = request.json.get('node_ids', [])
name = request.json.get('name', '')
anonymous = request.json.get('anonymous', False)
if node._id not i... | 24,355 |
def access_token_old_api(authen_code):
"""
通过此接口获取登录用户身份(疑似是一个旧接口)
:param authen_code:
:return:
"""
# 先获取app_access_token
app_access_token = _get_app_access_token()
if not app_access_token:
return None
access_token_old_url = cfg.access_token_old_url
headers = {"Content-T... | 24,356 |
def denoising(image):
"""improve image quality by remove unimportant details"""
denoised = cv2.fastNlMeansDenoisingColored(image, None, 10, 10, 7, 21)
return denoised | 24,357 |
def test_normalize_paths(value, expected):
"""Verify we normalizes a sequence of paths provided to the tool."""
assert utils.normalize_paths(value) == expected | 24,358 |
def teams():
"""Redirect the to the Slack team authentication url."""
return redirect(auth.get_redirect('team')) | 24,359 |
def _clarans(metric):
"""Clustering Large Applications based on RANdomized Search."""
# choose which implementation to use, hybrid or cpu
get_clusters = _get_clusters(metric, method='cpu')
@jit(nopython=True)
def clarans(data, k, numlocal, maxneighbor):
"""Clustering Large Applications base... | 24,360 |
def create_outlier_mask(df, target_var, number_of_stds, grouping_cols=None):
"""
Create a row-wise mask to filter-out outliers based on target_var.
Optionally allows you to filter outliers by group for hier. data.
"""
def flag_outliers_within_groups(df, target_var,
... | 24,361 |
def closing_all(*args):
"""
Return a context manager closing the passed arguments.
"""
return contextlib.nested(*[contextlib.closing(f) for f in args]) | 24,362 |
def _non_max_suppression(objects, threshold):
"""Returns a list of indexes of objects passing the NMS.
Args:
objects: result candidates.
threshold: the threshold of overlapping IoU to merge the boxes.
Returns:
A list of indexes containings the objects that pass the NMS.
"""
if len(... | 24,363 |
def log_prefect(
msg: str, start: bool = True, use_prefect: bool = False
) -> None:
"""Logging with Prefect."""
if use_prefect:
if start:
logger = get_run_logger()
logger.info(msg)
else:
print(msg) | 24,364 |
def binary_search(x,l):
""" Esse algorítmo é o algorítmo de busca binária, mas ele retorna
qual o índice o qual devo colocar o elemento para que a lista
permaneça ordenada.
Input: elemento x e lista l
Output: Índice em que o elemento deve ser inserido para manter a ordenação da lista
"""
lo... | 24,365 |
def check_abrp(config):
"""Check for geocodio options and return"""
try:
abrpOptions = config.abrp.as_dict()
except:
return {}
options = {}
abrp_keys = ["enable", "api_key", "token"]
for key in abrp_keys:
if key not in abrpOptions.keys():
_LOGGER.error(f"Miss... | 24,366 |
def connect(config, job, attach):
"""
Connect to job.
JOB may be specified by name or ID, but ID is preferred.
"""
jobs = config.trainml.run(config.trainml.client.jobs.list())
found = search_by_id_name(job, jobs)
if None is found:
raise click.UsageError("Cannot find specified job."... | 24,367 |
def convert_magicc7_to_openscm_variables(variables, inverse=False):
"""
Convert MAGICC7 variables to OpenSCM variables
Parameters
----------
variables : list_like, str
Variables to convert
inverse : bool
If True, convert the other way i.e. convert OpenSCM variables to MAGICC7
... | 24,368 |
async def fetch_disclosure(start, end):
"""期间沪深二市所有类型的公司公告
Args:
start (date like): 开始日期
end (date like): 结束日期
Returns:
list: list of dict
"""
start, end = pd.Timestamp(start), pd.Timestamp(end)
start_str = start.strftime(r'%Y-%m-%d')
end_str = end.strftime(r'%Y-%m-... | 24,369 |
def get_loader(
image_dir,
attr_path,
selected_attrs,
crop_size=178,
image_size=128,
batch_size=16,
dataset="CelebA",
mode="train",
affectnet_emo_descr="emotiw",
num_workers=1,
):
"""Build and return a data loader."""
transform = []
if mode == "train":
transfo... | 24,370 |
def remove_samples(request, product_id):
"""Removes passed samples from product with passed id.
"""
parent_product = Product.objects.get(pk=product_id)
for temp_id in request.POST.keys():
if temp_id.startswith("product") is False:
continue
temp_id = temp_id.split("-")[1]
... | 24,371 |
def test_search_value_not_list():
""""Testing for value not found in list."""
test_instance = LinkedList("NotHere")
test_node = Node("notnode")
assert test_instance.search(test_node.data) is None | 24,372 |
def csu_to_field(field, radar, units='unitless',
long_name='Hydrometeor ID',
standard_name='Hydrometeor ID',
dz_field='ZC'):
"""
Adds a newly created field to the Py-ART
radar object. If reflectivity is a masked array,... | 24,373 |
def RunQa():
"""Main QA body.
"""
rapi_user = "ganeti-qa"
RunTestBlock(RunEnvTests)
rapi_secret = SetupCluster(rapi_user)
if qa_rapi.Enabled():
# Load RAPI certificate
qa_rapi.Setup(rapi_user, rapi_secret)
RunTestBlock(RunClusterTests)
RunTestBlock(RunOsTests)
RunTestIf("tags", qa_tags.Te... | 24,374 |
def test_parse(component_validator):
"""Test that action data is properly parsed.
1. Create an action.
2. Create an action parser.
3. Replace parser methods so that they return predefined data.
4. Parse the action.
5. Check the parsed data.
"""
action = Action(
name="parsed name... | 24,375 |
def get_port_use_db():
"""Gets the services that commonly run on certain ports
:return: dict[port] = service
:rtype: dict
"""
url = "http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.csv"
db_path = "/tmp/port_db"
if not os.path.isfile(db_path):
w... | 24,376 |
def calculate_com(structure):
"""
Calculates center of mass of the structure (ligand or protein).
Parameters
----------
structure : biopython Structure object
PDB of choice loaded into biopython (only chains of interest).
Returns
-------
A list defining center of mass of th... | 24,377 |
def generate_config(context):
""" Generate the deployment configuration. """
resources = []
name = context.properties.get('name', context.env['name'])
resources = [
{
'name': name,
'type': 'appengine.v1.version',
'properties': context.properties
}
... | 24,378 |
def check_regs(region_df, chr_name=None, start_name=None, stop_name=None,
strand_name=None, sample_name=None):
""" Modifies a region dataframe to be coherent with the GMQL data model
:param region_df: a pandas Dataframe of regions that is coherent with the GMQL data model
:param chr_name: (o... | 24,379 |
def build_assets_job(
name: str,
assets: List[OpDefinition],
source_assets: Optional[Sequence[Union[ForeignAsset, OpDefinition]]] = None,
resource_defs: Optional[Dict[str, ResourceDefinition]] = None,
description: Optional[str] = None,
config: Union[ConfigMapping, Dict[str, Any], PartitionedConf... | 24,380 |
def isinf(a):
"""isinf(a)""" | 24,381 |
def createBinarySearchTree(vs):
"""
Generate a balanced binary search tree based on the given array.
Args:
vs - an integer array
{4, 5, 5, 7, 2, 1, 3}
4
/ \
2 5
/ \ / \
1 3 5 7
"""
def _help... | 24,382 |
def remove_end_same_as_start_transitions(df, start_col, end_col):
"""Remove rows corresponding to transitions where start equals end state.
Millington 2009 used a methodology where if a combination of conditions
didn't result in a transition, this would be represented in the model by
specifying a trans... | 24,383 |
def visualizeDomain():
""" Run the simplest case with random policy; visualize the domain to see how it looks. """
print 'in visualizeDomain'
plotSettings = RoverSettings(rewardType = 'DIFFERENCE',
moveRandomly = False,
numAgents = 30,
... | 24,384 |
def read_config(path: str) -> Dict[str, Any]:
"""Return dict with contents of configuration file."""
newconf = {
"setup": False,
"servers": [],
"okurls": [],
"loggers": [],
"localaddr": None,
# Legacy idlerpg option
"debug": False,
# Non-idlerpg co... | 24,385 |
def cleanup_one_header(header_path, patterns, options):
"""Clean regex-matched lines away from a file.
Arguments:
header_path: path to the cleaned file.
patterns: list of regex patterns. Any lines matching to these
patterns are deleted.
options: option flags.
"""
with... | 24,386 |
def turn_on(hass, entity_id=ENTITY_MATCH_ALL):
"""Turn on specified media player or all."""
hass.add_job(async_turn_on, hass, entity_id) | 24,387 |
def sieve(iterable, inspector, *keys):
"""Separates @iterable into multiple lists, with @inspector(item) -> k for k in @keys defining the separation.
e.g., sieve(range(10), lambda x: x % 2, 0, 1) -> [[evens], [odds]]
"""
s = {k: [] for k in keys}
for item in iterable:
k = inspector(item)
... | 24,388 |
def get_model(config: BraveConfig) -> embedding_model.MultimodalEmbeddingModel:
"""Construct a model implementing BraVe.
Args:
config: Configuration for BraVe.
Returns:
A `MultimodalEmbeddingModel` to train BraVe.
"""
init_fn, parameterized_fns = _build_parameterized_fns(config)
loss_fn = _build_... | 24,389 |
def upilab6_1_5 () :
"""
6.1.5. Exercice UpyLaB 6.2 - Parcours vert bleu rouge
(D’après une idée de Jacky Trinh le 19/02/2018)
Monsieur Germain est une personne très âgée. Il aimerait préparer une liste de courses à faire à l’avance. Ayant un
budget assez serré, il voudrait que sa liste de courses soit dans se... | 24,390 |
def construct_filtering_input_data(xyz_s, xyz_t, data, overlapped_pair_tensors, dist_th=0.05, mutuals_flag=None):
"""
Prepares the input dictionary for the filtering network
Args:
xyz_s (torch tensor): coordinates of the sampled points in the source point cloud [b,n,3]
xyz_t (torch tenso... | 24,391 |
def on_follow_action_notify_followed_party(sender, **kwargs):
"""
when a new person follows me, a notification is created and email queued
"""
notification = Notification(
title='Someone followed you',
body=user_followed_message.format(
username=kwargs['who_followed'].usernam... | 24,392 |
def rmean(x, N):
""" cutting off the edges. """
s = int(N-1)
return np.convolve(x, np.ones((N,))/N)[s:-s] | 24,393 |
def add_variant_to_existing_lines(group, variant, total_quantity):
"""
Adds variant to existing lines with same variant.
Variant is added by increasing quantity of lines with same variant,
as long as total_quantity of variant will be added
or there is no more lines with same variant.
Returns q... | 24,394 |
def calculate_position(c, t):
"""
Calculates a position given a set of quintic coefficients and a time.
Args
c: List of coefficients generated by a quintic polynomial
trajectory generator.
t: Time at which to calculate the position
Returns
Position
"""
retu... | 24,395 |
def step_impl(context, query):
"""
Send a query to the Indigo reinforcement learning reasoner
"""
context.query_json = {"message": {
"query_graph": {
"nodes": [
{
"id": "n00",
... | 24,396 |
def get_dqa(df):
"""Method to get DQA issues."""
try:
df0 = df[(df.dob == '') | (df.dqa_sex != 'OK') |
(df.dqa_age != 'OK') | (df.case_status == 'Pending')]
df1 = df0[['cpims_id', 'child_names', 'age', 'case_category',
'dqa_sex', 'dqa_dob', 'dqa_age', 'case_st... | 24,397 |
def get_3C_coords(name):
"""
Formatted J2000 right ascension and declination and IAU name
Returns the formatted J2000 right ascension and declination and IAU name
given the 3C name.
Example
>>> ra,dec,iau = get_3C_coords('3C286')
>>> print ra,dec,iau
13h31m08.287984s 30d30'32.95885... | 24,398 |
def get(player):
"""Get the cipher that corresponding to the YouTube player version.
Args:
player (dict): Contains the 'sts' value and URL of the YouTube player.
Note:
If the cipher is missing in known ciphers, then the 'update' method will be used.
"""
if DIR.exists() and CIPHERS.... | 24,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.