content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def list_volumes(vg):
"""List logical volumes paths for given volume group.
:param vg: volume group name
:returns: Return a logical volume list for given volume group
: Data format example
: ['volume-aaa', 'volume-bbb', 'volume-ccc']
"""
out, err = utils.execute('lvs', '--no... | 4cd613c8c10aaec443dce31cef8b132e3b2c65da | 3,640,900 |
def question_aligned_passage_embedding(question_lstm_outs, document_embeddings,
passage_aligned_embedding_dim):
"""create question aligned passage embedding.
Arguments:
- question_lstm_outs: The dimension of output of LSTM that process
... | 8dbcb298a24ec18da4904a8f48a7c63331b27c91 | 3,640,901 |
def lm_loss_fn(forward_fn, vocab_size, params, rng, data, is_training=True):
"""Compute the loss on data wrt params."""
logits = forward_fn(params, rng, data, is_training)
targets = hk.one_hot(data['target'], vocab_size)
assert logits.shape == targets.shape
mask = jnp.greater(data['obs'], 0)
loss = -jnp.su... | 44188d717759a82d80079b5e4f7309b3cf7b5cb0 | 3,640,902 |
import argparse
import os
import logging
def ParseArguments():
"""Parse command line arguments, validate them, and return them.
Returns:
A dict of:
{'args': argparse arguments, see below,
'cur_ip': the ip address of the target, as packed binary,
'cur_node_index': the current node index of... | 1fd47dafe3fcc30b6bf18174fe3da9f10e3e6c2b | 3,640,903 |
def chroms_from_build(build):
""" Get list of chromosomes from a particular genome build
Args:
build str
Returns:
chrom_list list
"""
chroms = {'grch37': [str(i) for i in range(1, 23)],
'hg19': ['chr{}'.format(i) for i in range(1, 23)]
... | c87431911c07c00aaa63357771258394cfff859e | 3,640,904 |
def get_ready_count_string(room: str) -> str:
"""Returns a string representing how many players in a room are ready.
Args:
room (str): The room code of the players.
Returns:
str: A string representing how many players in a room are ready in the format '[ready]/[not ready]'.
"""
pla... | eb8ae2a308ccd58355de5a8a15629bfccd1fcc2c | 3,640,905 |
from typing import List
def switches(topology: 'Topology') -> List['Node']:
"""
@param topology:
@return:
"""
return filter_nodes(topology, type=DeviceType.SWITCH) | e489740b29f8aff7368147274d020cb467422669 | 3,640,906 |
def geometric_progression(init, ratio):
"""
Generate a geometric progression start form 'init' and multiplying
'ratio'.
"""
return _iterate(lambda x: x * ratio, init) | 6b2626bc9d4016518b1cc7e41b63d34924c1ee30 | 3,640,907 |
import urllib
def resolve(marathon_lb_url):
"""Return the individual URLs for all available Marathon-LB instances given
a single URL to a DNS-balanced Marathon-LB cluster.
Marathon-LB typically uses DNS for load balancing between instances and so
the address provided by the user may actually be multi... | f192d66a8a12d772ad33b2b8030796af2393ec16 | 3,640,908 |
def _parse_bluetooth_info(data):
"""
"""
# Combine the bytes as a char string and then strip off extra bytes.
name = ''.join(chr(i) for i in data[:16]).partition('\0')[0]
return BluetoothInfo(name,
''.join(chr(i) for i in data[16:28]),
''.join(chr(i)... | ef46576102cfb5d1df0b40e84529a89e2ed6bfa8 | 3,640,909 |
async def get_reverse_objects_topranked_for_lst(entities):
"""
get pairs that point to the given entity as the primary property
primary properties are those with the highest rank per property
"""
# run the query
res = await runQuerySingleKey(cacheReverseObjectTop, entities, """
SELECT ?ba... | d975ba3ac3a0983d3a08057c91cd96ca466708df | 3,640,910 |
def LU_razcep(A):
""" Vrne razcep A kot ``[L\\U]`` """
# eliminacija
for p, pivot_vrsta in enumerate(A[:-1]):
for i, vrsta in enumerate(A[p + 1:]):
if pivot_vrsta[p]:
m = vrsta[p] / pivot_vrsta[p]
vrsta[p:] = vrsta[p:] - pivot_vrsta[p:] * m
... | 79d6a00b4e16254739b987228fd506cae133907b | 3,640,911 |
def jni_request_identifiers_for_type(field_type, field_reference_name, field_name, object_name="request"):
"""
Generates jni code that defines C variable corresponding to field of java object
(dto or custom type). To be used in request message handlers.
:param field_type: type of the field to be initial... | 4f23ba559124b938fa82a044ae1adc0f16f4a7ad | 3,640,912 |
def _ValidateDuration(arg_internal_name, arg_value):
"""Validates an argument which should have a Duration value."""
try:
if isinstance(arg_value, basestring):
return TIMEOUT_PARSER(arg_value)
elif isinstance(arg_value, int):
return TIMEOUT_PARSER(str(arg_value))
except arg_parsers.ArgumentTyp... | b08b65831e04ece410be7f0a490cd6ebf7bcaa6f | 3,640,913 |
def get_jaccard_dist1(y_true, y_pred, smooth=default_smooth):
"""Helper to get Jaccard distance (for loss functions).
Note: This mirrors what others in the ML community have been using even for
non-binary vectors."""
return 1 - get_jaccard_index1(y_true, y_pred, smooth) | c64ba7fd81c3697bc472d372afeb940e19d35e3c | 3,640,914 |
from pathlib import Path
from typing import Dict
import json
import warnings
def deduplicate_obi_codes(fname: Path) -> None:
"""
Remove duplicate http://terminology.hl7.org/CodeSystem/v2-0203#OBI codes from an instance.
When using the Medizininformatik Initiative Profile LabObservation, SUSHI v2.1.1 inse... | 336a143e30224b64c39358137bab26e4013c5049 | 3,640,915 |
def fold_conv_bns(onnx_file: str) -> onnx.ModelProto:
"""
When a batch norm op is the only child operator of a conv op, this function
will fold the batch norm into the conv and return the processed graph
:param onnx_file: file path to ONNX model to process
:return: A loaded ONNX model with BatchNor... | 25c2748b0e964310cc9909b60e68a9740e3e0df1 | 3,640,916 |
def numdays(year, month):
"""
numdays returns the number of days in the given month of
the given year.
Args:
year
month
Returns:
ndays: number of days in month
"""
NDAYS = list([31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31])
assert(year >= 0)
assert(1 <=... | 159a41f3706b087194e0ba5d107a1ceb88583c21 | 3,640,917 |
def normalise_diversity_year_df(y_div_df):
"""Normalises a dataframe with diversity information by year and parametre set"""
yearly_results_norm = []
# For each possible diversity metric it pivots over parametre sets
# and calculates the zscore for the series
for x in set(y_div_df["diversity_metric... | 83e12072e65a707dd61b98383ce295fac8e9f2f7 | 3,640,918 |
def allowed_file(filename):
"""Does filename have the right extension?"""
return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS | f42ac5ef5470515258715b4552945206a440effb | 3,640,919 |
from typing import Dict
from typing import Optional
from typing import Any
from typing import List
import tokenize
def render(
template: str,
context: Dict,
serializer: Optional[CallableType[[Any], str]] = None,
partials: Optional[Dict] = None,
missing_variable_handler: Optional[CallableType[[str,... | b660c0ac97915121d061fd5c7dde8cccea42f03f | 3,640,920 |
def preprocess_observations(input_observation, prev_processed_observation, input_dimensions):
""" convert the 210x160x3 uint8 frame into a 6400 float vector """
processed_observation = input_observation[35:195] # crop
processed_observation = downsample(processed_observation)
processed_observation = remo... | 885fbb2a1f81200843bb15d37f3c13726c23ea90 | 3,640,921 |
def expand_configuration(configuration):
"""Fill up backups with defaults."""
for backup in configuration['backups']:
for field in _FIELDS:
if field not in backup or backup[field] is None:
if field not in configuration:
backup[field] = None
... | 218f5c5cb67d3fa0f52b453d3cd00cde40835025 | 3,640,922 |
def create_feature_extractor(input_shape: tuple, dropout:float=0.3, kernel_size:tuple=(3,3,3)) -> tf.keras.Sequential:
"""
Create feature extracting model
:param input_shape: shape of input Z, X, Y, channels
:return: feature extracting model
"""
model = Sequential()
model.add(Conv3D(filters... | 47f52bab452e6bf7c9875a3c9c85bed02b79fcdc | 3,640,923 |
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:
"""Set up the component."""
hass.data.setdefault(DOMAIN, {})
async_add_defaults(hass, config_entry)
router = KeeneticRouter(hass, config_entry)
await router.async_setup()
undo_listener = config_entry.add_updat... | beac0da52a530aa63495003b78a87638b869779c | 3,640,924 |
def log_set_level(client, level):
"""Set log level.
Args:
level: log level we want to set. (for example "DEBUG")
"""
params = {'level': level}
return client.call('log_set_level', params) | d9f0c7cda877497acbe832bbc6c767bf331d0dc5 | 3,640,925 |
import subprocess
def exec_local_command(cmd):
"""
Executes a command for the local bash shell and return stdout as a string.
Raise CalledProcessError in case of non-zero return code.
Args:
cmd: command as a string
Return:
STDOUT
"""
proc = subprocess.Popen(cmd.split(), stdout=subprocess.PIP... | be0912712f4f5987b848cb08422fc6601be62653 | 3,640,926 |
def OGH(p0, p1, v0, v1, t0, t1, t):
"""Optimized geometric Hermite curve."""
s = (t-t0)/(t1-t0)
a0 = (6*np.dot((p1-p0).T,v0)*np.dot(v1.T,v1) - 3*np.dot((p1-p0).T,v1)*np.dot(v0.T,v1)) / ((4*np.dot(v0.T,v0)*np.dot(v1.T,v1) - np.dot(v0.T,v1)*np.dot(v0.T,v1))*(t1-t0))
a1 = (3*np.dot((p1-p0).T,v0)*np.dot(v0.... | 8bf86bbb2105ec26586a3568bb1a6448b284fbec | 3,640,927 |
def permutation_test(v1, v2, iter=1000):
"""
Conduct Permutation test
Parameters
----------
v1 : array
Vector 1.
v2 : array
Vector 2.
iter : int. Default is 1000.
The times for iteration.
Returns
-------
p : float
The permutation test result, p-... | 3b618069b610d0ee37e8bcb32f814e34efaeebab | 3,640,928 |
def registered_paths():
"""Return paths added via registration
..note:: This returns a copy of the registered paths
and can therefore not be modified directly.
"""
return list(_registered_paths) | 4bd8471fc2bff1e09a84b1ae8878c0db5f7afd65 | 3,640,929 |
import torch
def nms_dynamic(ctx, g, boxes: Tensor, scores: Tensor,
max_output_boxes_per_class: int, iou_threshold: float,
score_threshold: float):
"""Rewrite symbolic function for default backend.
Support max_output_boxes_per_class, iou_threshold, score_threshold of
const... | 6b6eea9ce2f2fe84cabb85ddbb069732fa78cca9 | 3,640,930 |
from typing import Union
from datetime import datetime
import pytz
def api_timestamp_to_datetime(api_dt: Union[str, dict]):
"""Convertes the datetime string returned by the API to python datetime object"""
"""
Somehow this string is formatted with 7 digits for 'microsecond' resolution, so crop the last d... | 26f4828a19d17c883a8658eb594853158d70fbcf | 3,640,931 |
from typing import List
def calc_mutation(offsprings: List[List[List[int]]], mut_rate: float, genes_num: int) -> List[List[List[int]]]:
"""
Not necessary, however when provided and returns value other than None, the simulator is going to use
this one instead of the given ones by default, if you are not i... | d665b7c2ff8ddfa2c4b905c3d6bab02028e30ec2 | 3,640,932 |
def compute_targets(ex_rois, gt_rois, weights=(1.0, 1.0, 1.0, 1.0)):
"""Compute bounding-box regression targets for an image."""
return box_utils.bbox_transform_inv(ex_rois, gt_rois, weights).astype(
np.float32, copy=False
) | de2a65b5c3c44bbd4bffcd0d99143982ed4c031c | 3,640,933 |
def _args_filter(args):
"""
zenith db api only accept list of tuple arguments for bind execute, that is ungainly
so we should make all kind of arguments to list of tuple arguments
"""
if isinstance(args, (GeneratorType, )):
args = list(args)
if len(args) <= 0:
return []
if ... | af9a836c1389acc4e0faf0d08e47ef8a39e57345 | 3,640,934 |
def getAreaDF(spark):
"""
Returns a Spark DF containing the BLOCK geocodes and the Land and Water area columns
Parameters
==========
spark : SparkSession
Returns
=======
a Spark DF
Notes
=====
- Converts the AREALAND and AREAWATER columns from square meters to square miles... | 181e84e98ca2cf83be0cf5dbf41a8dbc46b88ad4 | 3,640,935 |
import os
import subprocess
def run_command(command, filename=None, repeat=1, silent=False):
"""
Run `command` with `filename` positional argument in the directory of the
`filename`. If `filename` is not given, run only the command.
"""
if filename is not None:
fdir = os.path.dirname(os.pa... | 0f24c79f9d557198645de75fe7160af41638ecb6 | 3,640,936 |
def how_many():
"""Check current number of issues waiting in SQS."""
if not is_request_valid(request):
abort(400)
lapdog_instance = Lapdog()
lapdog_instance.how_many()
return jsonify(
response_type="in_channel",
text="There are 4 issues waiting to be handled",
) | db132bed6c957ad1f922776165ccb999bfcedb32 | 3,640,937 |
import struct
def read_sbd(filepath):
"""Reads an .sbd file containing spectra in either profile or centroid mode
Returns:
list:List of spectra
"""
with open(filepath, 'rb') as in_file:
header = struct.unpack("<BQB", in_file.read(10))
meta_size = header[1] * 20... | 364499580d5531d7361b87d3f575bf006fc79791 | 3,640,938 |
def dct2(X, blksize):
"""Calculate DCT transform of a 2D array, X
In order for this work, we have to split X into blksize chunks"""
dctm = dct_mat(blksize)
#try:
#blks = [sp.vsplit(x, X.shape[1]/blksize) for x in sp.hsplit(X, X.shape[0]/blksize)]
#except:
# print "Some error occurred"
... | 79aa158f4fd05ac35bad2d16c14b3b8cbd8351af | 3,640,939 |
def print_filtering(dataset, filter_vec, threshold, meta_name):
"""Function to select the filtering_names(names of those batches or cell types with less proportion of cells than threshold),
and print an informative table with: batches/cell types, absolute_n_cells, relative_n_cells, Exluded or not.
"""
... | c637a9d219443de730156e546d52461b9bcdfc84 | 3,640,940 |
import os
def attempt_input_load(input_path):
"""Attempts to load the file at the provided path and return it as an array
of lines. If the file does not exist we will exit the program since nothing
useful can be done."""
if not os.path.isfile(input_path):
print("Input file does not exist: %s" ... | f75e95258c803175d1f13d82c6479987cfdecbf9 | 3,640,941 |
from typing import Dict
def get_chunk_tags(chunks: Dict, attrs: str):
"""
Get tags for
:param chunks:
:param attrs:
:return:
"""
tags = []
for chunk in chunks:
resource_type = chunk['resource_type']
original_url = chunk['url']
parse_result = urlparse(original_u... | e7076b345bcca4e7fe8ac96002aad7499cf0b0f3 | 3,640,942 |
def __discount_PF(i, n):
"""
Present worth factor
Factor: (P/F, i, N)
Formula: P = F(1+i)^N
:param i:
:param n:
:return:
Cash Flow:
F
|
|
--------------
|
P
"""
return (1 + i) ** (-n) | b6e7424647921b945a524a22d844925573b6490a | 3,640,943 |
def pw2dense(pw, maxd):
"""Make a pairwise distance matrix dense
assuming -1 is used to encode D = 0"""
pw = np.asarray(pw.todense())
pw[pw == 0] = maxd + 1
# pw[np.diag_indices_from(pw)] = 0
pw[pw == -1] = 0
return pw | 68bbf753d80032a0e697b161c8836283a030a54a | 3,640,944 |
from typing import Awaitable
def run_simulation(sim: td.Simulation) -> Awaitable[td.Simulation]:
"""Returns a simulation with simulation results
Only submits simulation if results not found locally or remotely.
First tries to load simulation results from disk.
Then it tries to load them from the ser... | 23524bff78ac326bbf74e2389180d924849e57f4 | 3,640,945 |
def get_cursor_position(fd=1):
"""Gets the current cursor position as an (x, y) tuple."""
csbi = get_console_screen_buffer_info(fd=fd)
coord = csbi.dwCursorPosition
return (coord.X, coord.Y) | b99cf19081af7e0d68523d1efdfc80c89cfe64cc | 3,640,946 |
from typing import Tuple
def _held_karp(dists: np.ndarray) -> Tuple[float, np.ndarray]:
"""
Held-Karp algorithm solves the Traveling Salesman Problem.
This algorithm uses dynamic programming with memoization.
Parameters
----------
dists
Distance matrix.
Returns
-------
T... | 982d771c1fef5e4f6311fd1b36216c95db7f1343 | 3,640,947 |
import os
def dl_files(go_directory):
"""function to download latest ontologies and associations files from geneontology.org
specify the directory to download the files to"""
# change to go directory
os.chdir(go_directory)
# Get http://geneontology.org/ontology/go-basic.obo
obo_fname = downl... | 898597925655c31dc3a6eb84c6d99b5bc3c3a5db | 3,640,948 |
def NS(s,o):
"""
Nash Sutcliffe efficiency coefficient
Adapated to use in alarconpy by Albenis Pérez Alarcón
contact: apalarcon1991@gmail.com
Parameters
--------------------------
input:
s: simulated
o: observed
output:
ns: Nash Sutcliffe efficient ... | 10c14022ae634a74f0a417454ddfa0fa52d89c8a | 3,640,949 |
def UTArgs(v):
"""
tag UTArgs
"""
tag = SyntaxTag.TagUTArgs()
tag.AddV(v)
return tag | 8d9ff601a5a2bf65e68e074dad1894342881950f | 3,640,950 |
from src.praxxis.sqlite import sqlite_rulesengine
from src.praxxis.notebook.notebook import get_output_from_filename
def rules_check(rulesengine_db, filename, output_path, query_start, query_end):
"""check if any rules match"""
rulesets = sqlite_rulesengine.get_active_rulesets(rulesengine_db, query_start, qu... | a81d29a8a9d61ba6a577fbe9899967b81a25ff7f | 3,640,951 |
def shortstr(s,max_len=144,replace={'\n':';'}):
""" Obtain a shorter string """
s = str(s)
for k,v in replace.items():
s = s.replace(k,v)
if max_len>0 and len(s) > max_len:
s = s[:max_len-4]+' ...'
return s | 396794506583dcf39e74941a20f27ac63de325ec | 3,640,952 |
def update_gms_stats_collection(
self,
application: bool = None,
dns: bool = None,
drc: bool = None,
drops: bool = None,
dscp: bool = None,
flow: bool = None,
interface: bool = None,
jitter: bool = None,
port: bool = None,
shaper: bool = None,
top_talkers: bool = None,
... | d6dce80a8543cae16eebf076eeaa3e1428831df5 | 3,640,953 |
def _get_nearby_factories(latitude, longitude, radius):
"""Return nearby factories based on position and search range."""
# ref: https://stackoverflow.com/questions/574691/mysql-great-circle-distance-haversine-formula
distance = 6371 * ACos(
Cos(Radians(latitude)) * Cos(Radians("lat")) * Cos(Radian... | b94c879d93a486b4ac0dd77bee6fb9d79395dc23 | 3,640,954 |
def add_register(request):
"""
处理注册提交的数据,保存到数据库
:param request:
:return:
"""
form = forms.RegisterForm(request.POST)
if form.is_valid():
data = form.cleaned_data
#清洗数据
data.pop("re_password")
data['password'] = hash_pwd.has_password(data.get('password'))
#添加必要数据
data['is_active'] = 1
#格式化储存
model... | acaf3886773b599df2853a5e73ef504af27f1c53 | 3,640,955 |
import numpy
import pandas
def confidence_interval(data, alpha=0.1):
"""
Calculate the confidence interval for each column in a pandas dataframe.
@param data: A pandas dataframe with one or several columns.
@param alpha: The confidence level, by default the 90% confidence interval is calculated.
@... | f9c31549287723f7f75c265485b7cd9911f68168 | 3,640,956 |
def RunInTransactionOptions(options, function, *args, **kwargs):
"""Runs a function inside a datastore transaction.
Runs the user-provided function inside a full-featured, ACID datastore
transaction. Every Put, Get, and Delete call in the function is made within
the transaction. All entities involved in these ... | 9236024d034f193919e976a04eec9105ee899d48 | 3,640,957 |
def notify(message, key, target_object=None, url=None, filter_exclude={}):
"""
Notify subscribing users of a new event. Key can be any kind of string,
just make sure to reuse it where applicable! Object_id is some identifier
of an object, for instance if a user subscribes to a specific comment thread,
... | 9da7f8a498a3fad1f1acbb9e35e798083d6a25c5 | 3,640,958 |
from pathlib import Path
def get_project_root() -> Path:
"""Return the path of the project root folder.
Returns:
Path: Path to project root
"""
return Path(__file__).parent | 0122844ae89a53b0cd28659be21fb932164719cd | 3,640,959 |
def FTCS(Uo, diffX, diffY=None):
"""Return the numerical solution of dependent variable in the model eq.
This routine uses the explicit Forward Time/Central Space method
to obtain the solution of the 1D or 2D diffusion equation.
Call signature:
FTCS(Uo, diffX, diffY)
Parameters
------... | 4b02749f3f50a2cff74abb75146159289d42b99e | 3,640,960 |
def epicyclic_frequency(prof) -> Quantity:
"""Epicyclic frequency."""
Omega = prof['keplerian_frequency']
R = prof['radius']
return np.sqrt(2 * Omega / R * np.gradient(R ** 2 * Omega, R)) | 917fc1e094719f0dbb6a3ac7ca0396601060bf1c | 3,640,961 |
import os
import re
def _filter_subset(systems, test_sets, langpair, origlang, subset=None):
"""Filter sentences with a given origlang (or subset) according to the raw SGM files."""
if origlang is None and subset is None:
return systems
if test_sets is None or langpair is None:
raise Value... | 0a15d2290d32b5556e18e2324b80e49300a0acca | 3,640,962 |
def get_groups(
a_graph,
method='component_infomap', return_form='membership'):
"""
Return the grouping of the provided graph object using the specified
method. The grouping is returned as a list of sets each holding all
members of a group.
Parameters
==========
a_graph: :cl... | 110dd9dc470d9426b388e0db1289ff0b23c4a963 | 3,640,963 |
def positional_rank_queues (service_platform,
api_key):
""" Get the queues that have positional ranks enabled.
References:
https://developer.riotgames.com/regional-endpoints.html
https://developer.riotgames.com/api-methods/#league-v4/GET_getQueuesWithPositionRanks
... | f48f9a445aac9611d4892e1aab5e7699a4c3ec1f | 3,640,964 |
def maplist(f, xs):
"""Implement `maplist` in pure Python."""
return list(map(f, xs)) | 894a58f9e2cd66fe9c327ea65433b8210051ed60 | 3,640,965 |
import string
import re
def pull_urls_excel_sheets(workbook):
"""
Pull URLs from cells in a given ExcelBook object.
"""
# Got an Excel workbook?
if (workbook is None):
return []
# Look through each cell.
all_cells = excel.pull_cells_workbook(workbook)
r = set()
for cell i... | 0359fb8e1fd552749e15cce631f756130c5199cf | 3,640,966 |
import click
import requests
def do_request(base_url, api_path, key, session_id, extra_params=''):
"""
Voer een aanvraag uit op de KNVB API, bijvoorbeeld /teams; hiermee
vraag je alle team-data op
"""
hashStr = md5.new('{0}#{1}#{2}'.format(key,
api_path,
... | 44217caa2c2cdf7543597405836cf0bb1ac650cd | 3,640,967 |
def write_code():
"""
Code that checks the existing path and snaviewpath
in the environmental viriables/PATH
"""
msg = """\n\n[Code]\n"""
msg += """function InstallVC90CRT(): Boolean;\n"""
msg += """begin\n"""
msg += """ Result := not DirExists('C:\WINDOWS\WinSxS\\x86_Microsoft.VC90... | 429eb64485a4fe240c1bebbfd2a2a89613b4fddd | 3,640,968 |
import re
def get_filenames(filename):
"""
Return list of unique file references within a passed file.
"""
try:
with open(filename, 'r', encoding='utf8') as file:
words = re.split("[\n\\, \-!?;'//]", file.read())
#files = filter(str.endswith(('csv', 'zip')), words)
files = set(filter(lam... | a1d8c396245cfc682ecc37edb3e673f87939b6fa | 3,640,969 |
def format_filename_gen(prefix, seq_len, tgt_len, bi_data, suffix,
src_lang,tgt_lang,uncased=False,):
"""docs."""
if not uncased:
uncased_str = ""
else:
uncased_str = "uncased."
if bi_data:
bi_data_str = "bi"
else:
bi_data_str = "uni"
file_name = "{}-{}_{}.seqlen-{}.tg... | 4a54c1fbfe371d628c1d7019c131b8fa6755f900 | 3,640,970 |
def is_holiday(date) -> bool:
"""
Return True or False for whether a date is a holiday
"""
name = penn_holidays.get(date)
if not name:
return False
name = name.replace(' (Observed)', '')
return name in holiday_names | edb68fa552f0f772b29b5d8a414758e63c252045 | 3,640,971 |
import re
def tokenize_text(text):
"""
Tokenizes a string.
:param text: String
:return: Tokens
"""
token = []
running_word = ""
for c in text:
if re.match(alphanumeric, c):
running_word += c
else:
if running_word != "":
token.appe... | b7f420d081d9cd658435ef623142a9d8ecf7b99b | 3,640,972 |
def generate_dummy_probe(elec_shapes='circle'):
"""
Generate a 3 columns 32 channels electrode.
Mainly used for testing and examples.
"""
if elec_shapes == 'circle':
electrode_shape_params = {'radius': 6}
elif elec_shapes == 'square':
electrode_shape_params = {'width': 7}
eli... | ea0f900390cf808cd8df3a38df9c47b99b77167b | 3,640,973 |
def try_decode(message):
"""Try to decode the message with each known message class; return
the first successful decode, or None."""
for c in MESSAGE_CLASSES:
try:
return c.decode(message)
except ValueError:
pass # The message was probably of a different type.
re... | 1dbbe5a6426b67690834673cd049535b018c0097 | 3,640,974 |
def build_where_clause(args: dict) -> str:
"""
This function transforms the relevant entries of dict into the where part of a SQL query
Args:
args: The arguments dict
Returns:
A string represents the where part of a SQL query
"""
args_dict = {
'source_ip': 'source_ip.va... | 3b85c92346be254646dd5208259cee317f6f9741 | 3,640,975 |
def matrix_scale(s):
"""Produce scaling transform matrix with uniform scale s in all 3 dimensions."""
M = matrix_ident()
M[0:3,0:3] = np.diag([ s, s, s ]).astype(np.float64)
return M | 22949a406865c18fe8200e43ea046ca6f16bdd6f | 3,640,976 |
from typing import List
def magnitude_datapoints(data: DataPoint) -> List:
"""
:param data:
:return:
"""
if data is None or len(data) == 0:
return []
input_data = np.array([i.sample for i in data])
data = norm(input_data, axis=1).tolist()
return data | b6c505f02042cfc34183a19cc0843b28e25dd6b2 | 3,640,977 |
import PyOpenColorIO as ocio
import logging
from typing import Mapping
def generate_config(data, config_name=None, validate=True, base_config=None):
"""
Generates the *OpenColorIO* config from given data.
Parameters
----------
data : ConfigData
*OpenColorIO* config data.
config_name :... | 7385989fd0afedd9bc5e74de7e48b2c8f27f4b85 | 3,640,978 |
def svn_stringbuf_from_aprfile(*args):
"""svn_stringbuf_from_aprfile(svn_stringbuf_t result, apr_file_t file, apr_pool_t pool) -> svn_error_t"""
return apply(_core.svn_stringbuf_from_aprfile, args) | d9faccd861d5382593988c1e2585207e0b5fa89f | 3,640,979 |
from pathlib import Path
def Arrow_Head_A (cls, elid = "SVG:Arrow_Head_A", design_size = 12, ref_x = None, stroke = "black", marker_height = 6, marker_width = 6, fill = "white", fill_opacity = 1, ** kw) :
"""Return a marker that is an arrow head with an A-Shape.
>>> mrk = Marker.Arrow_Head_A ()
>>> svg... | 661409c1ed37e33e9aea306b1c5b8d2a369bbaf2 | 3,640,980 |
def signup() -> Response | str | tuple[dict[str, str | int], int]:
"""Sign up"""
# Bypass if user is logged in
if current_user.is_authenticated:
return redirect(url_for("home"))
# Process user data
try:
# Return template if request.method is GET
assert request.method != "GE... | 9496c11a9015b69c7cf2f89d19a45f93405f5dfe | 3,640,981 |
import copy
def evaluate_all_configs(hparams, agent_model_dir):
"""Evaluate the agent with multiple eval configurations."""
def make_eval_hparams(hparams, policy_to_action, max_num_noops):
hparams = copy.copy(hparams)
hparams.add_hparam("num_agents", hparams.eval_num_agents)
hparams.add_hparam("policy... | 107fb692adec1ce7dbb580c30e3e7b0402874054 | 3,640,982 |
from typing import Tuple
def shape(a: Matrix) -> Tuple[int, int]:
""" Returns the num of rows and columns of A """
num_rows = len(a)
num_cols = len(a[0]) if a else 0 # number of elements so columns in first element if it exists
return num_rows, num_cols | 24ef9045e86b6027f76ddf57bf5eba44553798c5 | 3,640,983 |
def solve(A, b):
"""
:param A: Matrix R x C
:param b: Vector R
:return: Vector C 'x' solving Ax=b
>>> M = Mat(({'a', 'b', 'c', 'd'}, {'A', 'B', 'C', 'D'}), { \
('a', 'A'): one, ('a', 'B'): one, ('a', 'D'): one, \
('b', 'A'): one, ('b', 'D'): one, \
('c', 'A'): one, ('c', 'B')... | b25a762ee8f8229d1bc573c828a7151770d3240c | 3,640,984 |
def token_groups(self):
"""The groups the Token owner is a member of."""
return self.created_by.groups | 9db411660db1def09b8dc52db800ca4c09a38cce | 3,640,985 |
import requests
def get_html_content_in_text(url):
"""
Grab all the content in webpage url and return it's content in text.
Arguments:
url -- a webpage url string.
Returns:
r.text -- the content of webpage in text.
"""
r = requests.get(url)
return r.text | fd8ddc992f34c186051ca8985ffb110c50004970 | 3,640,986 |
def subscribe():
"""Subscribe new message"""
webhook_url = request.form.get("webhook_url")
header_key = request.form.get("header_key")
header_value = request.form.get("header_value")
g.driver.subscribe_new_messages(NewMessageObserver(webhook_url, header_key, header_value))
return jsonify({"succe... | 97a47fb298bbc0bac3e333037210556525dd837f | 3,640,987 |
def SegAlign(ea, alignment):
"""
Change alignment of the segment
@param ea: any address in the segment
@param alignment: new alignment of the segment (one of the sa... constants)
@return: success (boolean)
"""
return SetSegmentAttr(ea, SEGATTR_ALIGN, alignment) | c0c380e194fbed43b87be81108eecf864809c447 | 3,640,988 |
import requests
def create_bitlink(logger, headers='', long_url='google.com'):
"""
Функция создает короткие ссылки из длинных
:param logger: logger object
:param headers: Generic Access Token сформированнный на сайте
:param long_url: Ссылка которую надо укоротить
:return: созданная короткая сс... | be5c7882a8577c8d406412c790f3d5fbcbd11019 | 3,640,989 |
import numpy
def compute_neq(count_mat):
"""
Compute the Neq for each residue from an occurence matrix.
Parameters
----------
count_mat : numpy array
an occurence matrix returned by `count_matrix`.
Returns
-------
neq_array : numpy array
a 1D array containing the neq ... | e3d738eb1c8ed58a3c4d4a4efc5323930d03be1f | 3,640,990 |
import optparse
def _GetOptionsParser():
"""Get the options parser."""
parser = optparse.OptionParser(__doc__)
parser.add_option('-i',
'--input',
dest='inputs',
action='append',
default=[],
help='One or more inp... | e1ec0530357ad3bebbac80c86b9d9b1010e6688c | 3,640,991 |
def spikalize_img(experiment, image, label):
"""
Transform image to spikes. Spike with poisson distributed rate proportional to pixel brightness.
:param experiment:
:param image:
:param label:
:return:
"""
image_shape = np.append(np.array(experiment.timesteps), np.array(image.shape))
... | 7159334b40c3841977a0772ac25c71a934d268ac | 3,640,992 |
def update_security_schemes(spec, security, login_headers, security_schemes,
unauthorized_schema):
"""Patch OpenAPI spec to include security schemas.
Args:
spec: OpenAPI spec dictionary
Returns:
Patched spec
"""
# login_headers = {'Set-Cookie':
# ... | 1ecb5cc3a121fc151794e4e24cd4aca4bc07ce46 | 3,640,993 |
def get_geckodriver_url(version):
"""
Generates the download URL for current platform , architecture and the given version.
Supports Linux, MacOS and Windows.
:param version: the version of geckodriver
:return: Download URL for geckodriver
"""
platform, architecture = get_platform_architectu... | 9d71728c551c67e86a61c3b870728bc70cad48ba | 3,640,994 |
def get_graph_size(depth: int):
"""returns how many nodes are in fully-equipped with nodes graph of the given depth"""
size = 1
cur_size = 1
ln = len(expand_sizes)
for i in range(min(ln, depth)):
cur_size *= expand_sizes[i]
size += cur_size
if ln < depth:
size += cur_siz... | 00f2a2ce714550785e99c0d193f47df05cc30b68 | 3,640,995 |
def inherits_from(obj, parent):
"""
Takes an object and tries to determine if it inherits at *any*
distance from parent.
Args:
obj (any): Object to analyze. This may be either an instance
or a class.
parent (any): Can be either instance, class or python path to class.
R... | 9d7e0665b4e4fe2a3f7c136436a2502c8b72527c | 3,640,996 |
from typing import Optional
def load_df_from_googlesheet(
url_string: str,
skiprows: Optional[int] = 0,
skipfooter: Optional[int] = 0,
) -> pd.DataFrame:
"""Load a Pandas DataFrame from a google sheet.
Given a file object, try to read the content as a CSV file and transform
into a data frame.... | adfcff1968eccfa44640b5e9a7e3143703284dfb | 3,640,997 |
def decomp(bits, dummies=default_dummies, width=default_width):
"""Translate 0s and 1s to dummies[0] and dummies[1]."""
words = (dummies[i] for i in bits)
unwrapped = ' '.join(words)
return wrap_source(unwrapped, width=width) | a6540cc90412b9e72b62c57fe6828b45ad5df593 | 3,640,998 |
def get_word_node_attrs(word: Word) -> WordNodeAttrs:
"""Create the graph's node attribute for a `Word`.
Build an attribute dict with the word's features. Note that we're using the
term `Word` instead of `Token` to be closer to the implementation of these
data structures in stanza. From stanza's docume... | 143a00206cfa8d98419f2d0e21e1013ea6dd02ab | 3,640,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.