content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Union
def calculate_annual_interest_rate(base_salary: Union[int, float], rpi: float, max_interest_cap: float = None) -> float:
"""
Calculates the annual interest rate based on the RPI and salary earned.
The interest rate charged is normally the Retail Price Index plus up to 3%, dependin... | ef805e69bbbe1838ae89cdf976907636e63d9548 | 66,500 |
def get_upload_commands(system, release, package):
"""Returns the required package_cloud commands to upload this package"""
repos = ["datawireio/stable", "datawireio/telepresence"]
res = []
for repo in repos:
res.append(
"package_cloud push {}/{}/{} {}".format(
repo, ... | db3fccb3302657367be121f4bb64affcd4879180 | 66,501 |
def vanity_about(request):
"""
The /about view, displays marketing mumbo jumbo.
"""
# # Redir https
# if request.headers.get('X-Forwarded-Proto') is not None:
# if request.headers['X-Forwarded-Proto'] != 'https':
# return HTTPMovedPermanently(location="https://%s%s" % (
# ... | 0969e6b3cc73bac994a434bb053152d04a2ea1bd | 66,502 |
def organisation_update_profile(request,organisation_id, *args, **kwargs):
"""
:param request:
:param organisation_id:
:return:
"""
return HttpResponse('') | ef2d5d635b89b7700be6f585244722a27785dec2 | 66,503 |
def get_attached_policy(client, policy_arn):
""" Get the policy document of an attached policy. """
try:
policy = client.get_policy(
PolicyArn=policy_arn
)['Policy']
version = policy['DefaultVersionId']
can_get = True
except Exception as error:
print('Get ... | 9a3f6e3a24727e203acc06b0b7022f695989c886 | 66,504 |
import json
import requests
def phone_home(phone_home_url=None,
phone_home_headers=None,
do_enabled=False,
ts_enabled=False,
as3_enabled=False,
status='ERROR',
verify_tls=True,
metadata={}):
"""Issues a Phone ... | d1357fcce4f0010c592bbecbddf60e20f7116b5a | 66,505 |
def adsr(x, t, a, d, s_val, r):
"""
x input vector
t signal total len
a attack duration
d decay duration
s_val sustain level
r release duration
"""
m0 = 1 / a
b0 = 0
m1 = (s_val - 1) / d
b1 = 1 - a * m1
s = t - r
m2 = s_val / (s - t)
b2 = -t * m2
y = []
... | c7861f2c97bcb1c6d65f7974afab4da7986b3cc3 | 66,506 |
def GetClosenessCentr(*args):
"""
GetClosenessCentr(PUNGraph const & Graph, int const & NId) -> double
Parameters:
Graph: PUNGraph const &
NId: int const &
"""
return _snap.GetClosenessCentr(*args) | f4e10abc66ae53f432dd936253692ea3dc17b680 | 66,507 |
def fix_whitespace_for_phantom(text: str):
"""Transform output for proper display
This is important to display pandas DataFrames, for instance
"""
text = text.replace(' ', r' ')
text = '<br>'.join(text.splitlines())
return text | 7a0e3cddd778263977da74096f7bd30f44a0ce45 | 66,508 |
def draw_shell(G, **kwargs):
"""Draw networkx graph with shell layout.
Parameters
----------
G : graph
A networkx graph
kwargs : optional keywords
See hvplot.networkx.draw() for a description of optional
keywords, with the exception of the pos parameter which is not
used... | b6777476d642fd07b13c52310e3209319f878da2 | 66,509 |
def iou_detection(box1, box2):
"""Computational object detection iou.
Args:
box1: [xmin1, ymin1, xmax1, ymax1]
box2: [xmin2, ymin2, xmax2, ymax2]
return:
object detection iou values.
"""
xmin1, ymin1, xmax1, ymax1 = box1
xmin2, ymin2, xmax2, ymax2 = box2
s1 = (xm... | efaf6d2bef0b6de40c4f05cad15ebfb5810ebc80 | 66,510 |
def normalize_assignments(assignments):
"""Convert a clustering state <assignments> so that all essentially equal states can be
same array. Return value type is Tuple so that it can be hashed as a dict key.
"""
convert_table = {}
new_id = 0
for cluster_id in assignments:
if cluster_id no... | 1574a62db1ca65c1051bfac6fce9b30918892404 | 66,511 |
def get_temperature_reading_as_json(temperature_reading):
""" returns a single temp reading as a json object """
result = '{\n "probe_id" : "' + temperature_reading.probe_id + '",\n "temperature_C" : "' + str(temperature_reading.temperature_C) + '",\n "temperature_F" : "' + str(temperature_reading.temper... | 4836532602e4b0c704c6eab439ac873d8e53c237 | 66,512 |
import os
def write_file(filecontents, filename):
""" writes a string of data to disk """
if not os.path.exists(os.path.dirname(filename)):
os.makedirs(os.path.dirname(filename))
logger.debug("Writing file '%s' to disk" % filename)
try:
with open(filename, "w") as fh:
fh... | 136a433edb3bc0546f683095418761ce74c5018a | 66,513 |
def get_source_type():
"""
Выдает все типы источников, с которым может работать AnchorBase
"""
try:
l_available_source_type=C_AVAILABLE_SOURCE_LIST
l_source_type_str="" # все типы источников в строку
for i_source_type in l_available_source_type:
l_source_type_str+=i_s... | b53e5824567562dbbf21a7ef9f0d62e5d443d3e6 | 66,514 |
def assign_allometric_eq(ds):
"""
Given a dataset with ecoregion values (Ecoregions2017, NLCD, EOSD, IGBP), f_slope, and senergy, assign the correct allometric equation
"""
# calculate f_slope and senergy if not in dataset
for v in ['f_slope', 'senergy']:
if v not in ds:
ds[v] = ... | 4d8dc387122ae582aaaa779d7a94431e9afe57b4 | 66,515 |
def get_aurocs(X, y, pipeline):
"""
Fit the classifier for the given mutation (y) and output predictions for it
"""
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=0)
pipeline.fit(X=X_train, y=y_train)
y_pred_train = pipeline.decision_function(X_train)
y... | 5434706d7ae47e04497376c2b95969e83ef80c75 | 66,516 |
def heugcd(f, g):
"""
Heuristic polynomial GCD in ``Z[X]``.
Given univariate polynomials ``f`` and ``g`` in ``Z[X]``, returns
their GCD and cofactors, i.e. polynomials ``h``, ``cff`` and ``cfg``
such that::
h = gcd(f, g), cff = quo(f, h) and cfg = quo(g, h)
The algorithm is purely h... | d82596709b15ae1ac501e0b1723a2fed4671dabc | 66,517 |
import json
def load_json_file(path_conf):
""" Loads a json file specified in the path """
with open(path_conf, "r", encoding="utf-8") as file_conf:
conf_physic = json.load(file_conf)
return conf_physic | 5eaa7a8a35c428a36bd6dc5608fc836a4a096253 | 66,518 |
import math
def step_decay(epoch: int):
"""
Learning rate scheduler.
Parameters
-----------
epoch: int
Number of epochs to perform
Returns
--------
float
Learning rate
"""
initial_lrate = 1e-3
drop = 0.5
epochs_drop = 50.0
lrate = initial_lrate * m... | 80af442b6ce0c7b454969896b7ac41efdf63eaf6 | 66,519 |
def api_call(url, **params):
"""Return response from API."""
data = get_url(url, **params).json()
remaining = data.get('quota_remaining') or 0
total = data.get('quota_max') or 0
if total and remaining:
log.info(u'%d/%d API requests remaining', remaining, total)
return data | 138800d21c9ec383be8545b2707c561d50e8f959 | 66,520 |
def baseCodeToJournalName(baseCode):
"""
Return the jrnl name for a baseCode
>>> print baseCodeToJournalName("ANIJP-IT.2006")
Annata Psicoanalitica Internazionale
>>> print baseCodeToJournalName("anijp-fr.2006")
Annee Psychanalytique Internationale
"""
base = baseOfBaseCode(baseCode)
... | a6511347f02d2245161a97b22326d3c93735dc9e | 66,521 |
def get_camera_parameters_intrinsic(scene):
""" Get intrinsic camera parameters: focal length and principal point. """
# ref: https://blender.stackexchange.com/questions/38009/3x4-camera-matrix-from-blender-camera/120063#120063
focal_length = scene.camera.data.lens # [mm]
res_x, res_y = get_scene_resolu... | 7db8f146bb36e3b209c8db56e8fa5a74c00a9344 | 66,522 |
def snr(spectrum, region=None):
"""
Calculate the mean S/N of the spectrum based on the flux and uncertainty
in the spectrum. This will be calculated over the regions, if they
are specified.
Parameters
----------
spectrum : `~specutils.spectra.spectrum1d.Spectrum1D`
The spectrum obj... | 9e29d6b2e5d6d3614ff10b2e8c3f24b4bc19c944 | 66,523 |
def input(_input, **options) -> Input:
"""Input options (ffmpeg pre_option ``-i`` input options)
You can also pass a cloud object as an input to the method. the file will be downloaded and will pass it to ffmpeg
if you want to open a resource from a pipe, set input "pipe:"
if you want to ope... | 229fa7f44488c9b54c17753b323bfdcff1407c53 | 66,524 |
import posixpath
def normalize_api_path(api_path):
"""Resolve paths with '..' to normalized paths, raising an error if the
final result is outside root."""
normalized = posixpath.normpath(api_path.strip('/'))
if normalized == '.':
normalized = ''
elif normalized.startswith('..'):
r... | b40f617631cbff27d6cc2bc8b42552cb0fc33cbc | 66,525 |
def define_plane_from_points(xyz1, xyz2, xyz3):
"""
Compute constants defining a plane from a set of points.
The equation defining a plane has the form ax+by+cz+d=0.
This utility returns the constants a, b, c and d.
Parameters
----------
xyz1 : numpy.ndarray
First point needed to d... | e3ed313882793b6483247ee94f4ab5dae1d9a2b7 | 66,526 |
def _internal_is_knet_ascii(buf):
"""
Checks if the file is a valid K-NET/KiK-net ASCII file.
:param buf: File to read.
:type buf: Open file or open file like object.
"""
first_string = buf.read(11).decode()
# File has less than 11 characters
if len(first_string) != 11:
return F... | 9ca251ef9c5eab64a97f69e1acd8b6aa746ea09b | 66,527 |
def _plot_1d(data, ax=None, **plt_kwargs):
"""Plot one dimensional functional data.
This function is used to plot an instance of functional data in 1D.
Parameters
----------
data: UnivariateFunctionalData or IrregularFunctionalData
The object to plot.
ax: matplotlib.axes._subplots.Axes... | f1a26ef962101758364f66f6acc7e79a39b06e69 | 66,528 |
def getAvgFeatureVecs(texts, keywords, stopwords, model, modelword_index, num_features):
"""
Obtains the vector representation for every word and takes the average over all tokens for every text
Returns a vector of average feature vectors for all texts
"""
counter = 0
# Initialise numpy vector ... | 4c3bc0787b47e9cac0f8318eac3120108492cdf2 | 66,529 |
def load_data(index: bool = False) -> pd.DataFrame:
"""
Function for loading and cleaning data in a usable format
Parameters:
-----------
index: boolean indicating whether to load data with a specified index column
Returns:
--------
A pandas DataFrame object containing cleaned data
... | 6725116d1e817f78e201e918671799d08bb28d12 | 66,530 |
def poly_real_part(poly):
"""Deprecated."""
return np.poly1d(poly.coeffs.real) | 26cb705b1da626d5342cafcf403346ba3f0bd24f | 66,531 |
import torch
from typing import List
from typing import Tuple
from typing import Callable
def graph_pit_loss(
estimate: torch.Tensor,
targets: List[torch.Tensor],
segment_boundaries: List[Tuple[int, int]],
loss_fn: Callable,
) -> torch.Tensor:
"""
Graph-PIT loss function.
... | c14a720c822554c1244cc323565557214b710b91 | 66,532 |
def encode_sentences(sentences, vocab=None, invalid_label=-1, invalid_key='\n', start_label=0):
"""Encode sentences and (optionally) build a mapping
from string tokens to integer indices. Unknown keys
will be added to vocabulary.
Parameters
----------
sentences : list of list of str
A l... | 2ee84f5f64ce383d025769a36515d33df41fad33 | 66,533 |
def make_affine_matrix(bbox, target_size, margin=1.2, aug_rotation= 0, aug_scale=1):
"""
transform bbox ROI to adapat the net-input size
`margin`: determine the distance between the bbox and input border . default: 1.2
`aug_rotation`: the rotation angle of augmentation, range from [0,180]. default: 0
... | 9be54cf4149d922c49afa2be27a8eceb030647c7 | 66,534 |
def flatten(lst):
"""Flat list out of list of lists."""
return [item for sublist in lst for item in sublist] | 3849afc94fdab885dbc6eea1960dba0294e03483 | 66,535 |
from sys import path
def read_localization_markdown(file: str, language: str) -> str:
"""Reads localization template.
Arguments:
file: Name of the section plus `.md`
language: Localization info
Raises:
KeyError: If no template for file/language exists.
"""
file_address = ... | cc451bd7d79c3daf8b9467bb74387410f1a99480 | 66,536 |
import posix
def _PopDirStack(mem, dir_stack, errfmt):
# type: (Mem, DirStack, ErrorFormatter) -> bool
"""Helper for popd and cd { ... }."""
dest_dir = dir_stack.Pop()
if dest_dir is None:
errfmt.Print('popd: directory stack is empty')
return False
try:
posix.chdir(dest_dir)
except OSError as... | 51496073a1aae766d09ae53f9d8b0af4fa7c295b | 66,537 |
async def get_fsc_revocation_job(request_id: UUID):
"""
Route for retrieving job status from an fsc revocation from the queue.
:param request_id: the id of the job.
"""
freischaltcode_service: FreischaltCodeService = get_service(RequestType.freischalt_code_revocate)
return freischaltcode_service... | d609665d7a831b80577a7a9db2f388999ffa92a7 | 66,538 |
from typing import Dict
from typing import List
def white_code_words(language_id: str) -> Dict[str, List[str]]:
"""
Words that do not count as code if it is the only word in a line.
"""
assert language_id is not None
assert language_id.islower()
return _LANGUAGE_TO_WHITE_WORDS_MAP.get(language... | acc0811ffb3a7e5947869affae98d01f90fc6edd | 66,539 |
def bits2octets(bits, rolen):
"""
Converts bits into octects modulo Curve.N, padded with zeros. Overflow is
discarded.
https://tools.ietf.org/html/rfc6979#section-2.3.4
Args:
bits (ByteArray): Bytes to convert.
rolen (int): Number of digits to allow.
Returns:
ByteArray... | 337422576f095104d4ebec54983f1c359318bfa5 | 66,540 |
def get_unique_names(to_lower=True):
"""
Get all product names.
Returns: list
"""
docs = products_ref().get()
unique_names = [
doc.to_dict()['producer'] + "_" + doc.to_dict()['product']
for doc in docs
if 'producer' in doc.to_dict() and 'product' in doc.to_dict()
]
... | c1fa49a42f67c62f1451063419c9bbb538e36309 | 66,541 |
def gae_advantages(rewards: jnp.ndarray, terminal_masks: jnp.ndarray,
values: jnp.ndarray, discount: float, gae_param: float):
"""Use Generalized Advantage Estimation (GAE) to compute advantages.
Args:
rewards: array shaped (actor_steps, num_agents)
terminal_masks: array shaped (actor_st... | 09d708c8b5e51452db585018db178d93980e9858 | 66,542 |
def list_opts():
"""Return a list of oslo.config options available.
The purpose of this is to allow tools like the Oslo sample config file
generator to discover the options exposed to users.
"""
opt_list = [
(service_available_group, ServiceAvailableGroup),
(sdn_group, SDNGroup),
... | 1ace405b375d26f6b374b9392030d69d0c8872e1 | 66,543 |
def GetBlueprintTargetForGit(messages, git_target, git_target_subdir='.'):
"""Returns the GitTarget representation of a blueprint git target.
Args:
messages: ModuleType, the messages module that lets us form blueprints API
messages based on our protos.
git_target: string, a Git repo path.
git_tar... | b5b7dc9ac3a9816482ecbfa05cebc59f83f60e8b | 66,544 |
import pathlib
import os
def get_program_email_list(program):
""" Return a list of emails for a given program. """
# Navigate to 'programs' directory in repository.
programs = pathlib.Path(os.getcwd()) / ".." / "resources" / "views" / "programs"
directory = programs / program
emails = os.li... | 44e03cd5fa018480044441fbd92ace771e063073 | 66,545 |
def getInviteAcceptedRedirect(entity, _):
"""Returns the redirect for accepting an invite.
"""
return '/%s/accept_invite/%s/%s' % (
entity.role, entity.scope_path, entity.link_id) | 39affb109481cb96bb4ca992911e6a6a1957962a | 66,546 |
def z_request_dict(df: gpd.geodataframe.GeoDataFrame) -> dict:
""" DF -> dictionary conversion
:param df: dataframe to be used
:return: converted dictionary
"""
df.reset_index(inplace=True) # resetting index
dict_from_df = df.to_dict('index')
return dict_from_df | d4b2c25fadc483c54733a046b2c1b22cc2d9f542 | 66,547 |
import logging
import time
def google_http_error_retry(tries=4, delay=3, backoff=2, logger=logging):
"""
Retry calling the decorated function using an exponential backoff.
It retries HttpErrors with status code > 400(except 404).
Errors with another status code are reraised
:param tries: number o... | 16c7b33b2cb5409f25400ae54defb95d323a8227 | 66,548 |
def format_month(month):
"""Formats a month to first 3 characters of the month input
Args:
month: user input month
Returns:
A ValueError if the input is not a month, or a 3 character month.
"""
months = ['Jan','Feb','Mar','Apr','May','Jun',
'Jul','Aug','Sep','Oct','Nov... | da7ffd8bc801377ecebcc76e972219633ae21566 | 66,549 |
def compute_fingerprint(molecule, fingerprint: str, nbits: int, use_chirality: bool) -> np.ndarray:
"""Calculate a single fingerprint.
Parameters
----------
molecule
RDKit molecule
fingerprint
Name of the fingerprint to apply
bits
Number of bits to use
use_chirality
... | b13c5ed9cf7d51dd0fb6c6906955b623df42f133 | 66,550 |
from dms.utils_form import get_base_vars
from dms.utils import get_site_actions
from django.shortcuts import render_to_response
def do_manage(request, item_container, user_perms, add_ons, app_name,
my_title, my_title_own, dont={}, allow_copy=True):
""" Pflegemodus der Ressou... | eb052e660531673e4771cd2feb94cd3cebab30ae | 66,551 |
import re
import codecs
import os
def liveTest():
"""
Runs the test of a program against the live testing environment
"""
retVal = True
count = 0
global_ = {}
vars_ = {}
livetests = readXmlFile(paths.LIVE_TESTS_XML)
length = len(livetests.getElementsByTagName("case"))
elemen... | 8c358debd99b01f98df382cf57d922d34cbf0bb5 | 66,552 |
async def portfolios(_request: Request, user: User) -> response.HTTPResponse:
"""
User's list of portfolios
"""
return response.json({"email": user.email}) | e9a91017c22163aae7184784e42eaabd3ea7bbc4 | 66,553 |
def LongestIncreasingSubsequence(S):
"""
Find and return longest increasing subsequence of S.
If multiple increasing subsequences exist, the one that ends
with the smallest value is preferred, and if multiple
occurrences of that value can end the sequence, then the
earliest occurrence is preferr... | 0d3755abee33ccbb110ee7dc0e6552a19770bfdd | 66,554 |
import os
def get_normal_payload_command(cmd, job, preparesetup, userjob):
"""
Return the payload command for a normal production/analysis job.
:param cmd: any preliminary command setup (string).
:param job: job object.
:param userjob: True for user analysis jobs, False otherwise (bool).
:par... | 972a64ed7665c694cbfd4a8515036d9631bb8a84 | 66,555 |
def get_data(fn, split=False, split_char=None, filter_blanks=False):
"""
:param fn: filename to open
:param split: if you want to split the data read
:param split_char: character you want to split the data on
:param filter_blanks: remove empty strings if split=True
Example:
>>>data = get_dat... | 6ff198281d41f96fb48c45c51525245cffe8e7ec | 66,556 |
def add_cors(resp):
""" Ensure all responses have the CORS headers. This ensures any failures are also accessible
by the client. """
resp.headers['Access-Control-Allow-Origin'] = '*'
resp.headers['Access-Control-Allow-Credentials'] = 'true'
resp.headers['Access-Control-Allow-Methods'] = 'POST, O... | 0e8044bcdbbfebad19b41b1323ba0935e178999c | 66,557 |
def FilterLabels(labels):
"""Filter label strings in label list.
Filter labels (list of strings) with the following conditions,
1. If 'label' has 'key' and 'value' OR 'key' only, then add the label to
filtered label list. (e.g. 'label_key=label_value', 'label_key')
2. If 'label' has an equal sign but no 'val... | 9ab4c5211d0f668c2bf83e359c27e0f7996964e8 | 66,558 |
import logging
def get_loglevel(level):
""" return logging level object
corresponding to a given level passed as
a string
@str level: name of a syslog log level
@rtype: logging, logging level from logging module
"""
if level == 'debug':
return logging.DEBUG
elif level == 'notic... | d20bbc8746b5ac58d564e710d085e8e33d452627 | 66,559 |
def route_urgent_task(name, args, kwargs, options, task=None, **kw):
"""Allow routing urgent tasks to a special queue, according to URGENT_TASK_QUEUES
e.g. task.apply_async(args, kwargs, urgent=True)
"""
if name in URGENT_TASK_QUEUES and kwargs.get('urgent'):
return {'queue': URGENT_TASK_QUEUES... | 79de2cdda22378c34826f6f72f10486804fc6022 | 66,560 |
import glob
def points_to_crowns(
field_data,
rgb_dir,
savedir,
raw_box_savedir,
client=None):
"""Prepare NEON field data int
Args:
field_data: shp file with location and class of each field collected point
rgb_dir: glob to search RGB images
savedir: direcory to sa... | 6e45481b3185fee7121f0b05441edaa14a3498d5 | 66,561 |
def get_all_data(path):
"""
Gets all the reviewText and Overall Sentiment from the json file
"""
dict = {}
generator = parse(path)
i = 0
for line in generator:
dict[i] = line
i+=1
data = {"reviewText": [], "overall": []}
for d in dict:
data["reviewText"].appe... | e24c0275ad248ea9ced0be04e5c8b6392ae3f6c7 | 66,562 |
def configuration_for(key):
"""Retrieve the configuration value for a specified key"""
try:
return Configuration.query.filter_by(key=key).first()
except:
return None | ab0d4101d7d0386569f1646a78c46b7150494363 | 66,563 |
def maybe_add(d, exclude_false=False, **kws):
"""
Adds keywork argumnts to a dict if their values are not None.
Parameters
----------
d: dict
The dictionary to add to.
exclude_false: bool
Exclue keys whose values are false.
kws: dict
The keys to maybe add
"""
... | bc7bc09261f37fe052d30d6b0c2452937f33c563 | 66,564 |
def string_to_datetime(date_time_string):
"""
transform the datetime string to object
:param date_time_string: datetime in string format
:return: datetime in datetime format
"""
return parse(date_time_string) | 0684cc0cb2482b1de0a3c13d1a76c78236fe0d8b | 66,565 |
import collections
def flatten_feature_dict(metapath_to_metric_dict):
"""
Processed the nested dictionaries returned by features_for_metapaths()
into a single dimension dictionary with keys representing metapath and
metric combinations.
"""
feature_dict = collections.OrderedDict()
for meta... | 5f92c9bb1b51fa130e9306b0740490d9fcc93e14 | 66,566 |
import os
def del_repo(base_path):
"""
delete repository.
"""
os.system("rm -R -f " + base_path)
return True | c46d87f2d38a52f70e2fcbb90cb3b07f3ee824a5 | 66,567 |
def decode_text(encoded_text: str, reverse_mapping: dict):
"""
This function returns the decoded text from the text file.
Uses for loops and if statement to obtain the decoded text.
"""
decoded_text = ""
current_code = ""
# iterates over dictionaries using for loops
reverse_mapping = ... | 58fbff9e00b691919537b40a765f437a566fc730 | 66,568 |
from typing import Mapping
def _get_stix_version(data):
"""
Bit of factored out functionality for getting/detecting the STIX version
of the given value.
:param data: An object, e.g. _STIXBase instance or dict
:return: The STIX version as a string in "X.Y" notation, or None if the
version ... | 5f94549d038789c837530bb97fc49651f173659b | 66,569 |
def zk_runner():
"""A runner of shell commands with a mocked zk client"""
zkcli = mock.MagicMock(read_only=True)
return izk.runner.ZkCommandRunner(zkcli) | 18cedc8ff1f12d27c2dfcc0e246b39eee5601cc0 | 66,570 |
from pathlib import Path
import pandas
def parse_vcf_file(filename: Path, set_index: bool = True) -> pandas.DataFrame:
"""
Converts the VCF file generated by breseq into a pandas Dataframe.
Parameters
----------
filename: Path
Either a folder containing a single breseq run or a path to the vcf file itself.
s... | 290fb561bbf7e2682fc8994ad58897ea27088775 | 66,571 |
def recurrent_unit_bilateral(input_dim, hidden_dim, scope_name, i):
""" Define the recurrent cell in the LSTM. """
params=[]
with tf.name_scope(scope_name+str(i)):
Wi = tf.Variable(init_matrix([input_dim, hidden_dim]), name='Wi_'+str(i)) # weight for input
Ui = tf.Variable(init_matrix([h... | e0ffb715c8dbf82a633e6480a2721aabb8c9874f | 66,572 |
from typing import Union
from pathlib import Path
import platform
def make(
dist_dir: Union[str, Path],
layer: LayerConfig,
silent: bool = False
) -> Path:
"""
Make a layer.
:param dist_dir: the path to the distribution directory
:param layer: the layer configuration
:para... | 48550934af1368d3360b1677ebabedd628af6c7f | 66,573 |
def check_repos(repo_configs: list[RepoInfo], tag: str = None) -> bool:
"""
Check a list of repos to verify that the given tag exists for each repo
:param repo_configs: list of RepoInfo to check
:param tag: Name of the tag to check
:return: True if all of the repos have the requested tag
"""
for repo in r... | df8258c86d43b7ff2678580b8dd1bf09f227809d | 66,574 |
def apply_withdraw(account, amount):
"""Apply atomic transaction for withdraw"""
assert isinstance(account, Account)
assert amount > 0.0
if (account.balance - amount) < 0:
return False
else:
account.balance -= amount
account.save()
return True | 4b34f3ba2e7ef56981334ede442784fa38cc3f3f | 66,575 |
import functools
def compose(*fns):
"""Compose functions."""
def _compose(*args, **kwargs):
return functools.reduce(lambda v, g: g(v),
fns[1:],
fns[0](*args, **kwargs))
return _compose | 118c05955584cb7dd494e0615cccb82c3ccd8142 | 66,576 |
def buy():
"""Buy shares of stock"""
#>>>>>>Distribution code end<<<<<<
# User reacher route via POST
if request.method == "POST":
# Store user input
shares = request.form.get("shares")
symbol = request.form.get("symbol")
# Store current stock information
stock = l... | 9b6f010b77de34a132b2fd08aba95620e60a16eb | 66,577 |
def freeze(module: Module) -> Module:
"""Freeze
Freeze module's parameters (grad to False).
Parameters
----------
module: Module
module to freeze
Returns
-------
module: Module
module with freezed parameters
"""
for param in module.parameters():
par... | a8ed78de299667772b2dae7b947be203aa7751fa | 66,578 |
def command(func, _funcs={}):
"""Decorate functions with this to register them as commands"""
# register the command
func_name = func.__name__.lower()
if func_name in _funcs:
raise Exception('Duplicate definition for command {}'.format(func_name))
_funcs[func_name] = func
# play nice a... | d408b459335e0cfbb7e261e551c429489ca8dcfb | 66,579 |
def expected_sequence(red_on, green_on, blue_on):
"""Generates clock and data sequence expected by the Pimoroni Blinkt! for the colour specified"""
zero = [(1, 0), (0, 0)] # Clock and data sequence representing a zero (0)
one = [(1, 1), (0, 1)] # Clock and data sequence representing a zero (1)
brigh... | b38e222a7b605b4c94332b00bab319761a5a6d30 | 66,580 |
def get_featuretypes(name):
"""
Get the dataset featuretypes.
Parameters
----------
name : str
The dataset name to look for in our object storage.
Returns
-------
bytes
The dataset featuretypes encoded.
Raises
------
NotFound
When the dataset does n... | fe2ab6d64b9d2dbc67ec12289b41a63e5cc247b0 | 66,581 |
import shutil
def cut_paste(src_path, dst_path):
"""Cut paste functionality just copied from shutil. Works on files or dirs.
Args:
src_path (string): Source path to be cut
dst_path (string): Destination path to paste to
"""
shutil.move(src_path, dst_path)
return True | 295eee15f8e31f510333967a45c683ff99c25efb | 66,582 |
from operator import index
def __randUTV_workforjit(A, b, q, p):
"""
Performs the "optimized" randUTV in Figure4 of the paper.
Arguments
---------
A: (m x n) matrix to be factorized.
Gwork: (m x b) matrix that will be used as a work space for the
randomized range finder.
b (in... | f1cc837666b8ba7f0f48b14cad4c05d0e0944bfc | 66,583 |
def get_rot_dir(src_point, rot_rad):
"""Get rotation direction.
Parameters
----------
src_point : tuple of float
Original point.
rot_rad : float
Rotation radian.
Returns
-------
tuple of float
Rotation.
"""
sn, cs = np.sin(rot_rad), np.cos(rot_rad)
... | f5da7e41bf88b6c9016320d49227d95ce411e37f | 66,584 |
def getBase(path):
"""
:param str path:
:return: Base
:rtype: str
"""
return path.split("|")[-1] | a7dd2364531c5e1bea528dae738f60e2c2985d4c | 66,585 |
def get_vectors(x_array, y_array):
"""This function is for calculating vectors of bones from the openpose skelleton"""
vector_joint_idx = [[0,1],[1,2],[2,3],[3,4],[1,5],[5,6],[6,7],[1,8],[8,9],[9,10],[1,11],[11,12],[12,13]]
vectors = []
for i in range(len(vector_joint_idx)):
vectors.append(get_v... | 181433627cae3994594f0f1a9f0fc84271fdde9e | 66,586 |
import requests
def read_all_jobs():
"""API for /read_job endpoint. Read job.
Returns:
DotMap (list of jobs): A DotMap object that contains the details job and its tasks.
"""
logger.debug('web_api/read_all_jobs')
response = requests.get(url="http://localhost:27131/job_status/read_all_jobs... | 2f08fcd7503525641504db68164daeb431af38e2 | 66,587 |
from girs.util.osu import create_tmp_directory, remove_directory # TODO: remove it
import os
import time
import operator
def get_thiessen_weights(point_shp, point_shp_id, polygon_shp, polygon_shp_id,
valid_points=None, work_directory=None):
"""Create Thiessen weights of points in area
... | b6b51fbdb91a7c2c8399c6b9855427a1f85254c4 | 66,588 |
def store_to_db(data):
"""
Store the input in database using SQLAlchemy
"""
# Assign the data to Bug model
bug = Bug(data['description'], data['action'], data['happened'],
data['expected'], data['security'], data['email'], data['browser'],
data['url'], data['screen'], data['c... | e72876aa70ab6bcce49603b05d67125d75ba4b67 | 66,589 |
import re
def parse_and_replace(instring):
""" Parse the input string for tokens, run replacers as needed. """
# Replace the token and command with the command return
instring = re.sub(r"!MyCmd\((.+)\)",
mycmd_replace,
instring)
return instring | dad749f0404c7c780ae201b18dab0d0ac166ab6e | 66,590 |
def get_predicted_points(gameweek, tag, position="all", team="all",
season=CURRENT_SEASON, dbsession=None):
"""
Query the player_prediction table with selections, return
list of tuples (player_id, predicted_points) ordered by predicted_points
"gameweek" argument can either be a ... | 301e69837426c200c16e2a069f2fcc0460c8e92d | 66,591 |
def average_one_rdm(filename, estimator='back_propagated', eqlb=1, skip=1, ix=None):
"""Average AFQMC 1RDM.
Returns P_{sij} = <c_{is}^+ c_{js}^> as a (nspin, M, M) dimensional array.
Parameters
----------
filename : string
QMCPACK output containing density matrix (*.h5 file).
estimator... | 8d83f2235d31edfac9e0f7d46c6c6601035e5adb | 66,592 |
from typing import Dict
from typing import Any
from typing import List
def get_all_external_files(filter_by: Dict[str, Any] = None) -> List[ExternalFile]:
"""
Get information about all external files in the system (note: no user access control)
:return: ExternalFile records
"""
if filter_by:
... | ae96240bd7af26de16f6135a1ad139fb26d91847 | 66,593 |
import os
def gdal_info_stac(input_item):
"""
Return incomplete STAC item from call to gdal.Info
"""
file_url = os.path.join("/vsicurl/" + input_item['item']['assets']['data']['href'])
info = gdal.Info(file_url, format='json', allMetadata=True)
# Calculating geometry and bbox
geometry = i... | fc3aa2c158a59961db9578f25beeac69cce7ed5b | 66,594 |
def data_entry_fields(fields,project,event):
"""
Gets the dataframe containing a specific arm from REDCap
"""
# Get a dataframe of fields
data_entry_raw = project.export_records(fields=fields, forms = forms, format='df', events=event)
return data_entry_raw | 42b562a65609cfc81f7584f86dfced0efcb8aab1 | 66,595 |
import torch
def to_device(m, x):
"""Send tensor into the device of the module.
Args:
m (torch.nn.Module): Torch module.
x (Tensor): Torch tensor.
Returns:
Tensor: Torch tensor located in the same place as torch module.
"""
assert isinstance(m, torch.nn.Module)
devic... | 13d1b9316222ee3f1d03eaca51fd3ab4fc15a0de | 66,596 |
def df_reindex(ts, index = None, method = None, limit = None):
"""
A slightly more general version of df.reindex(index)
:Parameters:
----------------
ts : dataframe or numpy array (or list/dict of theses)
timeseries to be reindexed
index : str, timeseries, pd.Index.
The new inde... | 342847321e1489a6c6aa760fafd1b4756f911ed3 | 66,597 |
def metadata_from_context_data(data):
""" Utility function transforming a `data` dictionary into metadata suitable
for a GRPC stream.
"""
metadata = []
for key, value in data.items():
name = "{}{}".format(METADATA_PREFIX, key)
value = encode_value(value)
metadata.append((name... | f6d5be9768d3a6b830cf31246a6546a21051e88b | 66,598 |
def encodePixel(px):
"""Given an RGB value, convert it to the nearest usable colour, and encode it as a character."""
r, g, b = px[0], px[1], px[2]
rgb = getNearestColour(r, g, b)
wsrgb = list(chars.keys())[list(chars.values()).index(rgb)]
return wsrgb | 59d6ba71638548fb12eb498d26b31a8c4091a275 | 66,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.