content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def formater (string, props):
""" This function does a regular substitution 'str%(dict)' with a
little difference. It takes care of the escaped percentage chars,
so strings can be replaced an arbitrary number of times."""
s2 = ''
n = 0
while n < len(string):
if n<len(string)-1 and stri... | 8ec2d52d3b26f54dc5d5b86fc7f5def1cfe77360 | 74,400 |
def flatten_complex_to_real(dataset, lazy=False):
"""
Stacks the real values followed by the imaginary values in the last dimension of the given N dimensional matrix.
Thus a complex matrix of shape (2, 3, 5) will turn into a matrix of shape (2, 3, 10)
Parameters
----------
dataset : array-like ... | 0dadd932917cdcce5f9f990bc8ce975499e55ad8 | 74,401 |
def get_template_from_path(path: str) -> str:
"""Convert a normal path back to its template representation."""
# replace all path parts with the template tags
path = path.replace("\\", "/")
return path | 1a62acca2c0531563fb4493bc06708671a601cda | 74,402 |
from typing import Union
from typing import Pattern
from typing import List
import re
from pathlib import Path
import fnmatch
def parse_simple_index_links(
text: str,
url=None,
url_regex: Union[str, Pattern] = "^https?://|^ftp://",
ignore_regex: Union[str, Pattern] = "\/\?C=.;O=.",
fileglob: str =... | d3958f682f4b9a94c6dfea73823b17d278dddf1f | 74,403 |
def compute_mean_average_precision(statistic_list):
"""
Compute the mean average precision:
(https://en.wikipedia.org/wiki/Evaluation_measures_(information_retrieval)#Mean_average_precision)
We define average precision as Area under Curve AUC)
https://medium.com/@jonathan_hui/map-me... | 81cac2d3dc38962f27ce87648455d5fa989e237a | 74,404 |
import re
def check_email(email):
"""
Checks an email format against the RFC 5322 specification.
"""
# RFC 5322 Specification as Regex
regex = """(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"
(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0... | 522547471730c6975246c301492f5b7676032c75 | 74,405 |
import templateflow.api as tf
from niworkflows.engine.workflows import LiterateWorkflow as Workflow
from niworkflows.interfaces.cifti import GenerateCifti
from niworkflows.interfaces.utility import KeySelect
def init_bold_grayords_wf(
grayord_density, mem_gb, repetition_time, name="bold_grayords_wf"
):
"""
... | 349bb5ce7c8bede76d4e73733f76dafde3e4f00a | 74,406 |
from typing import Dict
from typing import Union
def reverse_endianness(string: str) -> str:
"""Convert hex string to hex string with opposite endianness.
E.g.
Little endian -> Big endian,
Big endian -> Little endian
Result for non hex string is undefined, no validation is done.
Args:
... | 3edd879711e1fe2b302e765fe6009da66c621969 | 74,407 |
import os
import logging
import json
def _parse_text(file_name: str, word_dict: dict, label_dict: dict, word_index_from: int = 5, label_index_from: int = 3,
n_gram:int=6, m_step:int=6, label_name:str='host_tax_id', lower: bool = True):
"""
Read corpus 读取语料
:param file_name:文件名称
:param ... | adc4ae159764da63af9a7a364fb84c376b19a12e | 74,408 |
import ast
def block_view(A, block=(3, 3)):
"""Provide a 2D block view to 2D array. No error checking made.
Therefore meaningful (as implemented) only for blocks strictly
compatible with the shape of A."""
# simple shape and strides computations may seem at first strange
# unless one is able to re... | 7f5bdbdfd1fe5fe113ae1a72de00b996c85b902f | 74,409 |
def compute_topk_scores_and_seq(sequences, scores, scores_to_gather, flags,
beam_size, batch_size):
"""Given sequences and scores, will gather the top k=beam size sequences.
This function is used to grow alive, and finished. It takes sequences,
scores, and flags, and returns... | 9b92df677cdf99420d51990e3fdf6cb882017780 | 74,410 |
import inspect
def open(file=None, mode='r', format=None, as_decorator=None, **kwargs):
"""
Open a file and return a file object. This method can be used as a function
or a decorator. When used as a decorator, the function to be decorated
should receive the handler using an argument named ``f``. File ... | e2584afe80ad4aa2f2f762292c0e186c910b7324 | 74,411 |
def sniff_features(**kw):
"""
Look at the source files and return the features for a task generator (mainly cc and cxx)::
snif_features(source=['foo.c', 'foo.cxx'], type='shlib')
# returns ['cxx', 'c', 'cxxshlib', 'cshlib']
:param source: source files to process
:type source: list of string or :py:class:`waf... | 5ba230ab16c3e7e96b913ad6bb31a23181d88b35 | 74,412 |
import pandas
def getCumSumForIntervalData(actualTimeSeries, predictedValuesOnLaggedData, intervalSize=365):
"""
:param actualTimeSeries: Object of DataFrame TimeSeries
:param predictedValuesOnLaggedData: Object of DataFrame TimeSeries
:param intervalSize: Period or Seasonality
:return: Cumulative... | 3bcbca64aff1652239b32f2c2454e897d8968334 | 74,413 |
import re
def extract_intro_and_title(filename, docstring):
"""Extract and clean the first paragraph of module-level docstring."""
# lstrip is just in case docstring has a '\n\n' at the beginning
paragraphs = docstring.lstrip().split('\n\n')
# remove comments and other syntax like `.. _link:`
para... | 44b1271f0826f21977e51c0c9a4e3852a47c6678 | 74,414 |
import sys
def get_mabe_help(path:str) -> str:
"""given path to mabe exe, returns --help output"""
if path is None:
print(f"Error: no mabe executable found in script location")
sys.exit(1)
command = f"{path} -h"
return run_command(command).strip().split('\n') | 2b2c31e2ce61396a0dbf3547ead7821dd8a9c96c | 74,415 |
def get_s3_file(s3_uri):
"""Retrieve an S3 file"""
s3_client = boto3.client('s3')
url_object = urlparse(s3_uri)
bucket = url_object.netloc
key = url_object.path.lstrip('/')
response = s3_client.get_object(Bucket=bucket, Key=key)
return response['Body'] | c585ccc59df430b991bec76daa47e17c6102c4a4 | 74,416 |
def duplicate_fraction_getter(doc: Doc, attr: str = "lines_counter") -> float:
"""Calculate the duplicate fraction of a Doc attribute based on a counter object
Args:
doc (Doc): A spaCy Doc
attr (str, optional): The attribute to be extracted.
Defaults to "lines_counter".
Returns... | 977b19e926fbd4e08e683d214ea31c4caad73006 | 74,417 |
def __audioread_load(path, offset, duration, dtype):
"""Load an audio buffer using audioread.
This loads one block at a time, and then concatenates the results.
"""
y = []
with audioread.audio_open(path) as input_file:
sr_native = input_file.samplerate
n_channels = input_file.channe... | 3ae3038e08f371be7b47682351cf25dd1ac416d9 | 74,418 |
def get_aggregate_positions(info=None):
"""Collapses all option orders for a stock into a single dictionary.
:param info: Will data_filter the results to get a specific value.
:type info: Optional[str]
:returns: Returns a list of dictionaries of key/value pairs for each order. If info parameter is prov... | 22a783961a3bd95fe065ea7f3d45d23e43021bb4 | 74,419 |
from unittest.mock import Mock
from unittest.mock import patch
import importlib
def session_indexing_decorator():
"""
Fixture that mocks the reddit object indexer for the test suite by default.
Decorators require some extra work to patch since they are already applied to functions
when a module is lo... | 47b36b8cf82977e3c72179a5eb2260abb2427da7 | 74,420 |
def get_theoretical_resolution_limit(f_central):
"""
Parameters
----------
f_central : float
wavelet central frequency in Hz
Returns
-------
float
"""
return 1 / f_central / 4 * 1000 | 187498a249466eade7774e7df86fd82a1d742577 | 74,421 |
def calc_check_digit(number):
"""Calculate the check digit for the number."""
alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
cutoff = lambda x: x - 9 if x > 9 else x
s = sum(
cutoff(alphabet.index(n) * 2) if i % 2 == 0 else alphabet.index(n)
for i, n in enumerate(number[::-1]))
re... | 967d9ac7eae3e45b42c6bb4e366345fd34207d0d | 74,422 |
import tqdm
import torch
def gen_waveform(
device, # cpu or cuda
labels, # フルコンテキストラベル
logf0_vuv, # 連続対数基本周波数と有声 / 無声フラグ
wavenet_model, # 学習済み WaveNet
wavenet_in_scaler, # 条件付け特徴量の正規化用 StandardScaler
binary_dict, # 二値特徴量を抽出する正規表現
numeric_dict, # 数値特徴量を抽出する正規表現
tqdm=tqdm, # プログレ... | daa74a7b269d1a781238e1c5de2eee438702f7c8 | 74,423 |
def create_reduced_mechanical_system(M_func, D_func, K_func, f_int_func, f_ext_func, V, W=None, constant_mass=False,
constant_damping=False):
"""
Create a mechanical system from a component where the constraints are applied by a constraint formulation
Parameters
---... | dbd174ebe68e234061ebed00aac50994e6e94c99 | 74,424 |
def load_file(filename: str) -> list:
"""Load the passwords and policies from a file
:param filename: Location of the input file
:return: List of passwords and policies
"""
with open(filename) as f:
entries = f.readlines()
entries = [parse_line(e) for e in entries]
return entries | 6670a23003e8903147a612d3e387673aa88d0da1 | 74,425 |
from sklearn.feature_selection import RFE
def select_features_RFE(X,Y,base_model,kbest=15,dir_result='./'):
"""采用RFE方法选择特征,用户可以指定base_model"""
rfe = RFE(base_model, n_features_to_select=kbest)
fit = rfe.fit(X, Y)
feature_names = X.columns.values.tolist()
# 挑选出的特征
index_selected_features =... | 68347f75fc3f9732d290f3561ce4dc40bf137d57 | 74,426 |
import argparse
def parse_arguments():
# type: () -> Namespace
"""
Argument parser.
:return: the command line arguments.
"""
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('dataset', type=str,
help='The ... | cd1be9026593fbecaa0a149cbf7ce5765b2c493c | 74,427 |
def reg_lnX(lnX, data, masks, F, B, K, H, epsilon):
"""
inputs:
lnX : Log of PSF shared for all data
data : patches of stars
masks: masks containing flaged pixels for each patch
F : list of flux values of the stars in different ... | 5807048c1bcf28f2eb624c2284317cbd17738e0d | 74,428 |
def to_stars(num):
"""
turn feed score to stars
:param num:
:return:
"""
return '★' * int(num / 10)
#return int(num / 10) | 0d89f52554662861d5947f8a9f91ff678554f5cf | 74,429 |
def merge_ngrams(word_list, dict_ngrams, exception_dict):
"""
Merge words to ngrams.
Parameters
----------
word_list : list
List of single words.
dict_ngrams : dictionary
dict_ngrams includes bi, tri, and quangrams.
Each ngram is a list.
exception_dict : list
... | dea7fa127c3cd2c955753081786e57de3082474d | 74,430 |
def get_xy_index_column_name(index_column_elt):
"""
Get the Xylinq name of an index column.
@param IN index_column_elt Index column XML element
@return The name as a string
"""
return _get_xy_name(index_column_elt, "index column") | 0bcca81c35c97bbe4cc2ca5c35190f45e5ccf135 | 74,431 |
def __ge__(self,other) :
"""Return True iff other is an initial substring of self"""
if not isinstance(type(other),bitstrings) :
return NotImplemented;
return self._l >= other._l and self[:other._l] == other; | 36c7473949b6d46e79fe20a6e0c9ac3c3d3c86d1 | 74,432 |
import socket
def is_multicast (address):
"""Return ``True`` iff address is a multicast address.
This function is used to eliminate retransmissions for confirmable
messages sent to multicast addresses.
:param address: A socket address as supported by the Python socket
functions: i.e. a pair ... | 2de5497a422b4b40288f09ea224462bd9956a96c | 74,433 |
from pandas.core import common as com
from pandas import NaT
def na_value_for_dtype(dtype):
"""
Return a dtype compat na value
Parameters
----------
dtype : string / dtype
Returns
-------
dtype compat na value
"""
dtype = pandas_dtype(dtype)
if (com.is_datetime64_dtype(... | 7e7f3041e435a67bdea90e489146d9b86b79340d | 74,434 |
def _get_array_index(array_path):
"""Translates @first @last @1 @-1 expressions into an actual array index.
:param str array_path: Array path in XJ notation.
:rtype: int
:return: Array index.
"""
if not array_path.startswith('@'):
raise XJPathError('Array index must start from @ symbol... | c83b848c1ad793323402f1c99bd3e8839fdb6401 | 74,435 |
def redir(regex, redirect_url, name=None):
"""
A shorter wrapper around RedirectView for 301 redirects.
"""
return re_path(
regex,
RedirectView.as_view(url=redirect_url, permanent=True),
name=name,
) | 730eab46c8f38ebf2c2594eaea48f21c0b75df13 | 74,436 |
def pyreq_dlg_trybuild(httpreq_hdlr: HTTPRequestHandler, project_id: int):
"""
Run trial-build on dialog model for Mix project with ID project_id, by sending requests to
API endpoint with Python 'requests' package.
Please note that the dialog trial build may have result where status is 'SUCCESS' while ... | 46474633ef7996ae0e2fbd18432b7b061235b003 | 74,437 |
def normframe(img: np.ndarray, Clim: tuple) -> np.ndarray:
"""
inputs:
-------
I: 2-D Numpy array of grayscale image data
Clim: length 2 of tuple or numpy 1-D array specifying lowest and highest expected values in grayscale image
Michael Hirsch, Ph.D.
"""
Vmin = Clim[0]
Vmax = Clim[1... | 808deb8c3463ff85a43ab4854f350d88acef0637 | 74,438 |
def calcul_positions_virages(coordonnees_du_personnage, orientation_du_personnage, profondeur_vision, liste_plan_du_labyrinthe):
"""
Prends en argument :
- La liste correspondant aux coordonnées du personnage, 'coordonnees_du_personnage';
- La chaîne de caractères correspondant à l'orientation du personnage, ... | 1fd818452750e98b0f24a269a19be324484fe6fc | 74,439 |
def load_embeddings(path = '../../NYT/glove.6B/glove.6B.300d.txt'):
"""
Loads pre-trained embeddings from the specified path.
@return (embeddings as an numpy array, word to index dictionary)
"""
word2idx = {} # Maps a word to the index in the embeddings matrix
embeddings = []
with ope... | 61cebe13602876c682ca35133aedadf69fd0a822 | 74,440 |
from typing import Union
def dL_df(
z: Union[float, np.array], cosmo: FLRW = Planck15
) -> un.Quantity[un.Mpc / un.MHz / littleh]:
"""
Get the factor to convert bandwidth to line-of-sight distance in Mpc/h.
Parameters
----------
z : float
The redshift
"""
return (cosmo.h * cns... | 14f6ce422028087042c7488f539d75a90302a668 | 74,441 |
def TFlt_GetPrcStr(*args):
"""
TFlt_GetPrcStr(double const & RelVal, double const & FullVal) -> TStr
Parameters:
RelVal: double const &
FullVal: double const &
"""
return _snap.TFlt_GetPrcStr(*args) | 24b6f564b74a37a59316209a58a4adb2bdde3052 | 74,442 |
def unique_filename(name):
"""
Returns unique file name based on "name" argument.
"""
return name | 1145ec89e9bbadf5944bc787ff1fda2805bfde1b | 74,443 |
def plasma_fractal(mapsize, wd):
"""
Generate a heightmap using diamond-square algorithm.
Return square 2d array, side length 'mapsize', of floats in range 0-255.
'mapsize' must be a power of two.
"""
assert (mapsize & (mapsize - 1) == 0)
maparray = np.empty((mapsize, mapsize), dtype=np.floa... | e950b5b71e4377cc5c04af946ba8e2c93833e598 | 74,444 |
import typing
def is_forward_ref(tp):
"""Returns true if `tp` is a typing forward reference."""
if hasattr(typing, 'ForwardRef'):
return isinstance(tp, typing.ForwardRef)
elif hasattr(typing, '_ForwardRef'):
return isinstance(tp, typing._ForwardRef) # pylint: disable=protected-access
else:
return... | 2220794e95e6b6f4333a856380d3cd47470623c9 | 74,445 |
from tqdm import tqdm
def GA(domain,fitness,N=50,nPAR=10,recomb_events=2,pS1=0.2,mut_prob=0.2,generations=1000,domain_gen=None,verbose=True,pop=[]):
""" Runs a Genetic Algorithm
Args:
domain (dict) : A <domain> dictionary
fitness (func) : A fitness function that accepts a sol
... | 16097ee6e22143936a79ce0039e6164b62af8738 | 74,446 |
from typing import Union
from typing import get_args
def smartround(num: Union[Integer, Float], ndigits=1) -> Union[int, float]:
"""Round number only if it's a float"""
if isinstance(num, get_args(Integer)):
return int(num)
else:
num = float(num)
if num.is_integer():
re... | 6ead0241e319e016d634862ef0ac38274b8a2468 | 74,447 |
def _get_previous_url(query, position, size):
"""Return the URL to retrieve the previous chunk of results."""
if position < 2:
return None
prev_pos = position - size if position - size > 0 else 1
url = '{0}?query={1}&position={2}&size={3}'
return url.format(request.base_url, query, prev_pos,... | 7090883f2cd5911577b99458ccc430b4b52360c6 | 74,448 |
import requests
import re
import os
def check_vox_files(url,available_files,dataset,voxnum):
""" Extract and return urls for all available .tgz files. """
req = requests.get(url)
if req.status_code != 200:
raise base.FailedDownloadException('Failed to download data (status {}) from {}!'.format(re... | 204f0db4f2d445fca8400b11a034128d96039aae | 74,449 |
def neuroscout_recorder():
""" Sets up client, recorder pair """
neuroscout = Neuroscout()
return betamax.Betamax(neuroscout._session), neuroscout | d9f83ee7d237d406aef3692d28e6e102f1ef6991 | 74,450 |
def sample_with_rotation(x, center, angle,
box_dim,
fill_value=255,
wraparound=True,
stdev_threshold=None,
test_stdev=False):
""" Get a patch from x, with rotation, without having to rotate t... | 4de637879d19124b21cdfbd2d8945ad97dfb60e0 | 74,451 |
def find_limits(pts):
"""
Find the limits which outline the provided list of points
Parameters:
* pts List of points [(z0,y0,x0),(z1,y1,x1),...]
Returns (min,max):
* min array of minimum indices array([zmin,ymin,xmin]
* max array of maximum indices array([zmin,ymin,xmin]
... | 8057e308499ceb930bdf6a7890c52258bc6ab5cf | 74,452 |
import re
def GetGcsSourceFromPath(input_file):
"""Validate a Google Cloud Storage location to read the PDF/TIFF file from.
Args:
input_file: the input file path arg given to the command.
Raises:
GcsSourceError: if the file is not a Google Cloud Storage object.
Returns:
vision_v1_messages.GcsSo... | b8c19ea9257e7287b8f396f2fab5bb931d7a9aed | 74,453 |
def left_child(node, new_node=None):
""" Set left child: left_child(node, new_left_child); Get left node: left_child(node). """
if new_node is not None:
node[1] = new_node
return node[1] | baabfbeb4acb7e8a2846b9a4a45b9d993619a1e4 | 74,454 |
from datetime import datetime
def prettify_timestamp(value: str) -> str:
"""
Returns a pretty version of a timestamp object.
Current format:
- %b short name of month like Mar, Jun
- %d day of the month from 1 to 31
- %Y year in 4 digit format
"""
return datetime.utcfromtimestamp(float(... | 82faefee2f98db33665c81c309e531d6dacab099 | 74,455 |
from typing import List
def find_colors(data: File, column: int) -> List[str]:
"""
Determine all the colors in a dataset.
"""
colors = set()
# Here, we show how to open a File to get a normal file stream.
with data.open() as infile:
for line in infile:
row = line.strip().s... | d9d356812e6be78388643d9edbd5e2e734c50a51 | 74,456 |
import sys
def compute_data_loss(pred_heatmap, pred_illum_uv, pred_illum_uv_sigma,
true_illum_uv, weight, step_size, offset, n, rgb):
"""Computes the data term of the loss function.
The data loss is the (squared) anisotropic reproduction error.
This function also returns the unweighted, ... | 806c3f1cdb931dfcf69ba401dc89e3119f0a2612 | 74,457 |
def _build_resubst_dict(rename_dict):
"""Build dictionary for later use with `_resubst()`.
**Example**
.. python::
>>> from SConsGnu.GVars import _build_resubst_dict
>>> _build_resubst_dict( {"xxx":"yyy", "vvv":"www", "zzz":"zzz" })
{'vvv': '${www}', 'xxx': '${yyy}'}
:Paramet... | 2eabc8da146cdaf80c4afa7eeac29077a293f8ab | 74,458 |
def getManifest(manifest_name = None):
"""
Download a client manifest.
"""
global MANIFESTS
baseurl = pref("RepoURL") + '/manifests/'
if manifest_name is None:
if 'client_manifest' in MANIFESTS:
return MANIFESTS['client_manifest']
#
# Make a list of the iden... | 2641f3de748f99fa14135e2061874b0854f1f147 | 74,459 |
import os
from src.praxxis.sqlite import sqlite_rulesengine
from src.praxxis.display import display_rulesengine
def new_ruleset(args, rulesengine_root, rulesengine_db):
"""create a new ruleset and associated db"""
if hasattr(args, "name"):
name = args.name
else:
name = args
n... | 3b20332b420e95b82e042858437c72d8ba141a62 | 74,460 |
def z_from_p(p, lat, geo_strf_dyn_height=0, sea_surface_geopotential=0):
"""Calculates height from sea pressure using the computationally-efficient
75-term expression for density in terms of SA, CT and p (Roquet et al.,
2015). Dynamic height anomaly, geo_strf_dyn_height, if provided, must be
computed wi... | 1dd8c16158f0225ca1426206a4ebaca9547446c0 | 74,461 |
def parse_other(lines):
"""Parse a series of lines in the format:
0123456789
a ~~~~~~~~~~
...
j ~~~~~~~~~~
Return a map of [x, y] -> MISS, NEAR_MISS or SUNK"""
parse = {}
for y, line in enumerate(lines[1:]):
for x, c in enumerate(line[2:]):
if c == Board.GUESS:
... | 338d71bfce9c580c9e15859a5913eba84bcc6a92 | 74,462 |
from typing import Optional
from typing import Callable
from typing import List
def cross_validate(
model: ModelBridge, folds: int = -1, test_selector: Optional[Callable] = None
) -> List[CVResult]:
"""Cross validation for model predictions.
Splits the model's training data into train/test folds and make... | b3a9d438fa1ea6fe3c856f63308590173ab2bdeb | 74,463 |
def boxcar(x, x1, x2):
""" DOC """
if hasattr(x, 'size'):
y = 1.0 * np.ones_like(x)
y[x < x1] = 0.0
y[x > x2] = 0.0
return y
if x1 <= x <= x2:
return 1.0
return 0.0 | ba9d81a4309e30a6613de6d5e8dca3ecef8fc96d | 74,464 |
def recarray2dict(recarray):
"""Return numpy.recarray as dict."""
# TODO: subarrays
result = {}
for descr, value in zip(recarray.dtype.descr, recarray):
name, dtype = descr[:2]
if dtype[1] == 'S':
value = bytes2str(stripnull(value))
elif value.ndim < 2:
va... | 86068bbb2100f401817c9b3b716a3e2000b3daaa | 74,465 |
def _extract_instance_parameters(attributes):
"""
Extracts instance parameters. If no name found, replaced with identifier.
:param attributes: dict, with the following structure:
{
"arn": string,
"name": string,
"tags": {
"{tag_name}": string
... | 99e76f5f663798667c8121c1f2c9ac243cf1a67c | 74,466 |
def show(db: Session, filename: str):
"""
:param db:
:param filename:
:return:
"""
file_obj = db.query(FileModel).filter(FileModel.s3_filename == filename).first()
if not file_obj:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
detail=f"File... | 1de63c2ef93fa415b7e40d13c3495cb641ff6e92 | 74,467 |
def TDictOf(key_type, val_type):
"""Checks a dict type for the type of its key/values.
"""
desc = WithDesc("Dictionary with keys of %s and values of %s" %
(Parens(key_type), Parens(val_type)))
def fn(container):
return (compat.all(key_type(v) for v in container.keys()) and
co... | 91672ef089e8c245d6fac8da8f7018719cfb6dfb | 74,468 |
def heading_html(hl, hd, nodes, attrs, context):
"""Formats a HTML heading."""
return [mkdata("<h{n}>{title}</h{n}>".format(n=clamp(1, hl, 6), title=hd))] | 76f8e8e1c22cd05bae07981a24e41fb6c8d63610 | 74,469 |
def remove_position(lmks, position=None):
"""If `position` is `None`, :func:`remove_position` translates `lmks` such
that :func:`get_position()` of `translated_lmks` is the origin. Else it is
the (:func:`get_position()` of `lmks`) - `position`.
Parameters
----------
lmks : array-like
... | 3dde882e1a1a752ccfde12a0088063e76fbbaffd | 74,470 |
def contains(text, pattern):
"""Return a boolean indicating whether pattern occurs in text."""
assert isinstance(text, str), 'text is not a string: {}'.format(text)
assert isinstance(pattern, str), 'pattern is not a string: {}'.format(text)
#funny storytime! initially did not pass because I falsely reme... | 4eff4e8d69e7843e2a4e4043df29139d92ded772 | 74,471 |
def custom_subparser_builder(subparser, subparser_id, description, options_func, runner_func, setup_func, shutdown_func, error_handler_func):
"""
Util to add subparser options
:param options_func: Function that will add args and options to Parser instance F(subparser) -> None
:param runner_func: Functi... | 0d5914646e07be26792fae321c32f3338d6b467b | 74,472 |
def get_transformer(name):
"""
some convenience methods for common
feature creation methods
todo: handle more manual feature creation pipelines
"""
transformer_map = {
"standard": build_numeric_column,
"standard_numeric": build_numeric_column,
"quantile_numeric"... | d2ee1e2cc1b67b6efec8db78c2cc80d011a9b049 | 74,473 |
import os
def backup_mongo():
"""
This task runs the MongoDB backup on our API server.
Then it commits the result to the "api-db-backups"
repository on Github.
"""
shell = spur.SshShell(
hostname=os.environ['TNYU_API_SERVER_IP'],
username=os.environ['TNYU_API_SERVER_USER'],
... | ec3cda17f4f68a3841d854d45d425814d51e1623 | 74,474 |
from typing import Union
from typing import Iterable
from typing import Any
def flag_nulls(
df: pd.DataFrame,
column_name: str = "null_flag",
columns: Union[str, Iterable[str], Any] = None,
) -> pd.DataFrame:
"""
Creates a new column to indicate whether you have null values in a given
row. If ... | 083da4f596b878a25b70e7f2b2648ac59e335e9c | 74,475 |
def std_dev_classification(data, window_length, threshold):
"""Perform wet/dry classification with Rolling standard deviation method
Parameters
----------
data : iterable of float
Time series of received signal level
window_length : int
Length of the sliding window
threshold ... | 3b2c75f417ec99290f7d41497610c356833f3934 | 74,476 |
def dynamic_slice_in_dim(operand, start_index, slice_size, axis=0):
"""Convenience wrapper around dynamic_slice applying to one dimension."""
operand = tf_np.asarray(operand)
start_indices = [0] * operand.ndim
slice_sizes = list(operand.shape)
axis = int(axis)
start_indices[axis] = start_index
slice_sizes... | e548384a1f2444716960e955f374a4eb710fbff7 | 74,477 |
def process_achievement(aid, data):
"""
Determines whether or not an achievement has been earned.
Should not be called directly.
Args:
aid: the achievement id
data: additional data dictionary
"""
if data.get("uid", None) is None:
data["uid"] = api.user.get_user()["uid"]... | 82bbc59eb90ef3763c879887b4825d13185c8588 | 74,478 |
def validate(db_ns, db_id):
"""Validate identifier, accepting HGNC name or ID"""
if db_ns == 'HGNC':
if db_id.isdigit():
return validate_id(db_ns, db_id)
else:
return get_hgnc_id(db_id) is not None
else:
return validate_id(db_ns, db_id) | 94ee9b009f4993d64c11b80e5d5ca5a307064b57 | 74,479 |
def timeseries_to_str(ts, fmt="%.18e"):
"""Transforms a time series to its representation as a string (used when saving time series to disk).
Parameters
----------
ts : array-like
Time series to be represented.
fmt : string (default: "%.18e")
Format to be used to write each value.
... | 898d129e239071a92b1de4a07e7613198c275833 | 74,480 |
def get_url(url, data=None):
"""
Возвращает открытый файловый объект
Запускает исключение parse_html.URLError в случае ошибки"""
res = True
msg = ''
try:
f = urllib2.urlopen(url, data)
except urllib2.HTTPError, err:
res = False
msg = str(err.code) # 404, ...
... | 5bf2dec2fb166fd2dce660351b417cd28651063d | 74,481 |
import skimage.restoration
def shift_invariant_denoising(x, max_shifts, func='denoise_wavelet', out_dtype='image', **kwargs):
""" A wrapper of the skimage.restoration module.
Unfinished, only support denoise_wavelet now.
"""
if not callable(func):
if isinstance(func, str):
fun... | 1513d7f95f161f46d682e7df184c74e1101a3847 | 74,482 |
from typing import List
def one_minus(data: List[float]) -> List[float]:
"""
return 1 - each element in list
"""
return list(map(lambda elem: 1 - elem, data)) | bb5c9a3d27866b408e519541778c7cdb8bd9ac13 | 74,483 |
def call_method(obj, methodName):
"""
Execute a method of an object using previously passed arguments with setarg filter
"""
method = getattr(obj, methodName)
if hasattr(obj, '__call_arguments'):
ret = method(*obj.__call_arguments)
del obj.__call_arguments
return ret
retu... | 7bd94cdf81f448a8b73bbf3bcdda47cf4f5580cd | 74,484 |
from typing import List
def boxes2polygons(boxes: np.ndarray or List[np.ndarray]):
"""
将矩形框转为多边形轮廓
:param self:
:param boxes:[num_polygons,4], box is [xmin, ymin, xmax, ymax]
:return: polygons: [num_polygons,num_point,2]
"""
polygons = []
for box in boxes:
xmin, ymin, xmax, yma... | 64dec0756d8d15c6b4ddc88f04b383c60bf8aa41 | 74,485 |
def get_bracketing_pattern_feature(dataset):
"""
Return bracketing_pattern feature (sorted tuple of adj_quantities seen).
"""
grouped = dataset.groupby(
['tube_assembly_id', 'supplier', 'quote_date'])
bracketing_pattern = [None] * len(dataset)
for t_s_q, indices in grouped.groups.iterite... | 9b262fcff8e227dc50ea769ac8953df0aeba62b7 | 74,486 |
import array
def sliceAtoms(atoms, select):
"""Slice *atoms* using the selection defined by *select*.
:arg atoms: atoms to be selected from
:type atoms: :class:`Atomic`
:arg select: a :class:`Selection` instance or selection string
:type select: :class:`Selection`, str
"""
if atoms == ... | 9a99a7d1b0ce198488c69b2069876ee527e9f37a | 74,487 |
import copy
def _deep_split(filenames, size_per_shard, parsed_formats):
"""Split files into roots using the first FileFormat.
Deep split can split within a file. It tells the first format how big
a split it wants and the first format will do the actually splitting
because only the first format knows how to o... | c1002dd5b6db28cbe6e8652d11d583bcc023a841 | 74,488 |
def files_in_handler(ctx, param, value):
"""Process and validate input file names"""
return tuple(file_in_handler(ctx, param, item) for item in value) | 9ca82d8b2b2fb4366a5d77f2291c55c225910174 | 74,489 |
def vCPA3(v_known, r1, r2, omg1=0, omg2=0):
"""
Complex-algebraic velocity analysis, Theory of Machines and Mechanisms
The unknowns are V1_T, V2_T
v_known + v_r1 = v_r2
"""
A = [[-np.cos(np.angle(r1)), np.cos(np.angle(r2))],
[-np.sin(np.angle(r1)), np.sin(np.angle(r2))]]
... | 2513ace57d568c865e2a016bb925bd419177620c | 74,490 |
from manubot.pandoc.bibliography import (
load_bibliography as load_bibliography_pandoc,
)
from manubot.cite.csl_item import CSL_Item
import pathlib
import logging
def load_bibliography(path: str) -> list:
"""
Load a bibliography as CSL Items (a CSL JSON Python object).
For paths that already ... | 026cd7218dbd0e4909db0e5915bf595a798415e1 | 74,491 |
def listObjects(s3, bucket_name, filepath):
"""Get list of filepaths to objects in bucket_name, filepath
Args:
bucket_name (str): s3 bucket name
filepath (str): Path to folder
"""
try:
list_object_key = [obj.key for obj in list(self.s3session.Bucket(self.bucket_name).objects.fil... | 2f2151c89718ea8167ec1ec3fd5732b82929193f | 74,492 |
def versions(request):
"""List version details of components used by the API."""
adapter_version = get_adapter_factory(request).describe_adapter()
adapter_version['type'] = 'adapter'
twitcher_version = {
'name': 'Twitcher',
'version': __version__.__version__,
'type': 'application... | 41846123112e75b148b60c2ac207aff29d744f70 | 74,493 |
import os
def get_jpl_results(jpl_path):
"""
:param jpl_path:
:return:
"""
all_data_dict = {}
for path, dirs, files in os.walk(jpl_path, topdown=False):
# print 'path', path
# print 'dirs', dirs
# print 'files', files
them_dates = []
them_files = []
... | b03405581b74f7f4d7d743911d79f45d8bb4a18b | 74,494 |
def exercise_output(template):
"""Outputs the way specified in the exercise"""
result = """Marca: {0}
Modelo: {1}
Preco: {2}
Motor: {3}
Ano: {4}
Km: {5}
Combustivel: {6}
Cambio: {7}
Direcao: {8}
Cor: {9}
Ar-cond: {10}
Opcionais: {11}\n"""
return result.format(
template["Brand"],
template["Mo... | 0944b47d28c8b95c7eab32b799066af14b2b95ea | 74,495 |
import torch
def load_dataset(name, device, args, return_nid=False):
"""
Load dataset and move graph and features to device
"""
if name not in ["ogbn-products","ogbn-papers100M"]:
raise RuntimeError("Dataset {} is not supported".format(name))
dataset = NodePropPredDataset(name=name, root=... | 6677245a9ecc4074cd6e2177987436b7c93b3ca2 | 74,496 |
def strings_to_ints(lst):
"""transforms a list of strings to a list of ints
ARGS:
list of strings
RETURNS:
list of ints
RAISES:
ValueError: when the string in the list is not a number
"""
return None | ec399c6e4ed7f737cdfe243112fe30bc4c4dd21e | 74,497 |
def get_table(tables, var, phi):
"""
Table Searching function
"""
if phi>=50:
phi = 50
#First find phi index
idx=0
while(True):
if tables['phi'][idx]>=phi:
break
idx+=1
if(tables['phi'][idx-1]==phi):
return tables[var][idx-1]
else:
... | 55a0feae3d67c960f815a46bb0bc43f0ed7cf5a9 | 74,498 |
async def get_genres_csv(csv_or_wild):
"""
Get genre fields by id or name when wild. ?full=0 for basic information.
"""
genres = []
for id in csv_or_wild.split(','):
genres.append(Genre(id=id))
action = {"mode":"get", "args":request.args}
outgoing = Manage_DATA(action=action, genres... | 5edea14a26ab734f97d7043eff95631beb48e679 | 74,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.