content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import torch
def get_bilstm_minus(batch_seq_encoder_repr, span_list, seq_lens):
"""This function gets span representation using bilstm minus
Arguments:
batch_seq_encoder_repr {list} -- batch sequence encoder representation
span_list {list} -- span list
seq_lens {list} -- sequence leng... | ca689a49a037b9dbd35305445f7f53fd07dd079c | 3,603,600 |
def create_pixel_vector(file):
"""Takes count and decimal vectors, then returns the pixel vector.
Args:
count_vector ([int]): Number of the counts of the bytes.
decimal_vector ([type]): Vector of the bytes in file.
Returns:
np.array: RGB pixel vector as np.array type.
"""
c... | 78e061782eb9e0c7b8e014e61485bebe9c02229b | 3,603,601 |
def run(align_bams, items, ref_file, assoc_files, region, out_file):
"""Run strelka2 variant calling, either paired tumor/normal or germline calling.
region can be a single region or list of multiple regions for multicore calling.
"""
call_file = "%s-raw.vcf.gz" % utils.splitext_plus(out_file)[0]
s... | 4422446ce0a68b72ce4f51e64ef0f573088019d4 | 3,603,602 |
def create_meandering_path(params):
"""
Returns a meander path based on input parameters
"""
deg_to_rad = 2 * pi / 360
radius = params.get('radius')
theta = params.get('theta')
width = params.get('trace-width')
number = params.get('bus-width') or 1
pitch = params.get('pitch') or 0... | 19dc35cf2f2836e618455287eb9de1e7b4571623 | 3,603,603 |
from hdl21.primitives import IdealCapacitor as C
def Ro(params: RoParams) -> h.Module:
""" Create a parametric oscillator """
ro = h.Module()
ro.ctrlb = h.Input(width=params.stages * params.rows, desc="Control code")
ro.osc = h.Output(width=params.stages, desc="Primary Oscillator Output")
ro.VDD,... | 6df84546a2b4ce1cf547dc29e9565135be1f4bcc | 3,603,604 |
import zipfile
def extract_csv_from_zip(filename):
"""Function to extract the csv file contained within the zip file."""
try:
with zipfile.ZipFile(filename, 'r') as zf:
contents = zf.namelist()
if len(contents) != 1:
raise zipfile.BadZipFile('There is more than ... | 9c3e32bc2d6966c9d295233e6aef6a3129f0242f | 3,603,605 |
import requests
import json
def updateData(url):
"""
Returns the symbol and the price of an asset.
Parameters
-----------
url: url used for information retrieval
Returns
-----------
tuple
(symbol name, symbol price)
"""
res = requests.get(url);
text = res... | b458dee9da7700f5c4f82a182724bba007c7a05f | 3,603,606 |
def sdc_pandas_dataframe_loc(self):
"""
Intel Scalable Dataframe Compiler User Guide
********************************************
Pandas API: pandas.DataFrame.loc
Limitations
-----------
- Loc always returns Dataframe.
- Parameter ``idx`` is supported only to be a single value, e.g. :o... | 6033e34cfa128da00af9dc1e37c8252d47242e2c | 3,603,607 |
import os
import shutil
def RetrieveData(args):
"""
This function retrieves JRC data for a given date from the
http://storage.googleapis.com/global-surface-water/downloads/ server.
Keyword arguments:
args -- A list of parameters defined in the DownloadData function.
"""
# Argument
[ou... | e88fca3f129be153661af090e7bb640e53722e29 | 3,603,608 |
from re import DEBUG
def load_watershed_seg_and_compute_dmap(seg_file_list, background_label=1):
"""
Loads a list of segmentation files and computes distance maps to the objects boundaries/background.
The segmentation file is assumed to have one integer label (2, 3, 4, ...) per object. The background has... | b541990057d6a2765e4a4670f301e23454737d3d | 3,603,609 |
def get_ast(module_path, python_version):
"""Get the AST for the code in a file.
Args:
module_path: pathlib.Path to the file containing the code.
python_version: Python version as a "MAJ.MIN" string.
Returns: The parso parse tree for the code in `module_path`.
"""
with module_path.... | b7bf0ebef52ac77f470378145938d954557f2a46 | 3,603,610 |
def formatPublisher(publisher):
"""The publisher's name. """
return publisher | 713cede34a67351d249439d83982331c60b26dcc | 3,603,611 |
import os
import sys
def get_file_path(file):
""" Get file path of file
:param file: the filename
"""
return os.path.join(os.path.dirname(sys.argv[0]), "res", file) | 015aa3a1b5d7c101c711bee23017cd926d6c9cdb | 3,603,612 |
def has_phrase(message: str, phrases: list):
""" returns true if the message contains one of the phrases
e.g. phrase = [["hey", "world"], ["hello", "world"]]
"""
result = False
for i in phrases:
# if message contains it
i = " ".join(i)
if i in message:
result = True
return result | f56fcc261e21c538f1f23b811e14ae29d92f3038 | 3,603,613 |
def _homogeneous_matrix(matrix=np.identity(3), offset=np.zeros(3)):
"""
Combine transformation matrix and translation vector for dimension d into homogeneous (d+1, d+1) transformation
matrix to be used with homogeneous coordinates.
Parameters
----------
matrix : array-like of int or float with ... | 69d9c2759eb19a6f97b44c8f40431ad20126f811 | 3,603,614 |
def einstein_relation(universe, input_time='ps', input_length='au',
length='cm', time='s'):
"""
Compute the (time dependent) diffusion coefficient using Einstein's relation.
.. math::
D\left(t\\right) = \\frac{1}{6Nt}\\sum_{i=1}^{N}\\left|\\mathbf{r}_{i}\left(t\\right)
... | 697518ef6ce29332f219fae9b8577c590059a7dc | 3,603,615 |
import warnings
def flatten_reply(reply):
"""Flatten node replies.
Convert from a list of replies in this format::
[{'a@example.com': reply},
{'b@example.com': reply}]
into this format::
{'a@example.com': reply,
'b@example.com': reply}
"""
nodes, dupes = {}, s... | 4cd32da49df926eea82acda70bf4a4cf053b9ca9 | 3,603,616 |
from joblib import dump
def knn_predictor(audio_feats):
"""
similar_song_ids, visual_df = knn_predictor(audio_features)
"""
# from sklearn.pipeline import Pipeline
# Scale the data with standard scaler
# pipeline = Pipeline([('encoder', StandardScaler()),
# ('model', ... | 6af767dd06e0d3890eef0aba98ed44f602abfeaf | 3,603,617 |
import os
def readFasta(filepath):
"""
Simple FASTA file reader
Input
-----
filepath = str, path to the fasta file to be read
Output
------
sequences = dict, keys = sequence id, values = sequence. Both keys
and values are strings.
"""
# Ensure file exist... | 2002ce29f1d7421a78e1529f6d9f09d5ffc1e124 | 3,603,618 |
def perform_dependency_parsing(doc_text: str, spacy_language_model):
"""
First phase of processing from the second part of the series.
Parses a document using SpaCy's depdendency parser, then converts the
outputs of the parser into a Pandas DataFrame using Text Extensions for Pandas.
"""
re... | ba4bcab8ef1dc126bf7e027eac4ac025b2245fde | 3,603,619 |
from typing import Optional
def substringBetween(s: str, left: str, right: str) -> Optional[str]:
"""Returns substring between two chars. Returns"""
try:
return (s.split(left))[1].split(right)[0]
except IndexError:
return None | 5cda5bc57fe1f65053dffb047bef0b34e0a39a2b | 3,603,620 |
from typing import List
from typing import Optional
from typing import Union
from typing import Tuple
def fit(
model: pyhf.pdf.Model,
data: List[float],
*,
minos: Optional[Union[str, List[str], Tuple[str, ...]]] = None,
goodness_of_fit: bool = False,
custom_fit: bool = False,
) -> FitResults:
... | 00a411a8f6fd29ae48f3d71573ea9cd616a970e5 | 3,603,621 |
def get_all_plans(db: orm.Session = Depends(get_db)):
"""Retrieves all existing plans
Args:
db (orm.Session, optional): [description]. Defaults to Depends(get_db).
Returns:
[dict]: key value pair of the following keys:
message (str): success message
data (List[plan_... | 234a112ddf4125a0ae9cca056972dab02495b2b9 | 3,603,622 |
def build(config, main_prog, startup_prog, mode):
"""
Build a program using a model and an optimizer
1. create feeds
2. create a dataloader
3. create a model
4. create fetchs
5. create an optimizer
Args:
config(dict): config
main_prog(): main program
... | 5ae652716cc92c54be419ffb8fd0bb4c12ffae19 | 3,603,623 |
def variables_from_file(filename: str, variables: _PyTree):
"""
Loads the variables of a variational state from a `.mpack` file.
Args:
filename: the file containing the variables. Assumes a .mpack
extension and adds it if missing and no file exists.
variables: An object variable... | 28c5f606a16a4af1507712056fcbae4716be8434 | 3,603,624 |
import logging
def get_campaign_data(ad_account: adaccount.AdAccount) -> {}:
"""Retrieves the campaign data of the ad account as a dictionary
Args:
ad_account: An ad account for which to retrieve the campaign data
Returns:
A dictionary with {campaign_id: {'name': 1, 'attributes': {}}} fo... | b4638222f6020a79eb0004bcde135a90b03f749c | 3,603,625 |
def label(row, structure_row, prefixes):
"""
Function to create and return a tuple of
Turtle property and Turtle object for a
given label
Parameters
----------
row : Series
row from structure_to_keep
pandas series from generator
ie, row[1] for row in iterrows()
... | 80de4a686cd07197d1c82494f81390a93022e597 | 3,603,626 |
import matplotlib.pyplot as plt
import code
import pickle
def interactive_ground_truth_main(args, tracked_results):
"""
Ground truth mode entry function.
:param args:
:param tracked_results:
:return: :raise SystemExit:
"""
acceptable_pos_chans = \
{p: list(range(len(tracked_resul... | 1e788dcb634efa47d0029dfc963133452abb8f12 | 3,603,627 |
def is_in_dimension(cloud_array):
""" check if the cloud segment is of required dimension i.e mxmxm"""
max_dim = np.amax(cloud_array, axis=0)
min_dim = np.amin(cloud_array, axis=0)
return all((max_dim-min_dim) < BOX_SIZE), (max_dim, min_dim) | 1326206647e15b0e02b44a232cf370871fdb8cd6 | 3,603,628 |
from typing import Optional
from typing import Dict
import sys
def get_record_by_id(record_id: str) -> Optional[Dict]:
"""
Retrieve record from Storage API by Record ID
:param record_id: record id
:return: record data
"""
response = _get_request(f"{STORAGE_URL}/{record_id}", SEARCH_OK_RESPONS... | 8062b45a0ce5bc56546347171a02259bc8848d44 | 3,603,629 |
def default_image_path(hass: HomeAssistant, config_entry: ConfigEntry) -> str:
"""Return value of the default image path
Returns the default path based on logic (placeholder for future code)
"""
# Return the default
return "custom_components/mail_and_packages/images/" | cf29851a3c639b5676591456ce10d86e3c9b6a20 | 3,603,630 |
def check_output(solution: str, output: str) -> bool:
"""Check if program's output is correct.
Parameters
----------
solution
Sample output taken from BOJ.
output
Output from program run.
Returns
-------
bool
True if correct, False if wrong.
"""
solution... | 66d35952d892842bd1b47329bfa7b77e0a878a51 | 3,603,631 |
def get_ida_bg_color():
"""
Get the background color of an IDA disassembly view.
-----------------------------------------------------------------------
The necessity of this function is pretty silly. I would like lighthouse
to be color-aware of the user's IDA theme such that it selects reasonable... | 4249dc51d91bc960eedd76b639258e06ef6a64f0 | 3,603,632 |
import os
import pandas
def get_to_publish_csv():
"""
Returns
-------
pandas.DataFrame
"""
this_dir = os.path.dirname(os.path.realpath(__file__))
path_to_to_publish_csv = os.path.join(this_dir, "to_publish.csv")
dtypes = {"publishable": object,
"license_files": str,
... | df1201a32faaffd8dc715c727461e3bea7d4fda7 | 3,603,633 |
def obtener_cantidad_vuelos_pais_en_ciudad_en_rango_anios(PaisDestino, CiudadDestino, AnioInicio, AnioFin): #OK
"""
Dado un pais, una ciudad y un rango de años obtiene la cantidad total de vuelos que llegan a esa ciudad durante esos años
Dado un pais, una ciudad y un rango de años obtiene la cantidad total ... | 38d12f17a842ef431327655a0068acfcf71c4a64 | 3,603,634 |
from typing import Sequence
def bit_array_to_int(bit_array: Sequence[int]) -> int:
"""
Converts a bit array into an integer where the right-most bit is least significant.
:param bit_array: an array of bits with right-most bit considered least significant.
:return: the integer corresponding to the bit... | d902a8e3db7b65ad348ef86cbfac371361aedd58 | 3,603,635 |
def download_trajectory_data_rep_site():
"""Download REPEATED SITE probe displacement data from Alyx
Downloads the most up-to-date data from Alyx for all repeated site
recordings, including their channel positions, and the orthogonal points
of each channel from the planned trajectory.
Sa... | e83765f86711fa74eb06bdfc97baff10df440254 | 3,603,636 |
def clip_args(func, arg1, arg2, bounds=(0., 1.)):
"""
Clip the arguments to bounds
Return the results of the function where the clipped arguments have been used.
Arguments below the lower bound are set to the lower bound and the arguments
above the upper bound are set to the upper bound.
Param... | 249b5fed30fd050da570ef5276f826c071457935 | 3,603,637 |
def distance_p2p(points_src, normals_src, points_tgt, normals_tgt):
"""Computes minimal distances of each point in points_src to points_tgt.
Arguments:
----------
points_src (numpy array): source points
normals_src (numpy array): source normals
points_tgt (numpy array): target point... | 31c2bc839e1eb7b8f16b946a81fe3cc768390574 | 3,603,638 |
from typing import VT
from typing import List
def match_pivot(g: BaseGraph[VT,ET]) -> List[MatchPivotType[VT]]:
"""Does the same as :func:`match_pivot_parallel` but with ``num=1``."""
return match_pivot_parallel(g, num=1, check_edge_types=True) | 051a9af33ac81844a23cb2c56cb14eccfd13e6c2 | 3,603,639 |
import math
def euclidean_distance(p1, p2):
"""Calculate the euclidean distance of two 2D points.
>>> euclidean_distance({'x': 0, 'y': 0}, {'x': 0, 'y': 3})
3.0
>>> euclidean_distance({'x': 0, 'y': 0}, {'x': 0, 'y': -3})
3.0
>>> euclidean_distance({'x': 0, 'y': 0}, {'x': 3, 'y': 4})
5.0
... | 8cdc0e0534b2ed9272832fc0f977b9aa0e594c65 | 3,603,640 |
def run_performance_test(ops, inputs, run_backward=True,
dtype='float32', ctx=mx.cpu(), profiler='native',
warmup=10, runs=50):
"""Run operator benchmark for given operator or list of operators, ops, with the given inputs.
Returns benchmark results as a list of... | c087916947fe5e3e32dfa1e25c776e85af9f9378 | 3,603,641 |
def increment(name, num_shards, delta=1, do_transaction=True, use_memcache=True):
"""
Increment the value for a given sharded counter.
This will create the counter if it does not exist.
Args:
name: The name of the counter.
num_shards: the number of shards in the counter
"""
retu... | ff64fe730c641e5fb606978ccb144f7ab62eef5f | 3,603,642 |
def parse_date_string(date_string):
"""
Parse date string into datetmie object.
"""
if not date_string.isdigit():
raise ex.ExcalValueError("Input date must be numbers")
length = len(date_string)
convert_string = None
if 0 < length <= 2:
year = dt.date.today().strftime("%Y")... | 1f198530c430df2f8d59c02a0e61bc1fb9789cbc | 3,603,643 |
def conflict(soup):
"""
Find the conflict notes in footnote tag
"""
conflict = None
try:
conflict = extract_node_text(soup, "fn", attr = "fn-type", value = "conflict")
except KeyError:
return None
return conflict | 962793ea5fb255264ae880407e55369d2827ae3f | 3,603,644 |
import warnings
def load_fits_spectrum(fname, ext=None, iraf_obj=None):
"""
Flexible inference of spectral data from FITS files.
The function allows to read a large number of spectral formats including
FITS tables, multi extension FITS ImageHDUs, or IRAF like arrays
Parameters
----------
... | 5fd13c8f1e92c8996d59e58cfc12020e6c87e8ac | 3,603,645 |
import re
def read_raw_dictfile(filename, language):
"""Read from unformatted dictfile: eliminate extra spaces and parens,
insert a tab. Return a list of word,pron pairs."""
S = []
with open(filename) as f:
for line in f:
words = re.split(r"\s+", line.rstrip())
S.appen... | a8c95c87551119a89bd2c686be35b3a3aba3f567 | 3,603,646 |
def make_grid_prw(grid_pwx, data_prw_obs, data_rsnstcsnorm_obs):
"""Grid rsnstcsnorm based on prw grid."""
gridded_rsnstcsnorm_obs = np.zeros(len(grid_pwx), dtype=float)
for jjj, bincenter in enumerate(grid_pwx):
index_obs = np.where((data_prw_obs >= bincenter - 1.0) &
... | 8166cde8037826f29cd6b60c1d333b6e51da6864 | 3,603,647 |
def backup_l3_attribute_map():
"""Return a backup of the original l3 attribute map."""
return dict((res, attrs.copy()) for
(res, attrs) in l3.RESOURCE_ATTRIBUTE_MAP.iteritems()) | f5649e7cc52404051bd8df15d75cf32496d560ad | 3,603,648 |
import zlib
def zlib_handler(method):
"""
Prepare hash method and seed depending on CRC32/Adler32.
:param method: "crc32" or "adler32".
:type method: str
"""
hashfunc = zlib.crc32 if method == "crc32" else zlib.adler32
seed = 0 if method == "crc32" else 1
return hashfunc, seed | 46e9d91e5ebe92f3b5b24f138ae693368128ce09 | 3,603,649 |
def hex_dump(string):
"""Dumps data as hexstrings"""
return ' '.join(["%0.2X" % ord(x) for x in string]) | 7c0286c57387c5b8f6a79e2a9350eb54e480465a | 3,603,650 |
def _nova_error_message(msg_type, message, status_code, request):
"""
Set the response code on the request, and return a JSON blob representing
a Nova error body, in the format Nova returns error messages.
:param str msg_type: What type of error this is - something like
"badRequest" or "itemNot... | 781b57a8b87316a49529e6b03fd19d4d391ac4c7 | 3,603,651 |
def get_operands_dtype(operands):
"""
Return the data type name of the tensors.
"""
dtype = operands[0].dtype
if not all(operand.dtype == dtype for operand in operands):
dtypes = set(operand.dtype for operand in operands)
raise ValueError(f"All tensors in the network must have the sa... | cda67513ea8ca9f7ea663d232a5358fad8f8597d | 3,603,652 |
def bmpToGDS(bmp, width, height, layer, datatype, black=0):
"""
Args:
bmp: A string refering to the file location of the BMP file
width: Physical Width (X) of the bmp image specified in micrometers
height: Physical Height (Y) of the bmp image
layer: Layer the bmp file should be ... | 86e90b6ece1e7e648ea24f570c0f901e570d3e61 | 3,603,653 |
def get_j(xi, j=0):
"""
得到小数定标标准化的j
"""
if xi / float(10 ^ j) <= 1:
return j
else:
return get_j(xi, j+1) | 975a74d70ceeba80debfadf171f6c32316cd7d7b | 3,603,654 |
def get_shortest_path_waypoints_old(planner, origin, destination):
"""Return a list of waypoints along a shortest-path
Uses A* planner to find the shortest path and returns a list of waypoints.
Useful for trajectory planning and control or for drawing the waypoints.
Args:
planner: carla.macad_... | bb6cfdeb139c6c10cbd4fd8c4d0dc31083ecc2d6 | 3,603,655 |
def delete_container(client, resource_group_name, name, **kwargs):
"""Delete a container group. """
return client.delete(resource_group_name, name) | d69c3fbd89ce684942af4980ca9931908b12db6a | 3,603,656 |
def translate_x(image, pixels):
"""Equivalent of PIL Translate in X dimension."""
image = tfa.image.translate(image, tf.constant([-pixels, 0], dtype=tf.float32))
return image | 691444a857aa0b0103fd9aee8fa3735f04cfe605 | 3,603,657 |
def clean_input():
"""
Make sure we're not getting bad data from the front end,
format data to be machine readable
"""
if empty(request.form.get('password', '')):
abort(400)
if empty(request.form.get('ttl', '')):
abort(400)
time_period = request.form['ttl'].lower()
if ti... | f6bf819d3b4bf5ea94c8346edd0719b6dfb11336 | 3,603,658 |
def nullspace_torques(mass_matrix, nullspace_matrix, initial_joint, joint_pos, joint_vel, joint_kp=10):
"""
For a robot with redundant DOF(s), a nullspace exists which is orthogonal to the remainder of the controllable
subspace of the robot's joints. Therefore, an additional secondary objective that does no... | c18a6deac63d835b5392af84c0becddcaf322b49 | 3,603,659 |
def general_net(feat_model, identity_model, img_shape):
"""Returns a keras Model for training
with classification and metric learning losses
Args:
feat_model: keras Model for feature extracting
identity_model: keras Model for classification
img_shape: tuple specifying (h,w)
Retu... | 88c029800347daf45c649be31a74525ea5390d53 | 3,603,660 |
def aga_contract_graph(adata, min_group_size=0.01, max_n_contractions=1000, copy=False):
"""Contract the abstracted graph.
"""
adata = adata.copy() if copy else adata
if 'aga_adjacency_tree_confidence' not in adata.uns: raise ValueError('run tool aga first!')
min_group_size = min_group_size if min_g... | 93db3555722b8af7be0ac2764462d8440f543841 | 3,603,661 |
def put_method(method):
"""Annotation for a callable method specifying that it is a PUT method."""
return MethodStub(Method.Put, method) | afac5a2ed79183054381c3179db2edca1fc7a2c8 | 3,603,662 |
from typing import Union
def get_difference_of_maxs(uni_ts: Union[pd.Series, np.ndarray]) -> np.float64:
"""
:return: The absolute difference between the maximums of the first and the second halves of a
given univariate time series.
"""
mid = int(len(uni_ts) / 2)
return np.abs(get_max... | c8e3c973ee25144a139c430ef07ea0d0d8255645 | 3,603,663 |
def generateMap(height, width):
"""
Generates the obstacle map as input for path planning
using Half Plane equations (with clearance).
Parameters:
height: int
Height of the obstacle map
width: int
Width of the obstacle map
... | 81d70f86f41f678eb3a97549ea4de345f535e8f2 | 3,603,664 |
import re
def export_filters(filename='filters.json', base_url=DEFAULT_BASE_URL, *, overwrite_file=True):
"""Saves filters to file in JSON format.
Args:
filename (str): Full path or path relavtive to current working directory, in addition to the name of the file. Default is "filters.json".
ba... | 611acec06867d2ecf873295cda905bff218086d8 | 3,603,665 |
import json
def transformation():
"""
Example:
{
"sentence_tokens": [
"show",
"me",
"the",
"cheapest",
"round",
"trips",
"from",
"dallas",
"to",
"baltimore"
]
}
... | c25b6912c3b0eab593ab0122a4f0098bc6f37e29 | 3,603,666 |
def TimeEvolution(time, hamiltonian):
"""
Time evolve a hamiltonian
Converts the Hamiltonian to an instance of the pyQuil Pauliterms and returns the time evolution
operator. This method mirrors the ProjectQ TimeEvolution interface.
:param [float, int] time: time to evolve
:param QubitOperator ... | 1dcb22e524a54276676f31c4c5696c64cecf4176 | 3,603,667 |
from typing import Any
from typing import Optional
from typing import Iterator
from typing import Tuple
from typing import Sequence
def distribute(
df: Any,
batch_size: Optional[int] = None,
**kwargs: Any
) -> Iterator[Tuple[Sequence[HOST_T], Any, Optional[Sequence[Text]]]]:
"""Fetch SNMP ... | 1a0b44545e0930b79972faaafe8ce86b0b252168 | 3,603,668 |
def train(train_loader, model, criterion, optimizer, epoch,current_iteration,rewire_period,DeepR_temperature,threshold):
"""Train for one epoch on the training set"""
batch_time = AverageMeter()
losses = AverageMeter()
data_time = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
... | 29334828e059ea63b27e6b5f435751db0a8f5042 | 3,603,669 |
def get_feature(internel_layer, layers, filters, batch_norm=False):
"""Get VGG feature body as stacks of convoltions."""
for i, num in enumerate(layers):
for j in range(num):
internel_layer = sym.conv2d(
data=internel_layer, kernel_size=(3, 3), padding=(1, 1),
... | 37670dd6204dc96531b645f68f25f67f5ce3f2dc | 3,603,670 |
def unmatched_places(w, open, close):
"""
Given a word ``w`` and two letters ``open`` and
``close`` to be treated as opening and closing
parentheses (respectively), return a pair ``(xs, ys)``
that encodes the positions of the unmatched
parentheses after the standard parenthesis matching
proc... | cfd2a50c50cecc6fcc08d4fd95df56ad503fa4d2 | 3,603,671 |
from typing import Callable
def apply(grid: Grid, func: Callable[[Point], Point]) -> Grid:
"""Apply a pointwise function to all points of a grid
Args:
grid (Grid): Grid to apply function to
func (callable): Pointwise transformation function
Returns:
Grid: Transformed grid
"""... | 74e940d4fa1694a4a2dbd01bca8fa0d138f0ba1e | 3,603,672 |
def _clip(n: float) -> float:
"""
Helper function to emulate numpy.clip for the specific
use case of preventing math domain errors on the
acos function by "clipping" values that are > abs(1).
e.g. _clip(1.001) == 1
_clip(-1.5) == -1
_clip(0.80) == 0.80
"""
sign = n / abs(n... | 78308e70a405b3b3d94827c00705e8842b242cde | 3,603,673 |
def proper_permutation(a):
"""
Computes the permutation matrix `P` such that all [n:t,n:t] submatrices of `P a P` are invertible.
Parameters
----------
a : numpy.ndarray
A symmetric binary matrix with ones along the diagonal.
Returns
-------
numpy.ndarray
"""
t = len(a)... | 1d4050a473aec25c28532e03b8fdcfbc03c019e9 | 3,603,674 |
from scipy import interpolate
def cmap_whitezero(cmap,N,Nwhites,pos):
"""Whites out middle index of a colormap from the continuous colormap cmap.
cmap: colormap instance, eg. cm.jet.
N: Number of colors.
Nwhites: Number of whites
pos: Position for white bar; if -1, will place in middle
... | 4e8de7fed03fe0834ccff4d28364f8b37f222b51 | 3,603,675 |
import time
import json
def get_response_with_refreshed_jwt_cookies(request, user):
"""
Generates the response and resets the JWT related cookies in the response for the given user.
"""
cookie_settings = standard_cookie_settings(request)
response = JsonResponse({})
_create_and_set_jwt_cookies(... | f990ce589b494f0e43cceabcfa26aa19a0e920be | 3,603,676 |
def _batch_stitch(features, mean_length=4.0, stddev=2.0):
"""Stitches a batch of single-step data to a batch of multi-step data."""
batch_size = common_layers.shape_list(features['task'])[0]
num_sequences = tf.maximum(
tf.to_int32(tf.to_float(batch_size) / mean_length), 1)
lengths = tf.random.truncated_no... | ffb1f4e3eb04e7223e32c5436bae3fe5478e74db | 3,603,677 |
def bay_name_patch_data(name=data_utils.rand_name('bay')):
"""Generates random baymodel patch data
:param name: name to replace in patch
:returns: BayPatchCollection with generated data
"""
data = [{
"path": "/name",
"value": name,
"op": "replace"
}]
return baypatch... | eb30368a933e32bd0fa37223be9bdece2a6e4ab3 | 3,603,678 |
import json
def generate_dataset_jtable(request, option):
"""
Generate the jtable data for rendering in the list template.
:param request: The request for this jtable.
:type request: :class:`django.http.HttpRequest`
:param option: Action to take.
:type option: str of either 'jtlist', 'jtdelete... | e2e5302f1c64970d6b0271da436dae65a9e29125 | 3,603,679 |
def make_field(obj_type):
"""Create a Field subclass out of some obj_type.
This works for any obj_type that subclasses OODict or FieldsSequence.
"""
if issubclass(obj_type, OODict):
class OODictField(ObjectField):
"""Field subtype that is stored as a dict in the backend and
... | 3ae47d9c61c7b099afc24273fe7eaaf81451328b | 3,603,680 |
import torch
def get_dataloader_training(paths, training_params, batch_size, device=None, uuid=None, caching_mode=None):
"""
Args:
paths (dict):
I/O paths
training_params (dict):
conatains various training parameters
batch_size (int)
... | 175428e435ee1afd49f1f725014002406b58dd98 | 3,603,681 |
import os
def skip_files(root):
"""Get a list of filenames to skip.
:param root: Root directory of the package template
:type root: str
"""
# We can use .gitattributes as a quick starting point
gitattributes = os.path.join(root, ".gitattributes")
fnames = []
with open(gitattributes, "... | 22394d690040d1e70a18aea85a99b11ae8ff540d | 3,603,682 |
import shutil
def hpc_batch_detect() -> str | None:
"""
Assuming a known job batching system, we will create a template for the user
to verify and then the user will run.
"""
batcher = None
if shutil.which("qsub"):
batcher = "qsub"
return batcher | 99c3b6d7dc9fe332b7cf027d53ca172c1776890f | 3,603,683 |
import sys
import ast
def execute_patched_func(original_func, execute_inspections_func, *args, **kwargs):
"""
Detects whether the function call comes directly from user code and decides whether to execute the original
function or the patched variant.
"""
# Performance aspects: https://gist.github.... | e45b953efc5faaf8350845fc43d6477acf9999a1 | 3,603,684 |
def HLRBRep_LineTool_IntervalContinuity(*args):
"""
:param C:
:type C: gp_Lin
:rtype: GeomAbs_Shape
"""
return _HLRBRep.HLRBRep_LineTool_IntervalContinuity(*args) | 55ce7570c2a7ef1844e4c46f0866f6a3f381557f | 3,603,685 |
def reproject_modis_wgs84(dataset, method = 2):
"""
A sample function to reproject and resample a GDAL dataset from within
Python. The idea here is to reproject from one system to another, as well
as to change the pixel size. The procedure is slightly long-winded, but
goes like this:
1. Set up ... | cd7b8569204e154040c7426fafeef74a4031fca6 | 3,603,686 |
def collaborationgroup_leave(request, pk):
"""
Leave a group.
Todo: show params on OPTIONS call.
Todo: permissions
:param pk pk of the collaboration group
"""
obj = CollaborationGroup.objects.filter(id=pk)
if not obj:
return Response({"error": "CollaborationGroup not found!", ... | ace9bfd22852ffa1ef9d95c9cad097bdedd7bdd3 | 3,603,687 |
def etminan(C, Cpi, F2x=3.71):
"""Calculate the radiative forcing from CO2, CH4 and N2O.
This function uses the updated formulas of Etminan et al. (2016),
including the overlaps between CO2, methane and nitrous oxide.
Reference: Etminan et al, 2016, JGR, doi: 10.1002/2016GL071930
Inputs:
... | e867ea6b5c715c6b1dbe6e4ac091c587798dedcb | 3,603,688 |
def validate_and_normalize_address(address):
"""
Return normalized address if the address is a valid ip or hostname.
Otherwise raise ValueError Exception. The hostname is
normalized to all lower case. IPv6-addresses are converted to
lowercase and fully expanded.
RFC1123 2.1 Host Names and Nubme... | 55f4baa68adff62831a6ae56e3ca734fb88c3b9e | 3,603,689 |
import sys
import os
def mainopt_trymac(i):
"""*<format> [<pronunciation>]
Convert phonemes from <format> into Mac and try it using the Mac OS 'say' command"""
format = sys.argv[i + 1]
if not format in lexFormats:
return (
"No such format "
+ repr(format)
+ " (u... | 58769c6963f7a49f546d56b7b3fb71ef8cbd5846 | 3,603,690 |
import torch
import io
def create_torch_cnn():
"""Create a torch CNN for testing purposes
Jit traces the torch Module for storage in RedisAI
"""
n = Net()
producer_forward_input = torch.ones(1, 1, 3, 3)
# Trace a module (implicitly traces `forward`) and construct a
# `ScriptModule` with ... | 39651a028f00e10f0fa4e5f5ca6c9c7707f63e8f | 3,603,691 |
import os
import json
def load_json(base_path):
"""
Load processing log
Args:
base_path (str): base directory
Returns:
"""
# Get file path
json_file = os.path.join(base_path, 'processing_log.json')
# Read file
with open(json_file, 'r') as f:
df = json.load(f)
... | 2821b70cfafe6fc352695eeffd63248bee350605 | 3,603,692 |
def cradmin_create_archiveimage_tag(context, archiveimage, imagetype, css_class='', fallbackoptions=None):
"""
Creates an ``<img>`` tag from the given cradmin archiveimage.
The URL is generated using
:meth:`.cradmin_transform_image_using_imagetype`.
The alt-tag is generated from ``archiveimage.scr... | 868c8aa0070977f98d03f5afbfa127655c913fde | 3,603,693 |
def extract_key(msk: MasterSecretKey, identity: bytes) -> SecretKey:
"""Extract secret key for an identity.
Key extraction is done by first mapping the identity into G_1 using H_1 and then
raising this group element to the secret exponent α, i.e, H_1(identity)^α.
"""
return SecretKey(map_identity(... | 837a09cb0602634fd6f111141a6c1eb680df6b6d | 3,603,694 |
from typing import List
def is_cmd_path_installed() -> bool:
"""Detects if the path is already installed."""
all_paths: List[str] = win32_path_manip.read_user_path()
return BIN_DIR in all_paths | cfcd288e650face161fcedc63545dbdd5c692f6f | 3,603,695 |
def getDefaultFetcher():
"""Return the default fetcher instance
if no fetcher has been set, it will create a default fetcher.
@return: the default fetcher
@rtype: HTTPFetcher
"""
global _default_fetcher
if _default_fetcher is None:
setDefaultFetcher(createHTTPFetcher())
return... | 03ad0606294103336e1653f499e041f560f63f7b | 3,603,696 |
def get_choices_from(raw_type_annotation: RawTypeAnnotation) -> Choices:
"""
Helper function to extract allowed values from a literal/enum like type.
Use case: Forward as `choices=...` argument to argparse.
"""
type_annotation = TypeAnnotation(raw_type_annotation)
while type_annotation.get_und... | 3c088ed8908314e47bfc1273262beb7ccf47dd00 | 3,603,697 |
def residuals(p, y, x):
"""Residual for calculating rate coefficient."""
A, b, E = p
err = y - calc_rate_coeff(p, x)
return err | 35436c6a2b903cc1b5dc899ee1119f15307debbd | 3,603,698 |
import enum
def dictToMongoStorable(data, logger=None, verbose=True, dollarEscape="__mongostorabledollar__", normalizeKeys=True, normalizeEnums=True, normalizeBigInts=True, convertTuples=True, convertSets=True):
"""
This function convert all set() in list()
and all "." in keys will be replaced by ... | 48b5aebd94940316bab2867fc5e7b58abea95ec6 | 3,603,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.