content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import requests
def get_filesize(pql_query: str,
datatype: str = "ssm") -> int:
"""
Calls an ICGC Data Portal API to retrieve the file size of the dataset
specified by a PQL query and a data type.
:param pql_query: PQL query to retrieve the dataset of interest.
:param datatype: d... | 3b262e91a51bf4c83012ce77fa4ca3be8430e63e | 597,709 |
def remove_punctuations(text):
"""
Removes all punctuations from the specified text
:param text: the text whose punctuations to be removed
:return: the text after removing the punctuations
"""
return text.replace(r'[^\w\s]', '') | c9e453a5c57de977b6819ced517a3d85e7e43a63 | 597,710 |
def extract_retryable(error):
"""
Extract a retryable status from an error.
It's not usually helpful to retry on an error, but it's useful to do so
when the application knows it might.
"""
return getattr(error, "retryable", False) | 30b5906a53993a42b720a04599aa48db908c6f84 | 597,715 |
def calcular_tiempo_recarga(potencia_pc, capacidad_bateria, rendimiento_carga):
"""
Definicion de la funcion calcular_tiempo_recarga:
Funcion de calculo del tiempo de recarga para un coche
y punto de recarga especifico
Parametros
----------
potencia_pc: float
... | 2ec1b27d8ae436da792552b11b823ce3d8d883f2 | 597,721 |
from typing import Counter
def match_guess_to_answer(answer: str, guess: str, lower: bool = False) -> str:
"""Match the guess to answer and returns the result.
The result is a combination of `C`, `P`, `A`,
where `C` means the letter is in the `correct` position,
`P` means the letter is `present` in t... | bc56d2a2fb0fd071194fb6f637dc4ad70d1c4693 | 597,722 |
import re
def strings(filename, minChars=4):
"""Search printable strings in binary file
:param filename: The file to be read
:type filename: str
:param minChars: Min-len of characters to return string *(default 4)*
:type minChars: int
:returns: List of printable strings
:rtype: list
... | caacb1385fa2676b24d38b9b749cdd6a5a497599 | 597,725 |
def _is_valid_uri(uri: str) -> bool:
"""Perform basic validation of link."""
_invalid_uri_chars = '<>" {}|\\^`'
for c in _invalid_uri_chars:
if c in uri:
return False
return True | 5d538f516bec1cbd237769a5910f165476a24ea2 | 597,731 |
import pkg_resources
def get_pip_packages_csv(writer):
"""
Takes a csv writer and writes installed pip packages to it.
"""
installed_packages = pkg_resources.WorkingSet()
for i in installed_packages:
writer.writerow([i.key, i.version])
return writer | ad0cef7bd0db7af560b38013c94225f99c8eeda4 | 597,732 |
def sRGBToLinearRGB(color):
""" Convert a grayscale value (single channel) value from sRGB to Linear """
# Note that range of input should be 0 to 1
if color < 0:
return 0
elif color < 0.04045:
return color/12.92
else:
return (((color + 0.055) / 1.055) ** 2.4) | 7a3550fcb5068e2fe8385c61d86ae50eb5eae28c | 597,734 |
def add_row(content, row_index, row_info=[]):
"""
From the position of the cursor, add a row
Arguments:
- the table content, a list of list of strings:
- First dimension: the columns
- Second dimensions: the column's content
- cursor index for col
- cursor ... | 99b256ed6581462488d396ece5261ef5fa431b45 | 597,736 |
import six
def bool_(val):
"""Like `bool`, but the string 'False' evaluates to `False`."""
if isinstance(val, six.string_types) and val.lower() == 'false':
return False
return bool(val) | 19684ddfc319e3a87233127273f3e21392281ed6 | 597,737 |
def noise_position(dfSummaries):
"""Utility function to recover the column indices of the noise features.
Args:
dfSummaries (pandas.core.frame.DataFrame):
the pandas DataFrame containing, for each simulated data (in rows),
the summary statistic values (in columns).
Returns:... | b8e37647677a08272a05e5668f1f2f905fb4f34c | 597,738 |
def select_subset_by_steps(dataframe, steps):
"""
Given a pandas dataframe from PELE's result it returns a subset of n PELE steps.
:param dataframe: pandas object
:param steps: int
:return: dataframe
"""
subset = dataframe[dataframe['Step'] <= int(steps)]
return subset | 3549642b1b033ad2fe94d1b846f11c43adf89937 | 597,739 |
def cat(files, join_str=''):
"""Concatenate `files` content with `join_str` between them."""
files_content = (open(f).read() for f in files)
return join_str.join(files_content) | 21e360c50752702b8a112d5ded12e21e5ae3f5dc | 597,740 |
from typing import Callable
from typing import Any
import time
def _pytimed(callback: Callable[..., None], *args: Any, **kwargs: Any):
"""Call the given callback and return time in nanoseconds as result."""
start_time = time.monotonic_ns()
results = callback(*args, **kwargs)
end_time = time.monotonic_ns()
d... | 1d7ece3d4da8fdb4305d96e1a7623bd2e3a9a89e | 597,742 |
def get_subpages(soup):
"""Images can be found on separate pages. Extract the URL of these subpages."""
pages = []
for tag in soup.findAll('li', {'class' : 'image'}):
a = tag.find('a', href=True)
if a:
pages.append(a['href'])
return pages | 1338e5e80c30b99538b89f6216a4276c857ed1b3 | 597,746 |
def parse_time(value):
"""Parse a time interval string into a floating point seconds value.
Supported formats include:
ss (seconds)
ss.dd (seconds with decimals)
mm:ss (minutes and seconds)
mm:ss.dd (minutes and seconds with decimals)
... | 7d494e9d62bbe1cb0a20425e04c5ef2192394cc4 | 597,747 |
def make_worlist_trie(wordlist):
"""
Creates a nested dictionary representing the trie created
by the given word list.
:param wordlist: str list:
:return: nested dictionary
>>> make_worlist_trie(['einander', 'einen', 'neben'])
{'e': {'i': {'n': {'a': {'n': {'d': {'e': {'r': {'__end__': '__... | b116d14ca342124696cee1409feef544f605f42f | 597,757 |
import json
def load_input_blocks(path):
""" Load stored blocks from disk e.g.,
load_input_blocks('./testdata/btc_blocks_json_samples/300000--300007')
"""
with open(path) as json_file:
blks = json.load(json_file)
return blks | 8b6c75411e4dc7e2d429ee57471f06fc3af6fdb0 | 597,758 |
def sc_and_bcc_kps(kmax):
"""Lists the k-point densities up to kmax for the sc and bcc cases.
Args:
kmax (int): The largest allowed k-point density.
Returns:
kpds (list): List of the allowed k-points for sc and bcc systems.
"""
kpds = []
for k in range(kmax):
for m in ... | 63bf1912583554348d0ad6652374d950e1011601 | 597,760 |
def yolo2xxyy(yolo):
"""convert yolo to coordinates bbox format
Args:
yolo (tuple): (ratio-bbox-centre-x, ratio-bbox-centre-y, ratio-bbox-w, ratio-bbox-h)
Rets:
box (tuple): (xmin, xmax, ymin, ymax)
"""
x,y,w,h = yolo
x1, y1 = x-w/2, y-h/2
x2, y2 = x+w/2, y+h/2
retu... | eaedb2ec437f42bf2e51176f5c4e56406a2a532e | 597,761 |
import math
def rotate(
x: float, y: float, z: float, axis: str, angle: float
) -> tuple[float, float, float]:
"""
rotate a point around a certain axis with a certain angle
angle can be any integer between 1, 360 and axis can be any one of
'x', 'y', 'z'
>>> rotate(1.0, 2.0, 3.0, 'y', 90.0)
... | 50a0736616c214a5bedeafbedb1bdc467a6994db | 597,765 |
import torch
def discretize(p_start, p_end, max_len=15, no_answer=False):
"""Discretize soft predictions to get start and end indices.
Choose the pair `(i, j)` of indices that maximizes `p1[i] * p2[j]`
subject to `i <= j` and `j - i + 1 <= max_len`.
Args:
p_start (torch.Tensor): Soft predict... | 2559d3912aa6ce5d87d0c3d3c37873e5d31f129c | 597,766 |
def generate_dbot_score(indicator):
""" Arbitrary (but consistent) scoring method
Assign a dbot score according to the last digit of the hash of the indicator.
parameter: (string) indicator
The indicator for which we need to generate a dbot score
returns:
Dbot score (0,1,2, or 3)
... | 4cd74601874c0e0cd79b91646927e56e91715f25 | 597,773 |
def parse_tool_output(text):
"""Given the tab-delimited output from an invocation of mp3gain
or aacgain, parse the text and return a list of dictionaries
containing information about each analyzed file.
"""
out = []
for line in text.split('\n'):
parts = line.split('\t')
if len(pa... | e154d586541ec2267f0388abe58ab8bec995dc23 | 597,775 |
import json
def load_json(path: str) -> object:
"""
Opens a JSON file and returns a dictionary.
Parameters
----------
path : Path to a JSON file
Returns
-------
The dictionary representation of the file
"""
with open(path, "r") as fp:
return json.load(fp) | 9666cfa9ecac546d90eb2588fcd8519fd0e64522 | 597,779 |
import glob
def is_compiled(filenameprefix):
"""Returns true iff a file 'filenameprefix.mex*' exists."""
# get all files with the given prefix
files = glob.glob(filenameprefix + '.*')
# return true iff one of the files contains 'mex'
ret = False
for f in files:
if '.mex' in f:
... | 2e1cbea79ae41226e2eec7142cdd200e4bf9fd29 | 597,780 |
def has_started(directory):
"""Returns True if the experiments in this directory appear to have
(non-trivially) started.
"""
return len(list(directory.iterdir())) > 1 | 45e5240712baa80eec53acf6adcb0aa0ef5f41f1 | 597,783 |
def orientation_unit_circle(angle):
"""Convert SUMO's angle to the standard unit circle.
SUMO defines 0 degrees facing North with the angle increasing clockwise (90 is East,
180 is South, etc.). This method converts SUMO's defintion to the standard unit circle
where 0 is East, 90 is North, etc.
Pa... | ae7a65c3c8fd144dc0c97f1a1eebda6fc6bcdb63 | 597,793 |
def hexToRgb(hexColors):
"""Convert hex colors to rgb colors (takes a list)."""
return [tuple(bytes.fromhex(color.strip("#"))) for color in hexColors] | 2c8d7fb751b03c660fcaf95a463f174b6da4f236 | 597,796 |
def make_batch(tensor, batch_size):
"""
Generate fake batch
:param tensor: input tensor
:type tensor: torch.Tensor
:param batch_size: batch size
:type batch_size: int
:return: fake batch
:rtype: torch.Tensor
"""
assert len(tensor.shape) == 3, 'Assume 3D input tensor'
return ... | b3b91b41f67e91a77516370936c6212a97fdcc9b | 597,798 |
def cell_renderer(item):
"""Simple cell renderer"""
return "%s item" % item.title | 0bc370d92c77f7d127e1052c732348558b8464ab | 597,801 |
def false_negative_rate_binary(num_positives, type='exp'):
"""
computes the false negative rate (FNR) of a pooled PCR test, based on the number of
positive samples in the pooled sample
INPUT:
num_positives = number of positive samples in the pooled sample
type = false negative rate function use... | f8aecc247e34efdd975c53da661c480e2f039c4b | 597,803 |
def write_flaggelin_db_fasta(df, fasta_name = "flagellin_db.fasta"):
"""
Creates a fasta file from a Dataframe
Parameters
----------
df : Pandas DataFrame
This will be the DataFrame output from construct_reference_flagellin_dataframe
fasta_name : str
Name of the output fasta file
Returns
-------
fasta_na... | 073d5501ede76006756adc2cca31e3b8b418af22 | 597,805 |
def has_role(role, roles):
""" Check if the a role is contained in a role list
Looks if a role is contained to a list independently to the case
sensitivity.
"""
if role is None or roles is None:
return False
return role.lower() in [r.lower() for r in roles] | a86cb5fd962d4e4ae82e615e0aac2b3211719633 | 597,806 |
def _bool(x) :
"""Convert string to boolean"""
if x.lower() in ("yes", "true", "1") :
return True
else :
return False | 3023bd7cd3a22934b1714612687827657e400c97 | 597,807 |
def px2mm(pixels, resolution=1600, precision=2):
"""Convert scanned pixels to millimeters.
Arguments:
pixels: measurement in pixels.
resolution: image resolution in pixels/inch.
precision: number of significant digits for rounding.
Returns:
The converted measurement.
""... | 7a35d6d9bc049273b092a5bd4ea5e4d608b7cace | 597,813 |
def _ExtractIdResources(rtxt_path):
"""Extract resources of type ID from the R.txt file
Args:
rtxt_path: Path to R.txt file with all the resources
Returns:
List of id resources in the form of id/<resource_name>
"""
id_resources = []
with open(rtxt_path) as rtxt:
for line in rtxt:
if ' id ... | 96c76f47678a395c9113b4c5a7aedcb1c4bb6d30 | 597,816 |
def _convert_method_arg(method):
"""
Convert argument `method` to a function that can be called after
resampling or reindexing a DataFrame. If `method` is a string such
as 'ffill' or 'bfill' then it will be converted to a function. Otherwise
if `method` is itself a callable function, then it will be... | 3d7897ff82d0fde788c34756ebd8737736d7f4e8 | 597,817 |
def cargar_vuelos(ruta_archivo: str) -> dict:
"""
Esta función carga la información un conjunto de vuelos a partir de un archivo CSV.
Los valores dentro del archivo deben estar separados por comas y estar en el siguiente orden:
aerolinea,codigo_vuelo,origen,destino,distancia,salida,duracion,retraso
... | 38c37bee024eafa0d16f0861881fd09e8f30c2b4 | 597,826 |
from typing import Iterable
from typing import ByteString
from typing import Counter
def count_byte_values(bss: Iterable[ByteString]) -> list[Counter[int]]:
"""Returns a list of Counters, each of which records the values of the
bytes at the corresponding index in the given ByteStrings."""
counts_for_idx: ... | 017bf765e5757825e4821837bfe010495df06894 | 597,828 |
import re
def camelcase_to_snakecase(string):
"""Convert CamelCase to snake_case."""
return re.sub(r"(?<!^)(?=[A-Z])", "_", string).lower() | 86fe210592e99807a86340683562291ebdbd0139 | 597,829 |
import hmac
import hashlib
def validate_signature(key, body, signature):
""" Validate the received signature against the secret key
:param str key: secret key
:param str body: message body
:param str signature: received signature
:return:
:rtype: bool
"""
signature_parts = signature.s... | f3522abb59c4ab07bfbeea51cffb68d2b786e714 | 597,837 |
def fsummarizer(pepseq, prop_dict, func):
"""
Summarize pepide sequence with by mapping amino acids to prop_dict entires and a summary func.
Parameters
----------
pepseq : str
sequence.
prop_dict : dict
amino acid property mapping.
func : function
Summary function (s... | 3b85a6cf920ec23e36bf42e122f6228e90203650 | 597,838 |
def get_species_reaction_sets(reaction_sets, species):
"""Returns species-specific reaction sets.
:param reaction_sets: ReactionSets object representing CoMetGeNe reaction
sets obtained from CoMetGeNe trails
:param species: query species (KEGG organism code)
:return: list of species-specific Co... | fc93e6232c37fffea67d20542ad5af4550303f3d | 597,841 |
import jinja2
import logging
def template_with_jinja2(text, variables):
"""
Template using jinja2 with the variables dictionary unpacked as keyword
arguments.
"""
jinja_environment = jinja2.Environment(
loader=jinja2.BaseLoader(),
undefined=jinja2.make_logging_undefined(logging.get... | bda6e022e0a5c52fe185be59fe370520cf4c8399 | 597,842 |
def team_bikes(team, include_reserve=False, include_inactive=False):
""" List bikes for given team.
Optionally include reserve and inactive bikes.
"""
bikes = team.bikes.all()
if not include_inactive:
bikes = bikes.filter(active=True)
if not include_reserve:
bikes = bikes.filter... | e5f20bd7db4d716c286ba7e843191aacde6c81aa | 597,844 |
import unicodedata
def nfkc(data):
"""Do NFKC normalization of Unicode data.
:Parameters:
- `data`: list of Unicode characters or Unicode string.
:return: normalized Unicode string."""
if type(data) is list:
data=u"".join(data)
return unicodedata.normalize("NFKC",data) | 531bcb8e64b06be444dfbdb90cdc04e6b73cdf80 | 597,845 |
from pathlib import Path
import yaml
def default_loader(file: Path) -> dict:
""" Default loader parses .yaml config file. """
result = yaml.safe_load(file.read_text())
if not isinstance(result, dict):
raise ValueError("Loaded config is not a mapping")
return result | e634e01c625e6994643a9b10d596f070fcac7a3a | 597,846 |
from datetime import datetime
def convert_format(dt_str: str, format: str) -> str:
"""「%Y:%m:%d %H:%M:%S」形式の日付文字列を別の形式に変換する"""
return datetime.strptime(dt_str, '%Y:%m:%d %H:%M:%S').strftime(format) | 5d5383cc24f7673b689047e1cafb4b0e4a950b51 | 597,849 |
import torch
def l_n_reg(model, device, norm = 2):
"""
Wrapper to add a weight regularizer, with adjustable norm.
----------
model: model with the weights to be regularized
device: either cpu or gpu
norm: default 2, the norm to use in regularization
"""
reg_loss = torch.tensor(0., requ... | 30fd55a6bf1a6c7145d786d1bf44f5cb741c6ea2 | 597,850 |
def health_status() -> tuple[dict[str, str], int]:
"""Ping-able server endpoint."""
return {"status": "ok"}, 200 | 533d15d6231c743750b453081791fa2dc4c499c7 | 597,851 |
from typing import List
from typing import Tuple
def _combine_mean_std(means: List[float], stds: List[float], iterations: List[int]) -> Tuple[float, float]:
"""Combines multiple groups of means and standard deviations.
The algorithm utilizes the algorithm as described by `Cochrane <https://training.cochrane.... | 9b997be9d4bfde83456672b9ac133ffd2df02ce5 | 597,852 |
def query_on_connection(dbapi_connection, statement):
"""Execute a single statement with a dbapi connection and return the result."""
cursor = dbapi_connection.cursor()
cursor.execute(statement)
result = cursor.fetchall()
cursor.close()
return result | 545d689e02c53fb4ab0c5f9da79aed24e6c1d4b3 | 597,859 |
def make_edge_data_table(profile_info,edge_data) :
"""
Given the edge list and a specified set of
user profiles we construct a dataframe containing
the list of edges and the attributes of the nodes
at each end of the respective edges.
Parameters
------------
profile_info : pandas dataf... | 92c481be7e918cb5de2b2c48a2ebc989581818f8 | 597,863 |
from PIL import Image
def rgba_to_rgb(im, rgb):
"""Translate an RGBA-mode image to an RGB image.
im
The transparent image.
rgb
The RGB-value to use for the transparent areas. This should be
a 3-tuple of integers, 8 bits for each band.
"""
new_im = Image.new("RGB", im.si... | 71e95d389b6fc447121135a04da959d44474a4a3 | 597,865 |
import json
def prepare_json(data):
""" Prepares a JSON-encoded HTTP message.
"""
data = json.dumps(data)
data = data.encode('utf-8')
header = {
'Content-type' : 'application/json'
}
return (data, header) | ead16981d84aeb58c5baf67638a63b315533ac76 | 597,867 |
import colorsys
def desaturate(color, prop=0.75):
"""Desaturate color like in default seaborn plot
Args:
prop (float): Amount to desaturate
Returns:
tuple: RGB tuple with the desaturated color.
"""
h, l, s = colorsys.rgb_to_hls(*color)
s *= prop
new_color = colorsys... | 85155cb055461d8aca17a071b6e5cd5295949ef7 | 597,868 |
def code(string: str) -> str:
"""
Add code md style.
:param string: The string to process.
:type string:str
:return: Formatted String.
:rtype: str
"""
return f"`{string}`" | 4926d6981a589dca3926205b42d3b43aa99da962 | 597,869 |
def multiplica(n1, n2):
"""Multiplica dois números maiores ou iguais a zero.
Atenção: seu algoritmo não pode usar o símbolo '*'.
"""
produto = 0
for i in range(abs(n2)):
produto += n1
if n1 and n2 < 0:
produto *= -1
return produto | 7bda2a2bb15fbd2ab375ba184bc3385054845de8 | 597,871 |
def pin_to_wire_and_idx(pin):
""" Break pin name into wire name and vector index.
Arguments
---------
pin : str
Pin name, with optional vector index.
Returns
-------
wire : str
Wire name
idx : int
Vector index
>>> pin_to_wire_and_idx('A')
('A', None)
... | ee2d5cda971c4b43780ebdcc58cdff034c208f8b | 597,872 |
def is_temp_dir(dname):
"""Determine if directory matches pattern for temp directory"""
if dname.startswith("."):
return True
else:
return False | 16ed4aab114803af28ff90956cf4bb0930c3708c | 597,873 |
import hashlib
def md5(file_path):
"""Get md5 hash of a file.
Args:
file_path (str): File path
Returns:
md5_hash (str): md5 hash of data in file_path
"""
hash_md5 = hashlib.md5()
with open(file_path, 'rb') as fhandle:
for chunk in iter(lambda: fhandle.read(4096), b''... | c63d974cddff78a825ba9cde8cac0fac8567b64e | 597,874 |
def remove_edges(image):
"""Applies a negative buffer of 6 km to sat. scenes to remove the edges."""
return image.clip(image.geometry().buffer(-6000)) | 8164f4cfa1018668764e0948136d6804e78baf78 | 597,883 |
def get_count_value(obj):
"""
Returns count of child objects from LLDB value.
:param lldb.SBValue obj: LLDB value object.
:return: Count of child objects from LLDB value.
:rtype: int | None
"""
# Passed None value.
if obj is None:
return None
# Return 0 if object has no val... | d2b4c66adfab7389c7508b878b766f6ee11f7938 | 597,884 |
import inspect
def GetDatasets(cls):
"""Returns the list of dataset functions (e.g. Train, Dev, ...)."""
datasets = []
for name, _ in inspect.getmembers(
cls, lambda x: inspect.isfunction(x) or inspect.ismethod(x)):
if name not in ['GetDatasetParams', 'Model', 'Task', 'ProgramSchedule'
... | cd21763ec5a219e7c49b59617df1feb17c202e92 | 597,885 |
def estimate_uvar(innov):
"""Estimate unconditional realized covariance matrix.
Parameters
----------
innov: (nobs, nstocks) array
inovations
Returns
-------
(nstocks, nstocks) array
E[innov' * innov]
"""
return innov.T.dot(innov) / innov.shape[0] | 91c6312e2ee3b97122e948fe81b4de1cd16978d0 | 597,886 |
def frame1_apply_thd(frame, thd_low, thd_high):
"""apply threshold filtering for a single chanel frame"""
frame[(frame < thd_low) | (frame > thd_high)] = 0
return frame | 2c2c8252ae21bde7e2cd5f105494e67384bf4a8f | 597,887 |
import math
def get_available(seat_map, seats_required):
"""Return the available contiguous seats that match the criteria"""
seats = []
end_seat = seat_map.bit_length()+1
if seats_required <= end_seat:
required_block = int(math.pow(2, seats_required))-1
for i in range(1, end_seat+1):
if (seat_ma... | 117f55f44179223e2b17308afd00f4ff69e6d417 | 597,889 |
import csv
def csvtolist(csvfile, delimiter=',', quotechar='"'):
"""
Translates a CSV iterator into a list of strings.
The list of strings can be used in any of the other CSV util functions as well as the csv lib.
Args:
csvfile: The csv file to be converted.
Must be a list, f... | 200a742bf3e09b566783eb2e6b04856269573d08 | 597,891 |
from datetime import datetime
def delta_date(start_date,end_date):
"""Function that returns the number of days between 2 dates """
return abs((datetime.strptime(start_date, "%Y-%m-%d") - datetime.strptime(end_date, "%Y-%m-%d")).days) | 29539d9179504449e0d36b08ea1c8c434f4bfb50 | 597,897 |
import json
def ExtractJQuery(jquery_raw):
"""Extract and return the data inside a JQuery as a dict object."""
data_part = u''
if not jquery_raw:
return {}
if '[' in jquery_raw:
_, _, first_part = jquery_raw.partition('[')
data_part, _, _ = first_part.partition(']')
elif jquery_raw.startswith('... | 09cc1061537f85824b77ff072b24dfa8672d19d3 | 597,900 |
def lr_decay(N, step, learning_rate):
"""
learning rate decay
Args:
learning_rate: base learning rate
step: current iteration number
N: total number of iterations over which learning rate is decayed
"""
min_lr = 0.00001
res = learning_rate * ((N - step) / N) ** 2
retu... | 307ac7a886a463320504a6983d1941e59d76b41a | 597,901 |
def double_linear_con(progress):
"""
Returns a linear value (x2) with a flattened tail for the Scheduler
:param progress: (float) Current progress status (in [0, 1])
:return: (float) 1 - progress*2 if (1 - progress*2) >= 0.125 else 0.125
"""
progress *= 2
eps = 0.125
if 1 - progress < e... | bf31b47464d7729d4db5975f0e0165e7db0bfd75 | 597,906 |
from typing import List
def check_if_cut(u: int, v: int, cut: List[int]) -> bool:
"""Checks if two nodes are on opposite sides of a graph partition.
Args:
u: The first node
v: The second node
cut: A set of nodes that represents one of the sides of a partition
on the graph
... | 06fbb292571f278361413e679c89c96b7709f151 | 597,907 |
def call_one_by_one(objs, method_name: str, args, **kwargs):
"""
Call specified method of given objects with given args in order.
"""
for obj in objs:
assert hasattr(obj, method_name), \
"'{cmd}' has no method '{method}".format(
cmd=obj.__name__,
metho... | 4a3eaf05a786df7978bd4168eb60c60a136f529a | 597,909 |
import requests
def fetch_jira(url, api_url=None, req=None):
"""
Return a fetcher for a Jira instance
>>> fetch_jira("https://issues.apache.org")("ZOOKEEPER-1234")
(u'https://issues.apache.org/jira/browse/ZOOKEEPER-1234', u'basic cleanup in LearnerHandler')
Some Jira instances may use different ... | b197801ea1514c76ac23d077c8210407cf41c75a | 597,915 |
def _get_relay_log(server):
"""Retrieve relay log and relay log position
server[in] Server instance
Returns tuple (relay log, relay log position)
"""
relay_log, relay_log_pos = '', ''
res = server.exec_query("SHOW SLAVE STATUS")
if res != [] and res is not None:
relay_log = ... | 0761a663d0ba0cbbd496b4cbec4f9774b0b4d8b1 | 597,922 |
import random
def _split_dataset(X,Y, train_perc = 0.7, dev_perc = 0.15, m_clip=5000, do_shuffle=False, n_samples_per_training_split = None):
"""Splits a dataset into training development and test sets.
Optionally shuffle the dataset before splitting. The splits are sized
according to the given perce... | 35df8cc64b9c764f7f58506564fe43af38ef9037 | 597,930 |
def tree_to_list(root_node):
"""Orders the nodes into a list recursivly using depth-first-search"""
ls = [root_node]
for child in root_node.children:
ls.extend(tree_to_list(child))
return ls | 43673ae2810af6b6c08b0379d45ff8d3d665236b | 597,939 |
def isNumeric(series):
"""Check if the series's type is numeric
Args:
series (Series): data series
Returns:
bool
"""
return series.dtype.kind in 'ifc' | 9e70c3267d25bb83d6f9a9aff799a7083f3e224e | 597,942 |
import math
def phase(x):
"""Return phase, also known as the argument, of a complex."""
return math.atan2(x.imag, x.real) | 0f9395add3c6cd2bc0f7509fb227f0f010e47d51 | 597,945 |
def build_dict(key_list, value):
"""
Build a hierarchical dictionary with a single element from the list of keys and a value.
:param key_list: List of dictionary element keys.
:param value: Key value.
:return: dictionary
"""
temp_dict = {}
if key_list:
key = key_list.pop()
... | 2373a50e4cea4aa4194bd3d2c64d41a94f352abc | 597,947 |
import json
def parse_broadcast_message(to_parse):
"""Parse the given string as a json and return a dictionary with the json's contents"""
try:
decoded = json.loads(to_parse)
if decoded is not None:
return decoded
except ValueError:
# this is a JSONDecodeError, but we a... | cf2db5a7b68b4bcebfbe592938084b13cbe731bf | 597,949 |
def get_audio_layer(layer):
"""
Get audio layer into a human easy readable format.
Arguments:
:param layer: integer
:return: string
"""
return "Layer %i" %(layer) | f8577e6e4a70e854f4c0bd2aeccc992ff850c423 | 597,951 |
import torch
def invert_permutation(p: torch.Tensor):
"""
The argument p is assumed to be some permutation of 0, 1, ..., len(p)-1.
Returns an array s, where s[i] gives the index of i in p.
Taken from: https://stackoverflow.com/a/25535723, adapted to PyTorch.
"""
s = torch.empty(p.shape[0], dt... | eeff0ddb3e82a854ff21808366727a80eb016b54 | 597,952 |
def expect_z(zp_po):
"""Compute the expectation of z"""
return zp_po | c85be63b0d8c0f36cabace4032aecf920fc36f34 | 597,960 |
def is_api_arg(arg):
"""Return True if argument is our API argument or self or used for internal
purposes
"""
return arg != 'self' and not arg.startswith('_') | a49d8a5eb6b3da93675db2438b008b07fbadb4eb | 597,964 |
def remove_prefix(text: str, prefix: str) -> str:
"""Remove prefix and strip underscores"""
if text.startswith(prefix):
text = text[len(prefix) :]
return text.strip('_') | d4934cc6f02a42e14dd58689446bb0853b988bb4 | 597,966 |
def unique_trees(msts):
"""
Test whether a list of minimum spanning trees are unique.
Args:
msts (list, nx.Graph): list of minimum spanning trees.
Returns:
(boolean): whether all trees in the list are unique.
"""
for i, mst1 in enumerate(msts):
for j, mst2 in enumerate(... | 9d7e2231adf376317f49e7ed438da632553ce76f | 597,967 |
def process_categories(json):
"""
Returns a list of category names required for querying the mealdb recipe filter endpoint.
:param json: Dict containing category objects from mealdb categories endpoint.
:return: Returns a list of strings.
"""
categories = [category['strCategory'] for category i... | 17a090f7094192ecaccce04dff39b86e8968413b | 597,969 |
import click
def universal_options(f):
"""Options required by every command."""
f = click.option('--genotype', type=click.Path(exists=True),
required=True, help='Genotype file path.')(f)
f = click.option('--verb', is_flag=True)(f)
return f | a98af94c7d427ebfe0ad5d5aae3af47c6d375b71 | 597,972 |
import random
def random_tuple(l, sigma):
"""returns a tuple of random numbers.
- the tuple is of length `l`
- the sum of the numbers in the tuple is `sigma`
Arguments:
l (int): length of the tuple
sigma (int): sum of all the values in the tuple
"""
percentage_indices = [0, ... | c548fc73f92f269a7079bed7e7ac1ee9b4dc62f0 | 597,975 |
import re
def SplitWords(input_string):
"""Split by '_' if found, otherwise split at uppercase/numeric chars.
Will split "some_TEXT" into ["some", "TEXT"], "CamelCase" into ["Camel",
"Case"], and "Vector3" into ["Vector", "3"].
"""
if input_string.find('_') > -1:
# 'some_TEXT_' -> 'some TEXT'
retur... | 6fd45c9c2cfcc08d0fe1bc2485a2efacd3014406 | 597,978 |
def order(matrix, psuedotime):
"""Order the rows of a matrix by rank of psuedotime.
Arguments:
matrix (pandas DataFrame): samples x features (rows x cols) matrix
psuedotime (pandas Series): Ordererable values indexed by the same row names of matrix.
Returns:
(pandas DataFrame): ... | 55045ad6873b6f9646ea70da8f9395a13f26524f | 597,980 |
def trim_dset(dset, good_idx):
"""
Trim a dataest based on a set of indices you want to keep.
Args:
dset (nff.data.dataset): NFF dataset
good_idx (list[int]): indices that you want to keep
Returns:
dset (nff.data.dataset): trimmmed NFF dataset
"""
for key, val in dset.pro... | e55acb6f81b1386b2ebee33f87c08f320c72a93c | 597,984 |
def semester_str(semester_code):
"""Returns a string representation of semestercodes. Example: h2009 ->
høsten 2009, v2013 -> våren 2013"""
time_of_year = 'våren' if semester_code[0] == 'v' else 'høsten'
return time_of_year + ' ' + semester_code[1:] | 59403d91958139af00fb9dc257ca24af77883cd9 | 597,993 |
from typing import Sequence
def validate_qubit_list(qubit_list: Sequence[int]) -> Sequence[int]:
"""
Check the validity of qubits for the payload.
:param qubit_list: List of qubits to be validated.
"""
if not isinstance(qubit_list, Sequence):
raise TypeError("'qubit_list' must be of type ... | 7021e256b41bff60540038c2e7aea22f398811ec | 597,998 |
def _same_cluster(site_a, site_b, clusters):
"""
Check if sites are in the same cluster
"""
a_index = [site_a in cluster for cluster in clusters].index(True)
b_index = [site_b in cluster for cluster in clusters].index(True)
return a_index == b_index | 5f47b68148e4c7209989971a80ff4cb1d6718161 | 597,999 |
import re
def slice_dict_to_tuple(d, keys, none_as_default=False):
""" Returns a tuple from dictionary values, ordered and slice by given keys
keys can be a list, or a CSV string
"""
if isinstance(keys, str):
keys = keys[:-1] if keys[-1] == ',' else keys
keys = re.split(', |[, ]', ... | 08fa246bf52641fbfa190edd5ad327c452cffc1e | 598,002 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.