content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def doHammingByte(byte):
"""Secures one byte by hamming code"""
#P1 = A1 xor A2 xor A4 xor A5 xor A7
P1 = str(
int(byte[0]) ^
int(byte[1]) ^
int(byte[3]) ^
int(byte[4]) ^
int(byte[6])
)
#P2 = A1 xor A3 xor A4 xor A6 xor A7
P2 = str(
int(byte[0]... | fca53ce3958820ac3ed122d00045edd46d7e36d8 | 41,700 |
def partial_flatten(x):
"""Flatten all but the first dimension of an ndarray."""
return np.reshape(x, (x.shape[0], -1)) | c2596b8cdc8097fb374b153da2246dc307568751 | 41,701 |
from typing import Counter
def get_spawn_day_counts(input: list[int], days: int) -> dict[int, int]:
"""Count the total number of fish after a given number of days and starting
fish (number of days until they spawn another fish).
"""
spawn_day_counter: dict[int, int] = {}
for spawn_day in range(d... | 7d43cea6c1f737d5977644715af7a2fa38f8abbb | 41,702 |
def get_all(*, db_session):
"""Returns all tickets."""
return db_session.query(Ticket) | dfc709adebe07b2be5ff56dca9eaca6c4baffd4b | 41,703 |
def _directly_configure_from_flags(fields):
"""Helper function that translate flag values to a dict."""
return {field: getattr(FLAGS, field) for field in fields} | 5a4d14486f9b7fbc97d0bc0f78fd8ba017593036 | 41,704 |
def clean_text(text):
"""
Applies all the filters to input text.
:param text: The input string.
:type text: String.
:returns: The processed String.
:return type: String.
"""
text = text.lower()
text = strip_accents(text)
text = strip_digitsAndSpecialChars(text)
retur... | 3e309ccc8784702b89bf75915ff3857def1bc5d9 | 41,705 |
def get_sleep_time(time_start, time_now, poll_int):
"""Calculate time to sleep.
Args:
time_start(datetime): Time loop started
time_now(datetime): Current time
poll_int(int): Poll interval in seconds
Returns:
sleep_time(float)
"""
time_sleep = poll_int... | 6d3a00d12c8ff5677c9625228a2150bca55762de | 41,706 |
def sqrt(node) -> Node:
"""square root of the node, np.sqrt"""
return Node(node, None, np.sqrt(node.value), 'sqrt' ) | f4be8b3c57c5467ef9cbf41cacb5a2bb40c4c17a | 41,707 |
import random
def permute_code_object(baseline):
"""Take a code object and change one byte of the bytecode."""
bytecode = list(baseline.co_code)
bytecode[random.randint(0, len(bytecode) - 1)] = random_char()
return clone_code_object(baseline, code="".join(bytecode)) | cf9444def6e2a33c7ef17b0bfaeef56295b66245 | 41,708 |
import os
import re
from datetime import datetime
def check_scraped(name_dataset, term, year, num):
"""
"""
name_src, name_dst, name_summary, name_unique, plot_unique = name_paths(name_dataset)
paths_to_check = []
paths_to_check.append(os.path.join(retrieve_path(name_src)))
paths_to_check.ap... | 1e29c38e7164d63eea8dc3734de850952a2d2100 | 41,709 |
import os
def expand_session(name):
"""
Helper function that creates the session names for the original mkdir and the actual code being run.
"""
user_name = os.environ.get('SUDO_USER') or os.environ['USER']
return "{}_cp_{}".format(user_name, name), "{}_run_{}".format(user_name, name) | 9426d2f3d867b7c69a0b366d0cecef585ec9ecc7 | 41,710 |
def _fix_values(key, md):
"""
Recursively search each item in metadata
and reassign values.
"""
i = md[key]
md = _set_val(i, key, md)
if isinstance(i, list):
new = []
for idx in range(len(i)):
new.append(_fix_values(idx, i)[idx])
md[key] = new
if isins... | 1b79b6ab391b64b1a8da59a78c216e744bec84b5 | 41,711 |
def imstackshow(im_stack, time_points=None,
color_mapper=None, downscale=1,
plot_height=400):
"""
Build display of image stack.
Parameters
----------
im_stack : list of tuple of 2d Numpy arrays
List of images
time_points : ndarray, default None
... | 96a9e20df9704a0d0bdfed80553f367e7c874609 | 41,712 |
def distinct_count(daskDf, columnName):
"""Counts distint number of values in Dask dataframe
Keyword arguments:
daskDf -- Dask dataframe
columnName -- Column name
Return:
return -- Distinct number of values
"""
return daskDf[columnName].drop_duplicates().size | 27a03a6eef1f9c949d22f02e5d880ef626b6acf6 | 41,713 |
def pow_3_of(number):
"""
cube input number
helper function from lalsimulation/src/LALSimIMRPhenomD_internals.h
"""
return number*number*number | 18a8a3922ec2315b7d170b00362511208792d2df | 41,714 |
def boolean_search(
query,
inverted_index
) -> list:
"""
Implementation of the boolean search by keywords: {"AND", "OR"}
:type query: str,
:type inverted_index: defaultdict
"""
resulting_index = []
# Extracting the dict of key/value pairs, where key is token
query_dict = ... | 93ac84dfea2811d637b56bb52bb8931293c1c4f9 | 41,715 |
def sample_views(nviews):
"""View sampling function.
Args:
nviews: Number of views to be sampled
Returns:
rot_trans_list: list of (rot, trans) tuples
"""
rot_trans_list = []
for _ in range(nviews):
x_cam = np.random.uniform(-0.5, 0.5)
y_cam = np.random.uniform(-0.5, 0.5)
z_cam = 0
... | edcd9ef0a30004f5d9cf03b97e26827f2f70e17a | 41,716 |
def get_step_rolling(cycle_nr=1):
""" Get the step name for rolling step in cycle cycle_nr
:param cycle_nr: The cycle number
:type cycle_nr: int
:returns: The step name
:rtype: str
"""
return 'rolling_' + cycle_str(cycle_nr) | cef011e1e1752d13eef5b96083679bd2ddf66442 | 41,717 |
def read_list_h5(h5):
"""
Read list from h5 file.
A list is a group of groups named with their index, and attributes as the data.
The format corresponds to that written in write_lattice_h5
"""
# Convert to ints for sorting
ixlist = sorted([int(k) for k in h5])
# Back to s... | df62927bf7afc0bad751a9b80b63ec2c1c944a7d | 41,718 |
def resultSetFacetsHandler(session, val, resp, resultSet=[], db=None):
"""Put facet for requested index into extraSearchRetrieveData
val is a CQL query.
Boolean used is meaningless, facets are returned for each clause.
Term in each clause is also meaningless and need be nothing more th... | b7d5f0a0add692881bbb970baa12588cb95bd450 | 41,719 |
def verse(num_of_bottles):
"""bottle verse"""
b = "bottle" if num_of_bottles == 1 else "bottles"
if num_of_bottles==1:
last = "No more bottles"
elif num_of_bottles==2:
last = "1 bottle"
else:
last = f'{num_of_bottles-1} bottles'
return '\n'.join([
f'{num_of_bot... | 57cf46e430a7a75deb9e6b88c5defa35991fda4e | 41,720 |
def fizz_buzz(tuple):
"""
Transform the input tuple to a string that follows
the Fizz Buzz rules
Args:
tuple: tuple
Returns:
string
"""
if tuple == 0:
return None
ret_val = ""
if tuple % 3 == 0:
ret_val += "Fizz"
if tuple % 5 == 0:
ret... | 4053cad878c05fa0430835a9a9728a6c0b8e420d | 41,721 |
def f1_score(precision, recall):
"""Creates an op for calculating the F1 score.
Args:
precision: A tensor representing precision.
recall: A tensor representing recall.
Returns:
A tensor with the result of the F1 calculation.
"""
return tf.where(
tf.greater(precision + recall, 0), 2 * (
... | 2cad9591eea0581b7076108cb50f15ddb9070c46 | 41,722 |
def observe_contour(firemap: GeoData, contour: float, n_uavs, uav_speed, duty_cycle=0.25):
"""Extract a contour and then simulate it is observed by N UAVs.
Each UAV gets an equal size chunk and observed a contigous portion of it (duty_cycle)
The observation time is estimated from the speed
speed is in m... | bbdbc9284ce26986cde69fa87727357622bd1cd7 | 41,723 |
import math
def gradient_and_profile_with_spline(T, F, period, phase_given, time_half_transit, amplitude, spline):
"""a variant of profile wtih spline it also returns gradient"""
if period < 0.0:
print(("Invalid period in gradient_and_profile_with_spline"))
raise ValueError
elif time_half_... | 23ab0af1abf73d1adcf332418f66611954236945 | 41,724 |
def disk_to_dict(disk):
"""Converts a lxml.objectify.ObjectifiedElement disk object to a dict.
:param lxml.objectify.ObjectifiedElement disk: an object containing
EntityType.DISK XML data.
:return: dictionary representation of disk object.
:rtype: dict
"""
result = {}
result['name... | 458c243018474bd2e3e331b71b972eae4d2bc0ee | 41,725 |
def get_hashID(username, hashMode=64, tableGroup=4):
"""根据 username 确定唯一 hash 值(确定分表)
# 分组公式:64 = 每组多少个count * group需要分组的个数
# 数据所在环的位置(也就是在哪个库中):value = key mode 64 / count * count
hash(key)在0~3之间在第0号表
hash(key)在4~7之间在第4号表
hash(key)在8~11之间在第8号表
hash(key)在0~3之间在第0号库
hash(key)在4~7之间在... | 068ed14923f9fdf57d12b233e94ee7dee8bf8a12 | 41,726 |
from typing import OrderedDict
def save_chain(config, chain):
"""
Encode a chain of operation classes as json.
:param config: dictionary with settings.
:param chain: OrderedDict of operation class lists.
:return: string-encoded version of the above.
"""
di = OrderedDict()
di['__config__'] = config
for k... | d6838dfe1f079233ba8e3d93c62ddc1ebbcec5e4 | 41,727 |
def _trigger_task(options):
"""Triggers a task on the compile server by creating a file in storage."""
task = _create_task_dict(options)
# Check to see if file already exists in Google Storage.
if not _does_task_exist_in_storage(task):
_write_to_storage(task)
return task | fe611b79ebe0ed52ef940784ebd1dc1d3d951f0d | 41,728 |
import os
def identical_data_outputs(pre_restart_path, post_restart_path, output_dir):
"""
Returns whether the contents of {pre_restart_path}/{output_dir} and
{post_restart_path}/{output_dir} are identical
Parameters
----------
pre_restart_path : str
Path to directory that stores sets... | be94f077b991c786bf204717db76a9da1e03e68b | 41,729 |
def map_vcf_row(row, df_cell_vcf):
"""
get ref and UMI for each variant
row: each row from merged_vcf
"""
pos = row['pos']
chrom = row['chrom']
alt = row['alt']
df_pos = df_cell_vcf[(df_cell_vcf['pos'] == pos) & (df_cell_vcf['chrom'] == chrom)]
df_ref = df_pos[df_pos['alt'] == '.']
... | ce80e83b8a16609038c637ed815df49677ff6efc | 41,730 |
import os
import torch
import tqdm
def calculate_fid_given_paths(paths, batch_size, cuda, dims, bootstrap=True, n_bootstraps=10, model_type='inception'):
"""Calculates the FID of two paths"""
pths = []
for p in paths:
if not os.path.exists(p):
raise RuntimeError('Invalid path: %s' % p)... | 2c0d01a350de4efa2ea8630928bf512e9963ac70 | 41,731 |
def plot_no_pooling_model(
samples: MonteCarloSamples,
query: RVIdentifier,
df: pd.DataFrame,
) -> Figure:
"""
Plot the no-pooling model.
:param samples: Bean Machine inference object.
:type samples: MonteCarloSamples
:param query: Bean Machine query object.
:type query: RVIdentifie... | 15c98eaa026b2394cde1b5c8cc96243757ccec74 | 41,732 |
import warnings
def get_space_permissions(id_value, id_type='browse_id', return_type='list'):
"""This **deprecated** function returns all of the defined permissions (aka ``appliedEntitlements``) for a space.
.. deprecated:: 2.6.0
The function has been renamed to be :py:func:`khorosjx.places.spaces.get... | c6a61298879d6a17c04905dc3dfb2de2c0670eff | 41,733 |
def validate(schema_filename, data_filename, seen_uids):
"""Validate a YAML file according to the supplied schema."""
schema = yamale.make_schema(schema_filename)
data = yamale.make_data(data_filename)
try:
print("")
print("Checking file '{}'...".format(data_filename))
yamale.va... | d23017533f485275705377952be364bd0e20c223 | 41,734 |
def register_shellcontext(app):
"""Register shell context objects."""
def shell_context():
"""Shell context objects."""
return {
'db': mongo}
app.shell_context_processor(shell_context) | 4206fa496d4593b451a333f67f81cb976aa408e8 | 41,735 |
def db_connection_string(dbconf): # type: (dict) -> str
"""
Constructs a database connection string from the passed configuration object.
"""
user = dbconf["user"]
password = dbconf["password"]
db_name = "traffic_ops" if dbconf["type"] == "Pg" else dbconf["type"]
hostname = dbconf["hostname"]
port = dbconf["por... | 3fbb52c398f5150f6101b9d0d286f1db1b8aa99f | 41,736 |
def memory_stream_one_way_pair():
"""Create a connected, pure-Python, unidirectional stream with infinite
buffering and flexible configuration options.
You can think of this as being a no-operating-system-involved
Trio-streamsified version of :func:`os.pipe` (except that :func:`os.pipe`
returns the... | 3fa29609d20ed5d55eed6ac4b8cc389b88ac2e82 | 41,737 |
def round2sigfig(num,nfig=1):
"""Round number to significant figures"""
def ndecimal(x):
if x==0 or not np.isfinite(x):
# "Behaviour not defined" => should not be relied upon.
return 1
else:
return -int(floor(log10(abs(x))))
nfig =nfig-1
n = nfig ... | 27cf8545ed33f3cca8f4da28370fd42a185e427d | 41,738 |
def _subsample_selection_to_desired_neg_pos_ratio(
indices, match, max_negatives_per_positive, min_negatives_per_image):
"""Subsample a collection of selected indices to a desired neg:pos ratio.
Arguments:
indices: an int or long tensor with shape [M],
it represents a collection of ... | b5e841fe9dd61f4ec1b3e0674dfddad758dcf7fb | 41,739 |
def normalize_units(
df,
unitsmap,
targetunit,
paramcol="parameter",
rescol="res",
unitcol="units",
napolicy="ignore",
):
"""
Normalize units of measure in a dataframe.
Parameters
----------
df : pandas.DataFrame
Dataframe contained results and units of measure d... | 89aa2692ae778eede36d02b8bea756793a55c172 | 41,740 |
def shorten(k):
"""
k an attrname like foo_bar_baz.
We return fbb, fbbaz, which we'll match startswith style if exact match
not unique.
"""
parts = k.split('_')
r = ''.join([s[0] for s in parts if s])
return r, r + parts[-1][1:] | 6d9c29849cc5a63ec466d2548ea2492d112946cf | 41,741 |
def get_time_query_for_trip_like(key, trip_like_id):
"""
Returns the query that returns all the points associated with this
trip-like (examples of trip-like objects are: raw trip, cleaned trip, raw section)
"""
trip = get_object(key, trip_like_id)
return get_time_query_for_trip_like_object(trip... | 057561a7cb014fd04be53fe1d57de5c739b36e26 | 41,742 |
def test_context_3():
"""
store and load 10 global variables, load the 10 variables again, repeat
with different values
"""
nvars = 10
numlist1 = [str(random_ndigits(10)) for _ in range(nvars)]
numlist2 = [str(random_ndigits(10)) for _ in range(nvars)]
inplist = numlist1 + ['pop'] * nva... | c91be8e3977065cfcbbca95a8086fa29a8f0f72a | 41,743 |
def drop_short_sentences(X, min_len=2):
"""
:param X: a data matrix: a list wrapping a list of strings, with each sublist being a sentence.
:return:
>>> drop_short_sentences([['ita', 'vero'], ['quid', 'est', 'veritas'], ['vir', 'qui', 'adest']])
[['quid', 'est', 'veritas'], ['vir', 'qui', 'adest']]... | 1cae9d06ca9b83ebd51df5be5ed0c32cc6973967 | 41,744 |
import re
import textwrap
def reflowed_lines(lines, regex, line_length):
"""Get the realigned lines
This method takes a list of strings and lays them out respecting the given
line length while also lining up the hanging lines
:param lines: list of strings to realign
:param regex: regex to identi... | c8972f0f42b4eb8e4ec04fa617b2783b3cb9b77a | 41,745 |
def get_current_formatted_date():
"""Get current date or previous business day"""
try:
current_time = get_current_time()
diff = 0
if current_time.weekday() == 5:
diff = 1
if current_time.weekday() == 6:
diff = 2
return format_date(current_time - ... | a4692d705612a0eece21296535dc2ca7662f371a | 41,746 |
def pdb_target_dataset(original_dataset_path, go_dataset_path,
mapping_dataset_path, human_dataset_path,
col_name_entry = 'entry_ac', col_name_pdb = 'pdb_ids'):
"""
1. original_dataset_path: the path of the target dataset, a.k.a the dataset of protein tha passed ou... | eb4888b065f4bbc46a0d79f5ef101b64eb2e3d0b | 41,747 |
def search(request):
"""
Search IETF Groups
**Templates:**
* ``groups/search.html``
**Template Variables:**
* form, results
"""
results = []
if request.method == 'POST':
form = SearchForm(request.POST)
if form.is_valid():
kwargs = {}
grou... | c0b5a558d56524f1bd65a4cf505a5632bf3625b2 | 41,748 |
from typing import List
def elitist_selection(chromosome: AbstractChromosome, mutated_chromosomes: List[AbstractChromosome],
objective: Objective) -> AbstractChromosome:
""" Selects a chromosome using the elitist strategy
Args:
chromosome (AbstractChromosome): The source chromos... | c922129c252af8e80325c4e09da6da474b3b9c11 | 41,749 |
def prettyprint_jobs_single(data: dict) -> str:
"""
Prettyprinter for single job output
"""
output = ''
job_data = data['data']['jobs'][0]
result = 'None'
exception = 'None'
if job_data['exception'] is not None and 'message' in job_data['exception']:
exception = job_data['exce... | 64818c27bb4486cf87f6ac1ce7471d447eea7093 | 41,750 |
from datetime import datetime
import time
def main(*args):
"""
Process command line arguments and invoke bot.
If args is an empty list, sys.argv is used.
@param args: command line arguments
@type args: str
"""
pywikibot.output(color_format("Start: {white}{0}{default}", datetime.now()))
... | 8ef728e8f32456972b60ffdce0b41096e104d9af | 41,751 |
def extractLightNovelCafe(item):
"""
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol or frag) or 'preview' in item['title'].lower():
return None
if 'Evolution Theory of the Hunter' in item['tags']:
return buildReleaseMessageWithType(item, 'Evolution Theory of t... | 12cea449bbc128842fe1ddc1e1c558e6efc28056 | 41,752 |
async def poll_control_device(zha_device_restored, zigpy_device_mock):
"""Poll control device fixture."""
cluster_id = zigpy.zcl.clusters.general.PollControl.cluster_id
zigpy_dev = zigpy_device_mock(
{1: {"in_clusters": [cluster_id], "out_clusters": [], "device_type": 0x1234}},
"00:11:22:33:... | 03a86a75e09eff4c05bafcdc7b01597c159766f8 | 41,753 |
from typing import List
def load_tf_sess_variables_to_keras_single_gpu(path: 'str', compressed_ops: List['str']) -> tf.compat.v1.keras.Model:
"""
Creates a Keras model subclass and loads the saved session, meta graph and variables to Keras model
:param path: Path to load the tf session saved using save_s... | d18f49f296a5274aafc53476c52de0c8939a6ac7 | 41,754 |
def standardizeText(line, forward=True):
"""
Remove whitespace, lowercase,
and end with termination character \r
"""
text = line.strip().lower()[:63]
return (text if forward else text[::-1]) + '\r' | 5487f416abe78385f712c7b0ec652b4548accbf0 | 41,755 |
def selstr(a, start, stop):
""" Select elements of a string from an array.
:param a: array containing a string.
:param start: int referring to the first character index to select.
:param stop: int referring to the last character index to select.
:return: array of strings
"""
if type(a... | 91400815c1be10f1691be2799ce84229d121afec | 41,756 |
from .preprocess import tokenize_docs, create_pipeline
from gensim.models import Phrases
from typing import Callable
from typing import Optional
from typing import Pattern
from typing import Iterable
import tqdm
def detect_phrases(
docs_reader: Callable,
passes: int = 1,
lowercase: bool = False,
detec... | 584031b4b20605e86740ab773a12f2fc09a72837 | 41,757 |
from typing import List
from typing import Dict
from typing import Any
def format_sents_for_output(sents: List[str], doc_id: str) -> Dict[str, Dict[str, Any]]:
"""
Transform a list of sentences into a dict of format:
{
"sent_id": {"text": "sentence text", "label": []}
}
"""
... | d6178ac48da4d95e8d3727ca9220168e06ba223e | 41,758 |
import re
def get_sale(word):
"""Convert the input into a dictionary, with keys matching
the CSV column headers in the scrape_util module.
"""
number_word = [idx for idx, val in enumerate(word) if is_number(val)]
cattle_string = word[number_word[0]+1]
# Skip lines describing sales of no... | 0c9e3d276cbc91906d66d1a8ea65fb75d25aba5d | 41,759 |
def get_all_feed_groups_detached(feed_name):
"""
Returns a list of FeedMetadata objects populated with FeedGroupMetadata objects as returned by the db, but detached from the session.
:return: list of FeedMetadata objects
"""
db_session = get_session()
try:
feeds = lookup_feed(db_session... | 0abc1d57753bed2b6392086e9e8cfe89832ad7f3 | 41,760 |
from ctypes import c_int, c_char, POINTER, byref
from mceq_config import mkl
from ctypes import c_double as fl_pr
from time import time
def solv_MKL_sparse(nsteps, dX, rho_inv, int_m, dec_m, phi, grid_idcs):
# mu_loss_handler):
"""`Intel MKL sparse BLAS
<https://software.intel.com/en-us/articles/intel-mkl... | 1e3a774747384e49c4fad7123228696e1749aeff | 41,761 |
from typing import List
from typing import Union
from typing import Dict
from typing import Set
def get_nearest_neighbors(
node_ids: List[Union[int, str]], embeddings: np.ndarray, num_nearest: int
) -> Dict[Union[int, str], Set[Union[int, str]]]:
"""
Compute similar nodes among a set of embeddings.
P... | d1bb386a9f1eb17f2a040c60fa0da219c777115d | 41,762 |
def compress_ind(x: np.ndarray, width: int):
"""
Compress array to a given size (width).
:param x:
Array
:param width:
Total size of the new array.
:return:
Compressed array.
"""
comp_arr = np.empty(width, dtype=np.float32)
comp_arr[:], ind_width, i = np.NaN, int(... | 0851ea83c27835d717a1c73fa85f4ba9d05d130f | 41,763 |
def get_link_target(path):
"""Takes a path to a .lnk file and returns a path the .lnk file
is targeting or None.
"""
link = pythoncom.CoCreateInstance(
shell.CLSID_ShellLink, None,
pythoncom.CLSCTX_INPROC_SERVER,
shell.IID_IShellLink)
try:
link.QueryInterface(pytho... | d9db8e3e29f61dad7f482519deaa17498af40011 | 41,764 |
import numpy
def _op_type_domain_classifier(dtype):
"""
Defines *op_type* and *op_domain* based on `dtype`.
"""
if dtype == numpy.float32:
return 'TreeEnsembleClassifier', 'ai.onnx.ml', 1
if dtype == numpy.float64:
return 'TreeEnsembleClassifierDouble', 'mlprodict', 1
raise Run... | 2ca981cd5a4be1a2c9cc8c013a3502ba08634ccb | 41,765 |
import sys
def richardson_extrapolation_lspr(test_result):
"""
Performs an estimate of the exact solution using
Richardson extrapolation, given by
f_ex = (f_1 * f_3 - f_2^2) / (f_3 - 2*f_2+f_1)
where f_1 is a result from the finest grid and f_3 is from the coarsest.
The grids f_1, f_2, f_3 s... | 4dcc1136e61352b2fafdd4d4ac168145cc93a8ae | 41,766 |
def get_guess(guesses):
"""
This function will get the user's guess.
"""
# Get the user's guess.
guess = input("------\nGuess a letter: ")
# Check if the user has already guessed the letter.
if guess in guesses:
print("You've already guessed that letter.")
return get_guess(guesses)
# Return the guess.
re... | 04b559d3850421ef91fa1ce5d9850b2f4852f917 | 41,767 |
def primes(n):
"""Prime number less than n"""
return takewhile(lambda p: p < n, erat2()) | acf35fda04f1824662aaafbc72f10c1c214daf48 | 41,768 |
import os
def _include_patterns(*patterns):
"""Factory function that can be used with copytree() ignore parameter.
Arguments define a sequence of glob-style patterns
that are used to specify what files to NOT ignore.
Creates and returns a function that determines this for each directory
in the fi... | 71b0e1e3d3897c17ebb4270c2072cb02df324e07 | 41,769 |
import json
def get_config(config_file: str = None) -> dict:
"""Returns the configuration from a config file
:param config_file: json file with the configurations
:type config_file: str
:return: dictionary with the configurations
:rtype: dict
"""
if not config_file:
return CONFIG
... | b4dc7d787f131990014d088cd85e07f60657b843 | 41,770 |
def browse(session, queue, timeout=0, transform=lambda m: m.content):
"""Return a list with the contents of each message on queue."""
r = session.receiver("%s;{mode:browse}"%(queue))
r.capacity = 100
try:
return [transform(m) for m in receiver_iter(r, timeout)]
finally:
r.close() | 2d09023c6b485338984b210d097e1ca50af4dbf2 | 41,771 |
import numpy
def _run_pmm_one_variable(
input_matrix, max_percentile_level=100):
"""Applies PMM to one variable.
E = number of examples (realizations over which to average)
:param input_matrix: numpy array. The first axis must have length E. Other
axes are assumed to be spatial dimension... | 4e4658b99ea2c6a2a5a27d2d1ba701709c3a7d94 | 41,772 |
def latitudinal_summary(ds, lat_dim='lat', lon_dim='lon', lat_res=5):
"""Compute latitudinal (bin) statistics, averaging over longitude."""
# Check lat_dim and lon_dim
# Check lat_res < 90
# TODO: lon between -180 and 180 , lat between -90 and 90
aggregating_dims = list(ds[lon_dim].dims)
bins... | 659acff234e3b07d5975150997dbdb137553b410 | 41,773 |
def is_addon_dir(addon_dir):
""" Test if a directory contains an Odoo addon. """
return bool(get_manifest_path(addon_dir)) | 82752c8abb18ea23abf6d5886446ea7643897d21 | 41,774 |
import warnings
def stats_summary(X, sigma=5.0, n_min=5, kde=True, bw=None,
prefix=None, verbose=False, return_clipped=False):
"""
Statistical summary of an array.
"""
keys = ['low', 'upp', 'mean', 'median', 'std', 'kde', 'sigmaclip']
if prefix is not None:
keys = ['_'.jo... | 4a7a147339654f344720dafba6e11c456afe8748 | 41,775 |
def forward_pfb(timestream,nchan=NCHAN,ntap=NTAP,window=h.sinc_hanning):
"""Performs the Chime PFB on a timestream
Parameters
----------
timestream : np.array
Timestream to process
nchan : int
Number of frequencies we want out (probably should be odd
number because of Ny... | 880994d33c28e6c4dca3292ab2355a4819a5f102 | 41,776 |
def get_jsrun_launcher(num_procs, args):
"""Return the base launch command using jsrun."""
ppn, num_nodes = get_ppn_and_nodes(num_procs, args.procs_per_node)
return ['jsrun',
'--nrs', str(num_nodes),
'--rs_per_host', '1',
'--tasks_per_rs', str(ppn),
'--cpu_per... | ddf32fc1e259d41916efd4b8521bea0f2dd96bb5 | 41,777 |
def generation_solution(villes):
"""
With the cities as a list, we generate a random permutation of this list
to create a solution
"""
return np.random.permutation(villes) | 1470150729f1ffd90f586e979906b05b9fbf8cf6 | 41,778 |
from typing import Dict
from typing import Any
import yaml
def get_config(config_path: str) -> Dict[str, Any]:
"""Parse the JSON config file at the given path and return the `dict`."""
with open(config_path, 'r') as config_file:
return yaml.load(config_file) | 71d37aa71ccb110ede2e808a37be051ed625b482 | 41,779 |
def dis_gamma_ll(ab, k, theta):
"""Log-likelihood of a discrete gamma distribution
k - shape parameter
theta - scale parameter
Normalization constant is calculated based on a cuf-off (currently set at 10**5)
"""
cutoff = 1e5
gamma_sum = sum(stats.gamma.pdf(range(1, cutoff + 1), k, ... | fdc7c1757b9212042b1032c4501bf93e70f991c9 | 41,780 |
import csv
def parse_input(input_file):
"""
Parse the input with a dict reader and returns tthe data aggregated per taxid
"""
data_per_taxid = defaultdict(list)
data_per_taxid_and_assembly = defaultdict(list)
with open(input_file) as open_file:
reader = csv.DictReader(open_file, delim... | 78594c103c8acc5afbb0c0fb800bfff2943869aa | 41,781 |
from typing import Counter
def generate_common_dict(d1, d2):
"""Generate a dictionary by combining d1 and d2
Args:
d1 (list): a list of words
d2 (list): a list of words
Returns:
Counter: combined dictionary
"""
word1 = d1.copy()
word1.extend(d2)
c = Count... | 581a41f60ae47caadced8a08ef1c4356a9b7d3b8 | 41,782 |
import six
def metrics(
metrics, has_script=None, has_capability=None, matcher=None, access=None, volatile=True
):
"""
Decorator to use inside get_metrics script to denote functions
which can return set of metrics
@metrics(["Metric Type1", "Metric Type2"])
def get_custom_metrics(self, metrics... | 288fa0bc59772cb3a8c77c28f1ae1d0bc82d7e0a | 41,783 |
import functools
def build_dummy_sequential_net(fc_layer_params, action_spec):
"""Build a dummy sequential network."""
num_actions = action_spec.maximum - action_spec.minimum + 1
logits = functools.partial(
tf.keras.layers.Dense,
activation=None,
kernel_initializer=tf.random_uniform_initializ... | 9e78571da336d6e82909f355aa5e15b7e2367ab9 | 41,784 |
import os
def just_the_name(path):
"""Remove extension and path"""
return remove_extensions(os.path.basename(path)) | 8408495922af5689a733e2aeb4b475b5dfb5fafd | 41,785 |
from sys import path
def get_view():
""" Responds with the form for the example"""
return render_template(
"eg001_get_monitoring_data.html",
title="Get monitoring data",
source_file=path.basename(path.dirname(__file__)) + "/controller.py",
source_url=DS_CONFIG["monitor_github... | 4fda7ca649268f50258ec1279a90b1fba8c95a40 | 41,786 |
def calc_process_time(t1, t2):
"""Calculates difference between times
Args:
t1 (float): initial time
t2 (float): end time
Returns:
str: difference in times
"""
return str(t2 - t1) | 72e59c1a053041aae53cdb4415b241499eefdd4c | 41,787 |
def mechanism_exponential_discrete_gumbel(x, candidates, epsilon, scorer, sensitivity, monotonic=False):
"""Return an `epsilon`-DP sample from the set of discrete `candidates`.
The sampling probabilities is constructed by running `scorer` on `x` for each candidate.
:param x: 1d dataset for which to release... | 3b2996d206b55ac0f804964eceb49a2d87898bba | 41,788 |
import sys
def setupStderrLogger(logger, level, formatter=None):
"""configure logging to stderr. Logger maybe a logger, logger name, or
None for default logger, returns the logger."""
return setupStreamLogger(logger, sys.stderr, _convertLevel(level), formatter) | cbb55a7636f7086f404179ad5ebd52877b614c03 | 41,789 |
from typing import Iterable
import math
def percentile(N: Iterable, percent: int):
"""
Find the percentile of a list of values.
Stolen from http://code.activestate.com/recipes/511478-finding-the-percentile-of-the-values/
"""
if not N:
raise ValueError('N must be non-empty iterable')
i... | 9e6402b60ec077fe43ca807fa73aac27267cfd2b | 41,790 |
import sys
import socket
import time
def connect_socket_with_backoff (address, port, max_backoff_seconds=32):
"""
Attempt to connect to the given address and port.
If the connection attempt fails, exponentially back off, up to the maximum.
return the connected socket, or raise an exception if the connection... | 8bea66256dff9cfbdf3836ca156b760881a5937d | 41,791 |
def application():
"""Set up global front-end app for functional tests
Initialized once per test-run
"""
application = create_api_app(env_level="TEST")
application.test_client_class = ApiClient
application.response_class = ApiResponse
return application | cebbc8ba5324c7d7eecda613e156ba04b521ffd1 | 41,792 |
import copy
def _initialize_options(img_stack,get_darkfield,options):
""" Initialize optimization options
This function modifies the default OPTIONS using information about the images to be processed.
Inputs:
img_stack - A numpy matrix where images are concatenated along the 3rd dimensions
... | 93f7a346c82ca7a41a8b4d992ed433cb3339472a | 41,793 |
from typing import Optional
def find_file_with_magic(data: bytes) -> Optional[str]:
"""Find files with the help of magic numbers library"""
res: Text
if len(data) < 8:
return None
try:
res = magic_handle.from_buffer(data)
# try again with a potential padding byte removed
... | 4d71ea645a151803d886157e80bd294a4a9927bd | 41,794 |
def read_info_from_data_file(file_path, step_timelength, time_begin, time_end, raw_input, samplerate):
"""
Detect if input is binary or wav then use the appropriate method
"""
if raw_input:
return read_info_from_bin(file_path, step_timelength, time_begin, time_end, samplerate)
else:
... | 57a49ce7788175c2158beb66492cd15d6ec288df | 41,795 |
from typing import Any
def _lower(obj: Any) -> str:
"""Helper for the sort filter"""
try:
return str(obj).lower()
except AttributeError:
return "" | 45b8d5de8b74cb40b32f2369a8a3d8ff9ae8d6d1 | 41,796 |
def update_cupcake(cupcake_id):
"""Update cupcake from data in request. Return updated data.
Returns JSON like:
{cupcake: [{id, flavor, rating, size, image}]}
"""
data = request.json
cupcake = Cupcake.query.get_or_404(cupcake_id)
cupcake.flavor = data['flavor']
cupcake.rating = d... | 76ccd5f110b4a39d416251c362361748302a6eb9 | 41,797 |
def fo_match(pat,inst,freesyms,constants):
""" Compute a partial first-order match. Matches free FO variables to ground terms,
but ignores variable occurrences under free second-order symbols. """
if il.is_variable(pat):
if pat in freesyms and all(x in constants for x in lu.variables_ast(inst)):
... | 541a7f8c8772a9705ecb6389926e969908fe2ba3 | 41,798 |
from typing import List
from typing import Union
from typing import Optional
def tune_te(
tensors: List[Tensor],
target: Union[str, Target],
config: SearchStrategyConfig,
work_dir: str,
*,
task_name: str = "main",
builder: Optional[Builder] = None,
runner: Optional[Runner] = None,
... | ed4e94d892de2183b714c55adc4a62b7942e9ebd | 41,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.