content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def check_region(exon_exp_reg, act_reg, t_nums):
"""Check if exon found in the expected region."""
q_regions = [exon_exp_reg.get(n) for n in t_nums if exon_exp_reg.get(n)]
if not q_regions:
# target exons are not covered with chain
# expected region does not exist actually
return "EX... | 810ef3643fb537d85c14eecab990c2f0e3f00e0c | 3,606,285 |
def __has_punctuation(word):
"""Check punctuations"""
return any(char in punctuation for char in word) | 5dd05c9994a8622ca0f941f3e921dcd869b7e2fe | 3,606,286 |
def trA(p):
"""
Compute the partial trace of A of the composed matrix of two subsystems A and B
Arguments:
p -- square matrix of 4 x 4
Return:
pA -- square matrix of 2 x 2
"""
pA = np.matrix([[p[0,0]+p[2,2],p[0,1]+p[2,3]],[p[1,0]+p[3,2],p[1,1]+p[3,3]]])
return pA | 5f2c58f549db22e3604feb6b146d07f781a6fd0d | 3,606,287 |
def logout_user():
""" logout a user and remove session data """
session.pop('username')
flash("Goodbye!", "info")
return redirect(url_for('home_page')) | dbade6ea1bd8e814982c84a215a742725768ac9c | 3,606,289 |
def get_least_squares_size(modelform, r, m=0, affines=None):
"""Calculate the number of columns in the operator matrix O in the Operator
Inference least-squares problem.
Parameters
---------
modelform : str containing 'c', 'A', 'H', 'G', and/or 'B'
The structure of the desired reduced-order... | 86cf6a0b3e4b256eaccb3f061d21f7de74dcc604 | 3,606,290 |
def nfvi_compute_initialize(config, pool):
"""
Initialize the NFVI compute package
"""
global _compute_plugin
if _compute_plugin is None:
_compute_plugin = NFVIComputePlugin(config['namespace'], pool)
if _compute_plugin.ready_to_initialize(config['config_file']):
_compute_plugin... | b84c292cc1b4d2d06f9862e63af87a17c02c2b46 | 3,606,291 |
import copy
def continuumTelluric(data, model=None):
"""
Return a continnum telluric standard data.
Default: return a telluric flux of mean 1.
Parameters
----------
data: spectrum object
The input telluric data to be continuum
corrected
model: (optional) model obje... | c299eae906cd87d352ec6cbc0e207c6a4cc9f942 | 3,606,292 |
def read(rows):
"""Reads the list of rows and returns the sudoku dict.
The sudoku dict maps an index to a known value. Unknown values are not written.
Indices go from 0 to 80.
"""
sudoku = {}
i = 0
for rn, row in enumerate(rows):
if rn in (3, 7):
continue
j = 0
... | 1f1a06a32d1be70f3d912bd42b9cca07f7d4879d | 3,606,293 |
from typing import Union
from re import T
from typing import Any
def _eval_decoder(obj: Union[str, T]) -> Union[Any, T]:
"""
Decoder function to help decoding string objects to objects using the Python interpeter.
If a non-string object is passed it will return the argument
"""
if isinstance(obj,... | 54170adeac71815eace9ec3ba8b90047431f396a | 3,606,295 |
def uniquify(iterable):
"""Remove duplicates in given iterable, preserving order."""
uniq = set()
return (x for x in iterable if x not in uniq and (uniq.add(x) or True)) | 563953cc6450a0136a4996d4a5f5a0057f6ad69b | 3,606,296 |
def count_candidate_votes(candidate_dict: dict, csv_data: list) -> dict:
"""
Go through the candidate list and count the number of votes each time it appears.
:param candidate_dict:
:param csv_data:
:return:
"""
# Go through the csv and get the candidate's name
for row in csv_data:
... | b2ca61d78183c1b152e22bb413ebb89a8dff8b0a | 3,606,298 |
def model_resnet50_keras(
input_shape: tuple, classes: int,
include_top=True, weights='imagenet',) -> keras.Model:
"""
Keras Applicationsに用意されているResNet50を読み込む。
Deep Residual Learning for Image Recognition
Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun
https://arxiv.org/abs/1512.03385
... | e6ba286d3ac2fb93d4d985c67e7d270e627034f7 | 3,606,299 |
def point_in_ellipse(point: Vector, center: Vector, angle: float, length: float, width: float) -> bool:
"""
Check if a point is inside an ellipse
:param point: a point
:param center: ellipse center
:param angle: ellipse main axis angle
:param length: ellipse big axis
:param width: ellipse s... | 66d040ed3a7f04ee9a03d07690e330c156af17a2 | 3,606,300 |
def __getDeviceByUDN(deviceElements, udn):
"""Search and return the device element defined by the UDN from the listDevices elements"""
for device_element in deviceElements:
if device_element.getAttribute("udn") == udn:
return device_element | 84d271b18dbcdf60688c1d921469bef45b4e4721 | 3,606,301 |
def parse_url(url: str) -> SFTPUrl:
"""Parse and validate url."""
if not url.startswith("sftp://"):
url = "sftp://" + url
parts = urlparse(url)
if parts.scheme != "sftp":
raise ValueError("Invalid url: scheme must be 'sftp'.")
if not parts.hostname:
raise ValueError("Invalid ... | 2b5823c66f7fedc2e6e892cc28baa15d59c0d874 | 3,606,303 |
def get_location_coordinates(siteid, roomid):
"""
Given a site and room, returns the co-ordinates of this location.
:param siteid:
:type siteid: str
:param roomid:
:type roomid: str
:raise Location.DoesNotExist: If the site can not be found
:returns: latitude and longitude, or None,No... | 3c0f0fcf792fe878fad96827b9727a3fdb6a8a87 | 3,606,304 |
from typing import Dict
def replacement_map_from_symbol_table(
old: SymbolTable, new: SymbolTable, prefix: str) -> Dict[SymbolNode, SymbolNode]:
"""Create a new-to-old object identity map by comparing two symbol table revisions.
Both symbol tables must refer to revisions of the same module id. The sy... | 5af51be994e43eeb16ac4792208b4c7f525cbc7c | 3,606,305 |
from typing import Union
from typing import Optional
import numpy
import torch
def si_sdr_pit_loss(
est: Union[np.ndarray, pt.Tensor],
ref: Union[np.ndarray, pt.Tensor],
zero_mean: Optional[bool] = False,
clamp_db: Optional[float] = None,
) -> Union[np.ndarray, pt.Tensor]:
"""
Computes the neg... | e802aee6ad0017cb8666ee0f54049496e56e6c4b | 3,606,306 |
def get_file_content_safe(path):
"""
Checks if the file on location 'path' exists, and if it does it returns
each line of text in the file as a list of strings. If not, the function
runs an ERR_CODE_NON_EXISTING_FILE error.
Arguments:
path: path to file
Returns:
List of lines o... | 93beeca3c1b84b85814f39829a904033ffbb8277 | 3,606,307 |
import pytz
from datetime import datetime
import time
def get_response(service_call, method, **kwargs):
"""Returns response from youtube service and handles API rate limit by
sleeping until API is available again.
Example
-------
service.playlistItems().list(**kwargs) can be retrieved as
>>... | 39838cc6e5ef7cec1af7267aca7cae0e064e24ce | 3,606,309 |
from requests_cache import CachedSession
def ensure_requests_session(config):
"""Build the singleton requests.Session (or subclass)
"""
session_attr = "check_links_requests_session"
if not hasattr(config.option, session_attr):
if config.option.check_links_cache:
conf_kwargs = geta... | 6e65e9101c8fd5a6f16645042b96ddb0a9b3ff20 | 3,606,310 |
def createTable(c):
"""This makes a table
Keyword arguments:
c -- the cursor object of the connected database
"""
try:
c.execute("""
CREATE TABLE IF NOT EXISTS members (
username TEXT,
password TEXT
);
""")
except:
print("Error")
... | 37e7eb9fda45871c0b8890c3111c920d608f80fb | 3,606,311 |
def stratified_cross_fold_knn(table, num_folds, k, class_index):
""" Uses knn and stratified cross folding to predict labels
:param table: a table of data
:param num_folds: the number of folds to calculate
:param k: the number of nearest nieghbors
:param class_index: the index where the class label... | 1c1af7fec43f672ae6eb541d675e1cd724add7d6 | 3,606,312 |
from datetime import datetime
from dateutil import tz
def time_ago(time=False):
"""
Get a datetime object or a int() Epoch timestamp and return a
pretty string like 'an hour ago', 'Yesterday', '3 months ago',
'just now', etc
Modified from: http://stackoverflow.com/a/1551394/141084
"""
now ... | 7cc27e885f84cdb4e06b79e0c40ee0aa204205d1 | 3,606,314 |
import _omniidl
def relativeScope(fromScope, destScope):
"""relativeScope(fromScope, destScope) -> list
Given two globally-scoped names, return a minimal scoped name list
which identifies the destination scope, without clashing with another
identifier. For example, given IDL:
module M {
typedef short A;
... | 7edb5bf137a4a751fad7a3f4d2946eba592aab88 | 3,606,316 |
import math
def k_0(nu, n, B, q=q_e, m=m_e):
"""
Coefficient ``k_0`` in absorption coefficient.
:param nu:
Frequency of radiation [Hz].
:param n:
Concentration [cm ** (-3)]
:param B:
Magnetic field [G]
:param q (optional):
Particle's charge. Default is ``q_e``.
... | 1d5700bfe40104d566696c37ed5f12eefd28bb8a | 3,606,317 |
def rogerstanimoto(u, v):
"""
Finds the Rogers-Tanimoto dissimilarity between two 1-D bool arrays.
.. math::
\\frac{ 2 \cdot \left(c_{TF} + c_{FT}\\right) }
{ c_{TT} + 2 \cdot \left(c_{TF} + c_{FT}\\right) + c_{FF} }
where :math:`c_{XY} = \sum_{i} \delta_{u_{i} X} \delta_{v_{i} Y}... | 88da4a71dc08dd4ba07c59c6d466d5714811ca9d | 3,606,318 |
import re
def checkLine(text):
"""
:param text:
:return:
>>> checkLine('1-3 a: abcde')
True
>>> checkLine('1-3 b: cdefg')
False
"""
m = re.match(r'(\d*)-(\d*)\s([a-z]):\s(\w+)', text)
low, high, letter, password = m.group(1, 2, 3, 4)
# print(low, high, letter, password)
occurencies = len(re.findall(let... | c9795cfd8c51bec3bf14acbd84618065ee72f82d | 3,606,319 |
def badFormatting(s, charSet):
"""Tells if a character from charSet appears in a string s."""
for c in charSet:
if c in s:
return True
return False | 23baba28be306e0d0c1ccaa0df48e1a9f94bdc8c | 3,606,320 |
def add_cp_analysis():
"""Submit files for static analysis
Files within zip archives will be submited separately.
This endpoint should be called only after files have been uploaded via
:http:post:`/cp/1.0/samples`. Also accepts :http:method:`put`.
**Example request**:
.. sourcecode:: http
... | 049463d8180d42aa0cf3a58027682545888f650e | 3,606,321 |
def Hamiltonian_from_file(file_name):
"""Creates a matrix operator out of a file with a list
of Paulis.
Args:
file_name : a text file containing a list of Paulis and
coefficients.
Returns:
A matrix representing pauli_list
"""
with open(file_name, 'r+') as file:
h... | 2a7d7f516bba52c5ee7be91588427fcc9d0bc61c | 3,606,322 |
def column_to_width(df_in, column, width):
"""Pad the column header and the values in the column with whitespace to a
specific width.
"""
df = df_in.copy()
df[column] = df[column].apply(lambda x: ('{:>' + str(width) + '}').format(x))
df = df.rename(columns={column: ('{:>' + str(width) + '}').f... | 988f021c7ff2f296ecacd83ddbced0de6404e3fc | 3,606,323 |
def view_proxy(request, promo_id, hash):
"""Track a view of a promotion and redirect to the image."""
promo = get_object_or_404(SupporterPromo, pk=promo_id)
if not promo.image:
raise Http404('No image defined for this promo.')
count = cache.get(promo.cache_key(type=VIEWS, hash=hash), None)
i... | 2eb36e212586a376e67c32edcb737ace069b73b0 | 3,606,324 |
def use_netrc(netrc, urls, patterns):
"""compute an auth dict from a parsed netrc file and a list of URLs
Args:
netrc: a netrc file already parsed to a dict, e.g., as obtained from
read_netrc
urls: a list of URLs.
patterns: optional dict of url to authorization patterns
Returns:
... | 561ee1388dbdde74614fdef1fb29b78c7ecc687b | 3,606,325 |
def str_cutoff(string: str, max_length: int, cut_tail: bool = False) -> str:
"""
Abbreviate a string to a given length.
The resulting string will carry an indicator if it's abbreviated,
like ``stri#``.
Parameters
----------
string : str
String which is to be cut.
max_length : i... | 05fdab8700dd07710c31d4007c9bc6b3f9eb6155 | 3,606,326 |
def bresenham(p0, p1, array=None):
"""
Line drawing in a grid
:param p0: initial point
:type p0: array_like(2) of int
:param p1: end point
:type p1: array_like(2) of int
:return: arrays of x and y coordinates for points along the line
:rtype: ndarray(N), ndarray(N) of int
Return x ... | be4fbce15ae53e1cd84aac51689b0454e6830fa6 | 3,606,327 |
from typing import List
def observations_from_data(experiment: Experiment, data: Data) -> List[Observation]:
"""Convert Data to observations.
Converts a Data object to a list of Observation objects. Pulls arm parameters from
from experiment. Overrides fidelity parameters in the arm with those found in th... | 4b6ea01899754e87e6badbbd65e2e0e9e2ae5c7b | 3,606,328 |
def is_over(board):
"""Returns True if the game is over, False if not"""
for player in range(2):
for move_x in range(board.height):
for move_y in range(board.width):
list_near_points = [] #list of the number of the player payns in each direction starting from the last one beg... | 9302d53f72ece8928763a70b10fb265bc6b8151b | 3,606,329 |
def wireless(card, mode=None, apn=None):
"""Retrieve wireless modem info or customize modem behavior.
Args:
card (Notecard): The current Notecard object.
mode (string): The wireless module mode to set.
apn (string): Access Point Name (APN) when using an external SIM.
Returns:
... | 355256bd8123f0f749561f61a2df3be93b91db61 | 3,606,330 |
def filter_none(x):
"""
Recursively removes key, value pairs or items that is None.
"""
if isinstance(x, dict):
return {k: filter_none(v) for k, v in x.items() if v is not None}
elif isinstance(x, list):
return [filter_none(i) for i in x if x is not None]
else:
return x | c1c478b2c367dd9453b5504bbfece7dfd8c05376 | 3,606,331 |
def get_task_mapping(task: str) -> str:
"""
Map the task in problem_doc to the task types that are currently supported
Parameters
----------
task: str
The task type in problem_doc
Returns
-------
str
One of task types that are supported
"""
mapping = {
... | 2dcff89a6bd924ad895f809e66960c047ab545ca | 3,606,332 |
def _dmet_orb_list(mol, atom_list):
"""Rearrange the orbital label
Args:
mol (pyscf.gto.Mole): The molecule to simulate.
atom_list (list): Atom list for IAO assignment (int).
Returns:
newlist (list): The orbital list in new order (int).
"""
newlist = []
for i in range(m... | 7998d9cec104bc02ad3daf600d2e24d9b1f5f243 | 3,606,333 |
from typing import Iterable
from typing import Optional
from typing import Sequence
from typing import Tuple
def _determine_domain_pairs_to_check(all_domains: Iterable[Domain],
domains_changed: Optional[Iterable[Domain]],
constraint: Constraint... | d210397b7c07fce9e4c9055bbfcce96ed0ef7659 | 3,606,334 |
def _post_processing(metric_map: dict[str, float]) -> dict[str, float]:
"""
unit conversion etc...
time:
taskTime, executorDeserializeTime, executorRunTime, jvmGcTime are milliseconds
executorDeserializeCpuTime, executorCpuTime are nanoseconds
"""
metric_map["executorDeserializeCpuTime"] = ... | 23ff301d55e0dc2d2208aca5761059fb8ade3e4e | 3,606,335 |
def decryptData(key, data, mode=AESModeOfOperation.ModeOfOperation["CBC"]):
""" Module function to decrypt the given data with the given key.
@param key: key to be used for decryption
@param data: data to be decrypted with initialization vector prepended
@param mode: mode of operations ... | 24b0f380d8bfe4d5d4ec358f394a125914eef2eb | 3,606,336 |
from typing import Sequence
from typing import Any
def get_batches(task_family: tasks_base.TaskFamily,
batch_shape: Sequence[int],
train_and_meta: bool = False,
numpy: bool = False,
split: str = "train") -> Any:
"""Get batches of data with the `batch_s... | 5c6c0ffb217a3b5c81e3c1f7c10767dc4b8cf872 | 3,606,337 |
import re
def wildcard_to_regex(wildcard):
"""
Converts a * syntax into a parsed regular expression
Maya wildcard validation:
1. Maya does not support '-' characters so we change those characters by '_'
2. Maya uses | as separators, so we scape them
3. We need to replace any '*' i... | aa8460305a6129d1a114845882dfcf29b547431b | 3,606,338 |
def plot_concentration_comparison(
posterior: Dataset, conc: pd.DataFrame
) -> Figure:
"""Compare physiological concentrations with kms."""
biology_cols = [
"Organism",
"ECNumber",
"UniprotID",
"parameter.associatedSpecies",
]
conc_mean = pd.Series(
pd.Series(... | a5b0448dacbaa292346b6fa32098980e33939f5c | 3,606,339 |
def make_il8n_image_carousel_column(number, action):
"""
Create a multilingual image carousel column object.
reference
- https://developers.worksmobile.com/jp/document/100500809?lang=en
- Check also: attendance_management_bot/model/data.py::make_image_carousel_column
"""
i18n_im... | b1bb8f11fd048c77e17b3059caf3594516128153 | 3,606,340 |
import math
def math_sqrt(number):
"""
Math.sqrt, according to Copilot
"""
global test_num
test_num += 1
return math.sqrt(number) | 346530a675229493ceac0723691b80ad996c5f92 | 3,606,341 |
from typing import Dict
import multiprocessing
import tqdm
def preprocess_papers_parallel(papers_dict: Dict, n_jobs: int, preprocess: bool) -> Dict:
"""
helper function to preprocess papers
Parameters
----------
papers_dict: Dict
the papers dictionary
n_jobs: int
how many cpus... | 38c98ec69d7cdbe1601f4c0e235b6b3b56bc8071 | 3,606,342 |
def build_generation_graph(cell, out_weights, out_biases, previous_state,
in_data, temperature):
""" Build one step lstm graph used in generation. """
state = []
# Reformat previous state to fit tensorflow requirements.
for i in range(previous_state.shape[0]):
state.ap... | 4a2e57d7642a37a50243993ee23a905ee7a58aa4 | 3,606,343 |
def create_ecs_task(cluster_arn_or_name, task_definition, region=DEFAULT_REGION):
"""
Create an ECS task with EC2 launch type in given cluster.
Wait till the task gets into RUNNING state
:param cluster_arn_or_name:
:param task_definition:
:param region:
:return: task_arn if task gets into RU... | 77051d7cfaac4e5d1e3194b4a932120156883ee4 | 3,606,344 |
from bs4 import BeautifulSoup
import requests
def get_soup(url: str) -> BeautifulSoup:
"""Get an instance of BeautifulSoup for a specific url"""
response = requests.get(url)
if response.status_code != requests.codes.ok:
print(f"url request error: response.status_code is {response.status_code}")
... | 34f172c2d6d2d7928d93f3a11768cc45272fc399 | 3,606,345 |
def producto_matrices(matriz_A, matriz_B):
"""
(list of list, list of list) -> list of list
Realiza el producto de matrices
>>> producto_matrices([[1,2], [3, 4]],[[1,2], [3, 4]])
[[7, 10], [15, 22]]
:param matriz_A:
:param matriz_B:
:return: list of list la matriz A * B
"""
r... | 9f2f3acad173f8e065ef41dd3492a2344b6f1327 | 3,606,346 |
def quaternion_upper_hemispher(q):
"""
The quaternion q and −q represent the same rotation be-
cause a rotation of θ in the direction v is equivalent to a
rotation of 2π − θ in the direction −v. One way to force
uniqueness of rotations is to require staying in the “upper
half” of S 3 . For examp... | 1a95442fa0016aa02968c294110b540391d35550 | 3,606,347 |
from typing import List
def sieve_of_eratosthenes(upper_bound: int) -> List[Prime]:
"""
Creates a Sieve of Eratosthenes from 0 to upper_bound
params:
upper_bound: Upper-Bound for the sieve
return:
Ordered list of all primes less than upper_bound
"""
# Assume everything is pr... | 7069925eb2147f32bf7fed17a5c006723eb6d576 | 3,606,349 |
def times_to_lags(T):
"""(N x n_step) matrix of times -> (N x n_step) matrix of lags.
First time is assumed to be zero.
"""
assert T.ndim == 2, "T must be an (N x n_step) matrix"
return np.c_[np.diff(T, axis=1), np.zeros(T.shape[0])] | 2f46a3a3049d374cc2af493b2c821ae04e35ca10 | 3,606,351 |
def atcab_write_zone(zone, slot, block, offset, data, length):
"""
Executes the Write command, which writes either 4 or 32 bytes of data into a device zone.
Args:
zone Device zone to write to (0=config, 1=OTP, 2=data). (int)
slot If writing to the data zone, it... | 17b4425c9c1630a77ad1abd29d8ed2e125a2afe8 | 3,606,352 |
def eexp(db, hb, rhop, mp):
"""
Calculates the overall void fraction of the expanded bed.
Parameters
----------
db : float
Diameter of the bed [m]
hb : float
Height of the expanded bed [m]
rhop : float
Mass density of the solids [kg/m^3]
mp : float
Mass o... | 91fb481e6b4aa790d789c334b90c8d2c197f362d | 3,606,353 |
def attendant_allowed(function):
"""
allows access for attendants only
"""
@wraps(function)
@jwt_required
def wrapper(*args, **kwargs):
"""wrapper for the function"""
verify_jwt_in_request()
claims = get_jwt_identity()
if type(claims) == dict:
if clai... | e0b200dac06de50f3ef420e359758aa4246b524a | 3,606,354 |
def dataarray_to_matrix(grid):
"""
Transform a xarray.DataArray into a data 2D array and metadata.
Use this to extract the underlying numpy array of data and the region and
increment for the grid.
Only allows grids with two dimensions and constant grid spacing (GMT
doesn't allow variable grid ... | 569f77a4939152a282360411e19aa9e05ace0085 | 3,606,355 |
def is_lock_expired(
end_state: NettingChannelEndState,
lock: HashTimeLockState,
block_number: BlockNumber,
lock_expiration_threshold: BlockNumber,
) -> SuccessOrError:
""" Determine whether a lock has expired.
The lock has expired if both:
- The secret was not register... | 02c4e5e8f5549c1eb56e422bdde52ce0de22a3d1 | 3,606,356 |
def get_genre_by_id(genre_id):
"""
Returns genre name from moviedb API given genre id
"""
# get movie genres
movie_genres_url = f'/genre/movie/list?api_key={MOVIEDB_API_KEY}'
movie_genres_data = get_moviedb_data(movie_genres_url)
# get tv genres
tv_genres_url = f'/genre/tv/list?api_key={MOVIEDB_API_KEY... | 729998058a1e4b14034168e09bae6e9b230d0092 | 3,606,358 |
def get_unique_node(name, node_type, meta_type):
"""
Gets or creates a NodeHandle with the provided name.
Returns the NodeHandles node.
"""
name = normalize_whitespace(name)
node_handle = utils.get_unique_node_handle(name, node_type, meta_type)
node = node_handle.get_node()
return node | 930c5f16874f7657a6d6517a7f47ed9154b81108 | 3,606,359 |
def get_leaf_artists(root_artist, matchfunc):
"""Return all the leaf artists.
which
Args:
root_artist: Artist.
matchfunc: callable: artist -> bool.
Return:
All the decendant Artists matched with `matchfunc`.
Note
----
As you might notice, this class is similar to `... | 63b7304137cfc502cd22b17be6b4869a7fff879b | 3,606,360 |
def str_to_numlist(s, bound):
"""
Returns a sequence of integers between 0 and bound-1
that encodes the string s. Randomization is included,
so the same string is very likely to encode differently
each time this function is called.
Input:
s -- a string
bound -- an integer >... | 1ed62018d5612bd465a3899fb17d0faa823e42d2 | 3,606,361 |
def intersect(hrect, r2, centroid):
"""
checks if the hyperrectangle hrect intersects with the
hypersphere defined by centroid and r2
"""
maxval = hrect[1, :]
minval = hrect[0, :]
p = centroid.copy()
idx = p < minval
p[idx] = minval[idx]
idx = p > maxval
p[idx] = maxval[idx]
... | 6050742ae4527f5baba3c6cb8a484b04d32c0b3c | 3,606,362 |
def extract_value_at_points2d(points: tf.Tensor,
value_map: tf.Tensor,
denormalize: bool = True) -> tf.Tensor:
"""Extracts value at given points from value_map (e.g., SDF map).
Args:
points: [batch_size, num_point, 2] tensor, (x, y) coordinates of poi... | d37f2d9a08269e315f545343eecb499eea0a8c6b | 3,606,363 |
from typing import Mapping
from typing import List
def _ExtractRemoteGraphOutput( # pylint: disable=invalid-name
pcoll: beam.pvalue.PCollection,
parent_remote_op_name: str,
child_remote_op_name: str,
remote_op_name_to_graph_name: Mapping[str, str],
graph_name_to_specs: Mapping[str, List[execution... | 05419ad7fb942ae8789fbbd704a9996e42b2beea | 3,606,364 |
def ISTORE_name(context, name):
"""Generate the opcode to store a variable with the given name.
This looks up the local variable dictionary to find which
register is being used for that variable, using the optimized
register operations for the first 4 local variables.
"""
try:
index = c... | 2d4860dbdc948d00b1f7684fc84ba3b4e87bb9bf | 3,606,365 |
def normalize(text):
""" Normalize whitespace for a string of html using tidy. """
return str(tidy.parseString(text.encode('utf-8', 'xmlcharrefreplace'),
drop_empty_paras=0,
fix_backslash=0,
fix_bad_comm... | 3d7eb09ba90146a36e9ef34a131bb74b7d5406e6 | 3,606,366 |
from datetime import datetime
def setup_pv_system(month, hour_of_day):
"""
This method is just basic setup
"""
offset = 0
when = [datetime(2020, month, 15, hour_of_day, 0, 0,
tzinfo=timezone(td(hours=offset)))]
time = pd.DatetimeIndex(when)
sandia_modules = pvlib.pvsy... | 5c8847a9d5f3d8725a88e4acdd8832d8af1991ca | 3,606,367 |
from pathlib import Path
import logging
def compress(file: Path, output_dir: Path, remove_original=True) -> None:
"""Replaces the original file with a compressed version"""
logging.info("Compressing {}".format(file))
compressed_file = output_dir.joinpath(file.stem).with_suffix(file.suffix + ".zst")
cc... | 0d356df1d5ef6efb7492e0489caaa4880a167e12 | 3,606,368 |
import re
def remove_trailing_commas(json_like):
"""
Removes trailing commas from `json_like` and returns the result.
Examples
--------
>>> remove_trailing_commas('{"foo":"bar","baz":["blah",],}')
'{"foo":"bar","baz":["blah"]}'
"""
trailing_object_commas_re = re.compile(
r'(,... | 0d51b1cb7508ab00ec353a1446210b6e44c64c58 | 3,606,369 |
def is_method_of(method, obj):
"""Return True if *method* is a method of *obj*.
*method* should be a method on a class instance; *obj* should be an instance
of a class.
"""
# Check for both 'im_self' (Python < 3.0) and '__self__' (Python >= 3.0).
cls = obj.__class__
mainObj = getattr(method... | 554ab48effb7ce996846192786ce2141abf671a4 | 3,606,370 |
def edit_savings_entry(savings_entry_id):
""" Edit savings entry """
entry = SavingsEntry.query.get(savings_entry_id)
savings_form = SavingsForm(obj=entry)
if savings_form.validate_on_submit():
entry.savings_date = savings_form.savings_date.data
entry.transaction_type = savings_form.tr... | da39ae75333bfe61bf2c07809adfc25ea4dfeba2 | 3,606,371 |
def generator_proportion_eia923(g, id_col='plant_id_eia'):
"""
Generate a dataframe with the proportion of generation for each generator.
Args:
g (pandas.DataFrame): a dataframe from either all of generation_eia923
or some subset of records from generation_eia923. The dataframe
... | 9a61432a69adf3fcee7276acb05ced497f880042 | 3,606,372 |
def copy(source_username,
source_path,
target_username,
target_path,
name=None):
"""Copy a user file into target_path dir."""
f = open(source_username, source_path)
return save(target_username, target_path, f, name=name) | 9689d57364bdca6def0acfd2b5d8ddfe815af35a | 3,606,373 |
from typing import Counter
def parse_sample_sheet_into_idat_datasets(sample_sheet, sample_name=None, from_s3=None, meta_only=False, np=1):
"""Generates a collection of IdatDatasets from samples in a sample sheet.
Arguments:
sample_sheet {SampleSheet} -- The SampleSheet from which the data originates.... | cdb608833e347db9ece5f92dfc33bdd35a0a3627 | 3,606,374 |
def build_minimum_permissions(config):
"""Build the minimum permissions required to operate."""
email_sensors = config.get(CONF_EMAIL_SENSORS, [])
query_sensors = config.get(CONF_QUERY_SENSORS, [])
status_sensors = config.get(CONF_STATUS_SENSORS, [])
minimum_permissions = [PERM_MINIMUM_USER, PERM_MI... | 8d9fe8498120a3b345915a7e02c4a8dbd4f49c22 | 3,606,375 |
def nanwrapper(f, x):
"""numpy freaks out if you pass an empty arrays
to many of its functions (like min or max).
This wrapper just returns a nan in that case.
"""
if len(x) == 0:
return np.nan
else:
return f(x) | f08cade024150d2a257dc7ea23912dfe4d89c49f | 3,606,376 |
def backend(name='jax'):
"""Returns the backend used to provide fastmath ops ('tf' or 'jax')."""
if override_backend:
return _get_backend_from_string(override_backend)
if default_backend:
return _get_backend_from_string(default_backend)
if isinstance(name, Backend):
return _backend_dict[name]
#... | adc5e355e01c40452bbfa5c54765865944990be0 | 3,606,377 |
import ast
def correlation_calculations(whole_graph, ds_le, raw_data):
""" Function to calculate correlations of l_e with dA, edge betweenness, product of node weights and product of node strengths.
Parameters:
raw_data: pandas edgelist dataframe, with columns seller id, buyer id total value... | c7b22cbf5a3065c359d2444cccdff5e32506fced | 3,606,378 |
def make_continious_dataframe(movies_df):
"""Transform rating data with continuous user and movies ids
Input dataframe: Takes in a pandas dataframe
Output it returns 1. movie_ids: Mapping of original movie id to continious column
2. num_movies: Total number of movies
... | 4b2d5f7cd287c2023b7381d617041ab81bf74520 | 3,606,379 |
def within_error(flag_name: str, key_name: str, within_list: list):
"""
:param flag_name:
:param key_name:
:param within_list:
:return:
"""
if key_name not in within_list:
logger.error(f"<ScaffoldBuild> Wrong input parameter: --{flag_name}=`{key_name}` @ "
f"Thi... | f527bc5b6206d4f138be97135565afedcdea86fa | 3,606,380 |
def get_cauldron_module():
"""
Returns the cauldron module loaded from the import library, or None if
the Cauldron module could not be loaded.
"""
try:
return import_module('cauldron')
except Exception:
return None | 3617deaddc77e9b9e9c29d56f84e508e8bc42362 | 3,606,383 |
def callback(func):
"""
A decorator to add a keyword arg 'callback' to execute a method on the return value of a function
Used to add callbacks to the API calls
:param func: The function to decorate
:return: The wrapped function
"""
def wrap(*args, **kwargs):
callback_ = kwargs.po... | a2599306d091bc48df5ab1ca90e34f4529c85cab | 3,606,385 |
def _cluster_measure(group):
"""Measure the distance between all points in a group from the centroid.
:param group: the group of points all belonging to the same cluster.
:returns: float -- mean value of the group.
"""
points = group[[0, 1]]
centroid = points.sum() / group.size
distances = ... | e0047dc020d3cf7dca5ff0191da58ec741041dbf | 3,606,386 |
from typing import ItemsView
from typing import Tuple
from typing import Dict
from typing import Any
def _instancecheck_items_view(items_view: ItemsView, type_args: Tuple, type_vars: Dict[TypeVar_, Any]) -> bool:
"""
>>> from typing import Any, Optional
>>> _instancecheck_items_view({0: 1, 1: 2, 2... | 4997f80f4344728b96c4931e41bd2af08616f0f0 | 3,606,387 |
def remove_dups_stringlist(str):
"""Remove duplicates from list as string"""
arr = str.split(',')
arr = list(dict.fromkeys(arr))
return ','.join(arr) | ac54bbfa9c48f730ffd29db0a2cd210b1f3a7c79 | 3,606,388 |
def get_lr_opt_global_step():
"""Intializes learning rate, optimizer and global step."""
optimizer = get_optimizer(CONFIG.OPTIMIZER, CONFIG.OPTIMIZER.LR.INITIAL_LR)
global_step = optimizer.iterations
learning_rate = optimizer.learning_rate
return learning_rate, optimizer, global_step | 0d5ef31715ac4948f3dec144d51fa12aa92dd330 | 3,606,389 |
from typing import Tuple
def _get_image_format(
ctx: cl.Context, num_channels: int, dtype: np.dtype, ndim: int, mode: str = "rw"
) -> Tuple[cl.ImageFormat, bool]:
"""Maximize chance of finding a supported image format for the current device.
Parameters
----------
ctx : cl.Context
The Cont... | 71dadb96cc13048b6ace3472e1e0f24498fb84ee | 3,606,390 |
def skewDiagram(sequence):
"""Draw the skew diagram (#G - #C) for dna."""
skew = 0
skewList = []
for nt in sequence:
if nt == 'C':
skew -= 1
elif nt == 'G':
skew += 1
skewList.append(skew)
plt.plot(range(len(sequence)), skewList)
plt.xlabel('Pos... | 8110e236d0bb54d62929effc735c7ced51479374 | 3,606,391 |
def _get_instance_masks_and_boxes_np(instance_img):
"""Get instance level ground truth.
Note: instance_img is expected to consist of regular ids, not trainIds.
Returns:
masks: (m, h, w) numpy array
boxes: (m, 5), [[x1, y1, x2, y2], ...]
classes: (m,) list of class names
"""
all_i... | 94724ed21af9a19c8bb0700e7b09c5eb97b0f144 | 3,606,392 |
def scoreMatrix(ai):
"""
Returns (rowNames, columnNames, S)
where:
- S is a matrix where S_{ij} represents the score delta
of mutation j against read i
- rowNames[i] is an identifier name for the the read i---presently
we use the the row number within the cmp.h5, encoded as a st... | 9e950b4a0e7f25c0f6fe551279272c96ae022f83 | 3,606,393 |
def is_sorted(items: t.Sequence[int]) -> bool:
"""Check if all items are in sorted order."""
for i in range(1, len(items)):
if items[i-1] > items[i]:
return False
return True | 509841bf99cabc6c31150d184edf86aa070c6b4a | 3,606,394 |
import torch
def dice_loss_norm(input, target):
"""
input is a torch variable of size BatchxnclassesxHxW representing log probabilities for each class
target is a 1-hot representation of the groundtruth, should have same size as the input
"""
assert input.size() == target.size(), "Input sizes must... | e3640a6660df0a572b1b8deccf9d508d7f7e40a9 | 3,606,395 |
def create_app(env_name):
"""Create app
Keyword arguments:
env_name -- enviroment ('development or production')
"""
# app init
app = Flask(__name__)
app.config.from_object(app_config[env_name])
app.register_blueprint(camera_blueprint, url_prefix='/api/v1/camera') #registering camera api
app.confi... | 9042bc23f91e19ef5d36e85f36eb47da05d78b1f | 3,606,396 |
import typing
import socket
def encode_address(addr: StrOrBytes) -> typing.Tuple[AddressType, bytes]:
"""Determines the type of address and encodes it into the format SOCKS expects"""
addr = addr.decode() if isinstance(addr, bytes) else addr
try:
return AddressType.IPV6, socket.inet_pton(socket.AF... | e0d8d8135c055090f2948fe1c0bcaed496f90949 | 3,606,397 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.