content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def Y_factory(s, Y_size, A_size, density, SNR: float = 1, lattice_structure=None):
"""
This function produces a QPI measurement with specified size, defect density, kernel size and number of levels
"""
n1, n2 = Y_size
m1, m2 = A_size
A = kernel_factory(s, m1, m2)
X = sparse.random(n1, n2, de... | edd349416479c194e5e76aa3a7802d014144e256 | 77,725 |
def return_driven_object(attr, skip_conversion_nodes=False, long_names=True):
"""
Returns the driven object of an attribute if it exists
:param attr: str
:param skip_conversion_nodes: bool
:param long_names: bool
:return: str
"""
dst_connections = maya.cmds.listConnections(
attr... | 66bbadf5d92518b4a0a3fcf5706d9d13d8ff604a | 77,727 |
from typing import Any
def get_full_name(obj: Any) -> str:
"""Returns identifier name for the given callable.
Should be equal to the import path:
obj == import_object(get_full_name(obj))
Parameters
----------
obj : object
The object to find the classpath for.
Returns
---... | 6f83f808f8c4d226b1d26365adc75f5cb6c4e28f | 77,729 |
import torch
from typing import Iterable
from typing import Dict
from typing import Any
def params_from_optimizer(
optimizer: torch.optim.Optimizer,
param_names: Iterable[str] = ['optim']) -> Dict[str, Any]:
"""Create a dict of optimizer parameters.
Parameters
----------
ompimizer
... | 681c5f0514272e21d2ac860e19213dd704ee6d77 | 77,730 |
from statistics import mean
from collections import namedtuple
def infer_user_based_cf(model, train, test):
""" Infer user CF Vanilla
"""
# Users' mean ratings - (user, mean_rating)
mean_user_ratings = train.map(lambda x: (x['user_id'],x['stars']))\
.groupByKey()\
... | 15185905fb86dcb40dfc29f0d1c58e142bb8bd42 | 77,731 |
def estimate_microturbulence(effective_temperature, surface_gravity):
"""
Estimate microtubulence from relations between effective temperature and
surface gravity. For giants (logg < 3.5) the relationship employed is from
Kirby et al. (2008, ) and for dwarfs (logg >= 3.5) the Reddy et al. (2003)
rel... | bf54342e00fc61f042f183c8bbebc01005eb6b4c | 77,732 |
def partition(self, predicate):
"""Returns two observables which partition the observations of the
source by the given function. The first will trigger observations for
those values for which the predicate returns true. The second will
trigger observations for those values where the predicate returns fa... | 7eb5b2ef248b195e9f836c1af64d3b2b3413b64f | 77,733 |
def sorensen_index(clustering1, clustering2):
"""
This function calculates the Sorensen index between two clusterings.
See Fmeasure
"""
return fmeasure(clustering1, clustering2) | 93f09bcbab977e3e2afdb6d5991a1d55e57cefdf | 77,734 |
import configparser
def ini_read_custom(file_ini):
""" Custom """
dict_return = {}
config = configparser.ConfigParser()
config.read(file_ini, encoding="utf8")
try:
custom_on = config.getint('Custom', 'on')
except:
custom_on = 0
dict_return['custom_on'] = entries.parse_li... | e6a9055edf3f3fb36675792134112b2ed9788742 | 77,735 |
from typing import Optional
async def gen_animation(idx: str, mode: str ="fade", backwards: Optional[bool] = False) -> str:
"""
Generate animation from given unsig.
Return path of image (.gif) file.
Options:
- animation style (blend or fade)
- extended animation (backwards=True)
... | e0863b1f81f4ce495d96690ce8b705964882a34c | 77,736 |
from typing import Type
def get_component_class(component_name: Text) -> Type["Component"]:
"""Resolve component name to a registered components class."""
if component_name not in registered_components:
if component_name not in old_style_names:
try:
return class_from_modul... | aee17caae1ea03881501190ecd1164d84cc24559 | 77,737 |
def calc_pol_constants(aa, slr, ecc):
"""
Call Kerr polar orbit (x = 0) functions.
Parameters:
aa (mpf): spin parameter [0, 1)
slr (mpf): semi-latus rectum
ecc (mpf): eccentricity [0, 1)
Returns:
En (mpf): energy
Lz (mpf): angular momentum
Q (mpf): Carte... | 0ed93ed652ce66513e43abacb233154f611332ce | 77,740 |
from platform import python_version
def pl_python_version() -> str: # pragma: no cover
"""
Stored procedure that returns databases python interpreter version
@return: semantic python version X.X.X
"""
return python_version() | 4c46818a35bf5b793fdfb58f0e8648efe59a777e | 77,741 |
import numpy
def _define_bins(bins_data, mag_bin_width, dist_bin_width,
coord_bin_width, truncation_level, n_epsilons):
"""
Define bin edges for disaggregation histograms.
Given bins data as provided by :func:`_collect_bins_data`, this function
finds edges of histograms, taking into ... | 1ae5317ac10bd9548419ecccb3287b5aef701a91 | 77,742 |
def compute_snr(st, bandwidth, check=None):
"""Compute SNR dictionaries for a stream, looping over all traces.
Args:
st (StationStream):
Trace of data.
bandwidth (float):
Konno-Omachi smoothing bandwidth parameter.
check (dict):
If None, no checks perfo... | 49443075b3c8be9dc76ecabbaee432bb968a4fd6 | 77,744 |
import pkgutil
import json
def electricity_schema():
"""Provides schema validation to tests"""
schema_file_contents = pkgutil.get_data("atomic6ghg.schemas", "electricity.json")
schema = json.loads(schema_file_contents)
v = Draft7Validator(schema=schema)
return v | bd8b6d6f396f0305cd42d32e5f92bc11c2921aee | 77,745 |
def do_search():
"""This allows users to search restaurant and lead them to the restaurant_info page."""
user_input = request.form["search-form"]
exist_usernames = User.query.filter(User.username.like('%'+user_input+'%')).all()
exist_restaurants = db.session.query(Restaurant).filter(Restaurant.name.lik... | 7e87e8226bb3e6a40d9136659c0e7d4c84c412e1 | 77,746 |
def planes2array(s_planes):
"""
Return all structure contour points as Point cloud array (x,y,z) points
:param s_planes: Structure planes dict
:return: points cloud contour points
"""
zval = [z for z, sPlane in s_planes.items()]
zval.sort(key=float)
# sorted Z axis planes
structu... | 4be54717d9bd7af2d53f6041a5a407b8eb051c51 | 77,747 |
def geomconvert_ConcatG1(*args):
"""
* This Method concatenates G1 the ArrayOfCurves as far as it is possible. ArrayOfCurves[0..N-1] ArrayOfToler contains the biggest tolerance of the two points shared by two consecutives curves. Its dimension: [0..N-2] ClosedG1 indicates if the ArrayOfCurves is closed. In thi... | 4cf65934d99e6f478dff2b9ac778362b4f4cae23 | 77,748 |
def ReverseBytes(byte_string):
"""Reverse bytes in the hex string: '09ab' -> 'ab09'. This converts
little-endian number in the hex string to its normal string representation.
"""
assert len(byte_string) % 2 == 0, byte_string
return ''.join([byte_string[i - 2 : i]
for i in xrange(len(byte_str... | 6ea80d31e4e7694f1f8e9c1117f20e6a6496bd37 | 77,749 |
def peak_smooth(params, max_iter, win,
min_win=2, voicing=[], TRACE=False):
"""
Iterative smoothing while preserving peaks, 'true envelope' -style
"""
smoothed = np.array(params)
win_reduce = np.exp(np.linspace(np.log(win), np.log(min_win), max_iter))
# std = np.std(params)
... | 5fb2fe2e55c93698c68da0a9d1ba98b42264b673 | 77,750 |
def trace(func):
"""Decorator for tracing of functions."""
if not execution_context:
return func
def tracer(self, *args, **kwargs):
tracer = get_bg_trace(self, func)
with tracer.span(name="%s.%s" % (self.module_name, func.__name__)):
return func(self, *args, **kwargs)
... | 2e0781de05019aafd2388c52c535730fd3e69030 | 77,751 |
def cloud_handler(event, context):
"""Cloud function which does a division by zero operation
Args:
event (dict): Event payload.
context (google.cloud.functions.Context): Metadata for the event.
Returns:
json: A simple json object with two keys and corresponding values
"""
div... | 6af9a3620969bf16f1e7e6a87a034bc6022c8a28 | 77,752 |
from re import VERBOSE
def process_cesar_out(cesar_raw_out, query_loci, inverts):
"""Extract data from raw cesar output."""
raw_data = parts(cesar_raw_out.split("\n"), n=4)[:-1]
exon_queries, exon_refs, percIDs, blosums, query_coords, prot_seqs, codon_seqs = (
{},
{},
{},
{... | 94182c5b64cef8b14e5b192e03602da3adb35222 | 77,753 |
import yaml
from typing import OrderedDict
def ordered_dump(data, stream, Dumper=yaml.Dumper, representer=OrderedDict, **kwds):
"""
write data dict into a yaml file.
:param: data: input dict
:param stream: output yaml file
:param Dumper: yaml.Dumper
:param representer: =OrderedDict to write in... | 77fd33e7726a75d7e2f93955e96118f6ff14e1a4 | 77,755 |
def k_fold(X, Y, k, seed=100):
"""
Inputs
------
X : dataframe or dictionary of dataframes which are features
Y : dataframe or dictionary of dataframe which are labels
k : int
Number of folds
seed : int
set seed retrieved from ignition yaml
Outputs
-------
Lis... | 19dde9343450c078a8b2ba220b6d707ff24530bb | 77,756 |
def goodit2_small_patch16_224(pretrained=False, **kwargs):
"""
convolutional + pooling stem
local enhanced feedforward
attention over cls_tokens
"""
backbone = ConvStem2()
model = VisionTransformer(
hybrid_backbone=backbone,
patch_size=4, embed_dim=384, depth=12, num_heads=6,... | d3f05af2d509f0ab409c45726c4d3424439b2caa | 77,757 |
def search_the_word(word_dict, search_word):
"""word_dict => a list of words to search from.
search_word => a word to search for in the provided list.
USAGE:
This function is used to search for a word in a list of provided
list of other words. It proviides a mathch according to ... | 311f63fb903e63e75a99b5ebbd09de5aba3a899c | 77,758 |
def baseline_length(paragraph, unused_parse):
""" Subsets the length features to only those used in the baseline """
return keep_only(length(paragraph, unused_parse), ["length_in_words", "num_words_greater_than_6"]) | c425d43ee63b264c7e43da672e157e9deadc517b | 77,759 |
def Ne(a, b):
"""
A handy wrapper around the Relational class.
Ne(a,b)
Examples
========
>>> from sympy import Ne
>>> from sympy.abc import x, y
>>> Ne(y, x+x**2)
y != x**2 + x
"""
return Relational(a,b,'!=') | 0802df6d5727a061e1e409522a6400aa19b594fa | 77,761 |
def fO2(celsius, bars=1., buffer_curve='QFM'):
"""
Input:
Temperature in Celcius
Pressure in bars (default is 1)
Buffer curve. Options are QFM (default), NNO, and IW
QFM = quartz - fayalite - magnetite buffer (default)
NNO = Ni-NiO
IW = iron-wustite; ... | a3bf160d4e0a51aed168e1aac783b90e5278c953 | 77,762 |
def get_tiles(row, column_no):
"""Get tiles from row besides and including column_no."""
tile_numbers = (column_no - 1, column_no, column_no + 1)
tiles = []
for tile_number in tile_numbers:
if tile_number < 0 or tile_number == len(row):
tiles.append(SAFE)
else:
ti... | 136ea45a442440c1fa7ce05a4b3a013fd29fcea8 | 77,763 |
from typing import Optional
import hashlib
def blake2bsum(file_path: str, chunk_size: Optional[int] = None) -> bytes:
"""Returns blake2b binary digest of a file.
The file is read sequentially in chunks to prevent large files from taking
too much memory.
Args:
file_path: The path of the file ... | 518991899dbfa917af20c783deb43e0a5ef7c23a | 77,764 |
def read_proveedores(path) -> pd.DataFrame:
"""Carga y limpia la lista de proveedores que esta en la
página del siscep"""
df = pd.read_excel(path, dtype={"Año de Registro": float, "Código Postal": str})
names = {
"Año de Registro": "año_registro",
"Nombre ó Razón Social": "razon_social",... | 446543e3d6f07da752b6e83c77e278412a2d24e5 | 77,765 |
import timeit
import csv
def runAlgorithm(param, outputText=""):
"""Function that runs the algorithm.
Inputs:
-param: a dict containing all the variables I can adjust
-outputText: used for writing to the output file
Outputs:
-test_accuracy: The test accuracy for the run.
... | a0d6cb3b8c93d62f09f62b671b8f38a4e4d8c71b | 77,766 |
def compute_graph(local, rules):
"""
Obtain a DAG given an STA
"""
graph = {}
for l in local:
graph[l] = [r['to'] for r in rules if r['from'] == l and r['to'] != r['from']]
return graph | 94bde12c64a461a3bcb296568deccf3bc7624bd0 | 77,767 |
def load_data(path):
"""
Load data, convert classes to ints, split inputs and labels.
:param path: path to data
:return:
"""
letter_map = {
'A': 0,
'B': 1,
'C': 2
}
convert_letter = lambda x: letter_map[x.decode('UTF-8')]
data = np.loadtxt(path, skiprows=1, c... | 48ec441458c7e54c86b7a268879b22109fbf61ba | 77,768 |
import re
def cb_any_detect_version(rc, stdout, stderr):
"""
Callback for analyzing stdout output of the command and detecting version
string.
"""
val = 'unknown'
mtch = re.match(r'^\s*([-.0-9a-zA-Z]+)\s*$', stdout)
if mtch:
val = mtch.group(1)
return { 'build_version': val } | cb98c0893808d7302160b0faa4dbbd8c800653b4 | 77,769 |
def test_column_data_type(data_frame):
"""code for unit test to be run manually"""
result = test_create_dataframe(data_frame, DATA)
if result:
print("Worked! column data types are equal")
else:
print("Sorry, the column name types are not equal according")
return result | 5b9d9bdb670c5dda8c5b94228e8c23b7de28bbf7 | 77,770 |
import urllib.request, urllib.error, urllib.parse
def getRemoteWebPage(url, username=None, password=None, realm=None):
"""getRemoteWebPage.
Args:
url:
username:
password:
realm:
"""
responseErrorCode = OK
responsePage = ''
if username and password:
# Use auth... | 3de8bb6c632359f0ef71dfb9daf9e8c5b080c1fe | 77,771 |
def full(shape, dtype, fill_value):
"""Fill tensor with fill_value
Parameters
----------
shape : tuple
Input tensor shape.
dtype : str
Data type
fill_value : float
Value to be filled
Returns
-------
y : tvm.Tensor
The result.
"""
return cpp.f... | 90ec830c06798a1df1fb3eee4ca6ba4e1d868eb2 | 77,772 |
import torch
def entropy_loss(v):
"""
Entropy loss for probabilistic prediction vectors
input: batch_size x classes x points
output: batch_size x 1 x points
"""
# (num points, num classes)
if v.dim() == 2:
v = v.transpose(0, 1)
v = v.unsqueeze(0)
# (1, num_c... | 827a37e3ae105be8f66103d468e7d9aa958bf501 | 77,773 |
def get_together_training_batch(s_t0, state_input, reward, train_number, train_len, state_trace_length, BATCH_SIZE):
"""
we generate the training batch, your can write your own method.
in our dataset, 1 means home score, -1 means away score, we transfer it to one-hot representation:
reward = [If_home_s... | 5b518a172af951880e5a5d64992d4bd33fad3e4f | 77,774 |
def get_workspace():
""" Make a workspace ready for user """
if WORKSPACE["path"]:
workspace = verify_workspace_name(WORKSPACE["path"])
else:
home_dir = get_home_path()
workspace = "{}/{}".format(home_dir, WORKSPACE["name"])
message = "Workspace in use: \"{}\"".format(workspac... | 6f443faf88858be45bc3a7ad6588c177ece0aa54 | 77,775 |
def PolygonalMesh_createBrickMesh(halfDims, resolution=1):
"""
createBrickMesh(Vec3 halfDims, int resolution=1) -> PolygonalMesh
Parameters
----------
halfDims: SimTK::Vec3 const &
resolution: int
PolygonalMesh_createBrickMesh(Vec3 halfDims) -> PolygonalMesh
Parameters
----------
... | 57b0aefa34038a82c45e9f5eaba2b3f977755fbb | 77,776 |
def verify(repo):
"""verify the consistency of a repository"""
ret = verifymod.verify(repo)
# Broken subrepo references in hidden csets don't seem worth worrying about,
# since they can't be pushed/pulled, and --hidden can be used if they are a
# concern.
# pathto() is needed for -R case
r... | 32e0abe0c43e1f19c0d4a4f34d24234ce6ca91b9 | 77,781 |
import re
def translate_mouse(code: str, method: str) -> list[MouseEvent | None] | None:
"""Translate the output of produced by setting report_mouse codes into MouseEvent-s.
This currently only supports `decimal_xterm` and `decimal_urvxt`. See `report_mouse` for more
information."""
mouse_codes = {
... | 4c76318472bcc5340e86e657d011ed1c21c165db | 77,782 |
def rw_protected_resource(scopes=None, validator_cls=OAuth2Validator, server_cls=Server):
"""
Decorator to protect views by providing OAuth2 authentication and read/write scopes
out of the box.
GET, HEAD, OPTIONS http methods require "read" scope. Otherwise "write" scope is required.
@rw_protec... | 9b41b919ac94c020e20c48862c443523eb19b475 | 77,784 |
import six
def active_qubits(linear, quadratic):
"""Calculate a set of all active qubits. Qubit is "active" if it has
bias or coupling attached.
Args:
linear (dict[variable, bias]/list[variable, bias]):
Linear terms of the model.
quadratic (dict[(variable, variable), bias]):
... | 0d8e8ae9b5b38593a502480886d0151f926f5c0d | 77,785 |
def pass_data(request):
"""
This context processor will pass data to template
that you defined in settings.py
enable context processor:
'context_processors': [
...
"handypackages.utils.context_processors.pass_data",
...
]
example data to pass in se... | 6a46b2ed93210fe02d7f41c77151c8f86333e6fb | 77,787 |
def distance_matrix(client, origins, destinations,
mode=None, language=None, avoid=None, units=None,
departure_time=None, arrival_time=None, transit_mode=None,
transit_routing_preference=None, traffic_model=None, region=None):
""" Gets travel distance and ... | d53fc12570ce55a8fdcc088e3768b4f3ae5754f1 | 77,788 |
def eval_promise(value):
"""
Used to convert lazy translations to text
"""
return isinstance(value, Promise) and force_text(value) or value | 9662c495258d9c88eb954d43b90c898e8244ec0f | 77,789 |
def sklearn_unflatten(output_np, input_xr):
"""
Reshape a numpy array with no 'missing' elements (NaNs) and
'flattened' spatiotemporal structure into a DataArray matching the
spatiotemporal structure of the DataArray
This enables an sklearn model's prediction to be remapped to the
correct pi... | 0d3fa683d911bed1dc8ee5421b0c04043e74b408 | 77,790 |
def _build_env(argv):
""" Build an environment object.
This method take an argv parameter to make function pure.
"""
cmdargs = _build_cmdargs(argv)
env = build_environment(cmdargs)
return env | 5e40d0f928bc4f330b3dec20c4ef66318d0963f5 | 77,791 |
import torch
def combine_patches(patches, patch_size, stride, img_shape):
"""
Combines patches into an image by averaging overlapping pixels
:param patches: patches to be combined. pytorch tensor of shape (N_patches, 3*patch_size**2)
:param img_shape: an image of a shape that if split into patches wit... | 94df0ccb7ee720ae58949f87af8807c5cc0b8347 | 77,793 |
def getNormals(meshName):
"""Get the average normal in world space of each vertex on the provided mesh.
The reason why OpenMaya.MItMeshVertex function has to be used is that the
MFnMesh class returns incorrect normal results.
:note: using old open maya here as maya 2019.3.1 has a hard crash when gather... | 64d8b68ba40abf8e9641af70ab85705dffa0112d | 77,794 |
def rotate_array_180(arr):
"""Rotate array 180 degrees
Args:
arr (numpy.array): input array
Returns:
numpy.array: rotated array
"""
slices = [slice(None) for _ in range(arr.ndim - 2)] + \
[slice(None, None, -1), slice(None, None, -1)]
return arr[tuple(slices)] | 95b4cbbbf5efd1fe211f2c5cc8253acbc9a6e4d9 | 77,795 |
def rotate_velocities(u, v, theta):
"""
Rotate velocities by angel theta in clockwise direction.
u_rot = u * xr.ufuncs.cos(theta) - v * np.sin(theta)
v_rot = u * xr.ufuncs.sin(theta) + v * np.cos(theta)
Parameter
---------
v: xarray.Dataset
Array of shape N providing meridi... | c6b69f752cb46cfe44917aff85b2f30ac517048b | 77,796 |
import re
def messagestat_formatting(messageBody):
"""
Formats the message body for messagestat functions.
This mostly involves replacing spaces with underscores
and doubling up on quotations so that SQL server
ignores them
"""
messageBody = re.sub(' ', '_', messageBody)
messageBody = ... | f91a8fe73b336f97be8322c6b5034013090e0807 | 77,798 |
from typing import OrderedDict
def get_labels(repo):
"""
Get all labels for repository.
Returns an `OrderedDict` keyed on label names. If normalize-labels was
specified in the configuration, this also normalizes all label names and
ignores their original spellings.
"""
normalize = get_r... | 90036bb644a38921e56c209468b26061f3af0598 | 77,799 |
def get_price_curr(ticker):
"""
Pulls data from Alphavantage using ticker.
Returns back close for today (latest value).
"""
ts = TimeSeries(api_keys.AV_KEY)
attempts = 1
while attempts <= 2:
try:
data = ts.get_quote_endpoint(symbol=ticker)
price = float(data[0... | e3b9b87caa8f68f7f4f6b73026221334ef953765 | 77,800 |
def round_value(val, unc=None, unc_down=None, method="publication"):
"""
Rounds a number *val* with a single symmetric uncertainty *unc* or asymmetric uncertainties
*unc* (interpreted as *up*) and *unc_down*, and calculates the orders of their magnitudes. They
both can be a float or a list of floats for... | 9ef9df64e8c9c68db4a393fc850d95f578f9860f | 77,801 |
def getWordAtIndex(line : str, index : int) -> str:
""" Get the i'th word in a space separated string of words.
Parameters
----------
line
The string from which the word should be extracted.
index
The integer indicating which word to extract.
Returns
-------
st... | d9c371a34c25f9e534f6e3d4ee0d0ff05c061b96 | 77,802 |
from typing import Type
from typing import Dict
from re import X
def checked_cast_dict(
key_typ: Type[K], value_typ: Type[V], d: Dict[X, Y]
) -> Dict[K, V]:
"""Calls checked_cast on all keys and values in the dictionary."""
new_dict = {}
for key, val in d.items():
val = checked_cast(value_typ,... | f7be0445dca615d57ff42cbd77d45ed5d01c7c4d | 77,803 |
from pathlib import Path
from typing import List
def load_camels_cl_attributes(data_dir: Path, basins: List[str] = []) -> pd.DataFrame:
"""Load CAMELS CL attributes
Parameters
----------
data_dir : Path
Path to the CAMELS CL directory. Assumes that a file called '1_CAMELScl_attributes.txt' ex... | 9dd446cbefdf5001ecfb2532d952c97eaaf81556 | 77,804 |
def change_pals_col_names(pals_df):
"""
:param pals_df: A dataframe returned fromm the PALS package
:return: The pals_df with columns removed and headings changed for use on the website
"""
pals_df.reset_index(inplace=True)
columns = pals_df.columns
# Drop the columns that are not required ... | ff81ca9f200bc80e2037b14779d674c98e2f155d | 77,805 |
from typing import Optional
from typing import Union
from typing import List
def list_validator(
input_value: Optional[Union[List[ListContent], ListContent]]
) -> List[ListContent]:
"""Add list validation for XML fields
xmltodict library captures list in various ways:
- null if nothing is provide... | 5ec01774fb604d872d338416d9818117e0299d8a | 77,806 |
def case_data(
atom,
building_block_atom,
building_block,
building_block_id,
):
"""
A :class:`.CaseData` instance.
"""
return CaseData(
atom=atom,
building_block_atom=building_block_atom,
building_block=building_block,
building_block_id=building_block_id... | 555a8f661d7e029cf658c97f43b1ab29bb87728e | 77,807 |
def remove_managed_variant(store, managed_variant_id):
"""Remove a managed variant."""
removed_variant = store.delete_managed_variant(managed_variant_id)
return removed_variant | 425c5f15f1896718dddea362f93434b05ee0d485 | 77,808 |
import json
def init(port):
"""Handshake with the coordinator, return config"""
global g_id
g_id += 1
req = {
'jsonrpc': '2.0',
'method': 'getconfig',
'params': {},
'id': g_id,
}
url = "http://localhost:%d/" % (port,)
response = session.post(url, data=json.d... | 72bb21f6e127ff94b24f7d95d7ef2b30a4e4e7fd | 77,809 |
def get_sol_ud_model_columns(df_columns):
"""Get experimental condition features."""
sol_ud_model_columns = list(filter(lambda column_name: column_name.startswith('_rxn_') and not column_name.startswith('_rxn_v0'), df_columns))
sol_ud_model_columns.remove('_rxn_organic-inchikey')
return sol_ud_model_col... | ab05433a6cb05af82c4642c27fb5cb85851e88e7 | 77,810 |
def _ngrams_from_tokens(tokens, n, join=True, join_str=' '):
"""
Helper function to produce ngrams of length `n` from a list of string tokens `tokens`.
:param tokens: list of string tokens
:param n: size of ngrams
:param join: if True, join each ngram by `join_str`, i.e. return list of ngram string... | 39afd35a4e715ea3e358a81d3a557eb1f0f0310a | 77,812 |
def shap_run(model_id, save=False):
"""
Outputs a dataframe with the top 5 variables with most impact for both possible predictions.
Parameters:
model_id (int): ID of the model to be used
save (bool): Whether the output table is to be saved to the database
"""
# get model-dataset correspon... | a1c80c3479e17d0a60401c446406150f40c4c76d | 77,813 |
def ac_solver(csp, arc_heuristic=sat_up):
"""arc consistency (domain splitting)"""
return ACSolver(csp).domain_splitting(arc_heuristic=arc_heuristic) | 0850f029b90ab50a90d1fd136de86364e495502e | 77,814 |
def parse_prior_params(bt_config, code_config, key, default, prior='pre'):
"""
Parse parameters with priority.
Args:
bt_config(dict): bt config
code_config(dict): code config
key(string): parameter name
default(default): default value
prior(string): use bt_config in ... | beee29f04562173d18cc95b2b49683dee02fbca8 | 77,815 |
def plot_cofactor_substrate_comparison(
posterior: InferenceData, lits: pd.DataFrame
) -> Figure:
"""Compare posterior means of cofactors and substrates."""
log_kms = az.extract_dataset(posterior, var_names="log_km", combined=True)
means = (
log_kms.mean(dim="sample")
.to_dataframe()
... | 10de6479a4935b86d30eba33923c0e03ddb4603e | 77,816 |
def host_allgather(in_tree: PyTreeDef, num_replica_sets: int,
replica_set_id: int,
is_first_host_in_replica_set: bool) -> PyTreeDef:
"""Gather data from across hosts/replica sets.
Args:
in_tree: pytree of arrays - each array _must_ have the same shape across the
host... | 8d3ebf499d0270fa420cc023c7b980b9be4f2496 | 77,817 |
import numpy
def CreateAndWriteRAT(fname):
"""
Creates file and writes some data
"""
# create
driver = gdal.GetDriverByName("HFA")
ds = driver.Create(fname, 10, 10, 1, gdal.GDT_Byte)
ds.SetGeoTransform([0, 1, 0, 0, 0, -1])
# write some image data
band = ds.GetRasterBand(1)
da... | 1ba22b8d905fc75a15bec75a43d4d996b8a83e2b | 77,818 |
def map_merge_cubes(process):
"""
"""
# intentionally empty, just for clarity
# the only thing needed for this process is to create a new pickled object from the input ones, already mapped by other functions in map_processes.py
return [] | 26d247c6ddb0ae217edd58666126ebb94bda0c7a | 77,819 |
def format_iteration_coordinate(coord, prefix=None):
"""
Format the iteration coordinate to a human-readable string.
Parameters
----------
coord : list
List containing the iteration coordinate.
prefix : str or None
Prefix to prepend to iteration coordinates.
Returns
--... | e434fdbeac2784b50af7037778800eff20695247 | 77,820 |
def score_macroboard(macroboard, player):
"""
Return the heuristics score of the player for the macroboard.
"""
if macroboard.winner() == player:
return SCORE_FOR_WIN
score = 0
for i in range(macroboard.SIZE):
for j in range(macroboard.SIZE):
score += score_microboard... | 9d060989c501697cc2089837c250c69670470501 | 77,821 |
def get_new_component_from_dialog(dialog: AddComponentDialog, name: str) -> Component:
"""
Get the stored component from an AddComponentDialog after the "Add Component" button has been pressed.
:param dialog: The AddComponentDialog.
:param name: The name of the component that is being searched for.
... | 2a19fd7d03de785a31f3ebf2b1e3da802a0b7d3a | 77,822 |
def _parse_field_name(key):
""" Convert the ovs header field name to the corresponding OpenFlow name
Note: this doesn't deal with VLAN oddities, as these don't directly
map to OpenFlow
"""
akas = {
"in_port_oxm": "in_port",
"dl_src": "eth_src",
"dl_dst": "eth_d... | 804f6e87538aa8f2e5e9013a10a8a9cf43b87933 | 77,823 |
def parse_test_groups(program_data: dict) -> list[TestGroup]:
"""
Parse TestGroups in the test file.
:param program_data: The Python object parsed
from JSON file containing the program data.
:return: The list of TestGroups inside the test.
"""
if "Default URI" in program_data:
d... | 01fc022061183eafb3fc8db4d6910058f3c87e12 | 77,824 |
from operator import concat
def fuzzy_left_merge(
left, right, left_on=None, right_on=None, on=None, suffixes=('_x', '_y'), score_name='match_ratio',
na_ratio=0.5, two_na_ratio=0.75, similarity_function=None, weights=None,
case_sensitivity=0.5, num_results=1, num_threads=-1, echo=1
):
"""
:type left: DataFram... | 1eae575b611c3073f5fb6641ebd148e98d49e6e0 | 77,825 |
def subsample(counts, n, replace=False):
"""Randomly subsample from a vector of counts, with or without replacement.
Parameters
----------
counts : 1-D array_like
Vector of counts (integers) to randomly subsample from.
n : int
Number of items to subsample from `counts`. Must be less... | 9c57370782cc9269f43717a21512374fba8418ea | 77,826 |
def theoreticalBER(snr: int, modulation: str) -> float:
"""Lookup the theoretical BER for a given modulation scheme that has been
precomputed using MATLAB's *berawgn*.
Args:
snr (int): Signal-to-Noise ratio (:math:`E_s/N_0` not :math:`E_b/N_0`).
modulation (str): Name of the modulation form... | e56dcff42a467138ada661e9d9af39997c74e741 | 77,827 |
def squeeze(self, dim=None):
"""Map of 'squeeze' pytorch method."""
dim = _dim_explicit(self.shape, dim)
final_shape = _shp_squeeze(self.shape, dim, False)
return reshape(self, final_shape) | 3d5964a28bb626c48394ee237ff93cefdb2ef256 | 77,828 |
def convert_image(image):
"""Convert the uint8 image tensor to float32."""
return tf.image.convert_image_dtype(image, dtype=tf.float32) | 094cb5332b97f6021bb94cdf7979f30005ae54dd | 77,829 |
def get_view():
"""Responds with the form for the example"""
return render_template(
"eg034_use_conditional_recipients.html",
title="Using conditional recipients",
source_file= "eg034_use_conditional_recipients.py",
source_url=DS_CONFIG["github_example_url"] + "eg034_use_conditi... | 588ca668151ed9d81804e39c8800c117b3f078d5 | 77,830 |
import copy
def getDefaultProfile():
"""Returns a deep copy of the default profile."""
profile = copy.deepcopy(DEFAULT_PROFILE)
return profile | 28f219553eb87f409f68edde70e1cfbd4cc1240a | 77,831 |
def vmtkbranchpatching(surface, longitudinalpatchsize=1.0,
circularnumberofpatches=12):
"""Patch surface of each branch.
Patching means to 'cut' a set of contiguous rectangular regions on the
surface mesh that follow iso-contours in the StretchedMapping and
AngularMetric arrays. ... | 55e525871894db736323f3807affa9be79661671 | 77,833 |
def column_grabber(dtype: str):
"""Returns a column maker for the specified data type. Accepted data types
are the following:
'timestamp': datetime64 with minute precision.
'date': datetime64 with day precision.
'int': np.int64.
'float': np.float64.
'str': strings.
... | df32b48f65f27f893ec75f0c5501f0525be14c8e | 77,834 |
def sophos_firewall_app_policy_add_command(client: Client, params: dict) -> CommandResults:
"""Add app policy object
Args:
client (Client): Sophos XG Firewall Client
params (dict): params to create the object with
Returns:
CommandResults: Command results object
"""
return g... | b336edf8b5b3312d46aa36b0732405b939006563 | 77,835 |
def selu(x):
""" Selu activation function.
Apply selu activation function to input tensor.
Parameters
----------
x : tf.Tensor
input tensor.
Returns
-------
tf.Tensor
"""
alpha = 1.6732632423543772848170429916717
scale = 1.0507009873554804934193349852946
return... | 24f3822e8c97c2e1f83726e23e723ef9fe32c2e6 | 77,836 |
def isXYZController(obj):
"""
Evaluates if the supplied object is a XYZ controller.
:type obj: pymxs.runtime.MXSWrapperBase
:rtype: bool
"""
return pymxs.runtime.classOf(obj) in XYZ_TYPES | 3e6b171d6feb4ff7062723adcc493fb378be32c8 | 77,837 |
def entity_tostring(entity):
"""Converts one GNL (Google Natural Language) entity to a readable string."""
metadata = ", ".join(['"%s": "%s"' % (key, value) for
key, value in entity.metadata.items()])
mentions = ", ".join(['"%s"' % mention for mention in entity.mentions])
re... | dd3e30247e36186e6eccfe1e32f8f31bf3577660 | 77,838 |
def list_trial_jobs():
"""return information for all trial jobs as a list"""
return _nni_rest_get(TRIAL_JOBS_PATH) | f4b8127b2523570a66db69ca689d8a7767aaa085 | 77,840 |
def adhoc_merge(datasets, filepattern):
"""File structures are heterogenious across time.
This function is to try to fix some of that to 2018-07 which is
the file structure I was working with first
"""
if 1 in datasets.keys():
# identify change by cfgrib extra splitting behaviour
# ... | fc90c7cc68c596892c2b0daa533de4f6efdd3fa2 | 77,842 |
def organization(cert):
"""
Attempt to get the organization name from a given certificate.
:param cert:
:return:
"""
try:
return cert.subject.get_attributes_for_oid(
x509.OID_ORGANIZATION_NAME
)[0].value.strip()
except Exception as e:
sentry.captureExcepti... | 86ade1ad329e96a0276fe5247261027c541dc0ca | 77,843 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.