content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import os
def p(*args):
"""
Convenience function to join the temporary directory path
with the provided arguments.
"""
return os.path.join(temp_dir, *args) | faee84d1f8887a12fb516ad260cf23fc3eff5e5b | 37,500 |
def decrypt_paste(encrypted: bytes, key: bytes) -> str:
"""Decrypts a Pastegram paste"""
iv = encrypted[:12]
encrypted_message = encrypted[12:-16]
tag = encrypted[-16:]
cipher = AES.new(key, AES.MODE_GCM, iv)
contents = cipher.decrypt_and_verify(encrypted_message, tag)
return contents.decode... | de28539da153abd46818415c52aa2b28d94ad28f | 37,501 |
async def list_(hub, ctx, top=None, expand=None, **kwargs):
"""
.. versionadded:: 1.0.0
List all resource providers for a subscription.
:param top: The number of results to return. Default returns all providers.
:param expand: The properties to include in the results. For example, use 'metadata' ... | a479e9870929a820772402c53de893ba60fb43cd | 37,502 |
from typing import List
def get_bccaqv2_opendap_datasets(
catalog_url,
variables: List[str] = None,
rcp: str = None,
method: ParsingMethod = ParsingMethod.filename,
models=None,
) -> List[str]:
"""Get a list of urls corresponding to variable and rcp on a Thredds server.
We assume that the... | 15424673faa1a70e3087dc6a369ff6cab5ce043e | 37,503 |
def poll_single_alert(outdir: str) -> (str, dict):
""" Connect to and poll fink servers once.
Parameters
----------
outdir: str
Directory to store incoming alerts. It must exist.
Returns
---------
topic: str
Topic name. None if no alert has been returned from the servers.
... | 447a7b20be69a346799d240f84255ae2618c98e4 | 37,504 |
def computeTF(doc_info,freqDict_list):
"""
tf =(frequency of the term in the doc/total number of terms in the doc
:param doc_info:
:param freqDict_list:
:return:
"""
TF_scores =[]
for tempDict in freqDict_list:
id = tempDict['doc_id']
for k in tempDict['freq_dict']:
... | 8a8567a98227226bc54de6c41010c9103d10be47 | 37,505 |
def render_pretty_expression(expr, indent = ''):
"""Renders a node to a string in a pretty way."""
if isinstance(expr, list):
if expr != [] and expr[0] in ['declare-const', 'declare-fun']:
return render_expression(expr)
if all(map(lambda e: not isinstance(e, list), expr)):
... | 27653c5f67d383c6456cd0d63bd1b43505d615e0 | 37,506 |
def assign_fingerprint_wells(fingerprint, treatment, dose):
"""Returns a set of wells along the edge that serve as barcode for
the plate based on the fingerprint word
Parameters
----------
fingerprint : str
treatment : str
the drug used to treat fingerprint wells
dose : float
... | e061194e6c79fe93b50f3504e75775986068ec28 | 37,507 |
import copy
def parent_request(parent_request_dict, ts_dt):
"""A parent request as a model."""
dict_copy = copy.deepcopy(parent_request_dict)
dict_copy["created_at"] = ts_dt
dict_copy["updated_at"] = ts_dt
dict_copy["status_updated_at"] = ts_dt
return Request(**dict_copy) | 4343fade1e3e3cdc00081dc3c2a0059153b32275 | 37,508 |
def generateBackground(df):
"""(pd.DataFrame)->pd.DataFrame
generate data used as prediction background
"""
x, y = df.columns[2:4]
minX, maxX = df.iloc[:, 2].min(), df.iloc[:, 2].max()
minY, maxY = df.iloc[:, 3].min(), df.iloc[:, 3].max()
# here are about 90000 points, it will slow down the ... | ccb6b4faa335d3a46b3f7c137ec8d8da4d822f7b | 37,509 |
import typing
def spark_filter(func: typing.Callable[[pyspark.rdd.RDD], pyspark.rdd.RDD]=default_function(1)):
"""Spark's filter
:param Callable func: The function to apply.
:input RDD data: The RDD to convert.
:output RDD result: The resulting RDD.
"""
def inner(data: pyspark.rdd.RDD) -> Ret... | 75736c3e6f24a402096aa3f657dfdd9f9967c60c | 37,510 |
import os
def load_sample(filename):
"""Helper to get the content out of the sample files"""
with open(os.path.join(SAMPLES, filename)) as f:
return f.read() | a5524b316679e132940e609495410a55f8222fe8 | 37,511 |
async def async_api_turn_on(hass, config, directive, context):
"""Process a turn on request."""
entity = directive.entity
domain = entity.domain
if domain == group.DOMAIN:
domain = ha.DOMAIN
service = SERVICE_TURN_ON
if domain == media_player.DOMAIN:
supported = entity.attribute... | e592090c83d43e0d96343e0c8b68b91a040843a7 | 37,512 |
def calculate_r_effective(df: pd.DataFrame, window_length: int = 7) -> pd.Series:
"""Calculate the effective reproduction number, :math:`R_e`.
More explanation can be found in the `Wikipedia article <Wikipedia>`_.
Note:
The infection counter is only reset to zero once a person becomes infected aga... | 31f00b4e030848ed234f87306e92e95d78e2ee11 | 37,513 |
def hydration(workspace):
"""Function for calculating hydration quantities
Args:
workspace (dict): workspace or dictionary with 'hydration_inputs', see above
Returns:
results (dict) : 'hydration_results' dictionary, see above
Raises:
TypeError: If 'hydration_inp... | a2eda0214322b5048024120002a5c99f29924edf | 37,514 |
from typing import Counter
from functools import reduce
import operator
def nb_permutations(word):
"""Retourne le nombre de permutations possibles d'un mot.
>>> nb_permutations("AAB")
3
>>> nb_permutations("ABC")
6
"""
num = factorial(len(word))
mults = Counter(word).values()
den ... | 1f17211dd6e6e34aa969fb38473e98a753704d1c | 37,515 |
def escape(data, entities={}):
"""Escape &, <, and > in a string of data.
You can escape other strings of data by passing a dictionary as
the optional entities parameter. The keys and values must all be
strings; each key will be replaced with its corresponding value.
"""
data = data.replace("&... | 3c2937f6475e7fc7e85e719dbb8d76fcbfa2f344 | 37,516 |
import torch
def rand(sharding_spec: ShardingSpec,
*size,
dtype=None,
layout=torch.strided,
requires_grad=False,
pin_memory=False,
memory_format=torch.contiguous_format,
process_group=None,
init_rrefs=False) -> ShardedTensor:
"""
Returns ... | 40f2c8151932e54a654d257120dbb950add8da5b | 37,517 |
def UploadPerfData(master_name, perf_id, test_name, builder_name, build_number,
revision, perf_data, point_id, dry_run=False,
testing_dashboard=True):
"""Uploads perf data.
Args:
Please see the help for command-line args.
Returns:
A boolean value indicating whether ... | 9a64b207f01152de1057937154004a6ee55865d9 | 37,518 |
def add(x: int, y: int) -> int:
"""Add two int numbers."""
return x + y | 734de9d22699dfff0d87c16d1c0fbd4bd0670b15 | 37,519 |
def parse(manifest_path, defaults):
"""
Parses a valid emane manifest file and converts the provided configuration values into ones used by core.
:param str manifest_path: absolute manifest file path
:param dict defaults: used to override default values for configurations
:return: list of core conf... | a6d5474f43078ad06f6b35776128b9cdba62f7d8 | 37,520 |
def get_linear_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, last_epoch=-1):
""" Create a schedule with a learning rate that decreases linearly after
linearly increasing during a warmup period.
From:
https://github.com/uds-lsv/bert-stable-fine-tuning/blob/master/src/transfor... | d4b93413a8430e895a8981a9720ab09633abbd49 | 37,521 |
def otc():
"""
Return spr for otc in period
"""
if request.method == "GET":
return redirect(url_for("insertdata", name="otc"))
f_data, l_data = get_user_dates_or_return_today()
title = "otc"
query = queryes["otc"]
query_result = con_to_firebird(
query,
(
... | 53a9724f965a280cbf0b5e0c19604aa8854586d6 | 37,522 |
def compute_target_weights(context, data):
"""
Compute ordering weights.
"""
# Initialize empty target weights dictionary.
# This will map securities to their target weight.
weights = {}
# If there are securities in our longs and shorts lists,
# compute even target weights for each sec... | a5e5cbaad867e1ea13bf81f970c147ef3a0acb86 | 37,523 |
def fit_databoxes_model(ds, model, xscript=0, yscript=1, eyscript=None, command="", settings={}, **kwargs):
"""
Loops over the supplied databoxe(s) and fits them using the supplied model
kwargs are sent to "data.load_multiple()" which
are then sent to "data.standard()". Useful ones to keep in m... | 691fd5ab79fd88cec07d24ff0723cb459f967736 | 37,524 |
import re
def ProcessOptionMultiprocessingParameters(ParamsOptionName, ParamsOptionValue):
"""Process parameters for multiprocessing and return a map containing processed
parameter names and values.
Arguments:
ParamsOptionName (str): Command line multiprocessing parameters option name.
... | 6e97753ecfb541013725f2f5c2d24ce4a99b535c | 37,525 |
import hashlib
def salt_password(password, salt=None, hash_name='sha1'):
"""Generate hashed password with salt hash(password + salt)
if salt is not given, generate_random_code will be used for generating
the salt value
"""
if isinstance(password, unicode):
password = password.encode('utf... | 3ba2a1baebfaa6e84355a4ab1c71d4a371e903fb | 37,526 |
def _perm_find(arr, x):
"""
Find permutation cutoff in array.
"""
return np.sum(np.abs(arr) >= np.abs(x)) / float(len(arr)) | 3303a3d38744aa40fddff94385649befccfca113 | 37,527 |
import scipy
def rayleigh_ritz(A, B, U):
"""
Rayleigh-Ritz procedure.
Extended for general eigen value problems e.g. Ax = λBx.
Parameters
----------
A : (n, n) array_like
A real or complex matrix of shape (n, n).
Matrix A in eigen value problems Ax = λBx.
B : (n, n) array_... | 8ec171f5e42c9501c481aff077eae682c9bdd968 | 37,528 |
from typing import List
from functools import reduce
def get_max_text_size(lines: List[str], font: str) -> Size:
"""Return the approximate size in pixels of the smallest bounding box that can enclose every line of text at a font size of 1pt"""
font_file = findfont(font)
font_image = PILtruetype(font_file,... | 556348dd4fe83784ed4713e28d13e0b175f6c58b | 37,529 |
def parse_response(response):
"""
Function used to remove the extra chars from the respone (bytes type)
after it was converted to string, Base64 decode it and decrypt it
The function will return an array, the first 3 elements will be
memory, cpu usage and uptime. All elements after that will have th... | d563d36427767caedb41ef4a0dc7d6588945ebaa | 37,530 |
import pathlib
def get_file(file_path):
"""
获取给定目录下的所有文件的绝对路径
:param file_path: 文件目录
:param pattern: 默认返回所有文件,也可以自定义返回文件类型,例如:pattern="*.py"
:return: 文件路径列表
"""
all_file = []
files = pathlib.Path(file_path)
f = files.rglob('*.md')
for file in f:
pure_path = pathlib.Pure... | b3819e7f8d307d5ad8dcc62442817b99b3d134fc | 37,531 |
def sachdr2origin(header):
"""
Provide a sac header dictionary, get a filled origin table dictionary.
A few things:
1) If sac reference time isn't event-based, origin time is unknown
2) magnitude is taken first from hdr['mag'], hdr['imagtyp'] if defined,
then replaced by hdr['user0'],hdr['kus... | 3129937cd8483ebd562b9dac86fe1e8e0f8f24bf | 37,532 |
from typing import List
from typing import Tuple
from typing import Optional
def input_board(layer: List[str], grid: List[str], coord: Tuple[int,int], flag: Optional[str]=None) -> bool:
"""
Function to test a coordinate on the board either revealing a mine or a number
Args:
layer: List[str]: a list... | b1448a90811c1ebf47e8ef7fcfe1448c79a34b85 | 37,533 |
def gauss_to_tesla(gauss):
"""Converts gauss to tesla"""
return gauss*1e-4 | 4f0239432a3436fd5c6cad4ae9747c8849289f34 | 37,534 |
from fullwavepy.ioapi.su import array2su
def su_decon(fname, d_inp, d_out, pnoise, **kwargs):
"""
Wiener deconvolution using SU's
sushape function.
d_inp : 1d array
Notes
-----
Is shaper a matrix?
Bash complains about too long list of arguments
=> trough files.
"""
if not exists(f... | 585b332f3a53191461dcbf621bb3b48d11c19bc7 | 37,535 |
import json
def create_artefact_file(artefact_path: str, artefact_kind: str) -> str:
"""
Create artefat file with specified PreLoadFilePath and kind
:param artefact_path: artefact file PreLoadFilePath
:param artefact_kind: artefact file kind
:return: artefact file srn (ResourceID)
"""
log... | 465d949303addb12069a0874b277ca8531db7a4d | 37,536 |
import warnings
def preprocess_labels(y, y_name=None, index=None, verbose=0):
"""
Does basic preparation of the labels. Turns them into Series, and wars in case the target is not binary.
Args:
y (pd.Series, list, np.array):
Provided labels.
y_name (str, optional):
Name of the y v... | e227991317845936e6c539d079f7dd0199e12df9 | 37,537 |
def G3_SF(tensors, cutoff_type, rc, lambd, zeta, eta, i="ALL", j="ALL", k="ALL"):
"""BP-style G3 symmetry functions.
NOTE(YS): here diff_jk is calculated through diff_ik - diff_ij instead of
retrieving the distance calcualted in cell_list_nl.
This makes is easier to get the jacobian with grad(sf, [dif... | 0c54ff28710c4c1e275427d6787910c1b06f0cf1 | 37,538 |
def createKey(problemData):
"""
Creates the key for a given 'problemData' list of number
of item types.
"""
key = ''
for itData in problemData:
key += str(itData) + ','
# Remove the last comma
return key[:-1] | 420a4e96dc6442ba2ae18f4bca3d8a10f8a19284 | 37,539 |
def tier_2_client_turnover():
"""
Real Name: Tier 2 Client Turnover
Original Eqn: Tier 2 Clients/Client Lifetime
Units: Persons/Month
Limits: (None, None)
Type: component
Subs: None
This is the flow of Tier 2 clients leaving the practice.
"""
return tier_2_clients() / client_lif... | 553d95d45e3f78531ece7348bf382e3d299e4c55 | 37,540 |
def create_app():
"""Creates and returns the Flask WSGI application
and initializes helping components"""
# Initialize json support for wtforms
wtforms_json.init()
# Define the WSGI Application object
app = Flask(__name__)
# Configurations
app.config.from_object('server.config')
#... | 10d92fc58d20f987fbd31d31c55bf56afbea8a34 | 37,541 |
def get_slug_from_request(request):
"""Returns the slug of the currently displayed category.
"""
slug = request.path.split("/")[-1]
try:
int(slug)
except ValueError:
pass
else:
slug = request.path.split("/")[-2]
return slug | a110e080bce3bade2ddd6c02cdf376ebfd4dfedb | 37,542 |
def even_or_odd(value: int) -> bool:
"""
BIG-O Notation = O(1)
"""
return value % 2 == 0 | 1f6f511c105dbea22f19c6143aa4f824f918fdd1 | 37,543 |
import scipy
def nn_overlap(X1, X2, k=100):
"""
Compute the overlap between the k-nearest neighbor graph of X1 and X2 using Spearman correlation of the
adjacency matrices.
"""
assert len(X1) == len(X2)
n_samples = len(X1)
k = min(k, n_samples - 1)
nne = NearestNeighbors(n_neighbors=k +... | fedbb69397325cb4c0c7d90d9ba1c1db291399d7 | 37,544 |
def login_registry():
"""
Login to a remote registry.
"""
if docker.login_registry():
return "success"
else:
return "fail" | 27fb3964fa1e4580f0d8141d0c2f73c9124696f6 | 37,545 |
def get_owner_mention(line):
"""
起案者 <@123> は🗑と🆗リアクションで削除出来ます。
の<@123>の部分を抽出する
"""
return line[len(BODY_TEXT_2) + 1:-(len(BODY_TEXT_3) + 1)] | 7c2f799ed0cbbe2f07bec9bc08e1183856988937 | 37,546 |
def service_array_to_list(array_pointer, length):
"""Convert ble_gattc_service_array to python list."""
data_array = driver.ble_gattc_service_array.frompointer(array_pointer)
data_list = _populate_list(data_array, length)
return data_list | 8d22df248e7a243ff3eca185a56411e2c42dc84b | 37,547 |
def lfsr_next_one_seed(seed_iter, min_value_shift):
"""High-quality seeding for LFSR generators.
The LFSR generator components discard a certain number of their lower bits
when generating each output. The significant bits of their state must not
all be zero. We must ensure that when seeding the gen... | 9cc82109ff3f491e6f880bdba2f598344556f92c | 37,548 |
import scipy
def mle_prob_many_coal_counts(As, Bs, t, n0):
"""
Find the maximum likelihood estimate of going from 'As' lineages
to 'Bs' lineages over generations 't'.
"""
# count unique (a,b) pairs
counts = defaultdict(lambda: 0)
for a, b in zip(As, Bs):
counts[(a, b)] += 1
As... | 793ba6a7f1ff0950682db0245d77e9fcbf2330d6 | 37,549 |
import csv
def import_data(csvfile):
"""
Iterates through each row of the provided csv, creating the a SiteSummarySnapshot object and saving to the DB
:param csvfile:
:return:
"""
total_count_stats = {"snapshots": 0}
reader = csv.reader(csvfile)
iter_reader = iter(reader)
try:
... | 6af2fac94844ba80fa71891168ecaf2a6701b0c8 | 37,550 |
def get_cmap_labels(im_label, cmap_name='cool', alpha=1):
"""Create list of L colors where L is the number of labels in the image"""
#cmap_original = plt.get_cmap(cmap_name)
cmap_original = colorify.cmaps_def(cmap_name=cmap_name)
colors = cmap_original(np.linspace(0,1,im_label.max()+1))
# backgroun... | 92391ea2bd44c7733c645d0bdcc1a159ad34b4c4 | 37,551 |
import torch
def test_elementwise_max():
"""Test of the PyTorch max Node on Glow."""
def test_f(a, b):
c = torch.max(a, b)
return torch.max(c, c)
x = torch.randn(4)
y = torch.randn(4)
jitVsGlow(test_f, x, y, expected_fused_ops={"aten::max"}) | 8c401933a79460f96a8034abe3748140570e7e52 | 37,552 |
def getVerticalIntervalsFromPitches(pitches):
"""Cached method. Returns 6 vertical intervals: BT, BA, BS, TA, TS, AS."""
cachedGetVerticalIntervalsFromPitches.append(pitches)
return [
getInterval(pitches[i], pitches[j])
for i in range(3)
for j in range(i + 1, 4)
] | 700f04d4a020930d59c8625005d9246733e320b2 | 37,553 |
def select_lines_by_tile(tile_xyz=(0, 0, 0), target_epsg_code='4326',
lines=None, include_intersections=False):
"""
Select lines by a tile
:param tile_xyz: tuple with tile x,y,z
:param target_epsg_code: the epsg_code to reproject the bbox to
before selecting.
:p... | ada32968cd1c104a764059f71122f0f165aa5439 | 37,554 |
from typing import List
def query_passwd(md5sum: bytes) -> List[str]:
"""查询数据库中可能存在的密码,如果没有,则返回空列表
"""
query = CertainPassword.select(
CertainPassword.passwd).where(CertainPassword.md5sum == md5sum)
passwords = [it.passwd for it in query]
if passwords:
now = date.today()
wi... | 11d09e4377eae897d87bfef7cb372f7b76232522 | 37,555 |
from typing import Union
from typing import Sequence
def create_relative_bias(config: Union[BaseBenchmarkerConfig, T5Config]) -> Sequence[RelativePositionBiasBase]:
"""
Creates empty list or one/multiple relative biases.
:param config: Model's configuration
:return: Sequence with created bias modules... | 8fa68a3fd8a9c72772484b6efa31073526557b6f | 37,556 |
def get_dois_for_review(review: Review):
"""Gets a list of dois (primary key) that are associated to a given review.
Args:
review: review-object
Returns:
list of dois as str: ["doi1", "doi2"]
"""
result_ids = []
for query in review.queries:
result_ids += query.results
... | 4a43f6d0de9c760200df0113c1f526b3fbe5b42f | 37,557 |
from pathlib import Path
from typing import Dict
from typing import Any
import asyncio
async def load_text_async(
path: Path,
options: Dict[str, Any] = {},
) -> str:
"""Load a text file asynchronously."""
loop = asyncio.get_running_loop()
data = await loop.run_in_executor(None, load_text, path, op... | b2d3dacce15940a636b1cb32e31ef58d3884ad4d | 37,558 |
from typing import Iterator
def find_as_products() -> Iterator:
"""
Returns a tuple with the following:
- full path to file
- ActiveState product the file is associated with
- product version
"""
files_to_check: Iterator[str] = dirwalker()
interesting_files_to_scan = filter... | 7c0dbb85f3ef83b2dc57a918b8490f63c629380b | 37,559 |
def function_to_dump(hallo,welt,with_default=1):
"""
non class function to be dumped and restored through
create_pickled_dataset and load_pickled_data
"""
return hallo,welt,with_default | 09bd551300d6672c685f3eeedd2e37fe528dfe14 | 37,560 |
def is_valid_batch_event_settings(val, file):
""" Validates if the value passed batch_event_settings has correct data type and values or not.
Args:
val (dict): value to be tested
Returns:
bool: True if all conditions are passed else False
"""
logger = VWOLogger.getInstance()
i... | c7bf96fbb67ab1faea6b98ec191e1fdfb265ffc6 | 37,561 |
def resources():
"""
:return: Renders Resource Page
"""
return render_template("resources.html") | d5c7b9f7584cdde3d1c44e3d0b63d03c8bab3a44 | 37,562 |
def objective(logits, labels, n_classes):
"""Defines classification loss and useful metrics"""
# defining the loss
cross_entr = tf.nn.sparse_softmax_cross_entropy_with_logits(
logits=logits, labels=labels)
loss = tf.reduce_mean(cross_entr)
inferred_class = tf.cast(tf.argmax(logits, 1), tf.i... | f5e0de6ff1be1cb99e8daa802b26f847c445b8da | 37,563 |
def resolve_compression_type(compression_type):
"""Turn a compression type string into a valid one.
:raises: ``ValueError`` if the compression type is invalid.
"""
if compression_type in COMPRESSION_TYPE_ALIASES:
return COMPRESSION_TYPE_ALIASES[compression_type]
elif compression_type in COM... | 6447ed443d12d8c575306d4ea6861a9756d5f1e6 | 37,564 |
def validate_long_url(value):
"""
Append schema if needed and validate.
"""
long_url = check_and_update_url_schema(value)
if len(long_url) >= 500:
raise ValidationError("Length of URL should be below 500 chars")
URLValidator()(long_url)
return long_url | 69836f81382542fc8e000a23bbd8e504feecbee1 | 37,565 |
def get_hashtag_spans(tokens):
"""
Finds the spans (start, end) of subtokes in a list of tokens
Args:
tokens: list[str]
Returns:
spans: list[tuple[int]]
"""
is_part = ["##" in t for t in tokens]
spans = []
pos_end = -1
for pos_start, t in enumerate(is_part):
if pos_start <= pos_end:
continue
if ... | 2e70466370e1171a2d29636d13c908c2e8b8e30e | 37,566 |
from typing import Tuple
from typing import List
import fsspec
from typing import Optional
from typing import Iterable
def _load_and_apply_indexer(
args: Tuple[Tuple[Tuple[str, int], ...], List[slice]],
delayed: bool,
fs: fsspec.AbstractFileSystem,
partition_handler: partitioning.Partitioning,
par... | 110ee585f232f27394a24d0f85b404794d3a7946 | 37,567 |
from typing import Mapping
def _snap_mask_to_type(
float_mask: xr.DataArray,
enumeration: Mapping[float, str] = SURFACE_TYPE_ENUMERATION,
atol: float = 1e-7,
) -> xr.DataArray:
"""Convert float surface type array to categorical surface type array
Args:
float_mask: xr dataarray of floa... | d0ce715b47ec10b2e763d186d19ba64dc6256269 | 37,568 |
def matrix_initialization(variable):
"""
Initialize the value of a variable inside a
force constant matrix, assuming the variable name
has the form 'Cnab' where n is an integer identifying
a set of independent variables and a and b identify
the directions (1,2 or 3).
Return a random numbe... | ed9c5b0bc35b8165c7676d191e9686d2bba77ec5 | 37,569 |
def svn_io_remove_file2(*args):
"""svn_io_remove_file2(char const * path, svn_boolean_t ignore_enoent, apr_pool_t scratch_pool) -> svn_error_t"""
return _core.svn_io_remove_file2(*args) | 80f6fa66eb22fc52575e35e71ac5564ec70f850d | 37,570 |
def create_fingers_dict_id():
"""
Create dictionary by ID of TCP group
usage: dict[id] return array with OS and theirs %
:return: dictionary from file with TCP params
"""
config = ConfigParser()
config.read('config.ini')
finger_path = config.get("TCP", "tcp_path")
with open(finger_pa... | 9d74d4dc1bbc58c8a1c2658eba74cf0c83d94b86 | 37,571 |
import os
def cutout_sdss(ra, dec, bands=['u','g','r','i','z'], dr=12, objid=None, psfmags=None,\
imDir="/data/sdss/", input_filename=[], saveFITS=False,\
width_as=20., smooth=False, cmap="binary", minmax="MAD", origin="lower", figTitle=True, \
return_val=False, saveDir... | 4c03e05f0059936dee2843eb27b0731bb1909c80 | 37,572 |
from typing import Type
import inspect
from typing import Any
def convert_type_annotation(annot: object) -> Type:
""" Converts a type annotation to a cowait type """
if annot == inspect._empty:
# an empty type signature defaults to the Any type.
return Any()
return convert_type(annot) | c21b5808b2a749dcf547bc7f70274f8c6b3cb6ae | 37,573 |
def body_cubic_5(size):
"""Generates symmetry preserving HNF's of a given size
for a base centered monoclinic basis
Args:
size (int): The determinate of the HNF matricies
Returns:
list (int): The generated HNF matricies
"""
symHNF = []
diags = find_HNF_diagonal(size)
... | 669ca2df9361fcc250f70b93da2389aab8a11264 | 37,574 |
def roundToNearest(number, nearest):
""" Rounds a decimal number to the closest value, nearest, given
Arguments:
number: [float] the number to be rounded
nearest: [float] the number to be rouned to
Returns:
rounded: [float] the rounded number
"""
A = 1/nearest
rounde... | 5f3974611b529e93ae8157182ff8b7dbc100a234 | 37,575 |
def _parse_schema_location(root):
"""Get all schema locations from xml."""
try:
namespace = root.nsmap["xsi"]
except Exception as e:
raise SchemaError("Can't get schema location namespace", e)
try:
schema_location = root.attrib["{%s}schemaLocation" % namespace]
except Excepti... | 134debda15620de66a1a47af1e584a71f6c994c9 | 37,576 |
def search_async():
"""New endpoint supporting async search."""
encoded_domain_parameter = flask.request.args.get('ed')
domain_parameter = tools.parse_domain(encoded_domain_parameter)
if domain_parameter is None:
return handle_invalid_domain(encoded_domain_parameter)
return flask.render_te... | d2a993b57e96d128ed20fa08c535270369d7ce65 | 37,577 |
import json
def digraph_from_multi_graph_json(file_name):
"""
file_name should hold a JSON which represents a MultiDigraph where there is a maximum of two edges each in opposing
directions between each node
:param file_name:
"""
with open(file_name) as f:
data = json.load(f)
G = n... | 299639fe469051c5678d11abe7f1183d55df36d8 | 37,578 |
def load_pretrained_model(root_dir, device=device):
"""load pretrained model for interpretation
"""
results = pkl.load(open(opj(root_dir, 'dnn_full_long_normalized_across_track_1_feat.pkl'), 'rb'))
dnn = neural_net_sklearn(D_in=40, H=20, p=0, arch='lstm')
dnn.model.load_state_dict(results['model_sta... | 7954fa149883f1a92e1433f4aea6f25cadb929c6 | 37,579 |
import os
def is_directory(filename):
"""Tells if the file is a directory"""
return os.path.isdir(filename) | 0e6d6c8aa9b666ec7d25d1a353e692bcb5220b06 | 37,580 |
def compare_dict_keys(d1, d2):
"""
Returns [things in d1 not in d2, things in d2 not in d1]
"""
return [k for k in d1 if not k in d2], [k for k in d2 if not k in d1] | 4b68c06d1598e325c5baa5ad8eefaa7af1e82d27 | 37,581 |
def fontawesome_link_button_html(
url: str,
fa_code: str,
button_type: str,
tooltip: str = None,
disabled: bool = False,
) -> str:
"""create fontawesome button and return HTML"""
return format_html(
'<a href="{}" class="btn btn-{}"{}>{}{}</a>',
url,
button_type,
... | df8f1f07b663a2bdbd1ba095047d9c2aab5d7b40 | 37,582 |
def factor_cumulative_returns(factor_data,
period,
long_short=True,
group_neutral=False,
equal_weight=False,
quantiles=None,
groups=None):
... | 051b53786f3c72f4f8e02f356ca4d609fdd7d734 | 37,583 |
def rotate(X, angle):
"""
This function rotates an aribitrary set of point coordinates by a given angle (in degrees)
around the mean centre of the given points.
X, the point coordinates rotated, is an array of form (n_instances * 2)
If applied to a distribution of points, has the effect of changing ... | 77f63b7700bd8b1727feaf18f2dccc99e51052a8 | 37,584 |
def make_path(segments, close=1):
"""
This function prepares a path given by a list of lists of
coordinates for the use with app.
"""
first_point = segments[0][0]
last_point = first_point
new_path = [[] + first_point, [], sk2const.CURVE_OPENED]
points = new_path[1]
for seg in segments:
if seg[0] ... | bcaeb73439ab3cf63941e3a1dfed37112b614d49 | 37,585 |
def make_stoppable(function_to_decorate):
"""Decorator allowing to stop or pause at the beginning of a task.
This is applied the perform method of every task marked as stoppable. This
check is performed before dealing with parallelism or waiting.
"""
def decorator(*args, **kwargs):
"""Wrap... | ead736574a95c7a6c28ae8892f2273771616f58d | 37,586 |
def parse_search_results(data: dict) -> list[OmdbMovie]:
"""
Parse search results into a list of Movie objects.
"""
movies = []
for movie in data["Search"]:
movies.append(_parse_movie(movie))
return sorted(movies, key=lambda m: m.year, reverse=True) | b08bb049b306bc3faff5d6b0829aef88bb10a70e | 37,587 |
import argparse
import json
def cmd_args_parser():
"""Parsing command-line arguments"""
parser = argparse.ArgumentParser(
prog="DatasetUpdater", description="Updates datasets-properties",
)
parser.add_argument(
"--project_id",
type=str,
action="store",
dest="pro... | 51f64a1198bac9273a682daa99205806e9c465e8 | 37,588 |
def _parse_res(expr: Expression) -> ResDescription:
"""
Parses the res operand of the instruction and returns the corresponding ResDescription.
"""
if isinstance(expr, ExprDeref):
return _parse_res_deref(expr.addr)
elif isinstance(expr, ExprConst):
# In this case op0 is not involved.... | 4c4119f247a8a11f1b972610756a77107bfa3210 | 37,589 |
def connect_to_uri(uri: str, loop=None) -> (Reader, Writer):
"""
Selecting connection type based on uri
"""
parsed = urlparse(uri)
if parsed.scheme not in AVAILABLE_SCHEMES:
raise UnavailableUriScheme(uri)
if parsed.scheme == 'tcp':
port = parsed.port
if parsed.host is No... | 7b5239f36707ea8772d5829167779d83c37e7512 | 37,590 |
def command_talk(current_buffer, args):
"""
Open a chat with the specified user
/slack talk [user]
"""
server = servers.find(current_domain_name())
if server:
channel = server.channels.find(args)
if not channel:
channel.open()
else:
user = server.... | 75ffd363c126fc43bb650aaa3b5bdf1e7192eb8a | 37,591 |
import os
def icon_path(name):
""" Load an icon from the res/icons folder using the name
without the .png
"""
path = os.path.dirname(os.path.dirname(__file__))
return os.path.join(path, 'res', 'icons', '%s.png' % name) | dd8254d4aae3b930623ec46dc6e262b37f8170ca | 37,592 |
def project_name(settings_dict):
"""Transform the base module name into a nicer project name
>>> project_name({'DF_MODULE_NAME': 'my_project'})
'My Project'
:param settings_dict:
:return:
"""
return " ".join(
[
x.capitalize()
for x in settings_dict["DF_MODU... | 07411942978ad769d25234f8c7286aaddc365470 | 37,593 |
def is_acceptable_smiles(smile: str, allowed_chars=smiles_encoding['indices_token'].values(),
min_len=smiles_encoding['min_smiles_len'], max_len=smiles_encoding['max_smiles_len']):
""" Checks which smiles
Args:
smile: (str) smiles string
allowed_chars: (lst) list of all... | 5eba7e323e17e4ced5e169d4bf107fd98bb39130 | 37,594 |
def parse_config_vars(config_vars):
"""Convert string descriptions of config variable assignment into
something that CrossEnvBuilder understands.
:param config_vars: An iterable of strings in the form 'FOO=BAR'
:returns: A dictionary of name:value pairs.
"""
result = {}
for val... | 1bc1b96b6a2b0bf8e42fca0bb4ee9601c883b124 | 37,595 |
def create_detections(detection_mat, frame_idx):
"""Create detections for given frame index from the raw detection matrix.
Parameters
----------
detection_mat : ndarray
Matrix of detections. The first 10 columns of the detection matrix are
in the standard MOTChallenge detection format. ... | ac17116651f90ae1e2e844f6e5e51473b13ea742 | 37,596 |
def GetFileSystemDebug(path: str, run_ps: bool = True) -> FileSystemDebugInfo:
"""Collect filesystem debugging information.
Dump some information to help find processes that may still be sing
files. Running ps auxf can also be done to see what processes are
still running.
Args:
path: Full path for direc... | 0e3bc7411137050c4ab8e0d600bb13f006dc0f2e | 37,597 |
def q_values(state, actions, weights, xf_vec):
"""
Calculate q values for current state and actions
Parameters
----------
state : tuple
current state-
actions : ndarray
possible actions-
weights : ndarray
weights of linear function approximation-
xf_vec : list
... | 1922b60dcc8bb64a78909288eeae21e38596c4c0 | 37,598 |
import textwrap
def _get_parsed_args():
"""Parses command line arguments and the config file.
Order of precedence for config values is: command line > config file values > defaults
Returns:
A "Namespace" object. See argparse.ArgumentParser.parse_args() for more details.
"""
parser = con... | 726a022e1e7278d07ee36c74df26793fd055c803 | 37,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.