content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def clif_deps_to_cclibs(labels):
"""Gets the cc_library name for each of label as a list."""
return [_clif_to_lib(name, PYCLIF_CC_LIB_SUFFIX) for name in labels] | aeb85cd716282099b9efc36efd6dcd6cd49413ba | 3,635,763 |
def _get_cache_filename(year=2020):
"""Returns the `Path` to the COBS data file for a given year."""
return CACHEDIR / f'cobs{year}.feather' | 70f989165b6e3e10604a468d06f5f565e499ab28 | 3,635,764 |
def get_critical_hours_end(critical_ffmc: float, solar_noon_ffmc: float, critical_hour_start: float):
""" Returns the hour of day (on 24H clock) at which the hourly FFMC drops below
the threshold of critical_ffmc.
Should only be called if critical_hour_start is not None.
"""
if critical_hour_start i... | f50bfca5769bbe36d597ad1ff42d73c8aa4b4bae | 3,635,765 |
def dolpc(x, model_order=8):
"""
Function dolpc computes the autoregressive model from spectral magnitude samples.
@param x: Critical band filters.
@param model_order: Order of model. Default is 8.
@returns: Autoregressive model from spectral magnitude samples.
"""
num_bands, num_frames... | 81e008bd00fd5f8efa3f55df1e310eb52727aa85 | 3,635,766 |
def filter_domains(domains, by="evalue", coverage_pct=0.5, tolerance_pct=0.1):
"""Filter overlapping Domain objects and test adjcency rules.
Adjacency rules are tested again here, in case they are missed within overlap
groups. For example, the NRPS-para261 domain is not always entirely contained by
a c... | b980c69bf3309628cbaf3d91c59b77b33b3be4e2 | 3,635,767 |
def _replicate_and_maybe_restore_latest_checkpoint(
unreplicated_optimizer_state,
unreplicated_params,
unreplicated_batch_stats,
unreplicated_training_metrics_grabber,
train_dir,
use_deprecated_checkpointing):
"""Restore from the latest checkpoint, if it exists."""
uninitialized_global_step ... | a49b0b74d4a1fdd6ed8cae715249ab8febd7c352 | 3,635,768 |
def minkowskiSum(obj1, obj2):
"""
Minkowski sum of two polygon objects
Args:
obj1, obj2: (n,2) array of corner point
Return:
poly: (n,2) array of minkowski polygon vertices centered at (0, 0)
bound: [min_x, min_y] max/min signed distances from vertices
... | 7000676601c40c7e32961f26a12c2c79c2c592bd | 3,635,769 |
def fix_dataset_dims(d):
"""Given one of the dataset files given by the organizers, fix its
dimensions so its easier to concatenate and use with xr.open_mfdataset.
Arguments:
d. xr.Dataset. The dataset you get when you open one of the provided files.
"""
month = int(d.forecast_time[0].dt.mon... | 323aa2c89cfcf124e06d9efa97c4d61775680bdf | 3,635,771 |
def prettyprint_xml(element):
"""
A rough and dirty way to prettyprint an Element with indention.
:param lxml.etree._Element element: The Element or ElementTree to format.
:rtype: str
:returns: A prettyprinted representation of the element.
"""
return etree.tostring(element, pretty_print=T... | 58749d409c3735b021045ba614888858d12b6651 | 3,635,772 |
def decorator(IterativeReconAlg, name=None, docstring=None):
"""
Calls run_main_iter when parameters are given to it.
:param IterativeReconAlg: obj, class
instance of IterativeReconAlg
:param name: str
for name of func
:param docstring: str
other documentation that may need ... | 0c7224ea3d58c367d8b7519f7f8ba4d68c00076e | 3,635,774 |
from typing import Any
import json
def read_json_file(filepath: str) -> Any:
"""Read JSON from a file.
Args:
filepath (str): Path to file
Returns:
Any: The parsed JSON
"""
with open(filepath, 'r') as json_file:
data = json.load(json_file)
return data | b4b492aa796b55b81dc8f6a8b91713fe1f00ecd4 | 3,635,775 |
def penalized_loss(loss_func,
model,
inputs,
targets,
output_regularization,
l2_regularization = 0.0,
use_dnn = False):
"""Computes penalized loss with L2 regularization and output penalty.
Args:
l... | c1e8403b274cef6d37ed419b8ba7ed2dc0e30845 | 3,635,776 |
def tx_deserialize( tx_hex ):
"""
Given a serialized transaction, return its inputs, outputs, locktime, and version
Each input will have:
* txid: string
* vout: int
* [optional] sequence: int
* [optional] scriptSig: {"asm": ..., "hex": ...}
Each output will have:
* value: Dec... | dfd97a8493430ea6600d8c45c0c0b5ea81cc803e | 3,635,778 |
import time
def wait_for_result(polling_function, polling_config):
"""
wait_for_result will periodically run `polling_function`
using the parameters described in `polling_config` and return the
output of the polling function.
Args:
polling_config (PollingConfig): The p... | 663f23b3134dabcf3cc3c2f72db33d09ca480555 | 3,635,779 |
from typing import Optional
def create_random_bytes(
min_length: Optional[int] = None, max_length: Optional[int] = None, lower_case: bool = False
) -> bytes:
"""Generates a random bytes given the constraints"""
if min_length is None:
min_length = 0
if max_length is None:
max_length = m... | 1e71debc3a495d2291a7989fe92c0f3712556baa | 3,635,781 |
def calculate_v_correction(df, photopic_response):
"""
Closure to calculate the e correction factor from a dataframe
"""
# Get angles from column names first
try:
angles = df.drop(["0_deg", "wavelength"], axis=1).columns.to_numpy(float)
except:
angles = df.drop(["wavelength"], a... | f9768d204813a89df6f246864ed669c8b8b305cf | 3,635,782 |
def wrap_statement(token_str):
"""
Wraps a long string of space-separated tokens
or a list of tokens.
"""
if isinstance(token_str, list):
token_str = ' '.join(token_str)
wrap_ind = '\n' + INDENT * 4
return wrap_ind.join(gtextWrapper.wrap(token_str)) | 447b74a2d33d6a053791c35112d43e356194f575 | 3,635,783 |
def mlas_packb(B, K, N, transb_size, transb=True):
"""Pre-pack B matrix if it is constant for mlas_matmul, C = A * B^T.
It only supports float32 datatype.
Parameters
----------
B : tvm.te.Tensor
The second input of mlas_matmul.
K : int
The number of colums of A.
N : int
... | c232e0f00b008c044c9843db90058425f6050cd3 | 3,635,784 |
def file_version_summary(list_of_files):
"""
Given the result of list_file_versions, returns a list
of all file versions, with "+" for upload and "-" for
hide, looking like this:
['+ photos/a.jpg', '- photos/b.jpg', '+ photos/c.jpg']
"""
return [('+ ' if (f['action'] == 'upload') else '-... | 8ca8e75c3395ea13c6db54149b12e62f07aefc13 | 3,635,785 |
def make_players(data, what_to_replace_null_data_with):
"""
1. feature selection
2. replacing null values
:param data:
:param what_to_replace_null_data_with: accepted values: "1", "mean", "median"
:return: players
"""
players = data[["Overall", "Potential", "Position", "Skill Moves", "C... | 081e563f475e7e05caf3761954646b8a35ec8e54 | 3,635,786 |
def pwm_to_duty_cycle(pulsewidth_micros, pwm_params):
"""Converts a pwm signal (measured in microseconds)
to a corresponding duty cycle on the gpio pwm pin
Parameters
----------
pulsewidth_micros : float
Width of the pwm signal in microseconds
pwm_params : PWMParams
PWMParams ob... | e627b84bf7e01f3d4dcb98ec94271cd34249fb23 | 3,635,787 |
import json
def update_plugin_packages_in_kv(rid, runit):
"""Update the plugin packages for this unit in the kv store.
It returns a tuple of 'install_packages' and 'purge_packages' that are
different from that which was previously stored.
:param rid: The relation_id of the unit
:type rid: str
... | 66d342e014f738e178629973b81c7a5c8d68dd41 | 3,635,788 |
def get_a_record(dns_name, zone_name):
"""Lookup an 'A' record with the supplied name.
Args:
dns_name: DNS nname of the resource.
zone_name: Cloud DNS managed zone name.
Returns:
The first A record for the DNS resource. None if not found
"""
rr_set_response = api.CLIENTS.dn... | c982fdb603d1c6accb7c205d64fc57a783559979 | 3,635,789 |
def get_file_obj(fname, mode='r', encoding=None):
"""
Light wrapper to handle strings and let files (anything else) pass through.
It also handle '.gz' files.
Parameters
----------
fname: string or file-like object
File to open / forward
mode: string
Argument passed to the '... | c8a24ef76869be8f743a7ddb7e66bf6ea4f0edf1 | 3,635,790 |
def decode(codes, alphabet):
""" Converts one-hot encodings to string
Parameters
----------
code : torch.Tensor
One-hot encodings.
alphabet : Alphabet
Matches one-hot encodings to letters.
Returns
-------
genes : list of Tensor
List of proteins
others : list... | 79ff69034293a8fb7d005ec89c98ae5e7535e487 | 3,635,791 |
import logging
def GetSuites(milo_client, waterfall, builder_name, build_number):
"""Gets a list of suites ids for a given build from Milo.
Args:
milo_client: MiloClient object.
waterfall: Buildbot waterfall.
builder_name: Buildbot builder name.
build_number: Buidlbot build number.
Returns:
... | 266ef9d5042d247b01d0f0819d8222104a591960 | 3,635,792 |
import re
def getNormform_space(synonym):
"""
"""
return re.sub("[^a-z0-9]", " ", synonym.lower()) | 5e03a89ca25cb5b4ae9a76ef9fb44c213a043cbd | 3,635,793 |
def electrolyte_conductivity_PeymanMPM(c_e, T):
"""
Conductivity of LiPF6 in EC:DMC as a function of ion concentration. The original
data is from [1]. The fit is from Dualfoil [2].
References
----------
.. [1] C Capiglia et al. 7Li and 19F diffusion coefficients and thermal
properties of no... | 61c5a0f8a8b514607d6829fabd784ab620e4bdf8 | 3,635,794 |
import re
def rename_leaves_taxids(tree):
"""
Rename the leaf nodes with just the NCBI taxonomy ID if we have it
:param tree: the tree to rename
:return: the tree with renamed leaves
"""
for n in tree.get_leaves():
m = re.search(r'\[(\d+)\]', n.name)
if m:
n.name =... | 26b55177b1e9372ff58f3a79ab703c639661551c | 3,635,795 |
def hshift(x, shifts=0):
"""shift batch of images horizontally"""
return paddle.roll(x, int(shifts*x.shape[3]), axis=3) | 176336fb7953197697b123041183798bf445b43f | 3,635,796 |
def getFirstCatalogKeyPath(cataloglist, keypath, default = None):
"""
Get the value of the keypath in the first catalog containing it.
"""
for name in cataloglist:
catalog = getCatalog(name)
if catalog is not None:
value = valueForKeyPath(catalog, keypath)
if valu... | 9e5a999e3bf9ae2e24c56c4e4fc1d6a8bf3e0095 | 3,635,797 |
def HT_DCPHASE(ds, count):
"""Hilbert Transform - Dominant Cycle Phase"""
return call_talib_with_ds(ds, count, talib.HT_DCPHASE) | bb1f98e8adc8f90f2f35418b7598bec574f014ae | 3,635,799 |
def ScreenToMouse(pt):
"""Convert a value in screen coordinates to mouse coordinates.
Mouse coordinates are specified as a percentage of screen dimensions,
normalized to 16 bits. 0 represents the far left/top of the screen,
65535 represents the far right/bottom. This function assumes that
the size of the s... | 6b25230f87d581b9cb91bca029b68f004f413fbf | 3,635,800 |
def triadic_closure_algorithm():
"""
How to do triadic closure.
"""
ans = """
I would suggest the following strategy:
1. Pick a node
1. For every pair of neighbors:
1. If neighbors are not connected,
then this is a potential triangle to close.
This strategy gives you potential triadic closures... | 2ee1ca511975f6f7d4ef0a2f55c95f70bc3a56da | 3,635,801 |
def parsed_args_gen():
"""Returns a function which creates an emulated parsed_args from kwargs
"""
def generator(**kwargs):
pdict = {}
for k, v in kwargs.items():
pdict[k] = v
return AttrDict(pdict)
return generator | 27cd56860ed4e1eca736b91b9a476b554df68512 | 3,635,803 |
def floordiv(a, b):
"""Compute the floordiv of two expressions.
Parameters
----------
a : PrimExpr
The left hand operand
b : PrimExpr
The right hand operand
Returns
-------
res : PrimExpr
The result expression.
"""
return _ffi_api._OpFloorDiv(a, b) | 9796e7c169e500c3ed7388d5f2756f3bc1fb478e | 3,635,804 |
import typing
import inspect
def optional(converter: typing.Callable) -> typing.Any:
"""
A modified version of attrs optional decorator that supports both `None` and `MISSING`
Type annotations will be inferred from the wrapped converter's, if it
has any.
args:
converter: The convertor th... | e44d0baa06859271d9ab1e37a7f14a5bfcc452ef | 3,635,805 |
def convert_symbol(mpl_symbol):
"""Convert mpl marker symbol to plotly symbol and return symbol."""
if isinstance(mpl_symbol, list):
symbol = list()
for s in mpl_symbol:
symbol += [convert_symbol(s)]
return symbol
elif mpl_symbol in SYMBOL_MAP:
return SYMBOL_MAP[m... | 931316aa19d1292bd9905292edf3bf9117209874 | 3,635,806 |
from typing import Dict
def remove_none_dict(input_dict: Dict) -> Dict:
"""
removes all none values from a dict
:param input_dict: any dictionary in the world is OK
:return: same dictionary but without None values
"""
return {key: value for key, value in input_dict.items() if value is not None... | 3f91d653a680f0f9d842ab44cbbb9ea4142c12ab | 3,635,807 |
def get_host(request, host_id, segment_id):
"""return single host """
return openstack_connection(request).get_host(host_id, segment_id) | 0c214a73c302ea5acb7de98723e9520dfd56acba | 3,635,808 |
def _GetAttachedDevices(blacklist_file, test_device):
"""Get all attached devices.
Args:
test_device: Name of a specific device to use.
Returns:
A list of attached devices.
"""
blacklist = (device_blacklist.Blacklist(blacklist_file)
if blacklist_file
else None)
attac... | bcbba1cf2297dffc9648145ee27c9dc75d266448 | 3,635,809 |
import numpy
def li_dong_2016_load_uy_profiles():
""" Load and return the y-velocity profiles (digitized from Fig. 4b).
Returns
-------
numpy.ndarray
y positions as a 1D array of floats.
numpy.ndarray
y-velocity (plus x position) as a 1D array of floats.
"""
filepath = DA... | 5847483141589c2b0cd8135ac688eb560c82cd71 | 3,635,810 |
import warnings
def read_tiff(path, pages=None):
"""
Reads in a tiff stack
:param path: Full path to file
:param pages: list or numpy array of pages to load
:return: height x width x num_pages array of image files
"""
# Get number of requested pages
if pages is None:
num_pages... | 6bc181b445cade4bd1d18f2fabb4e655af97d73b | 3,635,812 |
import pandas
import base64
import csv
def parse_file_buffer_to_seldon_request(file):
"""
Reads file buffer and parse to seldon request.
Parameters
----------
file : dict
Spooled temporary file.
Returns
-------
dict
Seldon API request
Raises
------
BadReq... | 4df8b477d0d3b4be0159550ebcc7a2162398e512 | 3,635,813 |
def load(data_dir, config, use_feature_transform=False, numeric=False, categorical=False):
"""
Load specific dataset.
Args:
data_dir (str): path to the dataset directory.
config (dict): general dict with settings.
use_feature_transform (bool): apply dense feature transform or not
... | 27aa0cea9bd393f860790f7fbfe7207386678f9e | 3,635,815 |
from datahandlers.mnist_data import MNISTData as CVData
from datahandlers.mnist_auto_data import MNISTAutoData as CVData
from datahandlers.fashionmnist_data import FashionMNISTData as CVData
from datahandlers.cifar10_data import CIFAR10Data as CVData
import torchvision
import datasets
import torch
def generate_comput... | c274245a71002d89b9b171cbd431ddbd627644bd | 3,635,816 |
import yaml
def create(client, spec: str, namespace: str = "default", timeout=100):
"""Create a CronJob.
:batch_v1_api: The Batch V1 API object.
:spec: A valid CronJob YAML manifest.
:namespace: The namespace of the CronJob.
:timeout: Timeout in seconds to wait for object creation/modification
... | da305d5a6af566c8dd465d191f5c842019bedff8 | 3,635,817 |
def get_expanded_types(types, type_hierarchy):
"""Expands a set of types with both more specific and more generic types
(i.e., all super-types and sub-types)."""
expanded_types = set()
for type in types:
# Adding all supertypes.
expanded_types.update(get_type_path(type, type_hierarchy))
... | a0f08ea1f96e960fedf1fe2a88139608a681cac1 | 3,635,819 |
def inject_where(builder):
"""
helper function to append to the query the generated where clause
:param builder: the current builder
:return:
"""
query = builder.v.query
if callable(query):
return builder
lower = query.lower()
where = lower.find(' where ')
before = -1
for before_q in [' group ... | 78682f5c3712ffcb9e96a8c7c624d6f0177884ec | 3,635,821 |
import colorsys
def loadCPT(path):
"""A function that loads a .cpt file and converts it into a colormap for the colorbar.
This code was adapted from the GEONETClass Tutorial written by Diego Souza, retrieved 18 July 2019.
https://geonetcast.wordpress.com/2017/06/02/geonetclass-manipulating-goes-16-d... | 3af8c564899c89afb3d6a4cc87ac90009526b2a4 | 3,635,822 |
def main():
"""
The main function to execute upon call.
Returns
-------
int
returns integer 0 for safe executions.
"""
print("Program to find the character from an input ASCII value.")
ascii_val = int(input("Enter ASCII value to find character: "))
print("\nASCII {asci} ... | 45bec0eb658cc17005b97e6fa812c806f5b77440 | 3,635,823 |
import random
def get_random_greeting():
"""
Return random greeting message.
"""
return random.choice(GREETINGS) | 89d4a93105ffe1a241730088388eaf4ffeff71da | 3,635,824 |
def dyad_completion(w):
""" Return the dyadic completion of ``w``.
Return ``w`` if ``w`` is already dyadic.
We assume the input is a tuple of nonnegative Fractions or integers which sum to 1.
Examples
--------
>>> w = (Fraction(1,3), Fraction(1,3), Fraction(1, 3))
>>> dyad_complet... | 3631e4db62607e18a22e652009747f25a8a585c7 | 3,635,825 |
def create_pv_string_points(x_coord: float,
y_coord: float,
string_width: float,
string_height: float
) -> [Polygon, np.ndarray]:
"""
:param x_coord:
:param y_coord:
:param string_width:
... | 212e666efa51d60fcf29da4afbbff498d6d94197 | 3,635,826 |
def phasor(H):
"""
Caculate phasor values from given histogram
g = 1 / N * sum(H * cos(f))
s = 1 / N * sum(H * sin(f))
===========================================================================
Input Meaning
---------- ---------------------------------------------------------------
... | 4034ec4e9a35c2792bd52a860ba61c729b80dcba | 3,635,827 |
def if_stmt(cond, body, orelse):
"""Functional form of an if statement.
Args:
cond: Boolean.
body: Callable with no arguments, and outputs of the positive (if) branch
as return type.
orelse: Callable with no arguments, and outputs of the negative (else)
branch as return type.
Returns... | 88db6bacfca094e94c8cec165e871127f8498175 | 3,635,828 |
def load_db(DB_Filename, ValueType, ValueColumnIdx, KeyColumnIdx):
"""Loads a database contained in file 'DB_Filename'. Creates a python dictionary
that maps from a string (contained in column KeyColumnIdx) to a number set
or a single number (contained in column ValueColumnIdx).
NOTE: The 'key... | 3291b3230a6b18945f26b16675d6d6fc27baba53 | 3,635,830 |
def createFoodObject(dataset, row):
"""
Create food URI and triples related to food properties
"""
food_onto_term = str(row['Food Ontology Term'])
food_label = row['Food']
food_type = row['NEW Food Type']
food_amount = row['NEW Food Matrix']
food_source = food_amount.split('\n')[0].repla... | 686ab766c7341e538741e20b0f70a32215db6daa | 3,635,831 |
from re import T
def business():
""" RESTful CRUD controller """
def rheader_table(r):
if r.record:
return TABLE( TR( TH("%s: %s" % (T("Name"),
r.record.business_name)),
TH("%s: %s %s" % (T("Address"),
... | c7b237196f4a614327b54fd4b53950aa16d18331 | 3,635,832 |
from pathlib import Path
def points_from_svg(svg_file_path):
""" Takes a SVG file as an input and returns a list of points in the complex plane from its path. """
# Read SVG into a list of curves.
paths, attributes = svg2paths(svg_file_path)
curves = paths[0]
# Get a list of the coordinates from... | a3fe434cda819b6c15f5ef3e854ab99455b879b6 | 3,635,833 |
from typing import List
from typing import Callable
from typing import Optional
import functools
import operator
def cluster_mols(
mols: List[Chem.rdchem.Mol],
cutoff: float = 0.2,
feature_fn: Callable = None,
n_jobs: Optional[int] = 1,
):
"""Cluster a set of molecules using the butina clustering ... | f38425183f42a994ba158a37a8b86463b7bf784d | 3,635,834 |
from typing import Optional
from typing import Tuple
def reshape_shuffle_ctg(fhr: np.array, uc: np.array, y: np.array, time: Optional[np.array]) -> Tuple[np.array, np.array, np.array, Optional[np.array], Optional[np.array]]:
"""
Reshape and optionally shuffle inputs and targets for the keras/tf input in model... | 5986d80fb31dbe87e7d4f65f750a2ff6d77cf27a | 3,635,836 |
from typing import Optional
from typing import Tuple
import requests
def do_project(project: str) -> Optional[Tuple[str, str, str]]:
"""
Query Anitya and zypper for current version.
"""
max_version = None
prog_id = anitya_find_project_id(proj_name=project)
if prog_id:
res = requests.ge... | 0011b617453a3358ce30c2d13a9c4cb0492d090e | 3,635,837 |
def save_channel_videoid(channel_id: str, video_id: str):
"""儲存單個影片ID與頻道ID
Args:
channel_id (str): [channel_id]
video_id (str): [video_id]
Returns:
[bool]]: [suss/fail]
"""
schemas = {
"video_id": video_id,
"channel_id": channel_id
}
play_list_model ... | f3c1c59cb5ff8f540335480b075fa4b6889e7733 | 3,635,838 |
def mark_point(mark_point=None, **kwargs):
"""
:param mark_point:
标记点,有'min', 'max', 'average'可选
:param kwargs:
:return:
"""
return _mark(mark_point, **kwargs) | 21287c07e77f69ce672ef1371225fad7f357277d | 3,635,839 |
def get_keys(opts):
"""Gets keys from keystore and known-hosts store"""
hosts = KnownHostsStore()
serverkey = hosts.serverkey(opts.vip_address)
key_store = KeyStore()
publickey = key_store.public
secretkey = key_store.secret
return {"publickey": publickey, "secretkey": secretkey,
... | 668447b134201e2b68e982d9cdf6219cb578dfff | 3,635,840 |
def _get_model_ptr_from_binary(binary_path=None, byte_string=None):
"""Returns a pointer to an mjModel from the contents of a MuJoCo model binary.
Args:
binary_path: Path to an MJB file (as produced by MjModel.save_binary).
byte_string: String of bytes (as returned by MjModel.to_bytes).
One of `binary... | a2aede03e3e137596bd8de689aad69272749d884 | 3,635,841 |
from typing import List
def emulate_decoding_routine(vw, function_index, function: int, context, max_instruction_count: int) -> List[Delta]:
"""
Emulate a function with a given context and extract the CPU and
memory contexts at interesting points during emulation.
These "interesting points" include c... | e663e3ce225fe5603a7debabb22ef9614f0a74ac | 3,635,842 |
def probs_to_costs(costs, beta=.5):
""" Transform probabilities to costs (in-place)
"""
p_min = 0.001
p_max = 1. - p_min
costs = (p_max - p_min) * costs + p_min
# probabilities to costs, second term is boundary bias
costs = np.log((1. - costs) / costs) + np.log((1. - beta) / beta)
return... | 77307ef656a8146286028d957d0bed64cda01a17 | 3,635,843 |
def requires_ids_or_filenames(method):
"""
A decorator for spectrum library methods that require either a list of Ids or a list of filenames.
:param method:
A method belonging to a sub-class of SpectrumLibrary.
"""
def wrapper(model, *args, **kwargs):
have_ids = ("ids" in kwargs) a... | df4cb705f11567e8e5a23da730aead8e7c90f378 | 3,635,844 |
from typing import List
from typing import Tuple
import requests
import fnmatch
def _list_nsrr(
db_slug: str,
subfolder: str = '',
pattern: str = '*',
shallow: bool = False,
) -> List[Tuple[str, str]]:
"""
Recursively list filenames and checksums for a dataset.
Specify a subfolder and/or ... | 7c0dbf352046245b189266435a4408ed739d99dd | 3,635,845 |
def red():
"""
Returns the red RGB tensor
Returns
-------
Tensor
the (1,3,) red tensor
"""
return color2float(Uint8Tensor([237, 28, 36])) | 7c627c88ca34f8b54f54711dfdf8a9b0301daa8b | 3,635,846 |
from io import StringIO
def get_temporary_text_file(contents, filename):
"""
Creates a temporary text file
:param contents: contents of the file
:param filename: name of the file
:type contents: str
:type filename: str
"""
f = StringIO()
flength = f.write(contents)
text_file =... | 7b29cb3b7bf09e78f24574555acfb24784dd9ccb | 3,635,847 |
def build_dynamic_focal_key_loss(task_cfgs):
"""According to "Dynamic Task Prioritization for Multitask Learning"
by Michelle Guo et al."""
losses = {}
for task_cfg in task_cfgs:
name = task_cfg['name']
losses[name] = build_dynamic_focal_key_task(task_cfg)
return WeightModule(losses... | 0b687461fea2cc73bf8671e1a1e97a32a422103c | 3,635,849 |
import io
import tokenize
def remove_comments_and_docstrings(source):
"""
Returns *source* minus comments and docstrings.
.. note:: Uses Python's built-in tokenize module to great effect.
Example::
def noop(): # This is a comment
'''
Does nothing.
'''
... | ffd185fc2517342e9eb0e596c431838009befde5 | 3,635,851 |
def get_arg_loc(callingconvention: str, bytecounter: int, size: int) -> str:
"""Return a string that denotes the location of a given function argument."""
index = bytecounter // 4
if index < 0:
raise Exception(
"Argument index cannot be smaller than zero: " + str(index))
if callingc... | fffd44a5d47e28fd571ee05a8332a570c24ddf95 | 3,635,852 |
import pathlib
import tqdm
def alignments_pass(alignments: pathlib.Path) -> Alignments:
"""Peform a single pass on all alignments to calculate meta information."""
meta = Alignments()
for speaker in tqdm(list(alignments.glob("*")), desc="Alignment Pass"):
# To ignore hidden files etc.
i... | bf5068e9fae3b3ae21188c7a76fb21b91045e465 | 3,635,853 |
def BRepBlend_HCurve2dTool_Intervals(*args):
"""
:param C:
:type C: Handle_Adaptor2d_HCurve2d &
:param T:
:type T: TColStd_Array1OfReal &
:param S:
:type S: GeomAbs_Shape
:rtype: void
"""
return _BRepBlend.BRepBlend_HCurve2dTool_Intervals(*args) | 7443a54617ebec6602521ed2e7cb765845972e46 | 3,635,854 |
def new_lunar_system_in_time(time_JD=2457099.5|units.day):
"""
Initial conditions of Solar system --
particle set with the sun + eight moons,
at the center-of-mass reference frame.
Defined attributes:
name, mass, radius, x, y, z, vx, vy, vz
"""
time_0 = 2457099.5 | units.day
delta_JD = time_JD-time_... | 7380e3b3f56c065865fbe64c1841a59851298113 | 3,635,856 |
import copy
def overlap3(data):
"""
"""
#
dataC = copy.copy(data)
temp = [[] for i in range(0, 12)]
index = int(dataC[0][0][5 : 7])
for x in dataC:
temp[(index % 12) - 1].append(x[1:])
index += 1
final = []
for x in temp:
final.append(np.array(x))
r... | 7baeb8bf5741b75262ca329b91e3a8625a5ad61c | 3,635,858 |
def gen_qsub_script(exp, run_type):
"""Populate qsub script with settings"""
reps = {}
qsub_path = ''
if config.is_cp_job(run_type):
reps = gen_cp_qsub_constants(exp, run_type)
else:
reps = gen_mask_qsub_constants(exp, run_type)
qsub_script = ''
qsub_template_path = config.get_template_qsub(run... | 66c7cf39512a0dfe8c1f7d62ed9542560eb0f927 | 3,635,859 |
import torch
def quat_diff_rad(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
"""
Get the difference in radians between two quaternions.
Args:
a: first quaternion, shape (N, 4)
b: second quaternion, shape (N, 4)
Returns:
Difference in radians, shape (N,)
"""
b_conj... | fe6d63dbe1b0bfc4d834af18e2260032ea405e25 | 3,635,860 |
def generate_dataset_db(
connection_string: str, file_name: str, include_null: bool
) -> str:
"""
Given a database connection string, extract all tables/fields from it
and write out a boilerplate dataset manifest, excluding optional null attributes.
"""
db_engine = get_db_engine(connection_strin... | e80c43f98c608e63c61cda50d952bd13fded4bce | 3,635,862 |
def salt(secret: str) -> str:
"""A PBKDF salt."""
return sha256(secret.encode("utf-8")).hexdigest() | edbbf13dd4ce72c8bdaf272267de13704ce9930e | 3,635,863 |
async def async_get_service(
hass: HomeAssistant,
config: ConfigType,
discovery_info: DiscoveryInfoType | None = None,
) -> KNXNotificationService | None:
"""Get the KNX notification service."""
if not discovery_info or not discovery_info["platform_config"]:
return None
platform_config ... | 9ffb1c0f2736dfde2aca18a73648c99f43c8d0f6 | 3,635,864 |
def _is_referenced_by_a_stack_frame_name(referrers, obj, name):
"""
Is there a reference among the given referrers, that is a stack frame,
which contains a local variable of the given name, which points to
the object of interest?
:param referrers: The references to scan.
:param obj: The object o... | c8ba5fcffc407d52a672b0ab9d95217c2886747c | 3,635,866 |
def prettify_name_tuple(tup):
""" Processes the intersect tuples from the steam API. """
res = []
for name in tup:
res.append(name.split("_")[0])
return ", ".join(res) | 68d9e7170f02cf4a5de434806e7abcd99e5a77e7 | 3,635,868 |
def init_repository(path, bare=False,
flags=C.GIT_REPOSITORY_INIT_MKPATH,
mode=0,
workdir_path=None,
description=None,
template_path=None,
initial_head=None,
origin_url=None):
"""
Creates a new Git repository in the given *path*.
If *bare* is True the repository will be bare, i.e.... | 1660cf767ddc393506d461d5c029f2f408c4b6de | 3,635,869 |
def deproject(center,depth,K,pose=None):
"""
center.shape = [1,2]
depth.shape = [1,1]
K.shape = [3,3]
"""
out_gt = center * depth
out_gt = np.concatenate((out_gt, depth), 1)
# out_gt = [1,3]
inv_K = np.linalg.inv(K.T)
xyz = np.dot(out_gt, inv_K)
return xyz | 62a996fc00453e9541a64c05c84b88fe316fa08e | 3,635,872 |
import requests
def get_branches(repo_id: str):
"""
Gets the branches from desired repository.
:param repo_id: repo id
:return: list(dict)
"""
branches = requests.get(url=BRANCHES_API_URL.format(repo_id), headers=HEADER).json()
return [parse_branch(branch) for branch in branches] | 80a8f84c6652ab63bdf11a5daa0447d4c60d7443 | 3,635,873 |
def lfs_cart_portlet(context, title=None):
"""Tag to render the cart portlet.
"""
if title is None:
title = _(u"Cart")
portlet = CartPortlet()
portlet.title = title
return {
"html": portlet.render(context)
} | 2791272ccc3ed3a0e38deb0f153e82c6528bbbb7 | 3,635,874 |
def test_declarative_barb_gfs_knots():
"""Test making a contour plot."""
data = xr.open_dataset(get_test_data('GFS_test.nc', as_file_obj=False))
barb = BarbPlot()
barb.data = data
barb.level = 300 * units.hPa
barb.field = ['u-component_of_wind_isobaric', 'v-component_of_wind_isobaric']
barb... | d4bb384802460354a93514c8be70fb699e16f481 | 3,635,875 |
from typing import Iterable
def new(entities: Iterable[DXFEntity] = None, query: str = "*") -> EntityQuery:
"""Start a new query based on sequence `entities`. The `entities` argument
has to be an iterable of :class:`~ezdxf.entities.DXFEntity` or inherited
objects and returns an :class:`EntityQuery` object... | 37b65767ec61c319da09518d438b7bc791f659c9 | 3,635,876 |
def create_pydot_graph(op_nodes, data_nodes, param_nodes, edges, rankdir='TB', styles=None):
"""Low-level API to create a PyDot graph (dot formatted).
"""
pydot_graph = pydot.Dot('Net', graph_type='digraph', rankdir=rankdir)
op_node_style = {'shape': 'record',
'fillcolor': '#6495ED... | 2b15ef833ef968d752ecbc19e705facac2038255 | 3,635,877 |
import requests
def info_session(request, session_type):
"""Information session request form."""
if not SESSION_TYPES.get(session_type):
raise Http404
if request.method == 'POST':
form = InfoSessionForm(session_type, request.POST)
if form.is_valid():
cd = form.cleaned_d... | 028d2832d728b4569473cd5b010c8da25d3717bf | 3,635,878 |
def transform_frame(frame, transformation_matrix):
"""
transform the selected region to bird's eye view
:param frame: the original image
:param transformation_matrix: the transformation matrix
:return: the image after transform, width scale, and height scale
"""
rows, cols, _ = frame.shape
... | 4652c855b29c17a208e4d7d054a7090fa82a6181 | 3,635,879 |
def _annotation_dict_all_filter(data, query):
"""Match edges with the given dictionary as a sub-dictionary.
:param dict data: A PyBEL edge data dictionary
:param dict query: The annotation query dict to match
:rtype: bool
"""
annotations = data.get(ANNOTATIONS)
if annotations is None:
... | bd71eaa995242afbad3c158874cf86bb1708d7c3 | 3,635,880 |
def split_storm_info(storm_list):
"""split_storm_info takes a list of strings and creates a pandas dataframe
for the data set taken off the NHC archive. This function is called in the main to
find all storms."""
name, cycloneNum, year, stormType, basin, filename = [], [], [], [], [], []
for line in... | fe41e6cf6dfa3d4be1c5549bd29284d0a29a5d90 | 3,635,881 |
def linear_inshape(module_masks, mask):
"""
Coarse grained input mask does not change the shape of weights and output tensor
Parameters
----------
module_masks : ModuleMasks
The ModuleMasks instance of the linear
mask : CoarseMask
The mask of its input tensor
Returns
--... | 51661e74575fe2b924ce6fa4a67c4b47ee53ea99 | 3,635,883 |
def test_enable_8021q_3(monkeypatch):
"""Verify that enable_802q_1 function return exception if 8021q can not be loaded.
"""
cmd_list = []
def mockreturn(command):
cmd_list.append(command)
so = "8021q"
if command == "lsmod | grep ^8021q":
so = ""
return CmdS... | f1cf3e6679d1d3c1bb8a25ff2873ae787164cb7d | 3,635,884 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.