content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def validate_besseli(nu, z, n):
"""
Compares the results of besseli function with scipy.special. If the return
is zero, the result matches with scipy.special.
.. note::
Scipy cannot compute this special case: ``scipy.special.iv(nu, 0)``,
where nu is negative and non-integer. The correc... | a8102c014fdcb2d256adf94aea842d1e5733ba72 | 3,637,800 |
from typing import Any
from typing import List
def delete_by_ip(*ip_address: Any) -> List:
"""
Remove the rules connected to specific ip_address.
"""
removed_rules = []
counter = 1
for rule in rules():
if rule.src in ip_address:
removed_rules.append(rule)
execut... | 88b430b83a5c3c82491f210e218a10719b5b75df | 3,637,801 |
def findMaxWindow(a, w):
"""
:param a: input array of integers
:param w: window size
:return: array of max val in every window
"""
max = [0] * (len(a)-w+1)
maxPointer = 0
maxCount = 0
q = Queue()
for i in range(0, w):
if a[i] > max[maxPointer]:
max[maxPointer... | af3e7f010b162e8f378e541be32a2d295e31e51c | 3,637,802 |
import logging
def filtering_news(news: list, filtered_news: list):
"""
Filters news to remove unwanted removed articles
Args:
news (list): List of articles to remove from
filtered_news (list): List of titles to filter the unwanted news with
Returns:
news (list): List of arti... | 98049b6bd826109fe7bc8e2e42de4c50970988a9 | 3,637,803 |
def extract_subsequence(sequence, start_time, end_time):
"""Extracts a subsequence from a NoteSequence.
Notes starting before `start_time` are not included. Notes ending after
`end_time` are truncated.
Args:
sequence: The NoteSequence to extract a subsequence from.
start_time: The float time in second... | cf8e1be638163a6cb7c6fd6e69121ccc7100afd6 | 3,637,804 |
import re
def read_data(filename):
"""Read the raw tweet data from a file. Replace Emails etc with special tokens """
with open(filename, 'r') as f:
all_lines=f.readlines()
padded_lines=[]
for line in all_lines:
line = emoticonsPattern.sub(lambda m: rep[re.escape(m.group(0)... | 8e15d6e4bd9e4a6b3b01ea5baffad8e6bc390034 | 3,637,805 |
def client():
"""AlgodClient for testing"""
client = _algod_client()
client.flat_fee = True
client.fee = 1000
print("fee ", client.fee)
return client | ad51102a58d9ffad4a9dd43c3e2b4bd5adc0f467 | 3,637,806 |
def GRU_sent_encoder(batch_size, max_len, vocab_size, hidden_dim, wordembed_dim,
dropout=0.0, is_train=True, n_gpus=1):
"""
Implementing the GRU of skip-thought vectors.
Use masks so that sentences at different lengths can be put into the same batch.
sent_seq: sequence of tokens c... | fe7090efe78ec97ba88651ecf8f7918bb5277eec | 3,637,807 |
def process_contours(frame_resized):
"""Get contours of the object detected"""
blurred = cv2.GaussianBlur(frame_resized, (11, 9), 0)
hsv = cv2.cvtColor(blurred, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv, constants.blueLower, constants.blueUpper)
mask = cv2.erode(mask, None, iterations=2)
mask = ... | 5725b12a3e5e0447a3b587d091f4fdeae1f5bac9 | 3,637,808 |
from typing import Optional
from typing import List
import itertools
def add_ignore_file_arguments(files: Optional[List[str]] = None) -> List[str]:
"""Adds ignore file variables to the scope of the deployment"""
default_ignores = ["config.json", "Dockerfile", ".dockerignore"]
# Combine default files and ... | f7e7487c4a17a761f23628cbb79cbade64237ce6 | 3,637,809 |
import torch
def compute_accuracy(logits, targets):
"""Compute the accuracy"""
with torch.no_grad():
_, predictions = torch.max(logits, dim=1)
accuracy = torch.mean(predictions.eq(targets).float())
return accuracy.item() | af15e4d077209ff6e790d6fdaa7642bb65ff8dbf | 3,637,810 |
def division_by_zero(number: int):
"""Divide by zero. Should raise exception.
Try requesting http://your-app/_divide_by_zero/7
"""
result = -1
try:
result = number / 0
except ZeroDivisionError:
logger.exception("Failed to divide by zero", exc_info=True)
return f"{number} divi... | b97d7f38aea43bfb6ee4db23549e89799bd299b7 | 3,637,811 |
def is_ELF_got_pointer_to_external(ea):
"""Similar to `is_ELF_got_pointer`, but requires that the eventual target
of the pointer is an external."""
if not is_ELF_got_pointer(ea):
return False
target_ea = get_reference_target(ea)
return is_external_segment(target_ea) | cd62d43bb266d229ae31e477dc60d21f73b8850a | 3,637,812 |
from pathlib import Path
def _normalise_dataset_path(input_path: Path) -> Path:
"""
Dataset path should be either the direct imagery folder (mtl+bands) or a tar path.
Translate other inputs (example: the MTL path) to one of the two.
>>> tmppath = Path(tempfile.mkdtemp())
>>> ds_path = tmppath.jo... | cf61da9a043db9c67714d7437c7ef18ee6235acb | 3,637,813 |
def get_customers():
"""returns an array of dicts with the customers
Returns:
Array[Dict]: returns an array of dicts of the customers
"""
try:
openConnection
with conn.cursor() as cur:
result = cur.run_query('SELECT * FROM customer')
cur.close()
... | 4440fb5d226070facb4e5c1b854535e40f42d607 | 3,637,814 |
def fixtureid_es_server(fixture_value):
"""
Return a fixture ID to be used by pytest for fixture `es_server()`.
Parameters:
fixture_value (:class:`~easy_server.Server`):
The server the test runs against.
"""
es_obj = fixture_value
assert isinstance(es_obj, easy_server.Server)
... | f795a8e909354e0004ea81ebdf71f7da81153a64 | 3,637,815 |
def topn_vocabulary(document, TFIDF_model, topn=100):
"""
Find the top n most important words in a document.
Parameters
----------
`document` : The document to find important words in.
`TFIDF_model` : The TF-IDF model that will be used.
`topn`: Default = 100. Amount of top words.
... | 4c58e2f041c76407bb2e7c686713b12e2c1e8256 | 3,637,816 |
def embedding_table(inputs, vocab_size, embed_size, zero_pad=False,
trainable=True, scope="embedding", reuse=None):
""" Generating Embedding Table with given parameters
:param inputs: A 'Tensor' with type 'int8' or 'int16' or 'int32' or 'int64'
containing the ids to be looked up in '... | bc509e18048230372b8f52dc5bbb77295014aec8 | 3,637,817 |
def get_trading_dates(start_date, end_date):
"""
获取某个国家市场的交易日列表(起止日期加入判断)。目前仅支持中国市场。
:param start_date: 开始日期
:type start_date: `str` | `date` | `datetime` | `pandas.Timestamp`
:param end_date: 结束如期
:type end_date: `str` | `date` | `datetime` | `pandas.Timestamp`
:return: list[`datetime.date`... | 5b0bf331376c5b2f9d1c8308be285b54fa053e5f | 3,637,818 |
def gm_put(state, b1, b2):
"""
If goal is ('pos',b1,b2) and we're holding b1,
Generate either a putdown or a stack subtask for b1.
b2 is b1's destination: either the table or another block.
"""
if b2 != 'hand' and state.pos[b1] == 'hand':
if b2 == 'table':
return [('a_putdown... | c9076ac552529c60b5460740c74b1602c42414f2 | 3,637,819 |
import os
def cs_management_client(context):
"""Return Cloud Services mgmt client"""
context.cs_mgmt_client = CSManagementClient(user=os.environ['F5_CS_USER'],
password=os.environ['F5_CS_PWD'])
return context.cs_mgmt_client | b90a435058625557ad4fff82925905bd9cf6c62e | 3,637,820 |
def pad_to_shape_label(label, shape):
"""
Pad the label array to the given shape by 0 and 1.
:param label: The label for padding, of shape [n_batch, *vol_shape, n_class].
:param shape: The shape of the padded array, of value [n_batch, *vol_shape, n_class].
:return: The padded label array.
"""
... | e40d7c1949cc891353c9899767c92419202c325d | 3,637,821 |
def download_report(
bucket_name: str, client: BaseClient, report: str, location: str
) -> bool:
"""
Downloads the original report
to the temporary work area
"""
response = client.download_file(
Bucket=bucket_name, FileName=report, Location=location
)
return response | d46fb279d5a315c60f1908664951436edc997ab8 | 3,637,822 |
import os
def _collect_exit_info(container_dir):
"""Read exitinfo, check if app was aborted and why."""
exitinfo_file = os.path.join(container_dir, 'exitinfo')
exitinfo = _read_exitinfo(exitinfo_file)
_LOGGER.info('check for exitinfo file %r: %r', exitinfo_file, exitinfo)
aborted_file = os.path.j... | c8e21d87dd1826591e8775b9101dd6adbc3795d1 | 3,637,823 |
from typing import Dict
from typing import List
import click
def main( # pylint: disable=too-many-arguments,too-many-locals
private_key: PrivateKey,
state_db: str,
web3: Web3,
contracts: Dict[str, Contract],
start_block: BlockNumber,
confirmations: BlockTimeout,
host: str,
port: int,
... | f1615a9ca1b9648fa3689d80258e8ac793653d39 | 3,637,824 |
def get_service(hass, config):
"""Get the Google Voice SMS notification service."""
if not validate_config({DOMAIN: config},
{DOMAIN: [CONF_USERNAME,
CONF_PASSWORD]},
_LOGGER):
return None
return GoogleVoiceS... | c7fda936ca9448587e2c4167d9c765186344fb43 | 3,637,825 |
import random
import time
def hammer_op(context, chase_duration):
"""what better way to do a lot of gnarly work than to pointer chase?"""
ptr_length = context.op_config["chase_size"]
data = list(range(0, ptr_length))
random.shuffle(data)
curr = random.randint(0, ptr_length - 1)
# and away we... | f4a51fe1e2f89443b79fd4c9a5b3f5ee459e79ca | 3,637,826 |
import os
import re
import warnings
def validate_sourcedata(path, source_type, pattern='sub-\\d+'):
"""
This function validates the "sourcedata/" directory provided by user to
see if it's contents are consistent with the pipeline's requirements.
"""
if not path:
path = './'
if not so... | 391c1cb9e5d7c372bf7cac0e3ba584fc8705d7c9 | 3,637,827 |
from typing import Callable
from typing import Mapping
import copy
import torch
def generate_optimization_fns(
loss_fn: Callable,
opt_fn: Callable,
k_fn: Callable,
normalize_grad: bool = False,
optimizations: Mapping = None,
):
"""Directly generates upper/outer bilevel program derivative funct... | 5e70f05c5aa0e754e5c1fbe585e4a0856a732006 | 3,637,828 |
def get_weighted_spans(doc, vec, feature_weights):
# type: (Any, Any, FeatureWeights) -> Optional[WeightedSpans]
""" If possible, return a dict with preprocessed document and a list
of spans with weights, corresponding to features in the document.
"""
if isinstance(vec, FeatureUnion):
return... | 0896a8449690895d922ae409c7e278f38002f111 | 3,637,829 |
def get_child(parent, child_index):
"""
Get the child at the given index, or return None if it doesn't exist.
"""
if child_index < 0 or child_index >= len(parent.childNodes):
return None
return parent.childNodes[child_index] | 37f7752a4a77f3d750413e54659f907b5531848c | 3,637,830 |
def testAtomicSubatomic():
"""
Test atomic/subatomic links defined in memes.
"""
method = moduleName + '.' + 'testAtomicSubatomic'
Graph.logQ.put( [logType , logLevel.DEBUG , method , "entering"])
resultSet = []
errata = []
testResult = "True"
expectedResult = "True"
errorMs... | 5ba9acee6b889c705d040a6e3607595659e19754 | 3,637,831 |
def extinction(species, adj, z, independent):
"""
Returns the presence/absence of each species after taking into account
the secondary extinctions.
Parameters
----------
species : numpy array of shape (nbsimu, S) with nbsimu being the number
of simulations (decompositions). This ar... | 2a9cb1884cfceb3a7c06aede60191d8a86f4741b | 3,637,832 |
def fix_variable_mana(card):
"""
This function was created to fix a problem in the dataset.
We're currently pretty up against the wall and I realized
that 'Variable' mana texts were not correctly converted to {X}
so this function is fed cards and corrects their mana values
if it detects this pro... | de0a0fe10d7ebbe02cd36088765be373c7dd9789 | 3,637,833 |
def cli_arg(
runner: CliRunner,
notebook_path: Path,
mock_terminal: Mock,
remove_link_ids: Callable[[str], str],
mock_tempfile_file: Mock,
mock_stdin_tty: Mock,
mock_stdout_tty: Mock,
) -> Callable[..., str]:
"""Return function that applies arguments to cli."""
def _cli_arg(
... | 5d7e02b11ace8ee44fa85ce7d2dc4c5a24fb72cf | 3,637,834 |
from sklearn.cluster import KMeans
from sklearn.model_selection import StratifiedKFold
import os
def grid_search(x_train, y_train, x_val=None, y_val=None, args=None, config_filename: str = None, folds: int = 5,
verbose: int = 0, default_config: str = CONFIG_PATH_MLP, working_dir: str = WORKING_DIR,
... | 3c0daeb512789dce892e093f586a983b9e71f71b | 3,637,835 |
def distinguish_system_application(vulner_info):
"""
Test whether CVE has system CIA loss or application CIA loss.
:param vulner_info: object of class Vulnerability from cve_parser.py
:return: result impact or impacts
"""
result_impacts = []
if system_confidentiality_changed(
vu... | c10ec04a761b038fe3c0d6408a31660ccf23a205 | 3,637,836 |
import os
def split_missions_and_dates(fname):
"""
Examples
--------
>>> fname = 'nustar-nicer_gt55000_lt58000.csv'
>>> outdict = split_missions_and_dates(fname)
>>> outdict['mission1']
'nustar'
>>> outdict['mission2']
'nicer'
>>> outdict['mjdstart']
'MJD 55000'
>>> ou... | 851fa5a85d0acfd9d309725284ebb1859734432e | 3,637,837 |
import platform
import os
def run_in_windows_bash(conanfile, command, cwd=None, env=None):
""" Will run a unix command inside a bash terminal It requires to have MSYS2, CYGWIN, or WSL"""
if env:
# Passing env invalidates the conanfile.environment_scripts
env_win = [env] if not isinstance(env, ... | 074b63e8fe1b482984afccda01f86f88890fb824 | 3,637,838 |
from sys import path
def remove_uploaded_records(db):
"""
Removes all records archived and uploaded.
:param db: DB Connection to Pony
:return: List of Records removed
"""
list_of_local_records = query.get_records_uploaded(db)
if len(list_of_local_records) == 0:
return 0
remo... | 29919e5d68cc6374f39c03d6f0bcb60eddd429c2 | 3,637,839 |
from typing import Tuple
def nearest_with_mask_regrid(
distances: ndarray,
indexes: ndarray,
surface_type_mask: ndarray,
in_latlons: ndarray,
out_latlons: ndarray,
in_classified: ndarray,
out_classified: ndarray,
vicinity: float,
) -> Tuple[ndarray, ndarray]:
"""
Main regriddin... | 75b69ddbbdca4c316ecf2d4e3933f6e3a55ff0e1 | 3,637,840 |
from typing import List
from typing import Literal
from pathlib import Path
import logging
import shutil
import json
def _validator(
directory: str,
output_types: List[str] = OUTPUT_TYPES,
log_level: Literal["INFO", "DEBUG"] = "INFO",
coverages: dict = {},
schemas_path: Path = Path(__file__).paren... | 4f50fd8ff4300af6cd9e5ade7883a6eeda655c4b | 3,637,841 |
def get_renaming(mappers, year):
"""Get original to final column namings."""
renamers = {}
for code, attr in mappers.items():
renamers[code] = attr['df_name']
return renamers | 33197b5c748b3ecc43783d5f1f3a3b5a071d3a4e | 3,637,842 |
async def clap(text, args):
""" Puts clap emojis between words. """
if args != []:
clap_str = args[0]
else:
clap_str = "👏"
words = text.split(" ")
clappy_text = f" {clap_str} ".join(words)
return clappy_text | 09865461e658213a2f048b89757b75b2a37c0602 | 3,637,843 |
from typing import Union
from typing import Callable
from typing import List
def apply_binary_str(
a: Union[pa.Array, pa.ChunkedArray],
b: Union[pa.Array, pa.ChunkedArray],
*,
func: Callable,
output_dtype,
parallel: bool = False,
):
"""
Apply an element-wise numba-jitted function on tw... | 853cd326b5812314bb6595fee191ca1c6e1f89f6 | 3,637,844 |
def product_review(product_id: str):
"""
Shows review statistics for a product.
Returns a python dictionary with content-type: application/json
"""
session = Session()
date = request.args.get('date') # parse a query string formatted as BIGINT unixReviewTime
# SELECT AVG(overall)... | 945f29a536a5645b602633c4558ac3d68affe85a | 3,637,845 |
def remove_extra_two_spaces(text: str) -> str:
"""Replaces two consecutive spaces with one wherever they occur in a text"""
return text.replace(" ", " ") | d8b9600d3b442216b1fbe85918f313fec8a5c9cb | 3,637,846 |
def reflect_table(table_name, engine):
"""
Gets the table with the given name from the sqlalchemy engine.
Args:
table_name (str): Name of the table to extract.
engine (sqlalchemy.engine.base.Engine): Engine to extract from.
Returns:
table (sqlalchemy.ext.declarative.api.Declara... | 414a04172cec7e840bf257eaf5b15b1fc3fa9d59 | 3,637,847 |
def load_utt_list(utt_list):
"""Load a list of utterances.
Args:
utt_list (str): path to a file containing a list of utterances
Returns:
List[str]: list of utterances
"""
with open(utt_list) as f:
utt_ids = f.readlines()
utt_ids = map(lambda utt_id: utt_id.strip(), utt_... | 6a77e876b0cc959ac4151b328b718ae45522448b | 3,637,848 |
def kfunc_vals(points, area):
"""
Input
points: a list of Point objects
area: an Extent object
Return
ds: list of radii
lds: L(d) values for each radius in ds
"""
# This function is taken from kfunction file in spatialanalysis library
n = len(points)
density = n/area... | 2fd56da45f8fb4ede38a219b158dce802d68ae44 | 3,637,849 |
from datetime import datetime
async def get_locations():
"""
Retrieves the locations from the categories. The locations are cached for 1 hour.
:returns: The locations.
:rtype: List[Location]
"""
# Get all of the data categories locations.
confirmed = await get_category("confirmed")
de... | 24272f06ca3732f053d6efcc41a31ec205603a27 | 3,637,850 |
def MDAPE(y_true, y_pred, multioutput='raw_values'):
"""
calculate Median Absolute Percentage Error (MDAPE).
:param y_true: array-like of shape = (n_samples, *)
Ground truth (correct) target values.
:param y_pred: array-like of shape = (n_samples, *)
Estimated target values.
:param m... | 05cfbef6bd3e63ca151a584dc25b9b6574d2aa37 | 3,637,851 |
import pandas
import numpy
def fast_spearman(x, y=None):
"""calculate the spearnab correlation matrix for the columns of x (MxN), or optionally, the spearmancorrelaton matrix between x and y (OxP).
In the language of statistics the columns are the variables and the rows are the observations.
Args:
... | 9debe5d3c47a3da93569e9668f7a1735852d6eb7 | 3,637,852 |
import matplotlib
from pycocotools.cocoeval import COCOeval
import copy
def analyze_individual_category(k, cocoDt, cocoGt, catId, iou_type, areas=None):
"""针对某个特定类别,分析忽略亚类混淆和类别混淆时的准确率。
Refer to https://github.com/open-mmlab/mmdetection/blob/master/tools/analysis_tools/coco_error_analysis.py#L174
A... | bcf5670bb78d4c5662cc3fbaec558bc22ddf0cd1 | 3,637,853 |
def read_line1(line):
"""! Function read_line1
Reads as argument a string formatted as a Line 1 in SEISAN's Nordic format
Returns a Hypocenter dataclass with all the fields in a SEISAN's Line 1
@param[in] line string with SEISAN's Nordic hypocenter format (Line 1)
@return Hypocenter... | 871f468c2ec4dd9e0a5e8784d2beb7dd958d068d | 3,637,854 |
import os
import tempfile
import subprocess
import time
import json
def ghidra_headless(address,
xml_file_path,
bin_file_path,
ghidra_headless_path,
ghidra_plugins_path):
"""
Call Ghidra in headless mode and run the plugin
Fun... | b3ee78b9f44a2dcf9cf145b9ae00580b3e7c1683 | 3,637,855 |
import logging
from datetime import datetime
def validate_id(
endpoint_name,
type_id,
cache_buster=False,
config=api_config.CONFIG,
logger=logging.getLogger('publicAPI'),
):
"""Check EVE Online CREST as source-of-truth for id lookup
Args:
endpoint_name (str): d... | 8c6ed549d8387fa43a713b96c19f8a2b31740067 | 3,637,856 |
import socket
import os
def init_server_socket() -> socket.socket:
"""Initialize and bind the server unix socket."""
socket_address = get_socket_address()
try:
os.unlink(socket_address)
except (OSError, EnvironmentError):
pass
sock = socket.socket(family=socket.AF_UNIX, type=socket... | bf73ff851536062c90ae9430054cf036a571cf84 | 3,637,857 |
def getInfo_insert(sql : str, tableInfo : table_info_module.TableInfo) -> tuple:
"""테이블 이름과 컬럼을 반환합니다."""
sql = string_module.removeNoise(sql)
tableName = string_module.getParenthesesContext2(sql, "INSERT INTO ", " ")
columns = tableInfo[tableName]
return (tableName, columns) | 25f2087b5fbb15ab1012d3f37749430a74e6faaa | 3,637,858 |
def compute_flow_for_supervised_loss(
feature_model,
flow_model,
batch,
training
):
"""Compute flow for an image batch.
Args:
feature_model: A model to compute features for flow.
flow_model: A model to compute flow.
batch: A tf.tensor of shape [b, seq, h, w, c] holding a batch of triple... | a74f392c1d4e234fdb66d18e63d7c733ec6669a7 | 3,637,859 |
import os
def _get_filename_from_request(request):
"""
Gets the filename from an url request.
:param request: url request to get filename from
:type request: urllib.requests.Request or urllib2.Request
:rtype: str
"""
try:
headers = request.headers
content = headers["conte... | 51d2f79ebc5f2abf57d5b12d0271d6d704a24297 | 3,637,860 |
def farey_sequence(n):
"""Return the nth Farey sequence as order pairs of the form (N,D) where `N' is the numerator and `D' is the denominator."""
a, b, c, d = 0, 1, 1, n
sequence=[(a,b)]
while (c <= n):
k = int((n + b) / d)
a, b, c, d = c, d, (k*c-a), (k*d-b)
sequence.append( (a... | d55bb90d05b4930d05a83dac9feb58e747288754 | 3,637,861 |
def make_vgg19_block(block):
"""Builds a vgg19 block from a dictionary
Args:
block: a dictionary
"""
layers = []
for i in range(len(block)):
one_ = block[i]
for k, v in one_.items():
if 'pool' in k:
layers += [nn.MaxPool2d(kernel_size=v[0], stride=... | 512543dfb32f9ed97b6ce99dd6ffc692d0ffa3b8 | 3,637,862 |
import os
def process_one(f, mesh_directory, dataset_directory, skip_existing, log_level):
"""Processes a single mesh, adding it to the dataset."""
relpath = f.replace(mesh_directory, '')
print('relpath:', relpath)
assert relpath[0] == '/'
relpath = relpath[1:]
split, synset = relpath.split('/')[:2]
log... | 57369ce24c2ed21829b8b7a8ca658d9d0185e9a2 | 3,637,863 |
def tld():
"""
Return a random tld (Top Level Domain) from the tlds list below
:return: str
"""
tlds = ('com', 'org', 'edu', 'gov', 'co.uk', 'net', 'io', 'ru', 'eu',)
return pickone(tlds) | 8e9341058ccf79d991aab6317ab3c29858f00fdf | 3,637,864 |
def validate_boolean(option, value):
"""Validates that 'value' is 'true' or 'false'.
"""
if isinstance(value, bool):
return value
elif isinstance(value, basestring):
if value not in ('true', 'false'):
raise ConfigurationError("The value of '%s' must be "
... | 85b9a256e57ce7715fceea556ff7ad48b05bd996 | 3,637,865 |
def A2RT(room_size, A_wall_all, F_abs, c=343, A_air=None, estimator='Norris_Eyring'):
""" Estimate reverberation time based on room acoustic parameters,
translated from matlab code developed by Douglas R Campbell
Args:
room_size: three-dimension measurement of shoebox room
A_wall_all: sound ... | 8a8df0bf8f91c93dfb7480775ea9eadc552edcfe | 3,637,866 |
def GetVideoFromRate(content):
"""
从视频搜索源码页面提取视频信息
"""
#av号和标题
regular1 = r'<a href="/video/av(\d+)/" target="_blank" class="title" [^>]*>(.*)</a>'
info1 = GetRE(content, regular1)
#观看数
regular2 = r'<i class="b-icon b-icon-v-play" title=".+"></i><span number="([^"]+)">\1</span>'
info2 = ... | 446343bc3f2597310b7e4b22dd784bb0bc9b06ea | 3,637,867 |
def PPVfn(Mw, fc, Rho, V):
"""Calculates the peak-particle-velocity (PPV) at the source
for a given homogeneous density and velocity model.
:param Mw: the moment magnitude
:type Mw: float
:param fc: the corner frequency in Hz
:type fc: float
:param Rho: Density at the source in kg/m**3
... | 5629abb351e46ff41f11feef00bd8b7195b90e8f | 3,637,868 |
import math
def extract_feature_label(feat_path, lab_path, audio_sr=22050, hop_size=1024):
"""Basic feature extraction block.
Parameters
----------
feat_path: Path
Path to the raw feature folder.
lab_path: Path
Path to the corresponding label folder.
audio_sr: int
samp... | 2bdca45bcfe19e0b103d4b1762aab6ddf8e67b89 | 3,637,869 |
import os
def get_local_episodes(anime_folder, name):
"""return a list of files of a anime-folder inside ANIME_FOLDER"""
episodes = []
name = name.replace("'", "_")
path = os.path.join(anime_folder, name)
if not os.path.isdir(path):
os.makedirs(path)
return episodes
for episode... | b12048fd49607b20d61f94b554a040c046c49f5e | 3,637,870 |
import os
def _find_pkg_info(directory):
"""find and return the full path to a PKG-INFO file or None if not found"""
for root, dirs, files in os.walk(directory):
for filename in files:
if filename == 'PKG-INFO':
return os.path.join(root, filename)
# no PKG-INFO file fou... | ada0afe963cb859a5c5b19813ebbdea03cda7db3 | 3,637,871 |
import re
def get_m3u8_url(text):
# type: (str) -> Union[str, None]
"""Attempts to get the first m3u8 url from the given string"""
m3u8 = re.search(r"https[^\"]*\.m3u8", text)
sig = re.search(r"(\?sig=[^\"]*)", text)
if m3u8 and sig:
return "{}{}".format(clean_uri(m3u8.group()), sig.group(... | 25373d6fe8958dc28c6ddcb4eda1b02c9497fd18 | 3,637,872 |
def xavier_init(fan_in, fan_out, constant=1):
""" Xavier initialization of network weights"""
# https://stackoverflow.com/questions/33640581/how-to-do-xavier-initialization-on-tensorflow
low = -constant*np.sqrt(6.0/(fan_in + fan_out))
high = constant*np.sqrt(6.0/(fan_in + fan_out))
return tf.rando... | df8c812a81d22082add014a8bb17e8cc4966f58c | 3,637,873 |
from typing import Union
from typing import Optional
def object_bbox_flip(
bbox: remote_blob_util.BlobDef,
image_size: remote_blob_util.BlobDef,
flip_code: Union[int, remote_blob_util.BlobDef],
name: Optional[str] = None,
) -> remote_blob_util.BlobDef:
"""This operator flips the object bounding bo... | 8be9a58c2c8a10e8aaba402d45abf25edc42c0ab | 3,637,874 |
def compile(spec):
"""
Args:
spec (dict): A specification dict that attempts to "break" test dicts
Returns:
JsonMatcher.
"""
return JsonMatcher(spec) | bddb743e9f4fcbf3987363007f67c7e8dcf44c37 | 3,637,875 |
import itertools
def labels_to_intervals(labels_list):
"""
labels_to_intervals() converts list of labels of each frame into set of time intervals where a tag occurs
Args:
labels_list: list of labels of each frame
e.g. [{'person'}, {'person'}, {'person'}, {'surfboard', 'person'}]
Retu... | 65b63ea3e6f097e9605e1c1ddb8dd434d7db9370 | 3,637,876 |
def get_wolfram_query_url(query):
"""Get Wolfram query URL."""
base_url = 'www.wolframalpha.com'
if not query:
return 'http://{0}'.format(base_url)
return 'http://{0}/input/?i={1}'.format(base_url, query) | 0122515f1a666cb897b53ae6bd975f65da072438 | 3,637,877 |
from typing import Sequence
def center_of_mass(points: Sequence[float]) -> np.ndarray:
"""Gets the center of mass of the points in space.
Parameters
----------
points
The points to find the center of mass from.
Returns
-------
np.ndarray
The center of mass of the points.
... | 8d142a0b2b680900d5a20a0119702124bcdf3db6 | 3,637,878 |
def get_posts(session, client_id, now=None):
"""Returns all posts."""
now = _utcnow(now)
try:
results = _get_post_query(session, client_id)\
.order_by(MappedPost.created_datetime.desc())
posts = tuple(_make_post(*result) for result in results)
return PaginatedSequence(posts)
except sa.exc.... | 8cf5eb1ef9ec84a8d98cd8cc285ade7725f0dc5a | 3,637,879 |
def tessellate_cell(csn, children, acells, position, parent, cell_params):
"""
Tessellate a cell.
:param int csn: Cell number.
:param ndarray children: Array specifying children of each cell.
:param ndarray acells: Array specifying the adjacent cells of each cell.
:param ndarray position: Array... | 0c9993f49a147488488c7131d772c1996bc12d0f | 3,637,880 |
import torch
def add_eig_vec(g, pos_enc_dim):
"""
Graph positional encoding v/ Laplacian eigenvectors
This func is for eigvec visualization, same code as positional_encoding() func,
but stores value in a diff key 'eigvec'
"""
# Laplacian
A = g.adjacency_matrix_scipy(return_edge_ids=False)... | a7487f048dfd14cc4d9e04e8a754327dd9c8b19a | 3,637,881 |
import numpy as np
from scipy import ndimage
from skimage.morphology import ball
def _advanced_clip(
data, p_min=35, p_max=99.98, nonnegative=True, dtype="int16", invert=False
):
"""
Remove outliers at both ends of the intensity distribution and fit into a given dtype.
This interface tries to emulate... | 9444db42b146798900fde89d8436b742ba9082a6 | 3,637,882 |
def allocate_buffers(engine):
"""
Allocates all buffers required for the specified engine
"""
inputs = []
outputs = []
bindings = []
# Iterate over binding names in engine
for binding in engine:
# Get binding (tensor/buffer) size
size = trt.volume(engine.get_binding_shape... | b7f28c256a1ec169392a4cfb27347ae742c922bb | 3,637,883 |
def D_to_M(D, ecc):
"""Mean anomaly from eccentric anomaly.
Parameters
----------
D : float
Parabolic eccentric anomaly (rad).
ecc : float
Eccentricity.
Returns
-------
M : float
Mean anomaly (rad).
"""
with u.set_enabled_equivalencies(u.dimensionless_a... | 2f6b6ac3c3a0d02456f0e9b03dd6a183583a8bb4 | 3,637,884 |
def dict_merge(a, b):
"""Merge a and b.
Parameters
----------
a
One dictionary that will be merged
b
Other dictionary that will be merged
"""
return _merge(dict(a), b) | 2209659fafb6c1d7d8877bfe923ca98516d255bc | 3,637,885 |
import copy
def merge_dictionary(src: dict, dest: dict) -> dict:
"""
Merge two dictionaries.
:param src: A dictionary with the values to merge.
:param dest: A dictionary where to merge the values.
"""
for name, value in src.items():
if name not in dest:
# When field is n... | 12305510a9a2d50bcdc691cb7fe8d5a573621e69 | 3,637,886 |
def create_from_source(wp_config, source: Location):
"""
Using a Location object and the WP config, generates the appropriate LuhSql
object
"""
if isinstance(source, SshLocation):
ssh_user = source.user
ssh_host = source.host
elif isinstance(source, LocalLocation):
ssh_u... | 3854d70889a1fdc0517f2557431887ca560acb14 | 3,637,887 |
def eye(N, M=None, k=0, dtype=DEFAULT_FLOAT_DTYPE):
"""
Returns a 2-D tensor with ones on the diagnoal and zeros elsewhere.
Args:
N (int): Number of rows in the output, must be larger than 0.
M (int, optional): Number of columns in the output. If None, defaults to N,
if defined,... | 952da74fbedfaa433244a65cff463ccf0b389cf1 | 3,637,888 |
import os
def create_inception_graph():
"""
从被保存的GraphDef文件创建一个graph
:return: 受inception 训练过的图,同时保存了几个tensor
"""
with tf.Session() as sess:
model_filename = os.path.join(model_dir, 'def.pb')
if not os.path.exists(model_filename):
model_filename = os.path.join(model_dir,... | 1b11127b0d1916cda0ccca5f869dba9178d7374b | 3,637,889 |
import requests
def team_game_log(request, team_id, season):
"""Individual team season game log page.
"""
response = requests.get(f'http://{request.get_host()}/api/teams/{team_id}/{season}/Regular')
return render(request, 'main/team_games.html', context=response.json()) | 1e4c59febb2d5d5f2c3496242c8de8068c4bb329 | 3,637,890 |
def infer_labels(fn_pickle,testdata, fout_pickle, weak_lower,weak_upper):
#def infer_labels(fn_pickle,testdata, fout_pickle, weak_lower=0.935,weak_upper=0.98):
"""
- this is the linear case of getting labels for new spectra
best log g = weak_lower = 0.95, weak_upper = 0.98
best teff = weak_lower = 0.9... | 8321f8cdc8c7cfb97106a3eba8c5846a108adcb5 | 3,637,891 |
import argparse
from pathlib import Path
def main():
"""Console script for vaqc."""
parser = argparse.ArgumentParser()
parser.add_argument('derivatives_dir',
type=Path,
action='store',
help='the root folder of a BIDS derivative datase... | 661e9ea78b1ba0fc507c0bddc6cc0f7a30a05225 | 3,637,892 |
import pylab as pl
def figure(*args, grid=True, style='default', figsize=(9, 5), **kwargs):
"""
Returns a matplotlib axis object.
"""
available = [s for s in pl.style.available + ['default'] if not s.startswith('_')]
if style not in available:
raise ValueError(f'\n\n Valid Styles are {avai... | 58a50dfda449518c1fed06a380ec0dac82eb1943 | 3,637,893 |
def boundcond(stato):
"""This function applies the boundary conditions that one chooses to adopt.
The boundaries can be reflective, periodic or constant.
It takes as input the state to be evolved. """
if bc=='const':
status=''.join(('.',stato,'.')) #constant boundaries
elif bc=='refl':
... | 826ea52b1b2bbda01b88f03ce546757225a3bec8 | 3,637,894 |
import logging
def general_string_parser(content_string, location):
"""
Parse the given string of endpoint/method/header/body content
* search for all parameters in this string
** all params are replaced with a starting and ending symbol of non priority tag
* evaluate what type of parameter it ... | aef44e4494d2db948a91b63740e6112afbcf7831 | 3,637,895 |
def get_compare_collection(name, csv_line):
"""get compare collection data"""
session = tables.get_session()
if session is None:
return {'isExist': False}
response = {}
try:
collection_table = CollectionTable()
cid = collection_table.get_field_by_key(CollectionTable.collectio... | 4312336786de0cd2107e4d662d5527bed37e89b9 | 3,637,896 |
from qutepart.indenter.base import IndentAlgNormal as indenterClass
from qutepart.indenter.base import IndentAlgBase as indenterClass
from qutepart.indenter.base import IndentAlgNormal as indenterClass
from qutepart.indenter.cstyle import IndentAlgCStyle as indenterClass
from qutepart.indenter.python import IndentAlgPy... | 3d6f905b66fa7808ad6863e891c30b0d0fb02e7f | 3,637,897 |
import json
def scheming_multiple_choice_output(value):
"""
return stored json as a proper list
"""
if isinstance(value, list):
return value
try:
return json.loads(value)
except ValueError:
return [value] | d45bbb1af249d0fed00892ccc55cf8f28f7f099f | 3,637,898 |
def logmap(x, x0):
"""
This functions maps a point lying on the manifold into the tangent space of a second point of the manifold.
Parameters
----------
:param x: point on the manifold
:param x0: basis point of the tangent space where x will be mapped
Returns
-------
:return: vecto... | be18b7a78f13f7159572429cf77fbc763747076b | 3,637,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.