content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def same_datatypes(lst):
"""
Überprüft für eine Liste, ob sie nur Daten vom selben Typ enthält. Dabei spielen Keys, Länge der Objekte etc. eine Rolle
:param lst: Liste, die überprüft werden soll
:type lst: list
:return: Boolean, je nach Ausgang der Überprüfung
"""
datatype = type(lst[0]).__... | 9c49376ec34ed0970171597f77de4c4c224350b4 | 12,600 |
def _show_stat_wrapper_Progress(count, last_count, start_time, max_count, speed_calc_cycles,
width, q, last_speed, prepend, show_stat_function, add_args,
i, lock):
"""
calculate
"""
count_value, max_count_value, speed, tet, ttg, = Pro... | 3c98f44acc8de94573ba37a7785df18fc8e72966 | 12,601 |
def _to_base58_string(prefixed_key: bytes):
"""
Convert prefixed_key bytes into Es/EC strings with a checksum
:param prefixed_key: the EC private key or EC address prefixed with the appropriate bytes
:return: a EC private key string or EC address
"""
prefix = prefixed_key[:PREFIX_LENGTH]
as... | 326580e714d6489a193347498c68ef9d90f6f651 | 12,602 |
def round_int(n, d):
"""Round a number (float/int) to the closest multiple of a divisor (int)."""
return round(n / float(d)) * d | 372c0f8845994aaa03f99ebb2f65243e6490b341 | 12,603 |
def merge_array_list(arg):
"""
Merge multiple arrays into a single array
:param arg: lists
:type arg: list
:return: The final array
:rtype: list
"""
# Check if arg is a list
if type(arg) != list:
raise errors.AnsibleFilterError('Invalid value type, should... | 649412488655542f27a1e7d377252c060107b57e | 12,604 |
def load_callbacks(boot, bootstrap, jacknife,
out, keras_verbose, patience):
"""
Specifies Keras callbacks, including checkpoints, early stopping,
and reducing learning rate.
Parameters
----------
boot
bootstrap
jacknife
out
keras_verbose
patience
batc... | 0ca09ccaca4424c1a546caade3d809b7f69cbb5e | 12,605 |
def build_sentence_model(cls, vocab_size, seq_length, tokens, transitions,
num_classes, training_mode, ground_truth_transitions_visible, vs,
initial_embeddings=None, project_embeddings=False, ss_mask_gen=None, ss_prob=0.0):
"""
Construct a classifier which makes... | 085d6a0538bfa06a34c543c27efd651c4c46168a | 12,606 |
def read_xls_as_dict(filename, header="top"):
"""
Read a xls file as dictionary.
@param filename File name (*.xls or *.xlsx)
@param header Header position. Options: "top", "left"
@return Dictionary with header as key
"""
table = read_xls(filename)
if (header == "top... | 9ed410e42a11ee898466bb2f36b6d02e051b21ec | 12,607 |
def check_hostgroup(zapi, region_name, cluster_id):
"""check hostgroup from region name if exists
:region_name: region name of hostgroup
:returns: true or false
"""
return zapi.hostgroup.exists(name="Region [%s %s]" % (region_name, cluster_id)) | b237b544ac59331ce94dd1ac471187a60d527a1b | 12,608 |
import tempfile
def matlab_to_tt(ttemps, eng, is_orth=True, backend="numpy", mode="l"):
"""Load matlab.object representing TTeMPS into Python as TT"""
_, f = tempfile.mkstemp(suffix=".mat")
eng.TTeMPS_to_Py(f, ttemps, nargout=0)
tt = load_matlab_tt(f, is_orth=is_orth, mode=mode, backend=backend)
... | e21087e2587368a55ece7a50f576573c5284373a | 12,609 |
def encode_mecab(tagger, string):
"""
string을 mecab을 이용해서 형태소 분석
:param tagger: 형태소 분석기 객체
:param string: input text
:return tokens: 형태소 분석 결과
:return indexs: 띄어쓰기 위치
"""
string = string.strip()
if len(string) == 0:
return [], []
words = string.split()
nodes = tagger.... | 847278728ebe7790d8aef2a125a420d5779adc6b | 12,610 |
def nutrient_limited_growth(X,idx_A,idx_B,growth_rate,half_saturation):
""" non-linear response with respect to *destination/predator* compartment
Similar to holling_type_II and is a reparameterization of holling II.
The response with respect to the origin compartment 'B' is approximately
linear for s... | 05e66a0e426a404a5356f04f8568ab23548b6dbe | 12,611 |
def aes128_decrypt(AES_KEY, _data):
"""
AES 128 位解密
:param requestData:
:return:
"""
# 秘钥实例
newAes = getAesByKey(AES_KEY)
# 解密
data = newAes.decrypt(_data)
rawDataLength = len(data)
# 剔除掉数据后面的补齐位
paddingNum = ord(data[rawDataLength - 1])
if paddingNum > 0 and paddin... | 520c03a509f63807a62ccb0385e99bc9b674fd67 | 12,612 |
def human_readable_size(size, decimals=1):
"""Transform size in bytes into human readable text."""
for unit in ["B", "KB", "MB", "GB", "TB"]:
if size < 1000:
break
size /= 1000
return f"{size:.{decimals}f} {unit}" | 5fb0dc79162d0bc0a945061aa0889735b24fff7b | 12,613 |
def generichash_blake2b_final(statebuf, digest_size):
"""Finalize the blake2b hash state and return the digest.
:param statebuf:
:type statebuf: bytes
:param digest_size:
:type digest_size: int
:return: the blake2 digest of the passed-in data stream
:rtype: bytes
"""
_digest = ffi.... | a81da8346bafb2f7d8fd40b0d9ff204689d002f8 | 12,614 |
def walker_input_formatter(t, obs):
"""
This function formats the data to give as input to the controller
:param t:
:param obs:
:return: None
"""
return obs | 651038cd4dc0e8c8ccb89a10a5b20f6031e17ba8 | 12,615 |
def build_url_base(url):
"""Normalize and build the final url
:param url: The given url
:type url: str
:return: The final url
:rtype: str
"""
normalize = normalize_url(url=url)
final_url = "{url}/api".format(url=normalize)
return final_url | a500a6d96ab637182abab966817209324ddc670a | 12,616 |
from typing import Tuple
from typing import List
def build_decoder(
latent_dim: int,
input_shape: Tuple,
encoder_shape: Tuple,
filters: List[int],
kernels: List[Tuple[int, int]],
strides: List[int]
) -> Model:
"""Return decoder model.
Parameters
----------
latent_dim:int,
... | efdac0fa9df81249e531b2568cd8f91816c209a6 | 12,617 |
def execute_with_python_values(executable, arguments=(), backend=None):
"""Execute on one replica with Python values as arguments and output."""
backend = backend or get_local_backend()
def put(arg):
return Buffer.from_pyval(
arg, device=executable.DeviceOrdinals()[0], backend=backend)
arguments ... | 26c9352feb2e5c7e6fb46702105245f582218e91 | 12,618 |
import subprocess
def run_cmd(cmd, cwd=None):
"""
Runs the given command and return the output decoded as UTF-8.
"""
return subprocess.check_output(cmd,
cwd=cwd, encoding="utf-8", errors="ignore") | 5d2f5b85878291efaa16dcb4bb8a8c72b3d22230 | 12,619 |
def _get_label_members(X, labels, cluster):
"""
Helper function to get samples of a specified cluster.
Args:
X (np.ndarray): ndarray with dimensions [n_samples, n_features]
data to check validity of clustering
labels (np.array): clustering assignments for data X
cluster (... | 18c213f88816108f93ddd38cdd2c934f431ea35a | 12,620 |
from typing import Tuple
def get_spectrum_by_close_values(
mz: list,
it: list,
left_border: float,
right_border: float,
*,
eps: float = 0.0
) -> Tuple[list, list, int, int]:
"""int
Function to get segment of spectrum by left and right
border
:param mz: m/z array
:param it: ... | 0ec34b044b9105fe1c232baa9b51760cbb96b9d9 | 12,621 |
import subprocess
import os
def speak():
"""API call to have BiBli speak a phrase."""
subprocess.call("amixer sset Master 100%", shell=True)
data = request.get_json()
lang = data["lang"] if "lang" in data and len(data["lang"]) else "en"
#espeak.set_parameter(espeak.Parameter.Rate, 165)
#espeak... | 81e75e88669ca90ff8f9dc6df8a7a8a08dcaf368 | 12,622 |
def refresh_wrapper(trynum, maxtries, *args, **kwargs):
"""A @retry argmod_func to refresh a Wrapper, which must be the first arg.
When using @retry to decorate a method which modifies a Wrapper, a common
cause of retry is etag mismatch. In this case, the retry should refresh
the wrapper before attemp... | 089b859964e89d54def0058abc9cc7536f5d8877 | 12,623 |
def compute_frames_per_animation(
attacks_per_second: float,
base_animation_length: int,
speed_coefficient: float = 1.0,
engine_tick_rate: int = 60,
is_channeling: bool = False) -> int:
"""Calculates frames per animation needed to resolve a certain ability at attacks_per_seco... | 44427cf28152de21de42f0220e75f87717235275 | 12,624 |
def pad_rect(rect, move):
"""Returns padded rectangles given specified padding"""
if rect['dx'] > 2:
rect['x'] += move[0]
rect['dx'] -= 1*move[0]
if rect['dy'] > 2:
rect['y'] += move[1]
rect['dy'] -= 1*move[1]
return rect | 48bdbdc9d4736e372afc983ab5966fc80a221d4d | 12,625 |
import asyncio
async def yes_no(ctx: commands.Context,
message: str="Are you sure? Type **yes** within 10 seconds to confirm. o.o"):
"""Yes no helper. Ask a confirmation message with a timeout of 10 seconds.
ctx - The context in which the question is being asked.
message - Optional messs... | 2b8ab0bfc51d4be68a42507bad6dbb945465d2e4 | 12,626 |
def __validation(size: int, it1: int, it2: int, it3: int, it4: int) -> bool:
""" Проверка на корректность тура
size: размер маршрута
it1, it2, it3, it4: индексы городов: t1, t2i, t2i+1, t2i+2
return: корректен или нет
"""
return between(size, it1, it3, it4) and between(size, it4, it2, it1) | 5fcb29f45c456115e8b87f0313e05f327c702849 | 12,627 |
def get_type_associations(base_type, generic_base_type): # type: (t.Type[TType], t.Type[TValue]) -> t.List[t.Tuple[t.Type[TValue], t.Type[TType]]]
"""Create and return a list of tuples associating generic_base_type derived types with a corresponding base_type derived type."""
return [item for item in [(get_gen... | fe18bf72a96d6dfa8fad2c625732e781d54cae4d | 12,628 |
import rpy2.robjects as robj
from rpy2.robjects.packages import importr
import anndata2ri
def identify_empty_droplets(data, min_cells=3, **kw):
"""Detect empty droplets using DropletUtils
"""
importr("DropletUtils")
adata = data.copy()
col_sum = adata.X.sum(0)
if hasattr(col_sum, 'A'):
... | 9c2d532d75afb6044836249eb525e86c60511c9b | 12,629 |
def catalog_category_RSS(category_id):
"""
Return an RSS feed containing all items in the specified category_id
"""
items = session.query(Item).filter_by(
category_id=category_id).all()
doc = jaxml.XML_document()
doc.category(str(category_id))
for item in items:
doc._push()
... | 13554cf1eba3a83c0fb23a6f848751721579dfea | 12,630 |
def get_caller_name(N=0, allow_genexpr=True):
"""
get the name of the function that called you
Args:
N (int): (defaults to 0) number of levels up in the stack
allow_genexpr (bool): (default = True)
Returns:
str: a function name
CommandLine:
python -m utool.util_dbg... | 6c6ce7690d1bc4bd51037056e27f5dbd73085e29 | 12,631 |
import os
import tempfile
def make_build_dir(prefix=""):
"""Creates a temporary folder with given prefix to be used as a build dir.
Use this function instead of tempfile.mkdtemp to ensure any generated files
will survive on the host after the FINN Docker container exits."""
try:
inst_prefix = ... | c298ed1446412b048f632daf8797670fc3b9095c | 12,632 |
from typing import Union
import json
def unblock_node_port_random(genesis_file: str,
transactions: Union[str,int] = None,
pause_before_synced_check: Union[str,int] = None, best_effort: bool = True,
did: str = DEFAULT_CHAOS_DID, seed: str = DEFAULT_CHAOS_SEED,
wallet_name: str = DEFAULT_CHAOS_WALLET_NA... | bc15266faa6b6c78cc37fca18bfa43ac7dd752c3 | 12,633 |
from typing import Any
def create_user(
*,
db: Session = Depends(deps.get_db),
user_in: schema_in.UserCreateIn,
) -> Any:
"""
Create new user.
"""
new_user = User(**{k: v for k, v in user_in.dict().items() if k != 'password'})
new_user.hashed_password = get_password_hash(user_in.passwo... | cd8c3036026639d3e29e6dc030335f328d11c144 | 12,634 |
import math
def number_format(interp, num_args, number, decimals=0, dec_point='.',
thousands_sep=','):
"""Format a number with grouped thousands."""
if num_args == 3:
return interp.space.w_False
ino = int(number)
dec = abs(number - ino)
rest = ""
if decimals == 0 and ... | 9d5ab0b9ed5dd6054ce4f356e6811c1b155e2062 | 12,635 |
from typing import Optional
def _serialization_expr(value_expr: str, a_type: mapry.Type,
py: mapry.Py) -> Optional[str]:
"""
Generate the expression of the serialization of the given value.
If no serialization expression can be generated (e.g., in case of nested
structures suc... | 5920a4c10dabe2ff061a1f141cd9c9f10faebafa | 12,636 |
def get_init_hash():
""" 获得一个初始、空哈希值 """
return imagehash.ImageHash(np.zeros([8, 8]).astype(bool)) | cd4665e6b5cdf232883093dab660aafcc2109a44 | 12,637 |
def get_vertex_between_points(point1, point2, at_distance):
"""Returns vertex between point1 and point2 at a distance from point1.
Args:
point1: First vertex having tuple (x,y) co-ordinates.
point2: Second vertex having tuple (x,y) co-ordinates.
at_distance: A distance at which to locate... | acb5cd76ef7dd3a16592c5fbaf74d6d777ab338c | 12,638 |
def disable_cache(response: Response) -> Response:
"""Prevents cached responses"""
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate, public, max-age=0"
response.headers["Expires"] = 0
response.headers["Pragma"] = "no-cache"
return response | 6f63c7e93a7c354c85171652dca51162e15b7137 | 12,639 |
def get_dir(src_point, rot_rad):
"""Rotate the point by `rot_rad` degree."""
sn, cs = np.sin(rot_rad), np.cos(rot_rad)
src_result = [0, 0]
src_result[0] = src_point[0] * cs - src_point[1] * sn
src_result[1] = src_point[0] * sn + src_point[1] * cs
return src_result | 40b36671c50a6b6b8905eca9915901cd613c2aaa | 12,640 |
def sparse_gauss_seidel(A,b,maxiters=100,tol=1e-8):
"""Returns the solution to the system Ax = b using the Gauss-Seidel method.
Inputs:
A (array) - 2D scipy.sparse matrix
b (array) - 1D NumPy array
maxiters (int, optional) - maximum iterations for algorithm to perform.
tol (floa... | 139fefa8e45d14f32ea9bb4dd25df03762737090 | 12,641 |
def delete_user(user_id):
"""Delete user from Users database and their permissions
from SurveyPermissions and ReportPermissions.
:Route: /api/user/<int:user_id>
:Methods: DELETE
:Roles: s
:param user_id: user id
:return dict: {"delete": user_id}
"""
user = database.get_user(user_id... | c8f86dc20db67a5e3511e082f6308903b1acdaa2 | 12,642 |
def selectTopFive(sortedList):
"""
从sortedList中选出前五,返回对应的名字与commit数量列成的列表
:param sortedList:按值从大到小进行排序的authorDict
:return:size -- [commit数量]
labels -- [名字]
"""
size = []
labels = []
for i in range(5):
labels.append(sortedList[i][0])
size.append(sortedList[i][1... | 747ad379ed73aeb6ccb48487b48dc6150350204e | 12,643 |
def get_license(file):
"""Returns the license from the input file.
"""
# Collect the license
lic = ''
for line in file:
if line.startswith('#include') or line.startswith('#ifndef'):
break
else:
lic += line
return lic | 126fff2dd0464ef1987f3ab672f6b36b8fa962f7 | 12,644 |
def quote_query_string(chars):
"""
Multibyte charactor string is quoted by double quote.
Because english analyzer of Elasticsearch decomposes
multibyte character strings with OR expression.
e.g. 神保町 -> 神 OR 保 OR 町
"神保町"-> 神保町
"""
if not isinstance(chars, unicode):
chars = c... | 8d1888df17a617d42e6a0d1b909e08e4f84fa4c9 | 12,645 |
def copy_params(params: ParamsDict) -> ParamsDict:
"""copy a parameter dictionary
Args:
params: the parameter dictionary to copy
Returns:
the copied parameter dictionary
Note:
this copy function works recursively on all subdictionaries of the params
dictionary but does... | 8248b31698f6b51103dc34bad7b13373591b10cd | 12,646 |
def watch_list(request):
"""
Get watchlist or create a watchlist, or delete from watchlist
:param request:
:return:
"""
if request.method == 'GET':
watchlist = WatchList.objects.filter(user=request.user)
serializer = WatchListSerializer(watchlist, many=True)
return Respon... | c92d39da05546fea9330ffe44cea5dd0c30f6427 | 12,647 |
async def user_has_pl(api, room_id, mxid, pl=100):
"""
Determine if a user is admin in a given room.
"""
pls = await api.get_power_levels(room_id)
users = pls["users"]
user_pl = users.get(mxid, 0)
return user_pl == pl | 5678af17469202e0b0a0232e066e7ed5c8212ee6 | 12,648 |
import cgi
from typing import Optional
def get_cgi_parameter_bool_or_default(form: cgi.FieldStorage,
key: str,
default: bool = None) -> Optional[bool]:
"""
Extracts a boolean parameter from a CGI form (``"1"`` = ``True``,
other st... | 905dfa96628414e3b076fd3345113588f3f6ef08 | 12,649 |
def loss_function_1(y_true, y_pred):
""" Probabilistic output loss """
a = tf.clip_by_value(y_pred, 1e-20, 1)
b = tf.clip_by_value(tf.subtract(1.0, y_pred), 1e-20, 1)
cross_entropy = - tf.multiply(y_true, tf.log(a)) - tf.multiply(tf.subtract(1.0, y_true), tf.log(b))
cross_entropy = tf.reduce_mean(cr... | 8426ef13bd56fa3ff11226556d37bf738333a165 | 12,650 |
def sanitize_for_json(tag):
"""eugh the tags text is in comment strings"""
return tag.text.replace('<!--', '').replace('-->', '') | 211c07864af825ad29dfc806844927db977e6ce0 | 12,651 |
def load_data_and_labels(dataset_name):
"""
Loads MR polarity data from files, splits the data into words and generates labels.
Returns split sentences and labels.
"""
for i in [1]:
# Load data from files
positive_examples = list(open('data/'+str(dataset_name)+'/'+str(dataset_name)+'... | d753494f3a614850c07f40230c3373eab13b0c6b | 12,652 |
def tileswrap(ihtORsize, numtilings, floats, wrapwidths, ints=[], readonly=False):
"""Returns num-tilings tile indices corresponding to the floats and ints, wrapping some floats"""
qfloats = [floor(f * numtilings) for f in floats]
Tiles = []
for tiling in range(numtilings):
tilingX2 = tiling * 2... | e9a9dc439307fc114c9abc939f642ea411acd26e | 12,653 |
def coerce(data, egdata):
"""Coerce a python object to another type using the AE coercers"""
pdata = pack(data)
pegdata = pack(egdata)
pdata = pdata.AECoerceDesc(pegdata.type)
return unpack(pdata) | dc7499530b77a25c8b51537e2e21115d3ce3ccee | 12,654 |
import os
def distorted_inputs(data_dir, batch_size, num_train_files, train_num_examples, boardsize, num_channels):
"""Construct distorted input for training using the Reader ops.
Args:
data_dir: Path to the data directory.
batch_size: Number of images per batch.
Returns:
images: Image... | 5a46724c30c30ce5dd846f8fbf522605c27396cc | 12,655 |
from typing import Union
from typing import List
def _write_mkaero1(model: Union[BDF, OP2Geom], name: str,
mkaero1s: List[MKAERO1], ncards: int,
op2_file, op2_ascii, endian: bytes, nastran_format: str='nx') -> int:
"""writes the MKAERO1
data = (1.3, -1, -1, -1, -1, -1, -... | ad45ec25989714685a6a2b2e61d6833a9ab56a6d | 12,656 |
def _mesh_obj_large():
"""build a large, random mesh model/dataset"""
n_tri, n_pts = 400, 1000
node = np.random.randn(n_pts, 2)
element = np.array([np.random.permutation(n_pts)[:3] for _ in range(n_tri)])
perm = np.random.randn(n_tri)
np.random.seed(0)
el_pos = np.random.permutation(n_pts)[:... | c2db6a3484dc4923d92519488d0b10d7a7cd75bb | 12,657 |
def cursor():
"""Return a database cursor."""
return util.get_dbconn("mesosite").cursor() | 516cf2a1716204487dd4cff4f063397365b21fa1 | 12,658 |
def custom_field_check(issue_in, attrib, name=None):
""" This method allows the user to get in the comments customfiled that are not common
to all the project, in case the customfiled does not existe the method returns an
empty string.
"""
if hasattr(issue_in.fields, attrib):
value = str(eval('iss... | d9c051fa922f34242d3b5e94e8534b4dc8038f19 | 12,659 |
def header(text, color='black', gen_text=None):
"""Create an HTML header"""
if gen_text:
raw_html = f'<h1 style="margin-top:16px;color: {color};font-size:54px"><center>' + str(
text) + '<span style="color: red">' + str(gen_text) + '</center></h1>'
else:
raw_html = f'<h1 style="m... | 646b0a16b35cd4350feadd75674eea6ab6da6404 | 12,660 |
def block_pose(detection, block_size=0.05):
# type: (AprilTagDetection, float) -> PoseStamped
"""Given a tag detection (id == 0), return the block's pose. The block pose
has the same orientation as the tag detection, but it's position is
translated to be at the cube's center.
Args:
detectio... | da6ee3bb1bf8a071ea5859d17dcad07ecd8781a3 | 12,661 |
async def batch_omim_similarity(
data: models.POST_OMIM_Batch,
method: str = 'graphic',
combine: str = 'funSimAvg',
kind: str = 'omim'
) -> dict:
"""
Similarity score between one HPOSet and several OMIM Diseases
"""
other_sets = []
for other in data.omim_diseases:
try:
... | 2da8dc25d867f132ec0f571b4d9dff3d7de38c21 | 12,662 |
def vector(*,
unit: _Union[_cpp.Unit, str, None] = default_unit,
value: _Union[_np.ndarray, list]):
"""Constructs a zero dimensional :class:`Variable` holding a single length-3
vector.
:param value: Initial value, a list or 1-D numpy array.
:param unit: Optional, unit. Default=di... | dda09f89ba00ffab789c7ed9f6f6713a45c9bd03 | 12,663 |
import laspy
def read_lidar(filename, **kwargs):
"""Read a LAS file.
Args:
filename (str): Path to a LAS file.
Returns:
LasData: The LasData object return by laspy.read.
"""
try:
except ImportError:
print(
"The laspy package is required for this function. ... | 5336c34223216d4a1857cc5c858ccca704508e22 | 12,664 |
def get_gene_starting_with(gene_symbol: str, verbose: bool = True):
""" get the genes that start with the symbol given
Args:
- gene_symbol: str
- verbose: bool
Returns:
- list of str
- None
"""
gene_symbol = gene_symbol.strip().upper()
ext = "search/symbol/{}*".format(gene_sy... | c0f092a93d44dd264f6b251ff3eba565b29abda0 | 12,665 |
import time
def gen_timestamp():
"""
Generates a unique (let's hope!), whole-number, unix-time timestamp.
"""
return int(time() * 1e6) | cb044e7428c062660eb998856245d4cd2c692a7e | 12,666 |
def learningCurve(X, y, Xval, yval, Lambda):
"""returns the train and
cross validation set errors for a learning curve. In particular,
it returns two vectors of the same length - error_train and
error_val. Then, error_train(i) contains the training error for
i examples (and similarly for error_val(i... | 8cdfdec694cbfadef92375c7cf8eba4da012be59 | 12,667 |
def decode_xml(text):
"""Parse an XML document into a dictionary. This assume that the
document is only 1 level, i.e.:
<top>
<child1>content</child1>
<child2>content</child2>
</top>
will be parsed as: child1=content, child2=content"""
xmldoc = minidom.parseString(text)
retur... | 826bdc1ff0c4df503fdbc6f7e76b013d907b208b | 12,668 |
def _qcheminputfile(ccdata, templatefile, inpfile):
"""
Generate input file from geometry (list of lines) depending on job type
:ccdata: ccData object
:templatefile: templatefile - tells us which template file to use
:inpfile: OUTPUT - expects a path/to/inputfile to write inpfile
""... | 3ca565c4c599bccfd3916a0003126b3085cc7254 | 12,669 |
def arrangements(ns):
"""
prime factors of 19208 lead to the "tribonacci" dict;
only needed up to trib(4)
"""
trib = {0: 1, 1: 1, 2: 2, 3: 4, 4: 7}
count = 1
one_seq = 0
for n in ns:
if n == 1:
one_seq += 1
if n == 3:
count *= trib[one_seq]
one_seq = 0
return count
# # one-liner...
# return r... | 01f3defb25624d7a801be87c7336ddf72479e489 | 12,670 |
def vtpnt(x, y, z=0):
"""坐标点转化为浮点数"""
return win32com.client.VARIANT (pythoncom.VT_ARRAY | pythoncom.VT_R8, (x, y, z)) | 1e7c79353d010d4dd8daa4b7fa7c39b841ff8ffe | 12,671 |
from datetime import datetime
def get_time_delta(pre_date: datetime):
"""
获取给定时间与当前时间的差值
Args:
pre_date:
Returns:
"""
date_delta = datetime.datetime.now() - pre_date
return date_delta.days | 4f8894b06dc667b166ab0ee6d86b484e967501ac | 12,672 |
from bs4 import BeautifulSoup
def render_checkbox_list(soup_body: object) -> object:
"""As the chosen markdown processor does not support task lists (lists with checkboxes), this function post-processes
a bs4 object created from outputted HTML, replacing instances of '[ ]' (or '[]') at the beginning of a list... | 640f00d726a1268eb71134e29dbde53ef0ec44f5 | 12,673 |
def slowness_to_velocity(slowness):
"""
Convert a slowness log in µs per unit depth, to velocity in unit depth
per second.
Args:
slowness (ndarray): A value or sequence of values.
Returns:
ndarray: The velocity.
"""
return 1e6 / np.array(slowness) | dbfc3b4206ddf615da634e328328c4b8588e5c7a | 12,674 |
def SingleDetectorLogLikelihoodModelViaArray(lookupNKDict,ctUArrayDict,ctVArrayDict, tref, RA,DEC, thS,phiS,psi, dist,det):
"""
DOCUMENT ME!!!
"""
global distMpcRef
# N.B.: The Ylms are a function of - phiref b/c we are passively rotating
# the source frame, rather than actively rotating the b... | 35c27e53833cb54f856adde6815bf51c3feca019 | 12,675 |
import numpy as np
def manualcropping(I, pointsfile):
"""This function crops a copy of image I according to points stored
in a text file (pointsfile) and corresponding to aponeuroses (see
Args section).
Args:
I (array): 3-canal image
pointsfile (text file): contains points' coordina... | eb3f49b5b46d1966946fc3d00bcae113f51c60d1 | 12,676 |
from datetime import datetime
def prepare_time_micros(data, schema):
"""Convert datetime.time to int timestamp with microseconds"""
if isinstance(data, datetime.time):
return int(data.hour * MCS_PER_HOUR + data.minute * MCS_PER_MINUTE
+ data.second * MCS_PER_SECOND + data.microsecon... | bfdfe40065db66417bf2b641a24b195f4114687e | 12,677 |
def get_configs_path_mapping():
"""
Gets a dictionary mapping directories to back up to their destination path.
"""
return {
"Library/Application Support/Sublime Text 2/Packages/User/": "sublime_2",
"Library/Application Support/Sublime Text 3/Packages/User/": "sublime_3",
"Library/Preferences/IntelliJIdea2018... | d7617139a36ca2e1d4df57379d6af73e3b075c84 | 12,678 |
import os
def plot_sample_variation_polar(annots_df_group, **kwargs):
"""
Function: plot polar coordinate values of R3, R4, T3, T4, T3' positions of wild-type flies of a specific age. bundles from one sample are plotted together on the same subplot.
Inputs:
- annots_df_group: DataFrame group. Processed annotatio... | 9fae03a8d588143745b6a971cd37ee5c1e071338 | 12,679 |
def num_from_bins(bins, cls, reg):
"""
:param bins: list
The bins
:param cls: int
Classification result
:param reg:
Regression result
:return: computed value
"""
bin_width = bins[0][1] - bins[0][0]
bin_center = float(bins[cls][0] + bins[cls][1]) / 2
return bin... | 468e56075cf214f88d87298b259f7253d013a3f3 | 12,680 |
def rotate90(matrix: list) -> tuple:
"""return the matrix rotated by 90"""
return tuple(''.join(column)[::-1] for column in zip(*matrix)) | 770a8a69513c4f88c185778ad9203976d5ee6147 | 12,681 |
def get_aspect(jdate, body1, body2):
"""
Return the aspect and orb between two bodies for a certain date
Return None if there's no aspect
"""
if body1 > body2:
body1, body2 = body2, body1
dist = distance(long(jdate, body1),
long(jdate, body2))
for i_asp, aspect in... | 11a9b05fbc924290e390329395361da0c856541e | 12,682 |
def create_rollout_policy(domain: Simulator, rollout_descr: str) -> Policy:
"""returns, if available, a domain specific rollout policy
Currently only supported by grid-verse environment:
- "default" -- default "informed" rollout policy
- "gridverse-extra" -- straight if possible, otherwise turn... | 563363589b4ecc6c75306773a6de6320dd697c29 | 12,683 |
def get_event_details(event):
"""Extract event image and timestamp - image with no tag will be tagged as latest.
:param dict event: start container event dictionary.
:return tuple: (container image, last use timestamp).
"""
image = str(event['from'] if ":" in event['from'] else event['from'] + ":la... | c9b4ded7f343f0d9486c298b9a6f2d96dde58b8c | 12,684 |
def add_extra_vars_rm_some_data(df=None, target='CHBr3',
restrict_data_max=False, restrict_min_salinity=False,
# use_median_value_for_chlor_when_NaN=False,
# medi... | b86c49f6af0ddf144a5388b842240ddb44cf7236 | 12,685 |
def cvCreateMemStorage(*args):
"""cvCreateMemStorage(int block_size=0) -> CvMemStorage"""
return _cv.cvCreateMemStorage(*args) | b6ced2d030345b5500daa051601a20bd19e01825 | 12,686 |
import json
def copyJSONable(obj):
"""
Creates a copy of obj and ensures it is JSONable.
:return: copy of obj.
:raises:
TypeError: if the obj is not JSONable.
"""
return json.loads(json.dumps(obj)) | 1cc3c63893c7716a4c3a8333e725bb518b925923 | 12,687 |
from typing import List
def get_eez_and_land_union_shapes(iso2_codes: List[str]) -> pd.Series:
"""
Return Marineregions.org EEZ and land union geographical shapes for a list of countries.
Parameters
----------
iso2_codes: List[str]
List of ISO2 codes.
Returns
-------
shapes: ... | 1cebbbbc4d8d962776bbd17e8d2053e1c3dcf5ef | 12,688 |
def putrowstride(a,s):
"""
Put the stride of a matrix view object
"""
t=getType(a)
f={'mview_f':vsip_mputrowstride_f,
'mview_d':vsip_mputrowstride_d,
'mview_i':vsip_mputrowstride_i,
'mview_si':vsip_mputrowstride_si,
'mview_uc':vsip_mputrowstride_uc,
'mview... | ad15cc8c0f3e7d88849aed6cfef5408013700a01 | 12,689 |
def list_tracked_stocks():
"""Returns a list of all stock symbols for the stocks being tracker"""
data = read_json("stockJSON/tracked_stocks.json")
return list(data.keys()) | 96c1eeb4fb728d447eb4e4ae055e0ae065df6466 | 12,690 |
def min_max_two(first, second):
"""Pomocna funkce, vrati dvojici:
(mensi ze zadanych prvku, vetsi ze zadanych prvku).
K tomu potrebuje pouze jedno porovnani."""
return (first, second) if first < second else (second, first) | 7ddda1ad69056c22d9ba890e19e62464f56c08e1 | 12,691 |
def expand_pin_groups_and_identify_pin_types(tsm: SMContext, pins_in):
"""
for the given pins expand all the pin groups and identifies the pin types
Args:
tsm (SMContext): semiconductor module context from teststand
pins_in (_type_): list of pins for which information needs to be expanded i... | 141485a5cef061615afb58e514504dcbc89087ca | 12,692 |
def multi_ways_balance_merge_sort(a):
"""
多路平衡归并排序
- 多用于外部排序
- 使用多维数组模拟外部存储归并段
- 使用loser tree来实现多路归并
- 归并的趟数跟路数k成反比,增加路数k可以调高效率
:param a:
:return:
"""
SENTRY = float('inf') # 哨兵,作为归并段的结尾
leaves = [] # 每个归并段中的一个元素构成loser tree的原始序列
b = [] # 输出归并段,此实现中简化为以为数组。实际情况下也需要对输出分... | 4abeceb361f662e2ae8bba1a2cd94c9f598bdc9d | 12,693 |
def check_instance_of(value, types, message = None):
"""
Raises a #TypeError if *value* is not an instance of the specified *types*. If no message is
provided, it will be auto-generated for the given *types*.
"""
if not isinstance(value, types):
if message is None:
message = f'expected {_repr_types... | 4d62fea56a3c33bf1a6bd5921ff982544e9fbe29 | 12,694 |
def create_input_metadatav1():
"""Factory pattern for the input to the marshmallow.json.MetadataSchemaV1.
"""
def _create_input_metadatav1(data={}):
data_to_use = {
'title': 'A title',
'authors': [
{
'first_name': 'An',
... | 3149876217b01864215d4de411acb18eb578f1a9 | 12,695 |
import logging
def create_job(title: str = Body(None, description='The title of the codingjob'),
codebook: dict = Body(None, description='The codebook'),
units: list = Body(None, description='The units'),
rules: dict = Body(None, description='The rules'),
de... | 3b8fbeee052fc17c4490f7b51c57b9a83b878bf0 | 12,696 |
from typing import Dict
async def finalize(
db,
pg: AsyncEngine,
subtraction_id: str,
gc: Dict[str, float],
count: int,
) -> dict:
"""
Finalize a subtraction by setting `ready` to True and updating the `gc` and `files`
fields.
:param db: the application database client
:param ... | f9f0a498f5c4345bf9a61cb65ff64d05874caee7 | 12,697 |
def find_path(a, b, is_open):
"""
:param a: Start Point
:param b: Finish Point
:param is_open: Function returning True if the Point argument is an open square
:return: A list of Points containing the moves needed to get from a to b
"""
if a == b:
return []
if not is_open(b):
... | e42be77beb59ec9ef230c8f30abab33f4bfcd12b | 12,698 |
def view_skill_api():
""" General API for skills and posts """
dbsess = get_session()
action = request.form["action"]
kind = request.form["kind"]
if kind == "post":
if action == "read":
post = models.Post.get_by_id(dbsess, int(request.form["post-id"]))
if not post:
... | 622c4d7eadac7abf23f0706fc49389bd1453846c | 12,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.