content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import sys
def verify_domain_disjoint(test_domlist, chaindict):
"""
Check that the supplied domain decomposition is valid in that
no residue is in more than one domain.
Parameters:
test_domlist - list of PTDomain from the test (predicted) decomposition
chain_dict - dict of { chainid : (... | 70e5d5585c094644f9f6b1c564e8fc0451f22655 | 653,725 |
def order(sentence: str) -> str:
"""
Sorts a given string by following rules:
1. Each word in the string will contain a single number.
This number is the position the word should have in the result.
2. Note: Numbers can be from 1 to 9. So 1 will be the first word (not 0).
3. I... | 6d69ed655274c6d0d6dc8ae935217e8b5663c2e4 | 653,726 |
import configparser
def setupcfg_has_metadata(setup_cfg_filename='setup.cfg'):
"""Parse the setup.cfg and return True if it has a metadata section"""
config = configparser.ConfigParser()
config.read(setup_cfg_filename)
if 'metadata' in config.sections():
return True
return False | 8c22cfac3614a43969e0adaa249e7440f83d74dd | 653,729 |
import torch
def solve_R(f1, f2):
"""f1 and f2: (b*)m*3
f2 * R -> f1
"""
batch_size = f1.shape[0]
S = torch.matmul(f1.transpose(-1, -2), f2) #B*3*3
try:
U, sigma, V = torch.svd(S)
except:
print("adding noise to avoid divergence in torch.svd")
noise = torch.diag_em... | 2edaad5d50f9f29aa386299c36cc972f0d6248c8 | 653,730 |
def _jinja2_filter_datetime(data):
""" Extract an excert of a post
"""
words = data.split(" ")
return " ".join(words[:100]) | 16a212e42f2301b6d496ecb81400c9e348659aab | 653,731 |
def load_data(spark, sqlContext):
"""pre-load data"""
vessels = sqlContext.read.format(
"org.apache.spark.sql.cassandra"
).options(
table="basic_position",
keyspace="ais_datas"
).load().createOrReplaceTempView("vessels")
v = spark.sql("SELECT * FROM vess... | b6e9aa24d6e33779f590517a95ab942a4f0ad733 | 653,732 |
def isnumber(word):
""" Checks if a string is a string of a number.
Parameters
----------
word : string
String of the possible number.
Returns
-------
Boolean.
"""
try:
float(word)
except (ValueError, TypeError):
return False
return True | 3b248a71cb97628bed2f10839e747be49da000f3 | 653,733 |
def token_list_to_text(tokenlist):
"""
Concatenate all the text parts again.
"""
return ''.join(item[1] for item in tokenlist) | 45d1ee5d990635aff5aa2073ccc3bda8b965bdef | 653,734 |
import distutils.sysconfig
import numpy
import numpy.core as core
import sys
import os
def get_include():
"""
Return the directory that contains the NumPy \\*.h header files.
Extension modules that need to compile against NumPy should use this
function to locate the appropriate include directory.
... | 99268828ce31672b6c8c146a2d3228068b994f5e | 653,735 |
import hashlib
def md5(filepath, blocksize=65536):
"""Generate MD5 hash for file at `filepath`"""
hasher = hashlib.md5()
fo = open(filepath, 'rb')
buf = fo.read(blocksize)
while len(buf) > 0:
hasher.update(buf)
buf = fo.read(blocksize)
return hasher.hexdigest() | 9906d76de66def0efeaafb2e2d4525bdf218ccb9 | 653,736 |
from pathlib import Path
from typing import Optional
def resolve_absolute_offset(
dataset_path: Path, offset: str, target_path: Optional[Path] = None
) -> str:
"""
Expand a filename (offset) relative to the dataset.
>>> external_metadata_loc = Path('/tmp/target-metadata.yaml')
>>> resolve_absolut... | cbeb2dfb6fea41d5a995ada529d964357c4e9fb9 | 653,737 |
import json
def to_json(data):
"""Return a JSON string representation of data.
If data is a dictionary, None is replaced with 'null' in its keys and,
recursively, in the keys of any dictionary it contains. This is done to
allow the dictionary to be sorted by key before being written to JSON.
"""... | c9c9309ccecbf37c513f18206a9eae495f30095a | 653,738 |
import torch
def _to_float(tensor: torch.Tensor) -> torch.Tensor:
"""create separate func b/c lambda not pickle-able"""
return tensor.float() | cce8ac81c2d821b367f74c1593584175683b3807 | 653,739 |
import subprocess
def install_app(apk_path):
"""
安装app
:param apk_path:
:return:0-success, 1-fail
"""
error = subprocess.call(['adb', 'install', '-r', '-d', apk_path])
return error | da17a790d5b319a413d863e5c04dc5d24c745bf0 | 653,740 |
def serialize_testinstance(test_instance):
"""return a dictionary of test_instance properties"""
ti = test_instance
info = {
'value': ti.value,
'date': ti.work_completed.isoformat(),
'save_date': ti.created.isoformat(),
'comment': ti.comment,
'status': ti.status,
... | 9a7c00e54d4180fbe21b8abf3a6ca1cba041dfe7 | 653,741 |
import math
def _calculate_target_load(num_reqs: int, rate: float = 100, baseline: int = 0) -> int:
""" Given the rate and number of URLs in data set, calculate how many URLs to send in this load"""
if baseline:
target_num_reqs = baseline * (rate / 100)
else:
target_num_reqs = num_reqs * (... | 953cbdafa18899f59743932f7edad31d72080ea8 | 653,743 |
def compute_over_actions(f, *args):
"""Runs f over all elements in the lists composing *args.
Autoregressive actions are composed of many logits. We run losses functions
over all sets of logits.
"""
return sum(f(*a) for a in zip(*args)) | db220d9297b7f7e4ddeebc4bc0003369326eac95 | 653,744 |
def format_name(name: str) -> str:
"""Formats a string for displaying to the user
Examples
--------
>>> format_name("manage_messages")
'Manage Messages'
>>> format_name("some_name")
'Some Name'
Parameters
----------
name : str
the raw name
Returns
-------
s... | 2147183419073f11270cb664df345ced98e44001 | 653,745 |
import os
import argparse
def file_path(path):
"""
Checks to see if the data file path is valid.
:param path: Path to data file.
:type path: str
:return: Path to data file.
:rtype: str
"""
if os.path.isfile(path):
return path
else:
raise argparse.ArgumentTypeError... | 585a41e3106ac670100a2c8e396d63f6067a4d99 | 653,746 |
def getvehcats(file):
""" Get vehicle indices from different coco object categories """
vehicles = {}
for i in file['categories']:
if i['supercategory'] == 'vehicle' and i['name'] not in 'boatairplane':
vehicles[i['id']] = i['name']
return vehicles | 8aec6d7ac8fb96121bf002a2b910c502fb838997 | 653,747 |
def isindex(l):
"""
Return True is l contains all integers of range(len(l)) else false.
"""
return next((False for i in range(len(l)) if i not in l), True) | 14d5343e064ba6dd4aef549357bca147916bdf03 | 653,748 |
def weekly_difference_to_goal(average_value, level):
"""
Calculate how many more hours a week the person would need to be usable for to
achieve a utiliztaion target
"""
weekly_difference = round((level-average_value) * 0.4, 1)
return str(weekly_difference) | d5a95f9e0b4379a4b2c9799f55f75621cb0e1135 | 653,749 |
def flatten_dict(data: dict, level_separator: str = ".") -> dict:
"""Flattens a nested dictionary, separating nested keys by separator.
Args:
data: data to flatten
level_separator: separator to use when combining keys from nested dictionary.
"""
flattened = {}
for key, value in data... | 37effdbe1dbc3638b3d2e5b55385f3a8d292e247 | 653,750 |
def string_to_int_list(line) -> list[int]:
"""
Given a line containing integers, return a list of ints.
Return list[int]: A list of integers from the string.
>>> string_to_int_list('22 13 17 11 0')
[22, 13, 17, 11, 0]
>>> string_to_int_list('22,13,17,11,0')
[22, 13, 17, 11, 0]
"""
... | 0a31a7e3b320effb1851d1f37e9fb640c78d0c72 | 653,751 |
import numpy
def jac(a, x, y):
""" return the Jacobian of fun """
# df0/da0
df0da0 = numpy.sum(numpy.exp(2.0*a[1]*x))
# df0/da1
df0da1 = numpy.sum(x*numpy.exp(a[1]*x)*(2.0*a[0]*numpy.exp(a[1]*x) - y))
# df1/da0
df1da0 = numpy.sum(x*numpy.exp(2.0*a[1]*x))
# df1/da1
df1da1 = n... | 4d4ac4b9ee655d9e5b27fe9b0e746b9d4074fbe0 | 653,752 |
def get_push_size(op):
"""Get push side increment for given instruction or register."""
ins = op.lower()
if ins == 'pushq':
return 8
elif ins == 'pushl':
return 4
else:
raise RuntimeError("push size not known for instruction '%s'" % (ins)) | 3381f917647cb5799fb66fb7803e95a570e02b5c | 653,753 |
import requests
def get_number_of_asa_service_groups(asa):
"""
Returns the number of service object-groups the given ASA object has configured.
:param asa: ASA device to count network object-groups.
:return: Integer which describes how many object-groups is found on ASA.
"""
url = asa.url() + ... | a175ea823dfad4bf791da8ad3198ee9c002f0134 | 653,754 |
from typing import Union
import logging
def create_logger(name: str, log_level: Union[str, int]) -> logging.Logger:
"""
return a logger configured with name and log_level
"""
logger = logging.getLogger(name)
logger.setLevel(log_level)
if not logger.hasHandlers():
handler = logging.Str... | 2fdf9d2de6589cc9e5ca8252b2b375c07a74519a | 653,755 |
def SetMakeTMplotColor(idxTM, TMname, foldType, base_outline_width, base_text_color, base_outline_color):# {{{
"""Set color scheme for makeTMplot
1. If foldType is labelled 5B, please colour BC1 and BC2 "Purple" (#600080)
2. If foldType is labelled 7B, please colour BC1 and BC2 "Dark pink"
3. If foldTy... | f823b21c96fb398c3130ce0e968a0570b7bf49b2 | 653,756 |
def manhattan(x: list, y: list) -> float:
"""Manhattan is the the sum of the absolute diff of their Cartesian co-ords
In a plane with p1 at (x1, y1) and p2 at (x2, y2).
Manhattan distance = |x1 – x2| + |y1 – y2|
This Manhattan distance metric is also known as
Manhattan length,
rect... | 47cab46f56c6cf15a0cd3169328d6496a6eebeca | 653,757 |
def treatment(s: list) -> tuple:
"""processing in std"""
n = int(s[0])
nlst = [i.strip('\r\n') for i in s[1:n + 1]]
q = int(s[n + 1].strip('\r\n'))
qlst = [i.strip('\r\n') for i in s[n + 2:n + q + 2]]
return nlst, qlst | 8a676a51e0b60ab37c79e0ee41cbcd10edb72b55 | 653,758 |
def zeros(n: int) -> int:
"""Return the number of trailing zeros in the binary representation of n.
Return 0 if n == 0."""
result = 0
while n & 1 == 0:
n = n // 2
result += 1
return result | b215f80dba4aa66ad6cf2baebb24bc6731acfd46 | 653,759 |
import re
def get_nb_query_params(nb_url_search: str) -> dict:
"""
Get the url query parameters from the search string.
Arguments:
nb_url_search {str} -- The URL search string
Returns:
dictionary of the query string parameters.
"""
nb_params = {}
query_string_match = re.... | 123ada462b3c5e29e42f7e66eb9bd5aceeab0419 | 653,760 |
from typing import Callable
from typing import Iterator
def _exponential_backoff(
retries: int = 10,
delay: float = 2,
backoff: float = 2,
max_delay: float = 60) -> Callable:
"""
Customizable exponential backoff strategy.
Args:
retries (int): Maximum number of times... | ba05a44009dcdf4bfb4176fbbc2b0b207b4d8757 | 653,761 |
def find_zeroes_2(f, a, b, epsilon=1e-10):
"""
A formulation of the recursive version of find_zeroes that does not do explicit recursion on the stack.
:param f: The function.
:param a: The lower bound of the interval.
:param b: The upper bound of the interval.
:param epsilon: The stopping toler... | 6ef58e6a32af6eca23bfb734416b9f3d30273b7a | 653,763 |
def update_readme_travis_url(main, file):
""" Update Travis CI URL
"""
if main.replace_in_file(file, "https://travis-ci.org/bincrafters", "https://travis-ci.com/bincrafters"):
main.output_result_update(title="README: Update Travis URL from .org to .com")
return True
return False | 0f9d75266a524599f858c22fdb8e5b0451c792bd | 653,764 |
def calculate_nd_slice(src, coords_lo, coords_hi):
"""Calculate the ``slice`` object list that is used as indices for
reading from a data source.
Unfortunately, this kind of slice list is not yet supported by h5py.
It only works with numpy arrays."""
# Separate spatial dimensions (..., H, W) from n... | 788418f54a7aa01c9e2a931aee7520944584b8b1 | 653,765 |
def number_string_2_integers(_list):
"""Gets a list of strings and returns a list of the correspondant integers.
Returns the translated list.
"""
integer_list = []
for _int_str in _list:
integer_list.append(int(_int_str))
return integer_list | 3c2e2edbedf5f56674c11be91e2416933d3b07b7 | 653,767 |
def find_scenario_string_from_number(scenario):
"""
Find a string to represent a scenario from it's number (or None in the case of baseline).
Args:
scenario: The scenario value or None for baseline
Returns:
The string representing the scenario
"""
if scenario == 0:
retu... | e5c60751506f9e6e79a863426d9ba80bab617bca | 653,768 |
import io
def load_data(dataset_path):
"""
load data from a file
:param dataset_path:
:return: a list of all the items in the file
"""
items = []
with io.open(dataset_path, "r", encoding="utf8") as f:
for line in f:
items.append(line.rstrip())
return items | d3f2f6916ea187cf48e1fc9bb8a5cec12d392ef1 | 653,769 |
import sys
def _defaultSysPathFactory():
"""
Provide the default behavior of PythonPath's sys.path factory, which is to
return the current value of sys.path.
@return: L{sys.path}
"""
return sys.path | d9ab887ec53603c5658b2704587d9965f922a9d7 | 653,770 |
def _get_sub_dict(d, *names):
"""
get sub dictionary recursive.
"""
for name in names:
d = d.get(name, None)
if d is None:
return dict()
return d | 78bb8d1cfbc8a41ba10b8bc6b5aa500700fffef8 | 653,772 |
from typing import List
def get_clusters_from_labels(texts: List[str], labels: List[int]) -> List[List[str]]:
"""Given a series of texts and their labels (as produced during clustering), reconstructs the clusters"""
return [[text for text, lab in zip(texts, labels) if lab == label] for label in set(labels) i... | fb91c228552d05395f87e508044c324a3784e324 | 653,773 |
def cache(feature):
"""Hack'ish and pretty straightforward cache for heavier calculations.
Usage:
f = cache(f)
f(x, y)
f(z)
feature -- the function to cache results for
"""
def decorator(*args, **kwargs):
if args in cache:
return cache[args]
else:
... | d4d803435e4c3add595d806791d87f0e7e3bf267 | 653,774 |
def parsing_explore_lines(explore_list, loc_list):
"""
This function parses a list of explore lines into a grouped structure of explore lines.
:param explore_list: the list representing raw explore file.
:type explore_list: list
:param loc_list: the list of dividers, each divider is the number of... | 272d6a2f5f04207a6dd18a78f8cc56967d5ed90f | 653,775 |
def names_to_labels(names, depth=1, sep='.'):
"""
convert names to grouping labels
Parameters
----------
names : [str]
account names in form of 'Foo.Bar.Baz'
depth : int, optional
returned label depth. The default is 1.
sep : char, optional
Separator character. The d... | 230d846ece8e4d054b69bc1bc8f417440c01b5d5 | 653,776 |
import os
def _get_get_parameters(get_tests_dir, expected_tests_dir, config_path,
suite_name, normalize_ids):
"""Return the parameters suitable for parametrizing HTTP GET tests."""
method = "GET"
test_argvalues = []
test_ids = []
requests_file_path = os.path.join(get_tests_... | 65c24ab221081822d1c9d6aab4c2e47d194f789f | 653,777 |
def apply_filter(x, W):
"""
Applies a filter on the mixture. Just corresponds to a matrix
multiplication.
Parameters
----------
x: np.ndarray [shape=(nb_frames, nb_bins, nb_channels)]
STFT of the signal on which to apply the filter.
W: np.ndarray [shape=(nb_frames, nb_bins, nb_chan... | 3ff75cc93afe9ac88dfe25022b04d73f266251fd | 653,778 |
def _get_smartx_specs_params(lunsetinfo, smartx_opts):
"""Get parameters from config file for creating lun."""
# Default lun set information.
if 'LUNType' in smartx_opts:
lunsetinfo['LUNType'] = smartx_opts['LUNType']
lunsetinfo['policy'] = smartx_opts['policy']
return lunsetinfo | a53cc90513a018a83359115c0e82a23c6f2f1bee | 653,779 |
import copy
def merge_dict(a, b):
"""Merge the fields of a and b, the latter overriding the former."""
res = copy.deepcopy(a) if a else {}
copyb = copy.deepcopy(b) if b else {}
for key in copyb:
res[key] = copyb[key]
return res | 8913662e3cb229ebbe3e4a2abd54041223dc0def | 653,780 |
def plaintext(text, **kwargs):
"""Renders plain text.
:param text: text to display
:type text: str
"""
def template(*args, **kwargs):
# convert to html
return f"<pre>{text}</pre>"
return template | cb10c9076f423b8873b79e9d82b3db13bc869584 | 653,781 |
def detect_encoding(csvfile):
""" Since encoding detection is hard to get right (and work correctly
every time), we limit ourselves here to UTF-8 or CP1252, whichever works
first. CP1252 is basically the csv format you get if you use windows and
excel and it is a superset of ISO-8859-1/LATIN1.
"""
... | 3c31073e8f8f426d89c1dba4d6e955de6c8be15b | 653,782 |
import math
def distance_between_points(x, y):
"""
distance between two points with the coordinates (x1, y1) and (x2, y2).
D=√(x2−x1)2+(y2−y1)2
"""
all_distances = []
zipped = zip(x,y)
for z in zipped:
z1, z2 = z
all_distances.append((z1-z2)**2)
return math.sqrt(sum(all... | 1abdf477f7b1045274727b5323b19f4351786459 | 653,783 |
import torch
def square_distance(src, dst):
"""
Calculate Squared distance between each two points.
"""
B, N, _ = src.shape
_, M, _ = dst.shape
dist = -2 * torch.matmul(src, dst.permute(0, 2, 1))
dist += torch.sum(src ** 2, -1).view(B, N, 1)
dist += torch.sum(dst ** 2, -1).view(B, 1, ... | 73d79746dcc17b7ae1fbaf0c2905e5c2bf540d23 | 653,784 |
def _convert_resolve_list_type(resolve_list):
""" Resolve is using indexed dictionary as list type.
`{1.0: 'vaule'}`
This will convert it to normal list class
"""
assert isinstance(resolve_list, dict), (
"Input argument should be dict() type")
return [resolve_list[i] for i in sorted(res... | c40a6c255d5c71cb1e65ec44cfdaceb60087cdab | 653,785 |
def bissextile(Y):
"""
Vérifie si une année Y est bissextile.
Entrée :
Y l’année
Retour :
True
False
Erreur si Y n’est pas convertible en entier
"""
Y = int(Y)
if(Y <= 1582):
return ((Y % 4) == 0)
else:
return (
... | 2111ac83fdf6a151b0a3834e21a7c391873c391c | 653,786 |
def calculate_new_offset(
current_image_0, new_image_0, new_norm_fac, n_old_param, n_new_param
):
"""Calculate the parameter offset for the new image range.
Returns:
int: An offset to apply when selecting the new parameters from the
existing parameters.
"""
if n_old_param == 2:
... | 153eeba54550990633caa5f9f90b54fe39283427 | 653,787 |
import subprocess
def _check_affected_tests(repo_info):
"""Runs the test suite for all packages that were changed.
Returns True if all tests pass (or if there are no affected tests), False otherwise.
This check does not run tests for packages that were indirectly affected, e.g. if
package A depends ... | f3e8f96daf79865df9ade5ef1530ca645abf177f | 653,788 |
def GetGlueCpp(idl_file):
"""Gets the name of the glue implementation file.
Args:
idl_file: an idl_parser.File, the source IDL file.
Returns:
the name of the implementation file.
"""
if 'npapi_cpp' in idl_file.__dict__:
return idl_file.npapi_cpp
else:
return idl_file.basename + '_glue.cc' | 2aeac9f681389d750866bdd3961cb0e2df569747 | 653,789 |
def key_wrap(flow, key):
# language=rst
"""
Add the ability to specify a key to initialize
"""
_init_fun, forward, inverse = flow
def init_fun(unused_key, input_shape, condition_shape):
name, output_shape, params, state = _init_fun(key, input_shape, condition_shape)
return name,... | 9ce26478b2f4a3bf6949629ef6154d09de015731 | 653,790 |
def _contains_only(container, type):
"""check that contents of a container are all of the same type"""
try:
container = container.values() # dict
except AttributeError:
pass
return all(isinstance(s, type) for s in container) | 979dba993adbbae82e8e9b6606d3190150538c77 | 653,791 |
def register_event(event_type, include_subclasses=False):
"""
Register a method to handle a specific `opsdroid.events.Event` object.
Args:
event_type (Event): The event class this method can handle.
include_subclasses (bool): Allow the function to trigger on subclasses of the registered
... | ab47a895471ae1911e6da30264677a596231de49 | 653,792 |
import getopt
import sys
def setup():
"""
Parses the command line arguements.
-d = update database
-f {file} where file is the progress file to use
-b {block} where block is the max block we will scan to
"""
try:
opts, args = getopt.getopt(sys.argv[1:], "f:db:")
except getopt.... | cb8338fa70577aec644ec94796da7ba2b520c7c4 | 653,793 |
import random
def CryptRandInt(length=10):
"""Get random integer in range"""
#byte = os.urandom(100)
#rand = int(byte.hex(),16)
r = random.SystemRandom()
rndint = r.randrange( length )
return rndint | e561d923ffcb62d7d456bf855c7be7d7779c9dc8 | 653,794 |
import random
def pickStep(tmp_steps, summe):
"""
Selects a step within the terrain
"""
if len(tmp_steps) == 1:
return tmp_steps[0][1] # returning the nucleotide of the only present step
else:
rand = random.random() # draw random number
mainval = 0
for choice in r... | 25dac1ee4daf55c900332e20aee9449e27ecb51f | 653,795 |
def find_already_present_insp_keys(replacements, bib_dbs):
"""Filter replacements to those whose INSPIRE key appear in bibs.
Parameters
----------
replacements: array of dict
Each dict has keys "ads_key", "insp_key", and "bib_str".
bib_dbs: array of `bibtexparser.bibdatabase.BibDatabase`
... | f7cac6beb09a90b053bab69e37f6d61bd3fd4839 | 653,796 |
def encode_data(data):
"""Encode sysex data as a list of bytes. A sysex end byte (0xf7)
is appended.
"""
return list(data) + [0xf7] | c3ad4a28f011deec89d3b96445c4dd2d8f6433c6 | 653,799 |
def splitProjectInfo(value: str):
"""Split a comma-separated list of 3 values (hub,group,project)"""
tokens = value.split(",")
if len(tokens) != 3:
raise RuntimeError(f"Invalid project: {value}")
return tokens | df60c85ac4778a6462012db7f9573dca1880ddc6 | 653,800 |
import uuid
import hashlib
def hash_password(password):
"""Encode password"""
salt = uuid.uuid4().hex
return hashlib.sha256(salt.encode() + password.encode()).hexdigest() + ':' + salt | 0745d420ec2d8d467eb2bbfb7581bc0c94b5fc70 | 653,801 |
import torch
def num_flat_features(x: torch.Tensor) -> int:
"""
Computes the total number of items except the first dimension.
:param x: input tensor
:return: number of item from the second dimension onward
"""
size = x.size()[1:]
num_features = 1
for ff in size:
num_features ... | 24a8889a070afb3365b60c9afe82cfc0440a3774 | 653,802 |
def uniqueIdentifierTypes_e(otype=None):
"""
unique identifier lookup function
Args:
otype: str, int
Returns: if is int then return string; otherwise, if the type is string return int
"""
uniqueIdentifierTypes_t = {
"unknown": 0,
"telemetryObject": 1,
"applicati... | 8891f88aa0152681dd321506cc31820b16ce3c34 | 653,804 |
import os
import re
def dropbox_basename(url):
""" Strip off the dl=0 suffix from dropbox links
>>> dropbox_basename('https://www.dropbox.com/s/yviic64qv84x73j/aclImdb_v1.tar.gz?dl=1')
'aclImdb_v1.tar.gz'
"""
filename = os.path.basename(url)
match = re.findall(r'\?dl=[0-9]$', filename)
if... | ad2f39b59756390cf1b3ed62ddb81604f16986c3 | 653,805 |
import re
def parse_role_for_profile(role: str) -> str:
"""Returns a 'safe' profile name for a given role.
Args:
role: The role to generate a profile name for.
Returns:
Formatted profile name.
"""
account_id = "000000000000"
role_name = "Unknown-Role-Name"
account_re = r... | 156624fe49ec033e6c55ef7f41cba1f7281d4c2f | 653,806 |
import sys
def load_dataset(dataset_name, dataset_kwargs):
"""Dynamically loads the specified `torch.utils.data.Dataset` object.
"""
if not hasattr(sys.modules[__name__], dataset_name):
raise ValueError
dataset_def = getattr(sys.modules[__name__], dataset_name)
return dataset_def(**dataset... | c538f8afc642ac9696ee3ab1cced47f1ed126578 | 653,808 |
import os
from datetime import datetime
def sorter(path):
""" to arrange files by date in the filename to be able to obtain the two most
recent files from the directory"""
filename = os.path.basename(path)
return datetime.strptime(filename[0:10], '%Y-%m-%d') | 25d067393ccc9e6aaa36e1fd1ea13237a31c988b | 653,809 |
def wgc(c, two_qb_weight=10):
"""A measure of the complexity of a given circuit. By default, 2-qubit
gates are treated as 10X more costly than single-qubit gates"""
c_tmp = c.to_basic_gates()
total = len(c_tmp.gates)
n2 = c_tmp.twoqubitcount()
single_qubit_count = total - n2
return two_qb_w... | 2bb69f4e5c5d7876c67806c9274583b2f9813333 | 653,810 |
def perfect_match(a, b):
"""
returns true if a and b are a perfect match
:param a: comma seperated fingerprint
:param b: comma seperated fingerprint
"""
return a == b | 7cebb08abfa929f57fb77543f66ffa4c240966e1 | 653,813 |
def datetime_to_str(date_time):
"""
Convert datetime to string. This format is specific to the 42API responses.
Arguments:
date_time: (datetime) the datetime.
Returns:
(str) containing the string equivalent of the datetime object.
"""
return (date_time.strftime("%Y-%m-%dT%H:%M:%S.%fZ")) | 1f190e3d39a78fb63f19abc386da0f288d3d720f | 653,814 |
def verbose_name(obj):
"""Return the object's verbose name."""
try:
return obj._meta.verbose_name
except Exception:
return '' | ae5542404b326be960331632239c11b0ad0411dc | 653,815 |
def unique(s, key=None):
"""
Return unique entries in s
:Returns:
A sequence of unique entries of s.
If `key` is given, return entries whose key(s) is unique.
Order is preserved, and first of duplicate entries is picked.
"""
if key is not None:
keys = (key(x) fo... | 46b69e2ad191cf5cd8e256b669b7158829b5a5ef | 653,816 |
async def index(request):
"""
This is the view handler for the "/" url.
:param request: the request object see http://aiohttp.readthedocs.io/en/stable/web_reference.html#request
:return: context for the template.
"""
# Note: we return a dict not a response because of the @template decorator
... | 254a1a741efb3c7bf3df57b046bacb94294c397f | 653,817 |
import re
def command_parser(ps1_command):
"""
:param ps1_command: which contain ps1.
:return: user's input command
"""
ret = None
ps1_pattern = re.compile('(\[.*@.*\][\$#])(.*)')
match = ps1_pattern.search(ps1_command)
if match:
ret = match.group(2).strip()
return ret | 3edc543a9e01ed997b5e5f893f1fa891833597e8 | 653,818 |
import copy
def CountUnique(inputList):
"""
Count the number of unique entries in the supplied list
"""
lInputList = copy.copy(inputList)
lInputList.sort()
count = 0
if len(lInputList) > 0:
count += 1
for i in range(1, len(lInputList)):
if not lInputList[i] == lInputList[i - 1]:
co... | 965610acf91339bd6b6fff93602c3fe5da5ca6d6 | 653,819 |
def simulate(job):
"""Run the minimization, equilibration, and production simulations"""
command = (
"gmx_d grompp -f em.mdp -c system.gro -p system.top -o em && "
"gmx_d mdrun -v -deffnm em -ntmpi 1 -ntomp 1 && "
"gmx_d grompp -f eq.mdp -c em.gro -p system.top -o eq && "
"gmx_d... | 2b4aad3e01f6e826e43114065748470361e7fc9b | 653,820 |
import torch
def extend_batch(tensor, extend_shape):
""" Extend tensor to the left
"""
extend_shape = torch.Size(extend_shape)
return tensor.expand(extend_shape + tensor.shape) | 432a5e2f07816598dbdb5b1aba29c5acdcc78f76 | 653,822 |
def categories_to_string(categories, queryset=False):
"""
Args:
categories: [{"title": "Business"}, ...] OR
[models.Category] (if queryset=True)
Returns:
['<category.title', ...]
"""
if queryset:
new_categories = [i.title for i in categories]
else:
... | d5e99477b30eb7fed20df837f7dbfb15da52958b | 653,825 |
from typing import Union
def _intermediate_helper(
start_unit: str,
end_unit: str,
quantity: Union[int, float],
imperial: dict,
metric: dict,
) -> Union[int, float]:
"""
Function turns any input quantity into an intermediate value based on dictionary constants. Function
then takes the... | 5d7c378bc39a61e9a271b65485a91ae65f5ae22e | 653,826 |
def get_tuple_wise_evaluation(d, correction_dictionary):
"""
This method evaluates data cleaning in tuple-wise manner.
"""
actual_errors_dictionary = d.get_actual_errors_dictionary()
actual_dirty_tuples = {i: 1 for i in range(d.dataframe.shape[0]) if int(sum([(i, j) in actual_errors_dictionary
... | a93dca047675248df9dcdc7139eea98d91ce1d8e | 653,827 |
import six
def _bytes(*args):
"""
Returns a byte array (bytes in py3, str in py2) of chr(b) for
each b in args
"""
if six.PY2:
return "".join(chr(c) for c in args)
# else: Python 3
return bytes(args) | 59fbdc1f10ef1a5e8d3b0f43aae8f18614c5d554 | 653,828 |
import torch
def hat(v: torch.Tensor):
"""Maps a vector to a 3x3 skew symmetric matrix."""
h = torch.zeros((*v.shape, 3), dtype=v.dtype, device=v.device)
h[..., 0, 1] = -v[..., 2]
h[..., 0, 2] = v[..., 1]
h[..., 1, 2] = -v[..., 0]
h = h - h.transpose(-1, -2)
return h | 60876797f76c407c01b0d729bccca5d3ab6f3366 | 653,829 |
import string
def create_character_list(args):
"""Create the list of allowed characters to generate passwords from"""
possible_chars = []
if args.uppercase_ascii:
possible_chars += string.ascii_uppercase
if args.lowercase_ascii:
possible_chars += string.ascii_lowercase
if args.n... | 79f660f48f713296887ec47a899a7b3af84ef75f | 653,830 |
import torch
from typing import Tuple
def _equalize_attributes(actual: torch.Tensor, expected: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""Equalizes some attributes of two tensors for value comparison.
If :attr:`actual` and :attr:`expected`
- are not onn the same memory :attr:`~torch.Tensor.de... | 9f69a726d31898489abcb3d6da2d196ea8193056 | 653,832 |
def rightDiagonalProduct(a, diag):
"""
Calculate the product of a matrix and a diagonal matrix, with broadcast.
Parameters
----------
a : 2D ndarray of float
diag : array of float
The diagonal elements of the diagonal matrix.
Returns
2D ndarray of float
Matrix (a @... | e45ba7f6ca950d581396c04cec972ccb7c7d903e | 653,833 |
def clean(s):
"""Custom parser for tests."""
return s, s.replace("-*-", "") | a679f886decb64ec4c11f3896d0c07b6712f9cd4 | 653,834 |
def calcStampAmount(aimPrice, listOfAvailableStamps):
"""
Work out in multiple different ways and choose the one with the least stamps
"""
# possibleStampLists is a master list of lists
possibleStampLists = []
# See if any stamps fit exactly into aimPrice
for stamp in listOfAvailableStamps:... | 1ed0f0f2fca57f45d1b7b61db41460f821ed1b01 | 653,836 |
def buildNewSol(neighbor, data):
"""
given a recently build solution (neighbor)
this function computes:
the cost,
the exceeding capacity,
the pending assignments
the total assigned hours
"""
totalw = 0
sumz = 0
columnarSum = [-1 * d fo... | 306b8e1444a7fab676f034cfdf152d8bef88e70d | 653,837 |
def bcon(reg, blocks):
"""
Block list converter.
If blocks is a list of integers, convert to a list of blocks using reg.blocks.
Else, do nothing.
Return list of blocks.
"""
## go
if len(blocks)>0 and type(blocks[0])==int:
blocks = [ reg.blocks[blocks[i]] for i in range(len(blocks)) ]
## return
return blocks | b253f83a36cf07f6bda2a4bb3e64826654650f3d | 653,838 |
def _get_vertex_location_name(location):
"""Get the location name from a location that is expected to point to a vertex."""
mark_name, field_name = location.get_location_name()
if field_name is not None:
raise AssertionError(u"Location unexpectedly pointed to a field: {}".format(location))
return mark_name | 26ccd09f7749506e31aa4fb8d02941b3816ea2c0 | 653,839 |
def _generate_manifest(ctx, srcs):
"""Create a `clang_format_manifest` output file
Args:
ctx (ctx): The rule's or aspect's context object
srcs (list): A list of File objects
Returns:
File: The manifest
"""
manifest = ctx.actions.declare_file(ctx.label.name + ".clang_format.... | e6659e3d498f7f3ac2354c664496e1c20a4b9478 | 653,840 |
import os
def exists(path):
"""Replacement for `os.path.exists` which works for host mapped volumes
on Windows containers
"""
try:
os.lstat(path)
except OSError:
return False
return True | 2f52509fbfc4037bed18a9cd820dcf9fba7ff41d | 653,841 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.