content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import re
def contains_chinese(text):
"""Returns whether the given text contains any chinese characters."""
return re.search(u'[\u4e00-\u9fff]', text) | a2ea77109b3af46cae1f99f8c7fb20fc6f1ab4b1 | 642,535 |
def annualIntervalDemand(aggprofilepowerdata):
"""
This function computes the mean annual power consumption for the interval aggregated in aggprofilepowerdata.
"""
interval = aggprofilepowerdata.interval[0]
try:
aggdemand = aggprofilepowerdata.groupby(['RecorderID','ProfileID_i']).... | b19ae5d3c4c4529bf9b16078f8c027dc020f3c77 | 642,536 |
import random
def get_ua():
"""
return a random ua
str:return:ua value
"""
uas = [
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.167 Safari/537.36'
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13) AppleWebKit/604.1.38 (KHTML,... | f990a07beb81687ba7dccfb24a3b0e46f630e322 | 642,537 |
def get_default_facteur_uct():
"""
The following UCT parameter could be equal to 0. Make sure to use a very small value. Typically, between 0 and 0.3.
"""
facteur_uct = 0.01
return facteur_uct | 1a8e6d679cf7ac4ff6f756032ab6e5086315c895 | 642,538 |
def text_encode(obj, name, n):
"""
Encode and check resulting byte string length.
"""
# The attribute name is a parameter to provide a useful error message.
value = getattr(obj, name)
if value is None:
value = ''
bytestring = value.encode('ascii').ljust(n)
if len(bytestring) > n:... | f9de8d95874f6df25039b38319fbc7f687066cd6 | 642,539 |
import tqdm.auto as t
import warnings
def tqdm(iterable=None, desc=None, total=None, leave=True, **kwargs):
"""ascii=Trueでncols=100なtqdm。"""
try:
return t.tqdm(iterable, desc, total, leave, ascii=True, ncols=100, **kwargs)
except ImportError:
warnings.warn("tqdm import error")
ret... | 7bcdcb01b3bc47f5adb65f4e92481709a11ff07c | 642,540 |
from typing import List
from typing import Any
def get_attr_path(data: dict, path: List[str]) -> Any:
"""
Used to get a value in a dict based on a path.
Args:
data (dict): A dict of data to be searched.
path (list): An ordered list of string attrs to be used for searching through the obje... | e9b415910104f12b7cdff90dbbc7939f7542b931 | 642,541 |
def s2b(s):
"""
Converts a string to boolean value
"""
s = s.lower()
return s == 'true' or s == 'yes' or s == 'y' or s == '1' | cd3fab7ab7f2a417a21d511fc2d33e07cb38fb31 | 642,542 |
from typing import Any
import base64
def file_value(file_name: str) -> dict[str, Any]:
"""
Opens the file with file_name and returns its content as a string.
Args:
file_name (string): Name of the file to read.
Returns:
(dic) with "bytes":value(String) and "fileName... | b6b3eb5921f678dfc187927c201c18e6df13d0f7 | 642,543 |
def getLastLine( filename, read_size = 1024 ):
"""return last line of a file.
"""
f = open(filename, 'rU') # U is to open it with Universal newline support
offset = read_size
f.seek(0, 2)
file_size = f.tell()
if file_size == 0: return ""
while 1:
if file_size < offset:
offset = file_size
... | dee053c77fc8201a8c7be9de733137bab17647c3 | 642,544 |
def parse_td(row_html):
"""
Return the td elements from a row element.
Parameters
----------
obj : node-like
A DOM <tr> node.
Returns
-------
list of node-like
These are the elements of each row, i.e., the columns.
"""
return row_html.find_all(("td", "th"), recurs... | 7a4d4c2a253053a2f3e3b428b3d0b288a7d5021a | 642,545 |
def get_constraints(image, derivative, param1, cycle4=True, cycle8=True):
"""
get constraints
"""
rows = []
rhs = []
senses = ""
# absolute value constraints
for i in range(image.shape[0]):
for j in range(image.shape[1]):
vars = ["w_{}_{}".format(i, j),
... | 1d0b1c7bb6bdc6bbdca1574adcf205746569a18f | 642,547 |
def configure_approle(client, name, cidr, policies):
"""Create/update a role within vault associating the supplied policies
:param client: Vault client
:ptype client: hvac.Client
:param name: Name of role
:ptype name: str
:param cidr: Network address of remote unit
:ptype cidr: str
:par... | c65befd6afa3cb865b9ecffdf35a2c04e534d59a | 642,548 |
def preparRequete(phrase1,phrase2):
"""
put database request in a string
phrase1: string with values of all items
phrase1: string with database name of all items
return final request to insert values of all item in the database
"""
requete = ''
requeteDebut = 'INSERT INTO tablename('
... | 98860efefe150fa6fbff73b23e965ef06ee17758 | 642,549 |
def event_handler(*event_types):
"""
Mark a function/method as an event handler for a particular type of event.
"""
def wrapper(func):
func.__event_types__ = event_types
return func
return wrapper | 22372db3674826c098fb760361080b439d640cdf | 642,551 |
def _get_update_fields(queryset, to_update, exclude=None):
"""
Get the fields to be updated in an upsert.
Always exclude auto_now_add, auto_created fields, and unique fields in an
update
"""
exclude = exclude or []
model = queryset.model
fields = {
**{field.attname: field for fi... | 40f0dc4efaf640b7cd5759a6310c83bf7e0f0460 | 642,552 |
def Metadata2dict(md):
"""
Converts a Metadata object to a Python dict.
This is the inverse of dict2Metadata. It converts a Metadata object to
a Python dict. Note that Metadata behavies like dict, so this conversion
is usually not necessay.
:param md: Metadata object to convert.
:type md:... | e59fc5bbcbb765c13e6d577dd0f750ca798aa59f | 642,553 |
def split_text(lines):
"""Split a text devided by newline into chunks of about 4000 characters."""
chunks = []
current_chunk = []
chars = 0
for line in lines:
# Append the length of the line + a newline
chars += len(line) + 1
if chars < 4000:
current_chunk.append... | 864ebc8d66fcd9370ada68e9cb9db8fbfd86208d | 642,554 |
def sellmeier(lmbda, B1, B2, B3, C1, C2, C3):
"""
Estimate refractive index of glass with wavelength.
Using the Sellmeier equation.
Input:
lmbda: the Wavelength
B(1-3) : B coefficients of glass
C(1-3) : C coefficients of glass
Returns:
n : Fitted refractive index
"""
n_squ... | 3c31a1087893e2abddd47d5e3164a326a7a8744d | 642,555 |
import subprocess
import shlex
def get_description():
"""
Get description.
Returns:
str, wheel package description.
"""
cmd = "git log --format='[sha1]:%h, [branch]:%d' -1"
process = subprocess.Popen(
shlex.split(cmd),
shell=False,
stdin=subprocess.PIPE,
... | 3398e08222880fa77fc95aeca7b897897efe7503 | 642,557 |
def discrete_binary_search(func, lo, hi):
""" Locate the first value x s.t. func(x) = True within [lo, hi] """
while lo < hi:
mi = lo + (hi - lo) // 2
if func(mi):
hi = mi
else:
lo = mi + 1
return lo | f8233515a822178898b93a333356c51069493440 | 642,558 |
def dummy_import(monkeypatch): # (MonkeyPatch) -> Callable
"""
This fixture monkeypatches the import mechanism to fail.
After raising an `ImportError`, the monkeypatch is immediately removed.
"""
def dummy_import(*args, **kwargs):
try:
raise ImportError("this is a monkeypatch"... | 341bd038135e1d689af50677d1fc1fbdc96c730a | 642,559 |
import sys
def is_str(s):
"""
Python 2 and 3 compatible string checker.
"""
if sys.version_info >= (3, 0):
return isinstance(s, str)
else:
return isinstance(s, basestring) | 577ea74d96ba636a634954c34e2f8889a2bb0db4 | 642,561 |
def wines_table_query() -> str:
"""
Retorna a query que cria a tabela wines
"""
return """
CREATE TABLE wines (
density FLOAT NOT NULL,
ph FLOAT NOT NULL,
alcoholLevel FLOAT NOT NULL,
quality INTEGER NOT NULL,
wineId INTEGER PRIMARY KEY,
chemicalId INTEGER NOT NULL,
sulfu... | e6c6a86f056437cb792fd36d037dc650007d10d3 | 642,562 |
def clean_sample_data(samples):
"""Clean unnecessary information from sample data, reducing size for message passing.
"""
out = []
for data in (x[0] for x in samples):
data["dirs"] = {"work": data["dirs"]["work"], "galaxy": data["dirs"]["galaxy"],
"fastq": data["dirs"].ge... | 75b8df2c42926cdcca111d4f4f68ea02a76e17f9 | 642,563 |
def noop(*args, **kwargs):
"""No-Op function for when callable is required"""
return None | f031dcfe98e5fe17faaed3d8e1a7820a84b8dfa7 | 642,564 |
def fixture_localhost(aiida_localhost):
"""Return a localhost `Computer`."""
localhost = aiida_localhost
localhost.set_default_mpiprocs_per_machine(1)
# By default, the codes are called with "mpirun -np N ..."
# Disable this, as multiple processes are not supported by e.g. cp2k.ssmp
localhost.se... | b70fd3bcac28588b53db1b914fa94d5fe6a3f515 | 642,565 |
import subprocess
def check_output(cmd_args):
"""Run the command and return the output. Raise an exception if the command returns
a non-zero return code. Similar to subprocess.check_output() which is only provided
in python 2.7.
"""
process = subprocess.Popen(cmd_args, stdout=subprocess.PIPE, stderr=s... | e6d45f94aedee97c2ac96ef4f22a5882a28d9a54 | 642,566 |
def is_source(f):
"""Returns true iff the input file name is considered a source file."""
return not f.endswith('_test.go') and (
f.endswith('.go') or f.endswith('.s')) | 8beea19b8f2918088d02970f571fb87a47bbf9a7 | 642,567 |
import argparse
def add_feature_options(parser: argparse.ArgumentParser) -> argparse.ArgumentParser:
"""Add arguments needed by feature extractor to parser
Args:
parser (argparse.ArgumentParser): Parser to extend to additional arguments
Returns:
argparse.ArgumentParser: Parser pa... | 03c132008c6eabf916350aac6dc193c10ebbdd13 | 642,568 |
def is_port_rx_stopped(api, port_name):
"""
Returns true if port is down
"""
req = api.metrics_request()
req.port.port_names = [port_name]
port_stats = api.get_metrics(req).port_metrics
if int(port_stats[0].frames_rx_rate) == 0:
return True
return False | 1c0206fe6c1f1751831652e32a9867dcd926c188 | 642,569 |
def primo(n):
"""Verifica se número é primo.
Considera que n sempre é maior que 1.
Retorna True se n for primo ou False caso contrário.
"""
if n % 2 == 0 and n != 2:
resultado = False
elif n % 3 == 0 and n != 3:
resultado = False
else:
resultado = True
return... | a10cedf721af61420d82ad532135533b0e2b389e | 642,570 |
def mod_juggle(arr, n, p):
"""Iterates through the list and returns a rotated list.
Args:
arr: The array to be rotated.
n: The size of arr.
p: The number of rotations to be performed.
Returns:
An array rotated by p values.
Raises:
None.
"""
n_arr = []
... | 74b713a513089901190d855a652e0d1ec3dbedf6 | 642,572 |
def eiler_func(p, q):
"""
Computes Euler's totient function for the modulus 'n' computed as `p`*`q`.
Args:
p (long): First modulus factor.
q (long): Second modulus factor.
Returns:
long: Euler's totient function value for the modulus n=`p`*`q`.
"""
phi = (p... | 75f8c75f5b2d58e5981e451b7f05497117ecffc2 | 642,573 |
def _CountPositives(solution):
"""Counts number of test images with non-empty ground-truth in `solution`.
Args:
solution: Dict mapping test image ID to list of ground-truth IDs.
Returns:
count: Number of test images with non-empty ground-truth.
"""
count = 0
for v in solution.values():
if v:
... | fe6efdc83b85eb3667067f22ffc8cba5bbb33d03 | 642,574 |
import os
def make_warp_kwargs(moving, reference, reg_sequence, invert_sequence):
"""
DEPRECATED. See ANTSWarpCommand.make_from_registration_sequence instead.
"""
raise DeprecationWarning
transform_infix = ''
command_sequence = ''
for (ants, invert) in zip(reg_sequence, invert_sequence):
... | 4c116c9bda9b9f0a07a5044447b0f5ff5905de46 | 642,576 |
def get_clipped_seq_length(bam_row):
"""
Clipped sequence length
"""
if bam_row.cigartuples[0] == 4 or bam_row.cigartuples[0] == 5:
return bam_row.cigartuples[0][1]
return 0 | 8edea052a180795e6655cf3e20af1620deca03af | 642,577 |
def firstMissingPositive(nums):
"""
:type nums: List[int]
:rtype: int
"""
# Method 1: Changing array values
# mark those elements who aren't in the range of [1, n]
n = len(nums)
for i in range(n):
if nums[i] <= 0 or nums[i] > n:
nums[i] = n + 1
# mark vi... | 6fcc953e510456df53ccc2219cccf9717fb52379 | 642,578 |
def evaluate_solution_score(inputs, solution, primitives, metric, posLabel, sol_dict):
"""
Scores each potential solution
Runs in a separate process
"""
print("Evaluating ", solution.id)
(score, optimal_params) = solution.score_solution(inputs=inputs, metric=metric, posLabel=posLabel,
... | 7bd6fb8aee5d16a7e1fa48953dead929a1a0a28d | 642,579 |
import os
import csv
def loadCSV(filename):
"""
Load a csv file into the format of a list of dictionary.
filename - the filename of the csv to be loaded.
return a list of dictonary.
"""
is_existed = os.path.exists(filename)
assert is_existed == True
data = []
with open(filena... | e893d01b48bc8c82c7a5e6fca4859522e23a33bf | 642,581 |
def get_bounds(points):
"""
Given a list of n-dimensional points, returns a list of length n where each
element is a tuple holding (min, max) for that dimension.
points -- list of n-dimensional points
"""
bounds = [[None, None] for dimension_num in range(len(points[0]))]
for point in poin... | 6edeeab0e5c0ea84276d4c4ecc83e0f603a62c9f | 642,582 |
from typing import Iterable
from typing import List
def flatten_nested(input_iter: Iterable) -> List:
"""Flatten a nested Iterable with arbitrary levels of nesting.
If the input is an iterator then this function will exhaust it.
Args:
input_iter: The input Iterable which may or may not be nested... | 2f452c8d0d5b0b79a7c757af9d3fa7d901beb701 | 642,583 |
def configure_amt_columns(dframe, config):
""" Configures AMT input and output columns. """
config.input = {}
config.output = {}
if config.inputColumns:
config.input = {c: 'input.'+c.replace('Input.', '') \
for c in dframe.columns.values if c in config.inputColumns}
... | b4fd489a4d757b025a75a614266edf9628ccaea5 | 642,584 |
def mass_spring(x, u, dt=0.05, m=1, c=2, k=1):
"""Mass-spring-damper system
x :: state variables (x1, x2) where
x1 = position (m)
x2 = velocity (m/s)
u :: input force (N)
dt :: timestep (s)
m :: mass (kg)
c :: damping coefficient (Ns/m)
k :: spring constant (N/m)
... | 97a303b80f0bc3eef9d27d474a7756ab539d089d | 642,585 |
import os
def _is_executable( path ):
"""
Tests a path to determine if it is a valid executable.
"""
if os.path.isfile( path ) == True:
return os.access( path, os.X_OK )
path += '.exe'
if os.path.isfile( path ) == True:
return os.access( path, os.X_OK )
return False | 856894cb47d1ca8210982b6b0fcc31bb37b73bb4 | 642,586 |
def transform_init_state_cause(cause, message):
"""
Transforms the init failure cause to a user-friendly message.
:param cause: cause of failure
:param message: failure message
:return: transformed message
"""
return {
'credentials': 'No or invalid credentials provided',
'to... | 53d443bc3952511328c4b2713d2fb7f885331aa1 | 642,587 |
import os
def emptyfile(request):
""" Provide a new, empty database file """
file_name = 'newdb.db'
_file = open(file_name, 'w')
_file.write('')
_file.close()
def fin():
""" remove the file after use """
os.remove(file_name)
request.addfinalizer(fin)
return file_name | 503d4cffba028ef0ff0ea1ebd03e728a1f9e46a1 | 642,588 |
import requests
from bs4 import BeautifulSoup
def get_song_urls(song_input):
"""
Gather all urls, titles for a search query
from youtube
"""
YOUTUBECLASS = 'spf-prefetch'
html = requests.get("https://www.youtube.com/results",
params={'search_query': song_input})
so... | fbf415c4891d614f5e12725d62af120209eef096 | 642,589 |
from typing import Tuple
from typing import List
def sekretion_uptake_fva(fva) -> Tuple[List, List]:
"""This computes the uptake and sekreation reaction using FVA, this is UNIQUE!
Args:
fva (DataFrame): Fva results
Returns:
list: List of uptake reactions
list: List of sekretion r... | a5cd22749b9636bcdf7b83a4289d5fe9091ed46d | 642,590 |
import torch
def get_optimizer(opt_config, model):
"""Creates an optimizer based on the opt_config and model parameters.
Args:
- opt_config: (dict) optimizer config. It should have the following fields:
* name: (str) name of the optimizer. It should be one of SGD, Adam, or LBFGS
* params: (dict) o... | 22f75b12dee5c79a5d278611141c23e273a8d252 | 642,591 |
def get_credentials_from_profile(cloud, request):
"""
Returns the stored database credentials for a given cloud for the currently
logged in user. If the user is not logged in or no credentials are found,
returns an empty dict.
.. note:: If no credentials are found but the server has environment
... | a0099096dd7dbad5c3595a5d049398b73cc692bc | 642,592 |
def is_triangular(k):
"""
k, a positive integer
returns True if k is triangular and False if not
"""
num = 1
triangularNo = 0
while triangularNo < k:
triangularNo += num
num += 1
if triangularNo == k:
return True
return False | d028f944338ad6781f8e45bc2a22d7c3d32d09d2 | 642,593 |
def pmi(p_union, p1, p2):
"""
计算pmi
:param p_union:
:param p1:
:param p2:
:return:
"""
return p_union - p1 * p2 | 70708e38edb66214e95fd500047dcde7951785da | 642,594 |
def height(grid):
"""Gets the height of a rectangular grid (stored row-major)."""
return len(grid) | 6dc5778cc695d71155dcca28aa29741c0ececee7 | 642,595 |
import os
def set_rendition_name(rendition_name):
"""
Function to extract source name from rendition path
"""
try:
return os.path.dirname(rendition_name).replace('/vimeo', '').split('/')[-1]
except:
return '' | 5e2e1fefd120762621d94826c7deb1a1d0a8e3ae | 642,596 |
def extras_msg(extras):
"""
Create an error message for extra items or properties.
"""
if len(extras) == 1:
verb = "was"
else:
verb = "were"
return ", ".join(repr(extra) for extra in sorted(extras)), verb | 4c62adf3c7bd1dbe622e462e868d5f06f7e2d576 | 642,597 |
import numpy
def QRFactors(A):
"""
usage: Q, R = QRFactors(A)
Function to compute the QR factorization of a (possibly rank-deficient)
'thin' matrix A (m x n, with m >=n) using Householder reflection matrices.
Input: A - thin matrix
Outputs: Q - orthogonal matrix
R - "upper ... | 3c969c03907d9fdbea8899d348fb2fd896ea6f19 | 642,598 |
import os
import re
def write_index(dst_path, titles, tags):
"""
Write index files under `dst_path`
"""
titles = dict(titles)
index_rst = os.path.join(dst_path, 'index.txt')
# Write doctree
toctree_items = []
index_text = []
# Fill in missing tags
for fn in titles.keys():
... | 623308b095ad06650103755c5b7cb984b2232e18 | 642,599 |
import sys
def get_args():
"""Gets arguments from the command line
"""
return sys.argv | 91a7fb9a2c1fcc7f156877f51acb960b0fbb352b | 642,600 |
import argparse
def get_args(args) -> argparse.Namespace:
"""Parses the command line arguments"""
parser = argparse.ArgumentParser(description=__doc__,)
parser.add_argument(
"files",
type=str,
nargs="+",
default="",
help="A list of paths to markdown files.",
)
... | 7f7c941fcf19bcfef6158cbb0c283df4d7c35041 | 642,601 |
import decimal
def ceiling(x):
"""Return the smallest integral value >= x."""
return x.to_integral(rounding=decimal.ROUND_CEILING) | cf22c44d4d6616236fb9bd99284627da9dfb13d7 | 642,602 |
def bioentity_type(str_type):
"""
In a nutshell, collapse all RNA related types into RNA
"""
if "RNA" in str_type or "ribozyme" in str_type or "transcript" in str_type:
return "RNA_cluster"
return str_type | 7d5ea671570a390e6e7bca1f8117b1da96526c2b | 642,603 |
def create_gist(github, description, files):
"""Creates a gist with the given description and files.
github - an
description - str
files - A dict of files in the form of {filename:{'content': content},...}
"""
return github.create_gist(description, files, public=False) | 932a10763f2dba70549558f449227715ae287edf | 642,604 |
def generalized_fibonacci_sequence(n, p):
"""Compute the generalized Fibonacci sequence.
Args:
n: An `int`. The number of terms to compute. Must be >= 2.
p: An `int`. The number of the generalized sequence. Must be >= 1. If `p` is
1, the sequence is the standard Fibonacci sequence.
Returns:
A ... | 2b7b2c5e2f7102166deb4f81b37e950fa900a17e | 642,605 |
import os
def make_eval_outdir(outdir, eval_config):
"""Create evaluation subdir unique for `eval_config`"""
subdir = eval_config.get_eval_subdir()
result = os.path.join(outdir, 'evals', subdir)
os.makedirs(result, exist_ok = True)
return result | db1d2e0a3ed218b250cbfcf72637b7be7d6e120d | 642,606 |
import sys
def Range37():
"""Sample of a function as a source operator."""
if sys.version_info.major == 2:
# zip behaviour differs on Python 2.7
return iter(zip(range(37)))
return zip(range(37)) | 7517a1b895c1705d1bc4982783e7f5a3dae52710 | 642,607 |
def apply_selection_cuts(input_catalog, snap_tolerance=1e-3):
"""
Select only galaxies with petrotheta > 3 and not within 1e-3 of bad measurement snap value
Args:
catalog (astropy.Table): Galaxy catalog including NSA information
snap_tolerance (float): Minimum deviation from bad measurement... | 7f3c0b6a6a6afa60508e4db7115eca227cead90d | 642,608 |
def list_to_dict(list_):
"""Transform a list to a dictionary with its indices as keys."""
dict_ = {
str(i): element
for i, element in enumerate(list_)
}
return dict_ | 8953ede9156ab93cca6ad5686be8b5b80bf0726f | 642,609 |
def sanitise_text(text: str):
"""Sanitise input text.
Args:
text: input text.
Returns:
Sanitised text
"""
return ''.join(e for e in text if e.isalnum() or e.isspace()) | 5b1c398893214d0680cc2da708b330183cccaf27 | 642,610 |
def Main():
"""
:return:
"""
a = range(100, 120)
# b = a[4] # this will fail, since the range list is only 4 elements long
# ( 0, 1, 2, 3 )
b = a[3]
# q = add_items(4, 4)
return b | 75b17e07e0b7e1f87b363d29050252b12876b0ec | 642,612 |
import requests
def _get(scheme, hostname, port, headers, **kwargs):
"""Makes a GET request for specified resource"""
url = "{0}://{1}:{2}".format(scheme, hostname, port)
if headers:
return requests.get(url, headers=headers, **kwargs)
else:
return requests.get(url, **kwargs) | a39daeef5fd76c00d9ea70a6056e2c49f9acd972 | 642,613 |
import torch
def orthonormal_basis(a, b, c, norm=True):
""" Find an orthonormal basis as a matrix of [a,b,c].
Useful for constructing rotation matrices between planes according to the first answer here:
https://math.stackexchange.com/questions/1876615/rotation-matrix-from-plane-a-to-b
:param a: (batc... | 7d2d509dad234cfff66f7584e4c721b70c6d4fe9 | 642,614 |
def getAllSubclasses(cls):
"""
Searches all subclasses of given class.
:param cls: The base class.
:type cls: class
"""
stack = [cls]
sub=[]
while len(stack):
base = stack.pop()
for child in base.__subclasses__():
if child not in sub:
... | 0fecd0f5ffedf4a113b6ba921606b78fce6e8bb4 | 642,615 |
def leave_required_keys(filter_dict: dict, required_keys: list) -> dict:
"""
Получить отфильтрованный по необходимым ключам словарь
Args:
filter_dict (dict): Словарь, который необходимо отфильтровать
required_keys (list): Список требуемых ключей
Returns:
dict: Отфильтрованный сл... | badb9a221fd5650234e661cf2715f57474f1a809 | 642,616 |
def bar():
"""
one more placeholder function for future usage. this is conflict line.
"""
return set() | e6592beca7ffc6865528a481b6535ad8b42ecdc8 | 642,617 |
def kid_kernel(x, y):
"""KID kernel introduced in https://arxiv.org/pdf/1801.01401.pdf.
k(x, y) = (1/ndim * x @ y + 1)^3
Args:
x: `numpy.ndarray` or `torch.Tensor` with shape [num_samples, ndim].
y: `numpy.ndarray` or `torch.Tensor` with shape [num_samples, ndim].
Returns:
`nu... | 7579e99f81d31f51e9c974534d915068a31c7116 | 642,618 |
def str2bool(val):
"""
convert string to bool (used to pass arguments with argparse)
"""
dict = {'True': True, 'False': False, 'true': True, 'false': False, '1': True, '0': False}
return dict[val] | eaeb7d553fc264cdc495298f97cb75554f1a3055 | 642,620 |
def convert_fixed_point_binary_16bit(uint):
"""
convert fixed point binary 16 bit to float
"""
return uint/float(2**16) | adbc2cda2dd0588c6817223e8640aa9420fa35b8 | 642,622 |
import re
def format_subtitle(subs):
"""
Format subtitle
"""
for sub in subs:
text = sub.text
if re.search(r'[\u4E00-\u9FFF]', text):
text = text.replace('(', '(')
text = text.replace(')', ')')
text = text.replace('!', '!')
text = text.re... | eb8d026aa0222a98e6ff71ad23e3c96f62b3373c | 642,623 |
import datetime
import datetime
def get_dates(start_date,end_date):
"""
Creates a list of dates in string format 'Y-M-D'
Yields
------
list
Note
------
To change collection time frame, mend start_date and end_date
"""
# the command argument is a string
# convert the strin... | 03f7fab9c603abe90946de927a69a39b291adfff | 642,625 |
def format_platform(platform):
"""Return formatted uppercase or capitalized platform value"""
if platform == "linux" or platform == "windows":
return platform.capitalize()
else:
return platform.upper() | be775ae1ec4a7647c72cc53f10dab2c317a47e97 | 642,626 |
def generator(func):
"""Generator methods on a Blueprint don't get flagged as fields.
Subsequently, they aren't subject to field treatment, and remain
callable on a mastered Blueprint instance.
"""
func.is_generator = True
return func | aaffe0946bb9a6ee67b64bf2f224021d3aa0abef | 642,627 |
def format_user_info(lst):
"""This will format a user object into a displayable format"""
return [{
'id': x.pk,
'text': u'{}: {}'.format(x.username, x.get_full_name())
} for x in lst] | c44abcf9e44ee8ea71025422971df69dba72dc8b | 642,628 |
def is_route_login_required(fn):
"""
Determine if a function is decorated to require a logged-in session.
:param fn: The function to check.
:return: True if this function requires a logged-in session, False otherwise.
"""
return hasattr(fn, "route_login_required") and fn.route_login_required | e64e145ff5299063d32d9adaa9eaea6c5232163d | 642,629 |
def to_titles(responses, value='title'):
"""api.utils.to_titles
将List of Response转换为List of Title
Args:
responses: List or Tuple Of Response(py.Dict)
value: Str, 默认'title'
Returns:
List of Title(py.Str)
"""
assert isinstance(responses, (list, tuple))
titles = []
for item in ... | 6adc058c00e884d4f7b8e616f47d5b9649039395 | 642,630 |
import json
def export_samples(samples_df, col_meta, out_file, pretty):
"""Export samples to out_file"""
samples = []
for index, row in samples_df.iterrows():
sample, result, files = {}, {}, {}
for fld in samples_df.columns:
meta = col_meta.get(fld)
section = meta[... | b186af95732682871e551b3675a4bf8a750b45f1 | 642,631 |
import json
def get_changes(changes_file):
"""Obtain changes from a changes file."""
with open(changes_file, "r") as ch_file:
return json.load(ch_file) | f0ff398ff4ca671764fa5bc5fd615fc718e8784c | 642,632 |
import re
def normalise(name):
"""
>>> normalise('Foo Bar Ltd.')
u'foo bar ltd'
>>> normalise('BAZ JIM LTD')
u'baz jim ltd'
>>> normalise('BAZ-JIM (South) LTD.')
u'baz jim south ltd'
"""
return re.sub('[^a-z]+', ' ', name.lower()).strip() | 6f581ea1b7a8827fa6af2488267ede238578050e | 642,634 |
def clean_tokens(tokens, callback=lambda token: token):
"""
>>> clean_tokens(['Hello', '3', 'P.M.'])
['hello', '3', 'p.m.']
>>> clean_tokens(['Hello', '3', 'P.M.'], lambda token: token.replace('.', ''))
['hello', '3', 'pm']
"""
return [callback(token.lower()) if isinstance(token, str)
... | bde861dafe5b365c77301139a02840124e183568 | 642,635 |
import torch
def get_error_instance_ids_by_class(model, batch_ids, batched_evaluation_data, batched_evaluation_target,
device="cpu"):
"""
Return the instance ids corresponding to errors of the model by class.
Args:
model: The model being evaluated.
batc... | 6e5665c1b70c4a8a86e6dd46101f30bed6cc7ec5 | 642,636 |
import csv
def get_reactions(input_file):
"""
Get all the reactions from the input file
Reads the input file and gets the reactions that the user might
want to add to the universal model.
Input file must be in the same folder as the script.
The file name must be a string including .csv ext... | 521850554b1eeef007e7b508a6dfb9c6261423a7 | 642,637 |
def have_shared_allelic_variation( ref_string, qry_string ):
"""
Because the VCF files have ellele columns with comma-separated values, this function
takes two of them and looks for any single shared allele among them, returning True
if one is found.
"""
refs = ref_string.split(",")
qrys = q... | e75d0be9ba1c2feb32159ce503bcee6fabbc8ba6 | 642,638 |
import os
import json
import logging
def setup_config(config_file_path='config.json'):
"""
Setup various parameters required for face-recognition
"""
if os.path.exists(config_file_path):
with open(config_file_path, 'r') as f:
data = json.load(f)
logging.info("Configur... | a1bfa8c8f2c7c5dc4b48860f85d85d566779a119 | 642,639 |
import requests
def get_running_instances(compute_url, project_id, token):
""" Get the list of running instances in the provider """
url = "%s/servers" % compute_url
headers = {"X-Auth-Token": "%s" % token, "Content-type": "application/json"}
data = 0 # in case status_code != 200
curl = request... | 15e7afd605acbc3bf9d3e451a12451803eea3be7 | 642,640 |
import os
def get_subdirs(directory):
"""
Returns: a list of subdirectories of the given directory
"""
return [os.path.join(directory, name)
for name in os.listdir(directory)
if os.path.isdir(os.path.join(directory, name))] | 006bc451ae9f3b4ea06741a1146b3c1ab043efdc | 642,641 |
def normalize_formula(formula):
"""
Insert ones after elements where the subscript is omitted. Streamlines the process of parsing the formula. Returns a copy of :formula: with ones inserted in it.
"""
previous_was_number = None
previous_index = 0
parts = []
for idx, item in enumerate(formula... | 676796d6efb8a5172bb64029d431fc05da024772 | 642,642 |
def construct_filter_url(zipcode, page_num=1):
"""
Return a landing url that filters by zipcode. page_num is used to determine the page of the search
results. Redfin search results are up to 18 pages long.
In the current version, the filter is set to 'sold-3yr' and
could be expanded to include 'sol... | acb9679da686d49c26ae183945b5f538b3ddcf28 | 642,643 |
import sys
import re
def safe_input(prompt, pattern):
"""
Function that handles user input
Parameters
prompt (str):
The message that is prompt to user.
pattern (re.Pattern):
the regex pattern to be used for matching.
Returns
userinput (str):
... | a43b1cd6303425de1f8d91ff445cb2a47b13e2bc | 642,645 |
def force_unicode(s):
"""
return string of a bytes
! borrow from onnx
Args:
s: string or bytes
Returns:
string
"""
try:
return s.decode('utf-8')
except AttributeError:
return s | e857312e980a214279be2f07e4e55e085aa5fac4 | 642,646 |
from typing import List
from typing import Dict
def make_task_name_to_index_map(
lifelong_learning_task_names: List[str]) -> Dict[str, int]:
"""Creates a map going from the task name to the task index.
The tasks might be repeated, so task indexes aren't just a range.
"""
task_name_to_task_ind... | bea6e4208ea541880cf61616ecf88fe3c7fffdbd | 642,648 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.