content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _bytes_chr_py3(i):
"""
Returns a byte string of length 1 whose ordinal value is i in Python 3.
Do not call directly, use bytes_chr instead.
"""
return bytes([i]) | b6cd1e5e7214d02c29a594e639fbddac901a1362 | 64,800 |
import array
def rot_arbit(angle, u_v):
"""Takes an angle in radians and a unit vector and outputs a rotation matrix around that vector
Arguments:
angle (int): Angle in radians.
u_v (list): Unit vector
Returns:
(array): Rotation matrix
"""
rot_mat = array(
[
... | d10731ab62b5fc30d81c035509f5ca60bc9a3fa6 | 64,801 |
def complete(request, reason=None, attempt_num=None, questionpaper_id=None):
"""Show a page to inform user that the quiz has been compeleted."""
user = request.user
if questionpaper_id is None:
message = reason or "An Unexpected Error occurred. Please contact your '\
'instructor/administ... | e4cbbfe08e3d8004d1bb6bd0803d68ca7791e307 | 64,802 |
def isPublic(ip_addr):
"""
description: 检测是否公有ip
param {str} ip_addr - [ip地址]
return {bool} 是否为公有ip
author: Senkita
"""
if IP(ip_addr).iptype() == 'PUBLIC':
return True
logger.warning('{} - Private.'.format(ip_addr))
return False | ec160f6da8d7b3260d6bfeb726982b710883a12d | 64,803 |
import os
import PIL
def update_output(
uploaded_filenames,
uploaded_file_contents,
graph_relayoutData,
any_label_class_button_value,
crf_theta_slider_value,
crf_mu_slider_value,
pen_width_value,
show_segmentation_value,
median_filter_value,
crf_downsample_value,
select_ima... | 6714bedbde0d2a06f1e6b3adca07a36ed5e38dac | 64,804 |
def makeDASRunNested(dasrun_ingredients):
"""
Used by the multiprocessing module within getDASRuns to more quickly build DASRun objects
"""
config_path, schema_name = dasrun_ingredients
return DASRunNested(config_path) | 40a9ada0497c77accd436054f940029fbb49e61b | 64,805 |
def _to_channel_first_bias(b):
"""Reshape [c] to [c, 1, 1]."""
channel_size = int(b.shape[0])
new_shape = (channel_size, 1, 1)
# new_shape = [-1, 1, 1] # doesn't work with tensorRT
return tf.reshape(b, new_shape) | 040d2cbda192998449e6e5727ff6632004057979 | 64,806 |
def Compile(text: str) -> str:
"""A preprocessor which attempts to compile the given code.
Args:
text: Code to compile.
Returns:
The input code, unmodified.
"""
clang.CompileLlvmBytecode(text, ".cpp", CLANG_ARGS)
return text | 9b02f6ef71eb8a33aee766d4736510059e838da0 | 64,807 |
def cart2pol(x, y):
"""
helper function for coordinate conversion of Cartesian to polar coordinates. See cart2pol in Matlab. From http://stackoverflow.com/a/26757297
:param x: x values
:param y: y values
:return: radius rho and angle phi
"""
rho = np.sqrt(x ** 2 + y ** 2) # radius
phi =... | 4ecbbc674cfd29f89b36a66caa6b8a2dfcaa53da | 64,808 |
def create_change(outputs: dict, total_selected: int, address: str, total_outputs: int, fees: int) -> (dict, int):
"""
Identify the change and create if necessary.
Change the outputs adding the change.
:param outputs: Dict with the outputs.
:param total_selected: Sum of the selected UTXO.
:param address: Address ... | 09945f0a2ada582ddd8763c7d165c2c26348580c | 64,809 |
import os
def load_java_system(bands=None, version="dr1"):
""" Use speclite to load Javalambre's SPLUS filters for convolution. """
bands = context.bands if bands is None else bands
wdir = os.path.join(os.path.split(__file__)[0], "tables")
filters_dir = os.path.join(wdir, "filter_curves", version)
... | f76e6e3c4632b60c9ef3b024ed42bcd482996f64 | 64,810 |
def parseDownloadRange(rangeStr : str):
"""Parse and get the download range indices"""
# validate first if it is a valid range format
if not validateRange(rangeStr):
return None
# get range specifiers
ranges = rangeStr.split(",")
try:
rangeFrom = None if ranges[0] == "" else i... | afc0a3dca18f4b78e1c342c5fd5a38f6425fa0f9 | 64,811 |
import logging
def _create_md_dict(clean_header):
"""
This function takes the sorted header list as input and populates the
metadata dictionary containing all relevant header information pertinent to
the image data set originally stored in the AmiraMesh file.
Parameters
----------
header_... | b65a5077672c554fbecc26a13997e671b1c124c0 | 64,812 |
import os
import uuid
def upload_file(f):
""" Upload a file and return the URL to it. """
# Create path under media root
name, ext = os.path.splitext(f.name)
name = "%s%s" % (str(uuid.uuid4()), ext)
path = date.today().strftime("%Y")
# Create base directory
filepath = os.path.join(setti... | 0d0adc02cb116386a4093a76feb5331e7d8df4c5 | 64,813 |
def state_changed(func):
"""Decorator indicating a function which changes the state
Parameters
----------
func : callable
The function to wrap.
Returns
-------
callable
The wrapped function.
"""
@wraps(func)
def wrapped(self, *args, **kwargs):
ret = fun... | d171e07c081d71deeba23f00f71fc36a62156d02 | 64,814 |
def linux_provisioners(**kwargs):
"""Linux specific provisioners."""
# Setup vars from kwargs
vagrant_box = kwargs['data']['vagrant_box']
build_scripts_dir = kwargs['data']['build_scripts_dir']
template = kwargs['data']['template']
scripts = [
f'{build_scripts_dir}/base.sh',
f'... | 7627205c94ca8c1d445a8d8af3fd7fb7e062226c | 64,815 |
def bin_points(XYZ_cms, map_size, z_bins, xy_resolution):
"""Bins points into xy-z bins
XYZ_cms is ... x H x W x3
Outputs is ... x map_size x map_size x (len(z_bins)+1)
"""
sh = XYZ_cms.shape
XYZ_cms = XYZ_cms.reshape([-1, sh[-3], sh[-2], sh[-1]])
n_z_bins = len(z_bins) + 1
counts = []
... | fee13961f841d44ecb6d291f713806ba4e42b0b6 | 64,816 |
from datetime import datetime
def weighted(weight):
"""
Функция, которая возвращает декоратор.
Каждый раз, когда это функция будет вызываться, будет смотреть,
с какого айпи был сделан запрос и считать количество запросов с
этого айпи. Если количество запросов слишком большое, даст ... | da5bcddcf0c424e8fecc9ff3518d6bf4816c819f | 64,817 |
def grade(quiz_code):
"""
Grades the instance according to the options selected using the answer method
:param quiz_code:
:return: json representing the quiz or with a custom error
"""
text_response = controller.grade_quiz(quiz_code)
return text_response | d4094c00cd9445824adc4a993717da4aa03c0241 | 64,818 |
from datetime import date
from sys import argv
from astropy.io import fits
from pydl import __version__ as pydlversion
def fits_polygon_file():
"""Create a small test version of a FITS polygon file.
"""
with fits.open(argv[1], uint=True) as hdulist:
header0 = hdulist[0].header
data = hduli... | bcd987466c9abeb427493ab35c91bf38e1a7c939 | 64,819 |
import os
from datetime import datetime
import uuid
def unique_filename(path):
"""
Return a unique filename, which is usefull for image upload for instance
"""
def _unique_path(obj, name):
parts = name.split('.')
extension = parts[-1]
directory_path = os.path.normpath(
... | bf804a24402f9d7cf78d1c081e80c7c8013e1cfc | 64,820 |
def summarize_obo(obo_file):
"""summarize content from an obo into a list
:param obo_file: path to obo file
:return: dictionary mapping ids to objects with
data, aux_pos, aux_neg components
"""
result = []
obo = Obo(obo_file)
for id in obo.ids():
term = obo.terms[id]
... | 573cf046698692b32638841c187bac8adedc6a8f | 64,821 |
def normalize(array, inplace=False):
"""
Normalize an array using the mean and standard deviation calculated over the entire dataset.
@param array: Numpy array to normalize.
@param inplace: Whether to perform the normalization steps in-place.
@return: Normalized array.
"""
if inplace:
... | 563c4b79392eaf653c2c09261f87b574e25b6398 | 64,822 |
def guess_type(v, consumer='python'):
"""Guess the type of a value (None, int, float or string) for different types of consumers
(Python, SQLite etc.).
For Python, use isinstance() to check for example if a number is an integer.
>>> guess_type('1')
1
>>> guess_type('1', 'sqlite')
'integer'
... | a9361d5ce7f070f09dca267afb4ffcae866040eb | 64,823 |
def _html_alert_danger(msg: str) -> HTML:
"""Display a message as a Bootstrap-styled HTML alert in a Jupyter notebook."""
html_str = f'<div class="alert alert-danger" style="margin: 5px;">☠️ {msg}</div>'
return HTML(html_str) | acce8d423bd3c831e2c06edfb188492be895e23d | 64,824 |
def melInfo( input ):
"""
Get information about procedures in a mel file.
>>> import pymel.tools.mel2py as mel2py
>>> mel2py.melInfo('attributeExists')
(['attributeExists'], {'attributeExists': {'returnType': 'int', 'args': [('string', '$attr'), ('string', '$node')]}}, {})
:Paramet... | ba90c519ef43580b63948f251ce7c527262123b1 | 64,825 |
from typing import Tuple
from typing import Dict
from typing import Set
from typing import Counter
import tokenize
def read_sentences(sentence_file: str) -> Tuple[Dict[int, Tuple[str, str]], Dict[str, Set[str]]]:
"""Read and process a sentence file.
Paramenters
-----------
sentence_file: str
... | 861e12e52019700ee5cf592e23be035969a0cb7a | 64,826 |
def resize_deprecated(X,shape=None):
"""
Deprecated since 2017.06.26
resizes N-D array X into shape.
For example,
2D 100 * 100 array -> 200 * 200
new = resize(img, [200,200])
NOTE
----
Doesn't work if the image is not rectangular.
"""
if shape==None:
return X
... | 44c8fdd32fa21bce892d76c5968b9be6dbbc74bc | 64,827 |
from sympy.integrals.meijerint import meijerint_inversion, _get_coeff_exp
from re import S
def _inverse_laplace_transform(F, s, t_, plane, simplify=True):
""" The backend function for inverse Laplace transforms. """
# There are two strategies we can try:
# 1) Use inverse mellin transforms - related by a s... | c7470ead8d8eb22bf6da6d8c172db46c7d303463 | 64,828 |
def _gaussian_weighting(x): # pragma: no cover
"""
Kernel function for loess with a gaussian shape.
The span f covers 95% of the gaussian.
"""
w = np.exp(-(x ** 2) / (2 * (1 / 1.96) ** 2))
w[x >= 1] = 0
return w | 0c4e9d15ee94d099aa9171898b825da6a272a995 | 64,829 |
import torch
def array_from_skew_matrix(x, device=torch.device("cpu"), dtype=torch.float32):
"""
Receives a skew matrix and returns its associated 3-element vector (array).
:param x: Skew matrix (3x3)
:return: Associated array (3-element).
:param device: Device to allocate new tensors. Default: torch... | 54dcb699db154e8c995dc324888b633451cfb7fc | 64,830 |
def binary(img,th=128):
"""generate binary image
Args:
img : image array
th : threshold
"""
img[img<th] = 0
img[img>=th] = 255
return img | 627c3fc928886facbae8ca4cf692f543f4cbca40 | 64,831 |
def serializenotes(sections, notes):
"""Serialize release notes from parsed fragments and notes.
This function essentially takes the output of ``parsenotesfromrevisions()``
and ``parserelnotesfile()`` and produces output combining the 2.
"""
lines = []
for sectionname, sectiontitle in sections... | c58c18610659c8303e2b66508319c3646f2d6513 | 64,832 |
from datetime import datetime
def parse_string_to_timedelta(string):
"""Convert a string in the form "4 horas" to timedelta object"""
string_mapping = {"horas": "hours",
"hora": "hours",
"días": "days",
"día": "days",
"dia... | 74acaba66dde87951b798df6a1957652d6a2a06e | 64,833 |
import zipfile
import os
def _SplitModuleForAssetTargeting(src_module_zip, tmp_dir, split_dimensions):
"""Splits assets in a module if needed.
Args:
src_module_zip: input zip module path.
tmp_dir: Path to temporary directory, where the new output module might
be written to.
split_dimensions: li... | b60b6e0f764b0dfe8fbda6ede1babb681841a769 | 64,834 |
from typing import Any
def squeezenet1_1(
pretrained: bool = False, progress: bool = True, **kwargs: Any
) -> SqueezeNet:
"""
Constructs the SqueezeNet 1.1 model.
.. note::
SqueezeNet 1.1 model from the `SqueezeNet: AlexNet-level accuracy with 50x fewer parameters and <0.5MB model size <https... | 7a01d0acdb551900d6d9302d54c50063e8a322a8 | 64,835 |
def get_set_layout_path():
""" creates and return the config folder path for layout files
"""
return get_set_config_path('layout_configs') | fcabe52039bccba5a1718d5db8870041c49b42d7 | 64,836 |
import socket
def make_data_sender_socket(ip_address=None):
"""Create a socket for sending multicast data."""
ip_address = gethostip() if not ip_address else ip_address
datasock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
datasock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
dat... | bc1b523a70fa41fb1d15245d6bf4e46ebc51e0c4 | 64,837 |
def tgp_eur_data_path():
"""
Return the path of the attached 1000G sample data for
European individuals (N=378) and chromosome 22 (p=15938)
"""
return osp.join(osp.dirname(__file__), 'data/1000G_eur_chr22') | daa617745dc47aaad688a4e90b92ed292d590ac3 | 64,838 |
import hashlib
def _bundle(repo, bases, heads, node, suffix, compress=True, obsolescence=True):
"""create a bundle with the specified revisions as a backup"""
backupdir = "strip-backup"
vfs = repo.vfs
if not vfs.isdir(backupdir):
vfs.mkdir(backupdir)
# Include a hash of all the nodes in ... | 831955e75e7fc3e11df1bde12211f3adec69f7d2 | 64,839 |
def make_external(url):
"""Return the external version of a url."""
return urljoin(request.url_root, url) | 81f11aff77d385e7eab351eb167b21c6438c1ff5 | 64,840 |
def preprocess_text(text, fix_unicode=False, lowercase=False, transliterate=False,
no_urls=False, no_emails=False, no_phone_numbers=False,
no_numbers=False, no_currency_symbols=False, no_punct=False,
no_contractions=False, no_accents=False):
"""
Normal... | f5472121bf3b9581df8cc58c32659ccf23d2c1f4 | 64,841 |
def makemove (b):
"""computer moves"""
# return makemove1st (b)
return makemoverand1 (b) | 5850639a09cfd64989ce4e33fec0ce87b2c99ea5 | 64,842 |
def float16_scope():
"""Scope class for float16."""
def _custom_getter(getter, *args, **kwargs):
"""Returns a custom getter that methods must be called under."""
cast_to_float16 = False
requested_dtype = kwargs['dtype']
if requested_dtype == tf.float16:
kwargs['dtype... | 8c5c555ba2f32853c40fb1799ca0de8f4bd9b275 | 64,843 |
def download_works_file(data_dir=None, save=True):
"""
Download the runeberg.org works file to t.lst and convert it to utf-8.
@param data_dir: the directory to which the data should be downloaded.
Defaults to DATA_DIR.
@param save: whether the file should be saved or the stream returned
@re... | a9e6a94ef976de12d2b64f5ea21221ff5db1277a | 64,844 |
import csv
def csv_download(request):
""" Creates a CSV file using all of the applications to the users
organization.
"""
apps = get_all_applications_for_users_org(request.user)
data = ApplicationCSVDownloadSerializer(apps, many=True).data
fields = []
for datum in data:
these_field... | 65fbf7937475abd40c7ebd8bf1d037dba878d3e5 | 64,845 |
import logging
def build_bifpn_layer(feats, feat_sizes, config):
"""Builds a feature pyramid given previous feature pyramid and config.
Args:
feats: [P3, P4, P5, P6, P7]
config: a dict-like config, including all parameters.
Returns:
{3:P3", 4:P4", 5:P5", 6:P6", 7:P7"}
"""
if conf... | 3a3f9d2dcccf6a36c23b044f19082c8732c7f165 | 64,846 |
def get_trace_len(df):
"""
get the length of trace
"""
cid = list(df['CaseID'])
dic = {}
for i in cid:
if i in dic:
dic[i] += 1
else:
dic[i] = 1
trace_len = int(max(dic.values()))
return trace_len | a199b320df2c61a04cde676814350878b0bf89a0 | 64,847 |
def div_pow2_fp(x, powof2):
"""Divide by a power of two."""
if _np_instance(x):
return x / np.power(2, powof2)
return _apply_vectorized(x, lambda z: z >> powof2) | c8f58a3425b5ecb73f99a8fada6d30be661ee534 | 64,848 |
def check_all_validations_for_new_login(email1,email2,pw1,pw2,shipName):
"""
This used during the create new user process.
This method calls other validation methods and baically determines
if any of the info that the user entered was illegal.
args:
all args should be strings and less than 256 ... | 24445871a2cc6da14a6966dced8eb72c9f248c8b | 64,849 |
import json
def hello(event, context): # pylint: disable=unused-argument
"""Hello lambda function.
Args:
event (dict): Contains information from the invoking service
(service defines the event structure)
context (obj): Contains methods and properties that provi... | fabe319ab98cfcdd9208b021a6b4e42d6aa46a05 | 64,850 |
def _check_dparam(dparam=None):
""" Check basic properties of dparam
It must be a dict
with only str as keys
with only some fields allowed for each key
with values that can be scalars, arrays, or functions
<Missing fields are filled in from defaults values in models._DFIELDS
"""
# ch... | 1d7527ea813cb5a55baf4bb8f0027ffd283dd937 | 64,851 |
def yaml_load(path: str):
"""Reads yaml file in path and return it content in string form."""
with open(path, "r") as file:
data = load(file, Loader=FullLoader)
return data | a690fddb842810ad2a48d17c9875a09793d29e69 | 64,852 |
def lr_domain(results, train_idx, test_idx, balance=False, clf_da=None, clf_base=None, inits=None):
"""
:param results:
:param train_idx:
:param test_idx:
:return:
"""
label_raw = results['label_raw']
fvs_base = results['fvs_base']
fvs_da = results['fvs_da']
print('------------... | 72d5afc4198eeaa328c37c199f8d87f7e500d235 | 64,853 |
def performChipSeq( sequences=[], spEnergies=[], numCells=100000, depth=100, ampRatio=1000, pExt=1.0, pcrCycles=15, bgEnergy=1, chemicalPotential=0, secondTFspEnergies=[], secondTFchemicalPotential=0, chromAccessibility=[], secondTFintEnergies=[], indirectLocations=[], indirectSequences=[], numFPlocations=0 ):
"""
... | bf5197442d8fec0cb4ed761c871e0d15e36354eb | 64,854 |
import pkg_resources
def get_duplicate_entry_points(group, name=None):
"""Create list of entry points with duplicates."""
return [pkg_resources.EntryPoint.parse('dev = tests.test_get_entry_points:dev'),
pkg_resources.EntryPoint.parse('dev = tests.test_get_entry_points:dev')] | 3bed4e7eecf8c74361f472928c4a9865956e051a | 64,855 |
from typing import List
def fill_array(
blocklist: List[int], maxsize: int, numdata: int, numblocks: int, blocksize: int
) -> Array:
"""Fills a new array of integers with the indices corresponding to the
specified block structure.
Parameters
----------
blocklist : list
List of integer... | 86da6914f039629e95f773676cd10518aabce24d | 64,856 |
import re
def find_dlls(data: bytes) -> list:
"""
lists the dlls mentioned in the strings
Args:
data: strings data from "Strings.txt" file
Returns:
List of hardcoded .dll names in the strings output
"""
pattern = rb".+\.dll|.+\.DLL"
return list(map(lambda x: x.decode(... | 51a44b0563dcd61990f35562f3a624aaed6085c7 | 64,857 |
import re
def uid(n=5):
"""
Generate a UID with the specified length.
"""
global _count
c = next(_count)
if len(str(c)) > n:
raise ValueError('UID width exceeded')
return re.sub('\s', '0', ('{c:%i}' % n).format(c=c)) | 4ce047e251813e236af62353730e4df7fdc7f518 | 64,858 |
def get(resource, data='', results_only=True):
"""
Makes an HTTP GET request to the API
:param resource: API resource (e.g. user)
:type resource: str
:param data: Data payload for request
:type data: dict
:param results_only: Whether or not to return metadata along with results
:type re... | 782c61f2d87f17956dfef68c5a8b0bf25355a5a4 | 64,859 |
def get_column_mapping():
"""
Reads the column names from columns.txt
Returns a list of column names as well as a mapping of the position of these columns
"""
with open(COLUMN_FILE, "r") as f:
columns = f.read().rstrip().split("\n")
# Mapping of column to column index
column_... | ad1c1f3f113c2c0f4bba9a2b7db6a72775035b91 | 64,860 |
from typing import List
from typing import Dict
def single__intent_topk_precision_score(
intent_prediction: List[Dict[str, str]],
y_true: List[str],
k: int = 1,
) -> float:
"""Compute the Precision of a single utterance with multi-intents
Precision of a single utterance is defined... | 3b67849670f80a3fa148249a6fe41ce4627546e5 | 64,861 |
import torch
from typing import Tuple
def cot_laplacian(
verts: torch.Tensor, faces: torch.Tensor, eps: float = 1e-12
) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Returns the Laplacian matrix with cotangent weights and the inverse of the
face areas.
Args:
verts: tensor of shape (V, 3) cont... | 04629711cf877e0d962475f9841f663e0c490000 | 64,862 |
from typing import List
from typing import Tuple
import copy
def codelToGraphNode(image: np.ndarray, inputCodel: codel, edgePointers: List[direction]) -> Tuple[graphNode, List[BaseException]]:
"""
:param image: image
:param inputCodel: set of positions within the same color
:param edgePointers: list o... | 4f60eb0ff761dff4a92e1c674578825affd436c5 | 64,863 |
def parameter_estimation_lr_n(follower_orig, total_follower_t, no_events, event_pred):
"""
Fit the parameters of the linear regression with degree
:param follower_orig: array, containing the number of followers of the original tweeting person for all tweets (d_0).
:param total_follower_t: array, contain... | 75aca1b801bc2f36f61ce482a478b67d2035dbee | 64,864 |
import os
def TIC_to_TOI(name):
"""Convert TIC name to TOI name.
Args:
name (str):
See also:
* :func:`stella.catalog.xindex.TOI_to_TIC`
"""
filename = os.path.join(xindex_path, 'TIC-TOI.csv')
tic = int(name)
f1 = lambda row: int(row.split(',')[0])
f2 = lambda row: int... | b3619e56d4cf988f2c785f78dd465ca9a3c883c1 | 64,865 |
import pandas as pd
import os
def already_done(output_file, combi):
""" Check if this model already has been run based on the output file. In case this script crashes (e.g. running out
of memory, this allows us to continue where we left off"""
if os.path.exists(output_file):
df = pd.read_csv(outpu... | ab080d3130cb4b350ffde58b6ab485c8d352427b | 64,866 |
import six
def time_monotonically_increases(func_or_granularity):
"""
Decorate a unittest method with this function to cause the value
of :func:`time.time` (and :func:`time.gmtime`) to monotonically
increase by one each time it is called. This ensures things like
last modified dates always increas... | 30f4896c41832737a33f5f67bc86ed763283a332 | 64,867 |
def b(s, encoding="utf-8"):
""" bytes/str/int/float type to bytes """
if isinstance(s, bytes):
return s
elif isinstance(s, (str, int ,float)):
return str(s).encode(encoding)
else:
raise TypeError(type(s)) | 8c98944fb018cb747cc79859a147e529b41dfdcb | 64,868 |
import re
def generate_vpp_config(vpp_config_path, vpp_interfaces):
"""Generate configuration content for VPP
Generate interface related configuration content for VPP. Current
configuration will be preserved, with interface related configurations
updated or inserted. The config only affects 'dpdk' se... | 98bb92459d9530eb6c38ae99e5c8f6ba37340f6a | 64,869 |
def process_results(results, check_mode):
"""
Process the list of individual (exitcode, output) `results`
according to `check_mode`, and return an overall (exitcode,
output) pair.
"""
statuses = [ status for (status,_) in results ]
critical_count = len([ s for s in statuses if s == EXIT_CRIT... | 9daf131c1b30221ead10e7732e0ef912ba745afc | 64,870 |
def conjugateGradient(*args):
"""
conjugateGradient(Matrix< double > * A, Vector< double > * b, Vector< double > * x, double const tol, int const itermax)
conjugateGradient(Matrix< float > * A, Vector< float > * b, Vector< float > * x, float const tol, int const itermax)
"""
return _spams_wrap.conju... | bd4aa58990599465088aae9a324ebe3151f94d69 | 64,871 |
def spatFT_RT(data, spherical_harmonic_weighted):
"""Perform spatial Fourier transform for real-time applications
(otherwise use `spatFT()` for more more convenience and flexibility).
Parameters
----------
data : array_like
Data to be transformed, with signals in rows and frequency bins in
... | 6942b48b50e3dc6879c9afbebd47835a2c754151 | 64,872 |
async def get_all_laps_for_driver(driver, laps):
"""Get the lap times for each lap of the race for one driver to tabulate.
Each dict entry contains lap number, race position and lap time. The API can take time to
process all of the lap time data.
Parameters
----------
`driver_id` : dict
... | 2fe52de69842ea9c7a36c752c4200b56d23d14d4 | 64,873 |
def snake_case(name):
"""takes a PascalCase input string and converts to snake_case."""
split_str = FIRST_CAP_RE.sub(r'\1_\2', name)
return ALL_CAP_RE.sub(r'\1_\2', split_str).lower() | 1af4ce05b83ba08753644bcb18e6d7503f687f8a | 64,874 |
def joint_from_driver_ctl(node):
"""
Will try find the joint given the Driver control by searching through the
mGear nodes.
TO DO:
Expand this to be more robust. Check all channels / not rely on
translate connections only.
Arguments:
node (PyNode): node to search connection... | 4fe6c9043c878407a44d64ea569b82e80d85b0e9 | 64,875 |
import heapq
def astar(
start,
neighbour,
finish_condition,
heuristic=None,
stat=None):
"""
Perform an A* search.
finish_condition = (position) -> bool
neighbour - neibhbourhood generation function
heuristic = A* heuristic function. (new position, old position) -> distance
... | d75d2595d0a4d433a54c096667e3497bb841d8d7 | 64,876 |
def load_data():
""" Load the cleaned data with latitudes, longitudes & timestamps """
travel_log = pd.read_csv("clean_data.csv")
travel_log["date"] = pd.to_datetime(travel_log["ts"])
return travel_log | c53a411c39da1b71ce2069f5b532a2cdb3b710d7 | 64,877 |
def spatial_reflection_2d_padding(x, padding=((1, 1), (1, 1)),
data_format=None):
"""
Pad the 2nd and 3rd dimensions of a 4D tensor.
:param x: Input tensor
:param padding: Shape of padding to use
:param data_format: Tensorflow vs Theano convention ('channels_last', ... | 0d6d99ae2685fd82891898c2f69dddb4ae6d9b23 | 64,878 |
def category_delete():
"""method to delete a recipe category """
if g.owner:
if request.method == "POST":
category_name = request.form['category_name']
delete_result = new_cat.category_delete(category_name, g.owner)
delete_recipes = new_recipe.delete_category_recipes(... | c4af21277e1a8601dda0cb4be69636de1a4550ec | 64,879 |
def create_zone(domain, profile, type="master", ttl=None):
"""
Create a new zone.
:param domain: Zone domain name (e.g. example.com)
:type domain: ``str``
:param profile: The profile key
:type profile: ``str``
:param type: Zone type (master / slave).
:type type: ``str``
:param ... | c01e876d3133ad21d99e83c3df5c78ba34eabebf | 64,880 |
def simulation(numTrials, numDoors = 3, toprint = False):
"""
numTrials: number of times the game will be played.
numDoors = number of doors in the game.
"""
results_switch = [] #storing the results of player that makes a switch
results_not_switch = [] #same for the player that doesnot mak... | dd5cfcb017c39383fda6875a8b3deadef9862a08 | 64,881 |
def setup_hdev_engine():
"""Setup HDevEngine by setting procedure search paths."""
source_dir = 'E:/Customer evaluation/Seagate/'
hdev_source_dir = source_dir
engine = ha.HDevEngine()
engine.set_procedure_path('C:/Program Files/MVTec/HALCON-20.11-Progress/procedures')
engine.set_procedure_path... | 9fc1fbca29970b19208dafb2cdaebedc46dac723 | 64,882 |
import xarray.plot.utils
def logpolar_plot(ds,
ax=None,
name='CONC',
perM=.95,
perm=0.0,
colorbar=True,
patch_args=None,
quantile=True,
fig_ops=None,
drop_z... | 093d573638bd5208813a0503c4a5c8e6f4607dba | 64,883 |
import sys
def create_matrix(dim):
"""Create the matix from user input.
Args:
dim: Dimension of the matrix.
Returns:
User-defined matrix as a nested list.
Raises:
Error if unsymmetric matrix is created.
"""
matr = []
for i in range(dim):
matr.append(input... | 125044d463a0ddbdc5029b556c1029427ec4d8c2 | 64,884 |
def orthogonal(shape, scale=1):
"""From Lasagne. Reference: Saxe et al., http://arxiv.org/abs/1312.6120"""
flat_shape = (shape[0], np.prod(shape[1:]))
a = np.random.normal(0.0, 1.0, flat_shape)
u, _, v = np.linalg.svd(a, full_matrices=False)
# pick the one with the correct shape
q = u if u.shape... | 1b54197d157fa36d52befb2386838a88a4d4902e | 64,885 |
def main():
"""main entrypoint"""
releases = get_releases()
render(releases)
return 0 | 30c1c1be0a418f06a07d0dc3729dca09861dbea1 | 64,886 |
def _init_hoomd_bonds(structure, ref_distance=1.0, ref_energy=1.0):
"""Harmonic bonds."""
# Identify the unique bond types before setting
bond_type_params = {}
for bond in structure.bonds:
t1, t2 = bond.atom1.type, bond.atom2.type
t1, t2 = sorted([t1, t2], key=natural_sort)
if t1... | 58ca189e825cf31358f81450c3d20eae1fa80281 | 64,887 |
import math
def _fix_lambda_path(lambda_path):
"""Replace the first value in lambda_path (+inf) with something more
reasonable. The method below matches what is done in the R/glmnent wrapper."""
if lambda_path.shape[0] > 2:
lambda_0 = math.exp(2 * math.log(lambda_path[1]) - math.log(lambda_path[2]... | b1587354156bdfeb63f5442e5ac3e171aecd3f99 | 64,888 |
def unf_fvf_Glaso_m3m3_below(rs_m3m3, t_K, gamma_oil, gamma_gas, p_MPaa):
"""
Glaso correlation(1980) for total formation volume factor below bubble point pressure
ref Generalized Pressure-Volume-Temperature Correlations, Glaso, 1980
:param rs_m3m3: gas-oil ratio in m3/m3
:param t_K: temperature in ... | 9d2b983a731e4436c2c18deb9c17744ac018ba8a | 64,889 |
def get_user_by_email(email):
"""依據 email 取得 user dict"""
if not email:
raise NotFoundException('No such user.')
db = get_db()
cursor = db.cursor()
# query user
cursor.execute("SELECT id, email, profile_id FROM users where email=? ", (email,))
db.commit()
user_record = cursor.f... | 4ef75d1f72054405fec165d4e276c075a2c29a8e | 64,890 |
def my_clip(x, a_min, a_max):
"""Unlike topi's current clip, put min and max into two stages."""
const_min = tvm.tir.const(a_min, x.dtype)
const_max = tvm.tir.const(a_max, x.dtype)
x = te.compute(x.shape, lambda *i: tvm.te.min(x(*i), const_max), name="clipA")
x = te.compute(x.shape, lambda *i: tvm.t... | 48fbf643d88451e97b46c373f3147d0dcb0e74d7 | 64,891 |
def parse_certificate(indata):
"""Parse the PEM or DER encoded X.509 certificate in indata.
Args:
indata: a string you want to be parsed as a X.509 certificate.
Can be PEM encoded or plain DER.
Returns:
Certificate class describing the actual contents of the
certificate.
"""
cert =... | 146c85e2ca28e487a06ead91e17a0b8b33286a3c | 64,892 |
import time
def session_end_pb(status, end_time_secs=None):
"""Creates a summary that contains status information for a completed
training session. Should be exported after the training session is completed.
One such summary per training session should be created. Each should have
a different run.
Arguments... | 3d9ffb7921c5b402b1141bebbc57007d19a6c14e | 64,893 |
import argparse
import sys
import os
import time
import csv
def main(argv):
"""\
Query a catlas with a sequence (read, contig, or genome), and retrieve
cDBG node IDs and MinHash signatures for the matching unitigs in the graph.
"""
p = argparse.ArgumentParser(description=main.__doc__)
p.add_a... | 95ff757644cc85f725531dc4ab5a56a8281ef156 | 64,894 |
from typing import Any
def compute_target(obj: Any, format_spec: FormatSpec) -> Target:
"""Retrieve the target formatting function given an object and format specifier.
The SimpleFormatters associated with obj are combined to find the target.
"""
cls = type(obj)
empty_dict = dict()
# build ... | b667a0d55f74fd72d307c7191949d131b500bef1 | 64,895 |
def createTeam(firstIndex, secondIndex, isRed,
first='OffensiveReflexAgent', second='DefensiveReflexAgent'):
"""
This function should return a list of two agents that will form the
team, initialized using firstIndex and secondIndex as their agent
index numbers. isRed is True if the red t... | 39094a0577b09a47827f5c34a6ba1fe78e5ce367 | 64,896 |
def make_ping():
"""Makes a ping transaction (a transaction that does nothing but make
sure the validator and transaction processor is up and responding)"""
payload = "ping".encode("utf-8")
header = transaction_pb2.TransactionHeader(
inputs=[],
outputs=[],
batcher_public_key=BATC... | d3a280382d9839b9c6e3a7be5c078ea20ab61818 | 64,897 |
def fetch_all_upids():
"""
Fetch all available genome accessions from genome table
return: A list of UP/RG ids as stored in genome
"""
# connect to db
cnx = RfamDB.connect()
# get a new buffered cursor
cursor = cnx.cursor(buffered=True)
# update is_significant field to 0
quer... | d2bc3d463b0d54b7e304f6366c6c468f8e49a12f | 64,898 |
import json
def photo_list():
"""
Retrieve Photo table items with signed URL attribute.
:return:
"""
current_user = cognito.user_info(cognito.get_token(app.current_request))
try:
photos = Photo.query(current_user['user_id'])
data = {'ok': True, 'photos': []}
[data['phot... | babf8ee7b4d5dd3241f06b1c8d8fd1515a9c10f0 | 64,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.