content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import re
def get_definitions(word):
"""
Load a page from pl.wikt and find all definitions in the Polish section.
This can be used to show the user a list of definitions beside an example,
so they can match the two.
Args:
word (str): page title on pl.wikt
Returns:
tuple:
... | 2d2afc2287e4c78b10be6cc9a5ddaa5205b0fa46 | 62,800 |
import json
def stream_n_messages(n):
"""Stream n JSON messages"""
response = get_dict('url', 'args', 'headers', 'origin')
n = min(n, 100)
def generate_stream():
for i in range(n):
response['id'] = i
yield json.dumps(response) + '\n'
return Response(generate_strea... | 5dd2e3acc6bd09c01f3c0e3aff96aaed5eea239a | 62,801 |
def get_ganesha_config(user_id, access_key, secret_key, rgw_hostname, nfs_version):
"""
This function is to get the ganesha configuration
Parameters:
user_id(char): uid of the user
access_key(char):
secret_key(char):
rgw_hostname(char): name of the rgw host running ganesha
... | 242723feca72d1147e2f6f3c6117bd068d92a02c | 62,802 |
def param_samples(sample_names: StringList = SAMPLES):
"""Parametrize with list of samples"""
names = 'samp'
vals = get_samples(sample_names)
ids = sample_names
return parametrize(names, vals, ids) | 32f833cc4c41b0c009f046887acebaf8b2bd8731 | 62,803 |
def add_ingredient_item(user_id, recipe_id):
""" Adds an ingredient to the database and references the recipe id
:return
returns the edit-recipe.html form ingredient tab with updated ingredient list
"""
# Insert ingredient record
DB_INGREDIENTS.insert_one(
{'ingredient_item': reque... | 642b363ce8baa07a76a9ec5f039207b6f33255e7 | 62,804 |
import inspect
def docstring(obj):
""" return un-inherited doc-attribute of obj.
(i.e. we detect inheritance from its type).
XXX: this should eventually go into the inspect module!
"""
if getattr(type(obj),'__doc__','')!=getattr(obj,'__doc__',''):
return inspect.getdoc(obj) | 94f2089b8b25e9d7e83192dd5e3c02992559a2e2 | 62,805 |
def nice_number_nl(number, speech, denominators=range(1, 21)):
""" Dutch helper for nice_number
This function formats a float to human understandable functions. Like
4.5 becomes "4 einhalb" for speech and "4 1/2" for text
Args:
number (int or float): the float to format
speech (bool): fo... | 4ba1103ace7dc1029cf372b487cacf672442acab | 62,806 |
def question_encoder(question, hparams, name="encoder"):
"""Question encoder, run LSTM encoder and get the last output as encoding."""
with tf.variable_scope(name, "encoder", values=[question]):
question = common_layers.flatten4d3d(question)
padding = common_attention.embedding_to_padding(question)
leng... | f1dd3ef983cfe0ddc0c77f7ac021b266b595eac4 | 62,807 |
def isstub(fn):
"""Returns true if a function is likely only a stub"""
if len(fn.basic_blocks) > 1 or len(fn.llil.basic_blocks) > 1:
return False
if fn.llil.basic_blocks[0].has_undetermined_outgoing_edges or len(fn.callees) == 1:
return True
return False | c980fdcaef2b1dc24b7e25bbf2230ded08b8615d | 62,808 |
import json
def flag_validate(flag:str,id:int):
""" flag_valiate : validate the flag
Args:
flag (str): flag string
id (int): user discord id
Returns:
result(str): result after validate
"""
solve_level = []
flaglist = open("./challenge/flaglist.txt").read().s... | 932cafcc6e3d62a0a095c019ff4d78bc04faabfc | 62,809 |
def query_preview(request):
"""Apply the query to the connection and return render with the column names and a preview of the data."""
connection_id = request.POST.get("connection_id", None)
query = request.POST.get("query", None)
connection = Connection.objects.get(id=connection_id)
# Only get th... | a7a42daa748d9a1147d66e99eb77942ec589cc99 | 62,810 |
def supplies_profit(buyer):
"""Calculate profit from supply transactions
supply profit = supply revenue - supply cost
Where supply revenue is pulled from FishdataExpense costs are pulled from
FishdataSupplypurchases.
Arguments:
buyer -- FishdataBuyer object
Returns:
supplies_income -... | e5c0da614904935a35837f629846eaa67984f9ff | 62,811 |
from typing import Optional
import pathlib
import json
def write_component(
component: Component,
gdspath: Optional[PosixPath] = None,
path_library: PosixPath = CONFIG["gds_directory"],
precision: float = 1e-9,
settings: None = None,
with_settings_label: bool = conf.tech.with_settings_label,
)... | 9c5b093977e830d20aba0d67dec79098b3707ba6 | 62,812 |
def getGeolocalisationFromJson(image):
"""Get geolocalisation data of a image in the database
Parameters:
image (json): image from the validation data
Returns:
float: lng (degree)
float: lat (degree)
float: alt (degree)
float: azimuth (degree)
float: tilt (degree)
float: roll (... | 4ea02780b4254dfb03ac335ca1214a7b7d6bf521 | 62,813 |
import tqdm
def evaluate(
data, parameters, feature_names, tagset, score_func, verbose=False
):
"""
Evaluates precision, recall, and F1 of the tagger compared to the gold standard in the data
:param data: Array of dictionaries representing the data. One dictionary for each data point (as created by t... | d097bf93147daae1a3662c3b28c20dd7d408cd60 | 62,814 |
def _class_for_name(module_and_class_name):
"""
Return the class object given an name.
Parameters
----------
module_and_class_name : strictly
The module and class name, e.g. "mymodule.MyClass"
Returns
-------
class
"""
parts = module_and_class_name.split('.')
module... | 5972b6d45e592e426db9516a74cf33fd3381eebe | 62,815 |
import random
def get_random_header():
"""
:return (dict): A header with a random browser/OS configurations out of the available list.
"""
return headers_list[random.randint(0, len(headers_list) - 1)] | cc42d553ec1dc17d41e139528055add5cde7cd69 | 62,816 |
def experiment_name_resolution(setup_pickleddb_database, experiment_name_conflict):
"""Create a resolution for a code conflict"""
return experiment_name_conflict.ExperimentNameResolution(
experiment_name_conflict, new_name="new-exp-name"
) | 1172fc3380cce7190528cf6125ed8ec3a625eaf2 | 62,817 |
import os
import csv
def matrix2list(input_file_path, output_file_path, delimiter=',', skip_null_rec=True, null_str='',
infile_encoding='utf-8', outfile_encoding='utf-8',
vertical_column_name_index=0, vertical_column_ignore_tail=0,
horizonal_column_name_index=0, horizonal_column_ignore_tail=0... | 30efb1693e2ea7055c3c0b2d95c6946b63752d99 | 62,818 |
import hashlib
def createBase(secret):
"""
Creates a base from a given secret
"""
hx = [e for e in "0123456789abcdef"]
base = ""
if not isinstance(secret, bytes):
secret = secret.encode()
for c in hexlify(hashlib.md5(secret).digest()):
try:
base += hx.pop(hx.ind... | d10c8953175c13a0f0ac8a771dcbe34bdb0d8e12 | 62,819 |
import re
def get_used_non_latest_image_tags():
"""Get the list of image tags that are currently used by Docker files"""
image_tags = {}
for file_path in BASE_DIR.glob('Dockerfile-*'):
image_tag = None
with file_path.open('r') as fdockerfile:
for line in fdockerfile:
... | 10588b59c91fb79b319cb369ebf33dba6069dfd2 | 62,820 |
def get_largest_components(np_array, nr_components):
"""
Get largest connected components (how many defined by nr_components) from a binary image, background==0
:param np_array: a binary np array (e.g. segmentation mask)
:param nr_components: the number of largest components to keep
:return: a binar... | 9374bc81024c9ecb023edc20e7a48bde021124e5 | 62,821 |
from typing import Callable
import os
import argparse
def regular_file() -> Callable:
"""
Returns a method that can be used in argument parsing to check the argument is a regular file or a symbolic link,
but not, e.g., a process substitution.
:return: A method that can be used as a type in argparse.
... | d4c5e05ba3aed574e54e6bee6513e189b15e4a40 | 62,822 |
def model(pDict, lamSqArr_m2):
"""Single Faraday component with Burn depolarisation"""
# Calculate the complex fractional q and u spectra
pArr = pDict["fracPol"] * np.ones_like(lamSqArr_m2)
quArr = (pArr * np.exp( 2j * (np.radians(pDict["psi0_deg"]) +
pDict["RM_rad... | 5083a4bd03b96afc3c9350064587fb4ad0867cfa | 62,823 |
def isPalidrome(subject: str):
"""Returns True if subject is a palidrome string, False otherwise."""
inputLength = len(subject)
if(inputLength < 2):
return True
# Ignore the single mid character in odd length input
if inputLength % 2 != 0:
subject = subject[0:inputLength//2] + subj... | 6653f3d0421fc62387037a6f3a9a632229b0dcab | 62,824 |
from typing import Union
import os
import yaml
def from_yaml(path: str, cls: Union[Config, TerminalConfig]=TerminalConfig
) -> Union[Config, TerminalConfig]:
"""Create a :py:class:`Config` or :py:class:`TerminalConfig` from a yaml
file.
:param path: The path to the file.
:param cls: T... | df4bd5aaf1f64006b0ee8afba4f1f0f5b3efba67 | 62,825 |
def fixquotes(u):
"""
Given a unicode string, replaces "smart" quotes, ellipses, etc.
with ASCII equivalents.
"""
if not u:
return u
# Double quotes
u = u.replace('\u201c', '"').replace('\u201d', '"')
# Single quotes
u = u.replace('\u2018', "'").replace('\u2019', "'")
# E... | 28f8ff0068b28ae0cca60ac850c89403bc347346 | 62,826 |
def parse_username(username):
"""
parses uncapitalized, whitespace-padded, and weird-charactered mediawiki
user names into ones that have a chance of being found in the database
needs to accept either a unicode or string input, returns str of bytes
"""
# not pretty but python 2.7 is a box of
... | 929706d4ec909f41fed1fe7184f5856d208fd545 | 62,827 |
def get_role_tempalte(context=None,name=None,opts=None):
"""
Use this data source to retrieve information about a Rancher v2 role template resource.
> This content is derived from https://github.com/terraform-providers/terraform-provider-rancher2/blob/master/website/docs/d/roleTemplate.html.markdown.
... | 42ba6baaa72eeaa587b9ff0083ca82d866b67240 | 62,828 |
def jp_server_config():
"""Allows tests to setup their specific configuration values. """
return {} | 20d71f1e271eaf4859e5e6f2c86a80b5b3c2c52a | 62,829 |
def coa_livestock_parse(*, df_list, year, **_):
"""
Combine, parse, and format the provided dataframes
:param df_list: list of dataframes to concat and format
:param args: dictionary, used to run flowbyactivity.py
('year' and 'source')
:return: df, parsed and partially formatted to flowbyact... | 2233d6c3f28dd6ef645af0d16155277cc323c930 | 62,830 |
def draw_figure(canvas, figure, canvas_toolbar):
"""
This is Matplotlib helper code to draw a canvas in Pysimplegui window.
"""
if canvas.children:
for child in canvas.winfo_children():
child.destroy()
if canvas_toolbar.children:
for child in canvas_toolbar.winfo_children... | fd361c035814a4c25b3d10e0acac75d82205b395 | 62,831 |
def is_form_15(data, encoding, delim, quotechar):
"""
Files that start with "Fornecedor;"
These files never have quotes (in the current training set)
"""
is_form_15.ID = 15
if data.startswith("Fornecedor;"):
return (True, None)
return (False, "no_match") | a788a1f26fdc30f8f64523e53ce38918a9b4accd | 62,832 |
def compare_tau1(G,L,sir_list,community,MRCNN):
"""使用肯德尔相关系数对比不同方法
Parameters:
G:目标网络
dc:度中心性
bc:介数中心性
ks:k-shell
sir_list:不同beta下的SIR模拟结果
model:训练好的模型
p:选择比较节点的比例
return:
tau_list:在不同beta情况下的tau值
"""
num_nodes = int(p*G.number_of_nodes... | 9ee589e11b311da5f30263ca83fa79baa401667f | 62,833 |
import random
def round1(teams):
"""Run the first round and return a sorted list of team names.
teams is the sorted list [group0, group1, ...] and not the actual names of
the agents. This is necessary to start the agents.
"""
raw_input('--- Press ENTER to continue ---\n')
print()
print("R... | 9153395bea1d825211c358412d4f8938cb8ceeb5 | 62,834 |
def run_garage(env, seed, log_dir):
"""
Create garage model and training.
Replace the ppo with the algorithm you want to run.
:param env: Environment of the task.
:param seed: Random seed for the trail.
:param log_dir: Log dir path.
:return:
"""
ext.set_seed(seed)
with tf.Grap... | a1a1f2adadab26460b0035c02d663af031db62cc | 62,835 |
def modified_helmholtz_adjoint_double_layer_singular(
test_points, trial_points, test_normal, trial_normal, kernel_parameters
):
"""Modified Helmholtz adjoint double layer for singular kernels."""
npoints = trial_points.shape[1]
dtype = trial_points.dtype
diff = _np.zeros((3, npoints), dtype=dtype)
... | afe0c8c8e9f2a6096fb4928000ae46dcc2c326cd | 62,836 |
import time
import shutil
def curate_dataset(sourcedataset, destinationdataset, pathdataset, newdatasetname,\
manifeststatus, jsonpath, jsondescription):
"""
Associated with 'Generate' button in the 'Generate dataset' section of SODA interface
Checks validity of files / paths / folders and then ge... | e4427d48d3bdb81d384d3d2673f1a88f817b377c | 62,837 |
def adp_to_cartesian(alpha, delta, parallax):
"""
Convert coordinates from (alpha, delta, parallax) format into the (x, y, z)
format.
:param azimuth: [rad]
:param altitude: [rad]
:param parallax: [mas]
:return: [parsec](x, y, z) array in parsecs.
"""
parallax = parallax / const.rad... | bc3dac955d57458fbcb3f737617850730e6862c7 | 62,838 |
def render_hunspell_word_error(
data,
fields=["filename", "word", "line_number", "word_line_index"],
sep=":",
):
"""Renders a mispelled word data dictionary.
This function allows a convenient way to render each mispelled word data
dictionary as a string, that could be useful to print in the con... | 9bbefd0b998abe25d0a977adfe69ef51185cde37 | 62,839 |
def atan2(y, x):
""" My implementation of atan2 in tensorflow. Returns in -pi .. pi."""
tan = tf.atan(y / (x + 1e-8)) # this returns in -pi/2 .. pi/2
one_map = tf.ones_like(tan)
# correct quadrant error
correction = tf.where(tf.less(x + 1e-8, 0.0), 3.141592653589793*one_map, 0.0*one_map)
tan... | 6874de9fa697102d7af47af241e73ee322ce54c7 | 62,840 |
def ElasticConstants(atoms, symmetry, minimize=False, **kwargs):
"""Calculate the anisotropic elastic constants of a system.
The atoms must be a periodic system with an orthorhombic cell,
and the lattice constant(s) should be the equilibrium value(s).
If not, the function will crash, unless calle... | ba0b70e21209c9eb1691ec8b2af247a86d755759 | 62,841 |
from typing import List
import torch
def sample_subgraph(graph_data: List[GraphInput], n_nodes=None,
max_graph_size=None, do_sample=True, permuted_nodes=None):
"""
@param do_sample: if False, return original graph.
@param graph_data: a list of N graphs, [anchor, ...], which share the ... | dca3d0af8b3f6256e7bfcf5581f9d51011731784 | 62,842 |
import re
def tokenize(document):
"""
A tokenizer for the Python Textmining Package that works for unicode strings
and doesn't replace non-ASCII characters (such as 'åäö') with spaces.
"""
document = document.lower()
document = re.sub(u'[^\w]|[0-9]', u' ', document, flags=re.UNICODE)
retur... | 1d4a1e8ed05796df3ac797a0a08b82dba5f640e6 | 62,843 |
def update_context_path_comp_service_objective_function_name_name_by_id(uuid, value_name, name): # noqa: E501
"""Update name by ID
Update operation of resource: name # noqa: E501
:param uuid: ID of uuid
:type uuid: str
:param value_name: ID of value_name
:type value_name: str
:param name:... | 921bc1f4859de1ec74b4ee84f51974c2a790639d | 62,844 |
def ldns_resolver_print(*args):
"""LDNS buffer."""
return _ldns.ldns_resolver_print(*args) | bd4aa9bceaf5d20c5a3d8da980641b952a3f2332 | 62,845 |
import logging
def show_metadata_probe(pad, info, user_data):
"""Buffer probe to show metadata in a buffer"""
gst_buffer = info.get_buffer()
if gst_buffer:
logging.info("show_metadata_probe: %20s:%-8s: pts=%23s, dts=%23s, duration=%23s, size=%8d" % (
pad.get_parent_element().name,
... | f10c06f2dc61e545bd408dc48d18bf43b2459ccd | 62,846 |
def _get_dataset_iterator(snli_data, batch_size):
"""Get a data iterator for a split of SNLI data.
Args:
snli_data: A `data.SnliData` object.
batch_size: The desired batch size.
Returns:
A dataset iterator.
"""
with tf.device("/device:CPU:0"):
# Some tf.data ops, such as ShuffleDataset, are ... | 5574e3d9eecbfbe4e3db6390b0ca9bb10e5ac813 | 62,847 |
import signal
def coherence(original_values, frames=[0]):
"""Calculate coherence and an idea ribo-seq signal
Parameters
----------
values : array like
List of values
Returns
-------
periodicity : float
Periodicity score calculated as
coher... | 0656b7c5a43feb9c6264a24177754afb9e56de0a | 62,848 |
def distance_matrix(coords: list) -> np.ndarray:
"""Return distance matrix from coords"""
return np.triu(spt.distance.cdist(coords, coords, "euclidean")) | 050061e9624148a83e056511535094a5345f57e6 | 62,849 |
def get_domain_alerts_command(client: MsClient, args: dict):
"""Retrieves a collection of Alerts related to a given domain address.
Returns:
(str, dict, dict). Human readable, context, raw response
"""
headers = ['ID', 'Title', 'Description', 'IncidentID', 'Severity', 'Status', 'Classification'... | 4d6a8fbaf929e3c55849d67e08abf5b88dd91a5c | 62,850 |
import torch
def load_model(config, from_checkpoint=False):
"""
Wrapper around initialize_model. Loads model with parameters in config
and loads weights if from_checkpoint is set to True.
Args:
config (coconet.core.Configuration object)
from_checkpoint (bool): whether to load a pre-tr... | 3bfae38e940f8158eddae0a0922a45054cb2b901 | 62,851 |
from create_gitrepo import create_gitrepo
import random
import tqdm
from pathlib import Path
import re
import json
from datetime import datetime
def make_gt_line_pairs(ctx, fpaths, outputfolder, psm, lang, ext,
autocontrast, level, padval, padprc,
regex, min_len, max_len,... | 86082484b630a3e3e52bb4f657bb354612054a91 | 62,852 |
from typing import Union
from typing import Tuple
import os
def get_range_for_installed_solcs(min_version: Union[semver.VersionInfo, str],
max_version: Union[semver.VersionInfo, str]) -> Tuple[
semver.VersionInfo, semver.VersionInfo]:
"""finds the minimal and maximal installe... | 41fdb50f0c4dfeb3e65e82724ade11c22e05cf56 | 62,853 |
def postprocess_metainfo( opts, doxyindex, result ):
"""finalizes a metainfo by adding some generic fields"""
result['base_name'] = result['base'].decl_string.lstrip( '::' )
assert result['base'] and result['type'] and result['category']
result['gcc'] = create_decl( result['base'], doxyindex, opts )
... | 8382e41a6cda86904364b9010e94f3ed9fd2837a | 62,854 |
def int2lehex(value, width):
"""
Convert an unsigned integer to a little endian ASCII hex string.
Args:
value (int): value
width (int): byte width
Returns:
string: ASCII hex string
"""
return value.to_bytes(width, byteorder='little').hex() | 1ce9bb9447236c36bb906560c65ffd8e058c5aa4 | 62,855 |
def get_df_from_list(audio_files):
"""
Will return a data frame
filled with the features from audio files from the list
"""
frames = [get_features_from_file(f) for f in audio_files]
return pd.concat(frames, ignore_index=True) | e68f80d7f556a746f4232c031d6d917fb30f95bb | 62,856 |
def check(delta_seconds=3*60):
""" Check if the service has a recent active time (within 3 minutes) """
has_recent = False
for line in get_ethminer_service_output(delta_seconds):
time = parse_time(line)
if time:
if is_old_time(time, delta_seconds):
logger.debug('F... | 53ec2cd03588cad8024cc7c503ebdba08ec1b029 | 62,857 |
def simple_env():
"""Start up a super simple OneVsOne config."""
env = envs.v0.Pomme
game_type = constants.GameType.OneVsOne
env_entry_point = 'pommerman.envs.v0:Pomme'
env_id = 'Simple-v0'
env_kwargs = {
'game_type': game_type,
'board_size': constants.BOARD_SIZE_SIMPLE,
... | ddfd7b03a95abb85ca23ddc332dc62aa7968a89f | 62,858 |
def batchnorm_forward(x, gamma, beta, bn_param):
"""
使用使用类似动量衰减的运行时平均,计算总体均值与方差 例如:
running_mean = momentum * running_mean + (1 - momentum) * sample_mean
running_var = momentum * running_var + (1 - momentum) * sample_var
Input:
- x: 数据(N, D)
- gamma: 缩放参数 (D,)
- beta: 平移参数 (D,)
... | 32d662f5a40f35c8d97d3823d25ca13fc6f5916f | 62,859 |
def nearest_cluster_center(point, cluster_centers):
"""Distance and index of the closest cluster center"""
min_index = point.group
min_dist = FLOAT_MAX
for i, cc in enumerate(cluster_centers):
d = sqr_distance_2D(cc, point)
if min_dist > d:
min_dist = d
min_inde... | ccbebac91402e1bb0d3e5f4a8dd42028f858201b | 62,860 |
from typing import Callable
from typing import Tuple
import time
import warnings
def lanczos_algorithm(mvp_fn: Callable[[tf.Tensor], tf.Tensor],
dim: int,
order: int,
random_seed: int = 0,
only_gpu: bool = True) -> Tuple[tf.Tensor... | 859c395531ff3edf3f2a8495a52eb03c288379b3 | 62,861 |
def calculate_active_senders(api, all_messages, top_n=20, template=None):
"""
Return a top_n long df group of number of messages and average length.
"""
groupbys = {group: am.groupby("usender") for group, am in all_messages.items()}
active_senders = {group: pd.DataFrame(groupby.count()['body'].sort_... | 64de84679c26b1b396a8335db65b9d50374ef98c | 62,862 |
def detect() -> tp.List[Device]:
"""
Calls all detectors and returns a list of available devices.
"""
devices = []
SmlReader.detect(devices)
PlainReader.detect(devices)
Bme280Reader.detect(devices)
return devices | 696813b833c9a28f4a1862de27327f7d6ac66cdc | 62,863 |
from datetime import datetime
from typing import Optional
def update_datetime(
dt: datetime.datetime,
date: Optional[datetime.date] = None,
time: Optional[datetime.time] = None,
date_delta: Optional[datetime.timedelta] = None,
time_delta: Optional[datetime.timedelta] = None,
) -> datetime.datetime... | f78e61232e6a886f669c210da0a8e051594acd87 | 62,864 |
def load_lr_data(data_path, sep='\t'):
"""
load data with features
:param data_path:
:return:
"""
data_x = []
data_y = []
with open(data_path, encoding='utf-8') as f:
for line in f:
parts = line.strip().split(sep)
if len(parts) < 2:
... | ec10ec910d250b6de17b45a4d3f38b485eca61ad | 62,865 |
from openedx.features.enterprise_support.api import enterprise_customer_for_request
def get_enterprise_readonly_account_fields(user):
"""
Returns a set of account fields that are read-only for enterprise users.
"""
# TODO circular dependency between enterprise_support.api and enterprise_support.utils
... | c64d7da904fc1d1865a9e73f9a5f5c2a9a7258a8 | 62,866 |
def patient_eval_before_2015(patient_eval_date, patient_phen):
"""Gets an updated dictionary of patient phenotype, with patients before 2015 with no negative \
values (cf paper for explanation of possible bias)
Parameters: patient_eval_date (dict): dict with patient as key, evaluation date as value
... | e9f3c9456dac3b178f3746eb7a923148a1b81763 | 62,867 |
from typing import List
def describeMSCollectionTime(trap_metrics: mzqc.QualityMetric, ms_level: int) -> List[mzqc.QualityMetric]:
"""
describeMSCollectionTime calculates the descriptive statistics metrics for ion collection times of spectra from a given level.
From the proto-metrics on ion collection for ... | 08904a388ae7b9f3521dc1ab6bdc1766f9241b3f | 62,868 |
def parse_file(infile, LOGFC_threshold=1.6, FDR_threshold=0.05):
"""to do"""
count = 0
gene_to_logFC = defaultdict(str)
f_in = open(infile, "r")
for line in f_in:
if test_line(line):
data = line.split()
gene = data[0].strip()
logfc = data[3].strip()
... | 01f9abe719da8c0db0170bfa949543085a4e35ef | 62,869 |
def post_message_log(body: hug.types.json, response: 'hug.Response') -> hug.types.json:
"""Creates a new message log from the given data."""
try:
log = create_message_log(body, db)
except ValidationError:
response.status = HTTP_422
else:
return {'log_id': log.id} | 857f4b4917ee101eae0a333d0754f93d46849f58 | 62,870 |
def skewness(data_list):
""" Skewness of the data
Inputs:
data_list - a list of floats
Outputs:
val - The skewness of the data
"""
sigma = std(data_list)
mu = mean(data_list)
n = count(data_list)
if n == 0 or sigma == 0:
return 'NaN'
skew = sum... | c187828fcdf54406dcb8b0117bdeecbbf30e3b5f | 62,871 |
import platform
def getAllContexts():
"""Returns all available contexts.
>>> allContext = getAllContexts()
"""
contexts = []
for contextType in contextTypes:
contexts.append(getPlatformContext(contextType=contextType))
if platform == 'darwin':
for contextType in contextTypesO... | d93d5173d9f00628092c38ddda59e8a342084ab6 | 62,872 |
def muted_help(ctx):
""" Returns help for muted players embed
"""
embed = Embed(colour=Color.blurple())
embed.add_field(name='You are currently muted!',
value='`=escape` See how long you are muted for, give back permissions if no longer muted',
inline=False)
r... | 84fe8f5855f2de9afe3d2140d590865fe8435095 | 62,873 |
import socket
import struct
def ip4_from_int(ip):
"""Convert :py:class:`int` to IPv4 string
:param ip: int representing an IPv4
:type ip: int
:return: IP in dot-decimal notation
:rtype: str
"""
return socket.inet_ntoa(struct.pack(">L", ip)) | 94091bd650cf15bb216e82072478e73180c0027c | 62,874 |
def keras_prepare_labels(model, labels):
""" Preformat labels to be processed by the Keras model
- mainly handle the case of categorical_crossentropy
"""
loss = None
if hasattr(model, 'loss_functions') and model.loss_functions is not None and len(model.loss_functions) > 0:
# As in test mod... | 22e6afe1370848c1db9be2f8b803da2b1fee281c | 62,875 |
def nameToClass(name):
"""Converts a class name to a class. Returns None if not an ee class.
Args:
name: The class name.
Returns:
The named class.
"""
return _registered_classes.get(name) | 00688c60ba236e39d9d4d538e154b01cc4c59ca2 | 62,876 |
import torch
def simulator(param, n=100):
"""
Simulate a given parameter combination.
Parameters
----------
param : vector or 1D array
Parameters to simulate (\theta).
n : integer
Time series length
"""
m = len(param)
g = np.random.normal(0, 1, n)
gy = np.rando... | 18c330b0890541dca27fdd1f81fd1e9f7b35c14b | 62,877 |
def overlap(start_1, end_1, start_2, end_2):
"""Return the `range` covered by two sets of coordinates.
The coordinates should be supplied inclusive, that is, the end coordinates
are included in the region. The `range` returned will be exclusive, in
keeping with the correct usage of that type.
Para... | 0bf76a98feaf94fffa2a13eb74f2a16e4fafe350 | 62,878 |
def fill_card(template: Template,
row: Row,
card_index: int,
card_copy_index: int,
definitions: dict) -> (str, TemplateRenderData):
""" Return the contents of a card using the specified template. """
# attempt to fill all fields discovered in the template... | e8cf14fd24e3f6c4c5909e7c2879df97146b7a65 | 62,879 |
import inspect
def _get_all_prior_frames():
"""
Gets the calling stack formatted as a string seperated by periods, e.g.:
__main__.bar.baz
"""
frame = inspect.currentframe()
out = [] #container for output
while True:
frame = frame.f_back
name = _filter_frame(frame)
i... | 84473e7ab6b26fa5a848936d3aae4eebef7a3191 | 62,880 |
import asyncio
from typing import Optional
def _begin_validation(
session: UpdateSession,
config: config.Config,
loop: asyncio.AbstractEventLoop,
downloaded_update_path: str,
actions: update_actions.UpdateActionsInterface,
) -> "asyncio.futures.Future[Optional[str]]":
"""Start the validation p... | 0aaca2bd393dd795a19befa608f8214bccd0709f | 62,881 |
def csc_zero_cols(csc, cols_to_zero):
"""Set rows given by cols_to_zero in a sparse csc matrix to zero.
NOTE: Inplace operation! Does not return a copy of sparse matrix."""
rows, cols = csc.shape
mask = np.ones((cols,), dtype=np.bool)
mask[cols_to_zero] = False
nnz_per_row = np.diff(csc.indptr)
... | ff3b9868d26c7b773d7073afa723f29aca00033f | 62,882 |
import os
def _package_fullname_to_path(fullname):
"""Converts a package's fullname to a file path that should be the package's
directory.
:param fullname: The fullname of a package, like package_a.package_b
:return: A derived filepath, like package_a/package_b
"""
return fullname.replace("."... | c05042d50058a008359392f65a4d7f57a8ac208b | 62,883 |
import os
def set_favicon_rule(app):
"""Favicon rule"""
@app.route("/favicon.ico")
def favicon():
"""Serve the favicon.ico file"""
return send_from_directory(
os.path.join(app.root_path, "static"),
"favicon.ico", mimetype="image/vnd.microsoft.icon") | 4a72a798c2c689d5a4887bf209073089aac48ea9 | 62,884 |
def tracer_injection(logger, log_method, event_dict):
"""Inject tracer information into custom structlog log"""
correlation_log_context = tracer.get_log_correlation_context()
# add ids and configs to structlog event dictionary
event_dict["dd"] = correlation_log_context
return event_dict | b0f29e1db7c9f8422b9a82f2635f146413079ad9 | 62,885 |
def view_public_cluster(name):
"""
- List Clusters Registered on SLATE
"""
if request.method == 'GET':
# Check if cluster exists
if cluster_exists(name):
print("Found cluster: {}".format(name))
# cluster_info = get_cluster_info(name)
# print("Response ... | 8e952c19acf3e897253a01351765e61aade7c724 | 62,886 |
def get_best_beam(beam_model, sess, inp, target, batch_size, beam_size,
bucket, history, p, test_mode=False):
"""Run beam_model, score beams, and return the best as target and in input."""
_, output_logits, _, _ = beam_model.step(
sess, inp, target, None, beam_size=FLAGS.beam_size)
new_tar... | 09ffe12279ec06333725832a77a8331c5d7e60d1 | 62,887 |
def total_anchors(object_boxes, object_class_name=None, class_name_set=None):
"""
对所有待检测目标进行聚类,求出聚类中心,并绘制散点图
:param object_boxes: 所有物体的boxes
:param object_class_name: 对应的boxes的物体类别的名称
:param class_name_set: 物体类别名称的集合
:return 聚类中心
"""
# 开始聚类
cluster_machine = KMeans(object_boxes, k=5,... | 0c1d0e33e7f4bbecd1c196f199e26c10b97ea8a9 | 62,888 |
import os
import logging
def get_events(eventids, textfile, eventinfo, directory,
outdir=None):
"""Find the list of events.
Args:
eventids (list or None):
List of ComCat event IDs.
textfile (str or None):
Path to text file containing event IDs or info.
... | 5551e4a2ab482a0df984b2c4d2f0209aeb67c218 | 62,889 |
def async_run_job(jsondata, program, env):
""" Run job asynchronously.
:param jsondata: a dictionary that will be sent as request body.
:param program: a dictionary that defined request meta and parameter.
:param env: a dictionary that contained environments.
:return: AsyncResult, a celery task.
... | 346f059deb367070aaed106b72b5acb01070c178 | 62,890 |
import torch
def count_examples(loader: data.DataLoader):
"""Count the number of examples in a dataloader."""
count = 0
for batch in loader:
unpacked = batch
while not torch.is_tensor(unpacked):
unpacked = unpacked[0]
count += unpacked.size(0)
return count | 93e8d9e7e3e74e94a5fdc81fbe5666f583802882 | 62,891 |
def issubset(a, b):
"""Determines if a exists in b
Args:
a: sequence a
b: sequence b
Returns:
bool: True or False
"""
return set(a).issubset(set(b)) | 39e3c974cb2f3bc3ecfe17589292646f7a1a3383 | 62,892 |
def compare_pdf_file(path1, path2):
"""
Compare content of 2 pdf files by converting pages to png image files
:param path1: path of the pdf file to compare
:param path2: path of the pdf file to compare
:return: difference of image files
"""
img1 = Image.open(path1)
img2 = Image.open(pat... | b89cedf19d805d4ce1113e3d4543a38239cbd444 | 62,893 |
from pathlib import Path
import os
def parse_config(config_file: str, dotenv_file: str, include_os_env: bool) -> dict:
"""
Parse configuration file(s)
"""
config_file = Path(config_file)
if not config_file.exists():
raise IOError("could not find config file: {}".format(config_file))
i... | 2734778c69a0c659fea276a06213aaf6f32bb06f | 62,894 |
def bot() -> Bot:
"""
Creates a valid bot instance, with a token from 'TOKEN' environment variable if exists,
or the default one from PUBLIC_TEST_BOT_PARAMETERS otherwise.
:return: a bot instance
"""
return Bot(_get_bot_parameter('token')) | a17f5daeeadda5f78107d9dcfa5f6fcaac7d47e9 | 62,895 |
def checkins_to_string(count: int, checkins: list):
"""Takes a list of checkins and returns a string"""
# checkin_text = ("**checkin** - **beerID** - **beer (caps)**\n\t**brewery** - **badges** - **when**\n")
checkin_text = ""
for num, checkin in zip(range(count), checkins):
checkin_text += ("{!... | 4bde62bd6a6c0b194e306080413ff686d29bd8c5 | 62,896 |
def check_from_dict(method):
"""A wrapper that wrap a parameter checker to the original function."""
@wraps(method)
def new_method(self, *args, **kwargs):
word_dict, = (list(args) + [None])[:1]
if "word_dict" in kwargs:
word_dict = kwargs.get("word_dict")
if not isinstan... | 79158edde23d2e2b8b812d6dd117ab91351b44fd | 62,897 |
from src.bot.common import bot
def safe(msg=None):
"""Call the decorated function and log any exception thrown but do not interrupt the program.
"""
def deco_safe(f):
@wraps(f)
def f_safe(*args, **kwargs):
try:
return f(*args, **kwargs)
except Except... | 20864f671617ba32677be884f13fb202c1b1fef5 | 62,898 |
def _get_eigen_vector(dot_matrix, variance_thresh):
"""
Get eigen values and eigen vector from matrix which explain % variance_thresh of total variance
:param dot_matrix: (np.array): matrix for which eigen values/vectors should be computed
:param variance_thresh: (float): % of overall variance whic... | 1e98aa9e6c1c1a5716d4c6b3f85a399de73a19f4 | 62,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.