content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Sequence from typing import Optional import math def partition_dataset( data: Sequence, ratios: Optional[Sequence[float]] = None, num_partitions: Optional[int] = None, shuffle: bool = False, seed: int = 0, drop_last: bool = False, even_divisible: bool = False, ): """...
a8a306e72d256d511d0a8f9493dd46dcbf6c1d7e
33,600
def canopy_PAR_absorbed(states: States, setpoints: Setpoints, weather: Weather): """The PAR absorbed by the canopy Equation 8.26 :return: The PAR absorbed by the canopy [W m^-2] """ return canopy_PAR_absorbed_from_greenhouse_cover(states, setpoints, weather) + canopy_PAR_absorbed_from_greenhouse_flo...
0ea8103d1087be3d283e4834ec7ec8b436357e28
33,601
def tiff_to_array(tiff): """ Open a TIFF file as an array, normalizing the dimensions. :param tiff: Filename :return: """ array = ( tiff.asarray(out='memmap') if tiff.pages[0].is_memmappable else tiff.asarray() ) if array.ndim < 3: array = array[np.newaxis, ...] retu...
157591e2f9980602fc9bca3f713fb512c696821b
33,602
def factor_costs_for_var(factor: Constraint, variable: Variable, recv_costs, mode: str): """ Computes the marginals to be send by a factor to a variable The content of this message is a table d -> mincost where * d is a value of the domain of the variable v * mincost is the minimum value of f when...
6910418aa2ce29ca98ba7bd85bc34a08ea44519d
33,603
def version(): """donghuangzhong version""" return "0.0.1"
ad5d9834dddad46c2f4add31f46ea470bf370304
33,604
def list_dot(a, b): """ Returns the Euclidean inner product of two itterable data-structures. """ try: if len(a) == len(b): temp = 0 for i in range(len(a)): temp += a[i]*b[i] return(temp) else: raise ValueError("The length o...
80dcdb22ed76a9cfe9750deb55971548efe4380e
33,605
import struct def pack_bytes(payload): """Optimally pack a byte string according to msgpack format""" pl = len(payload) if pl < (2**8): prefix = struct.pack('BB', 0xC4, pl) elif pl < (2**16): prefix = struct.pack('>BH', 0xC5, pl) else: prefix = struct.pack('>BI', 0xC6, pl) ...
eaea52c44a766d74d0aa10e1da20e70f49b624f6
33,606
import torch def disparity_consistency_src_to_tgt(meshgrid_homo, K_src_inv, disparity_src, G_tgt_src, K_tgt, disparity_tgt): """ :param xyz_src_B3N: Bx3xN :param G_tgt_src: Bx4x4 :param K_tgt: Bx3x3 :param disparity_tgt: Bx1xHxW :return: """ B, _, ...
c407085bf10b0f7c67152d7d92f55a4984520766
33,607
import re def split (properties): """ Given a property-set of the form v1/v2/...vN-1/<fN>vN/<fN+1>vN+1/...<fM>vM Returns v1 v2 ... vN-1 <fN>vN <fN+1>vN+1 ... <fM>vM Note that vN...vM may contain slashes. This is resilient to the substitution of backslashes for slashes, since Jam, unb...
8b15697f6ae15b2fb634144987893ca04eabcccc
33,608
def abort_behavior(token): """ Abort behavior identified with the token """ return True, stop_nodenetrunner(behavior_token_map[token])
faee270933a225ab376fef9b3ede589960e9c594
33,609
def limit_to_value_max(value_max, value): """ :param 1.(int) value_max -- value that should not be exceed 2.(int) value -- actual value :return 1. return a value in the given range bound with value_max """ if value > value_ma...
a568bc1febe9a0cb6115efb4c95c0e1705787bfe
33,610
def reference_col( tablename, nullable=False, pk_name="id", foreign_key_kwargs=None, column_kwargs=None ): """Column that adds primary key foreign key reference. Usage: :: category_id = reference_col('category') category = relationship('Category', backref='categories') """ foreign_...
17da349907c2764b4d4a205a9a5a4e4ff9d02484
33,611
import numpy as np def extract_municipality_hashtags(df): """ This function takes a twitter dataframe as an input then the output is the dataframe with 2 new columns namely a hashtag column and a municipality column. Example ------ if the tweet contains the @mention '@CityPowerJhb' then the c...
1c58e3154f57ad82a8129c5ed765a622b12b8d08
33,612
import math def vertices_homography(vertices, H): """Apply projective transformation (homography) on a sequence of points. Parameters: vertices: List of (x, y) tuples. A list for projective transformation. H: A homography matrix. Return: vertices_homo: List of (...
ad0b1cd397d0b01a0f333d872b4f8a8d2e5f0736
33,613
def SRCNNv2(input_shape, depth_multiplier=1, multi_output=False): """ conv 9-64 puis 7-64 puis 5-32 puis 7-1 -> 1.006 120 epoch conv 9-128 puis 7-64 puis 5-32 puis 7-16 puis 9-1 -> 1.007 130 epoch @ multi_output : set to True """ inputs = Input(input_shape, name="inputs") conv1 ...
752d4e7da9f62a532db326c9eb68d91369a44dd9
33,614
import json def parse_labels(string, bb_label_mapping, static_label): """Returns array of rectangles geometry and their labels Arguments: string {str} -- JSON string bb_label_mapping {dict} -- Mapping from color to label static_label {list} -- List of labels valid for the whole im...
3a671abaac1faa326d0faa7e618249b5f17cd705
33,615
def spike_profile(*args, **kwargs): """ Computes the spike-distance profile :math:`S(t)` of the given spike trains. Returns the profile as a PieceWiseConstLin object. The SPIKE-values are defined positive :math:`S(t)>=0`. Valid call structures:: spike_profile(st1, st2) # returns the bi-variate ...
ffaff8b0e1e3f81dcbbf8cb0762224dc3850b2b3
33,616
import re import pandas def wig_to_dataframe(infile, step, format): """Read a wig file into a Pandas dataframe infile(str): Path to file Returns: Dataframe """ fs = open(infile, 'r') coverage_data = [] pos = 0 chr = "" for line in fs.readlines(): try: ...
07873b340b450ef3d0eb3d7715afb9b204a8277e
33,617
from corehq.apps.users.models import CommCareUser def get_all_commcare_users_by_domain(domain): """Returns all CommCareUsers by domain regardless of their active status""" def get_ids(): for flag in ['active', 'inactive']: key = [flag, domain, CommCareUser.__name__] for user i...
2b9209ac899b73eb534ba98cd5930bb0dc4749c2
33,618
def print_cycles_info(data): """ Print various information about cycles. """ n_cycles = len(data.cycles) output('number of cycles:', n_cycles) if not n_cycles: return data slengths = sorted(set(data.cycles_lengths)) lhist, lbins = np.histogram(data.cycles_lengths, ...
d22d827d966ff467de232818edd7854c20e12bb9
33,619
def get_block_size(sigma = 1.5): """ Devuelve el tamaño de los vecinos (block_size) que se va a utilizar para obtener los puntos Harris. El valor se fija al valor correspondiente al uso de máscaras gaussianas de sigma 1.5. El tamaño de la máscara Gaussiana es 6*1.5+1. """ return int(6*sigma...
52f4aa88580252ab9c0f7a1840ac3097166c3930
33,620
import os def load_fixture(filename: str) -> str: """Load a fixture.""" path = os.path.join(os.path.dirname(__file__), "fixtures", filename) with open(path, encoding="utf-8") as fptr: return fptr.read()
fa37cdd1e9a89df1188a67eb1fafb62882a329ca
33,621
from typing import Callable from typing import Union from typing import Tuple import typing def approxZeroNewton(f: Callable[[float], float], df: Callable[[float], float], ddf: Callable[[float], float], a: Union[int, float], b: Union[int, float], epsilon: float, iteration: int) -> Tuple[float, int]: """ Appro...
f15e37f581f2f040af8b2c7edcec11ebce75c93f
33,622
def chain_data(symbol, info=None): """Gets chain data for stock. INSTANT. Includes possible expiration dates for options.""" assert type(symbol) == str return robin_stocks.options.get_chains(symbol, info)
04cdb028420fbabdd1a4951762a5a6fea24a821a
33,623
def convert_Cf2manningn(Cf, h): """ Convert the friction coefficient Cf to the Manning's n """ n = h**(1 / 6) * np.sqrt(Cf / g) return n
6552425ed1deea8ea93b226e1cbd19df40d3e5af
33,624
def lstmemory_unit(input, name=None, size=None, param_attr=None, act=None, gate_act=None, state_act=None, mixed_bias_attr=None, lstm_bias_attr=None, ...
5e4ec7203b58d44b7b07c865ea7683994869dd90
33,625
def _GetPrivateIpv6GoogleAccess(dataproc, private_ipv6_google_access_type): """Get PrivateIpv6GoogleAccess enum value. Converts private_ipv6_google_access_type argument value to PrivateIpv6GoogleAccess API enum value. Args: dataproc: Dataproc API definition private_ipv6_google_access_type: argument va...
56c830257ce996716a6dea7d205dca00e06ab6a9
33,626
def retry_(f, ex, times=3, interval=1, on_error=lambda e, x: None, *args, **kwargs): """ Call a function and try again if it throws a specified exception. :param funciton f: The function to retry :param ex: The class of the exception to catch, or an iterable of classes :type ex: class or iterable ...
e28d39dfee43c9c651b174f87acdd077920f3ed9
33,627
from sklearn.decomposition import PCA from sklearn import linear_model def pca_analysis(model, data): """Run PCA analysis on model to visualize hidden layer activity. To get the values of the intermediate layer, a new model needs to be created. This model takes the normal input from the RNN, and returns...
00ec016e4c47cd15b2570457b835990ae9aef2e2
33,628
def get_plugin_history(name): """ Get history of results for single plugin :param name: name of the plugin :type name: string """ plugin = smokerd.pluginmgr.get_plugin(name) results = [] for res in plugin.result: res = standardized_api_list(res) results.append({'result'...
64225c04d13ee228c0a375c78ff805c0dcd56bb4
33,629
def _parse_instance_info(node): """Gets the instance and driver specific Node deployment info. This method validates whether the 'instance_info' and 'driver_info' property of the supplied node contains the required information for this driver to deploy images to the node. :param node: a single Nod...
65e687704ad5fa70f8fc23eaf73f3c48eec9e17c
33,630
import sys def pipe(db_new, db_old, table): """新表中默认数据的insert语句""" res = db_new.query('select * from %s' % table) if len(res) <= 0: return [] values = '' keys = None _sqls = [] for i, _item in enumerate(res): # TODO 导入默认数据 if keys is None: _keys = '`, `'...
ce4d42438ed50f463228e3a4d0cce92c0b72984a
33,631
def str2polynomial(string): """ Get a string, return a polynomial """ try: parts = advanced_split(string, '+', '-', contain=True) terms = [str2term(each) for each in parts] return Polynomial(*terms) except: raise Exception('Example input: -5x_1^2*y_1^3+6x_2^2*y_2^4-x_3^1*y_3^...
a52641bcbbc67159f5b73bbbc91ba84ea38cb223
33,632
def transpose_2d(array): """Transpose an array represented as an iterable of iterables.""" return list(map(list, zip_equal(*array)))
48249de78d7d7c591f6d9fc8d79e184d3f291b49
33,633
def get_test_examples(args): """See base class.""" src = file2list(args.src_data) trg = file2list(args.trg_data) return _create_examples(src, trg, "test")
b1353a7b2bb87379c71c025f7abeb6142c55cf30
33,634
import json def parse_site_config(config_site): """ Parse Site level configuration :param config_site: Site config dict :return: Tuple of WAN Interface config, LAN Network config, Element Config, DHCP Server config, and Site Extension config """ local_debug("SITE CONFIG: " + str(j...
9835469789e7c14f8abca0cfa641bc5f37e51b93
33,635
def precrec_unvoted(preds, gts, radius, pred_rphi=False, gt_rphi=False): """ The "unvoted" precision/recall, meaning that multiple predictions for the same ground-truth are NOT penalized. - `preds` an iterable (scans) of iterables (per scan) containing predicted x/y or r/phi pairs. - `gts` an iterable ...
eff8aef552999db2377c9d053c548a705f07bf3a
33,636
def get_weapon_objects(json_load): """creates weapon objects by iterating over the json load and making an object of each dictionary, then returns a list of all the objects """ weapon_object_list = [] for weapon_dict in json_load: # weapon_dict is a dictionary which has data for one weap...
e3b7309b4267ce4f237db3e7d6e17c69b187a1fc
33,637
def _t_P(P): """Define the boundary between Region 2 and 3, T=f(P) >>> "%.2f" % _t_P(16.52916425) '623.15' """ n=[0, 0.34805185628969e3, -0.11671859879975e1, 0.10192970039326e-2,0.57254459862746e3, 0.1391883977870e2] return n[4]+((P-n[5])/n[3])**0.5
196f4fae80d9425b0f3a06213c21f77d3049e401
33,638
import inspect def add_as_function(cls): """ Decorator for classes. Automatically adds functional interface for `call` method of class. For example, `ConvBlock` class is transformed into `conv_block` function, while `Conv1DTranspose` class is transformed into `conv1d_transpose` function. """ name...
38f2e604e03e5a356450569bbfe7d0764bd784cb
33,639
def remove_from_cart(request): """ Remove product from cart """ product_id = int(request.POST['product_id']) # Checking if user session has cart or session may already flushed # Cart an empty cart for user if 'cart_id' in request.session: cart_id = int(request.session['cart_id']) ...
7a5fe35bce0d8ad7adb00c6b8a5677099c728c14
33,640
def preresnet164bn_svhn(classes=10, **kwargs): """ PreResNet-164(BN) model for SVHN from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default Fal...
ebad863e846fd865772e93daf1225dd71654fc6a
33,641
import os import hashlib def compute_hash_info(fd, unit_size=None): """Get MediaFireHashInfo structure from the fd, unit_size fd -- file descriptor - expects exclusive access because of seeking unit_size -- size of a single unit Returns MediaFireHashInfo: hi.file -- sha256 of the whole file ...
6672b0c4245998401199265a00afe24edd174223
33,642
from typing import List def value_map_distribution(value_map: dict, bounds: List[float] = None): """Percent of values that fall in ranges. Args: value_map: dict, value map bound: list of float, boundaries to count values within Returns: dist: dict, distribution values...
09988024007327ee26f27f43d9dc647e78a78915
33,643
def expand_basic(state): """ Simple function which returns child states by appending an available move to current state. """ assert(len(state) < 9) # Calculte set difference to get remaining moves. n = tuple(set(range(9)) - set(state)) # Create tuple of available new states and return...
0889a21b043f6f675d133fed6e3c825eb69f4a82
33,644
def schedule_conv2d_winograd_nnpack_weight_transform(attrs, outs, target): """Schedule conv2d_winograd_nnpack_weight_transform""" with target: return topi.generic.schedule_conv2d_winograd_nnpack_weight_transform(outs)
24882fd6b578fd34f806970c44991dec023e150e
33,645
def bce_loss(input, target): """ Numerically stable version of the binary cross-entropy loss function. As per https://github.com/pytorch/pytorch/issues/751 See the TensorFlow docs for a derivation of this formula: https://www.tensorflow.org/api_docs/python/tf/nn/sigmoid_cross_entropy_with_logits ...
9f9c722fbc8a9be4ed436084097af40241d2a7ee
33,646
import os from pathlib import Path import re def get_best_files(folder, filters): """ Compare all files in a folder that differ only by tags (and extension) and return only the best one according to their tags. If filters is None, return all files. folder: folder containing the files to check ...
a36c681838ccc739b286ff3e0400e503dfe17610
33,647
from typing import List def query_normalised_list(x: str or None, ref: List[NormalisedName]) -> str: """ Internal method for querying a channel/marker against a reference list of NormalisedName's Parameters ---------- x: str or None channel/marker to query ...
a52e0aba0c67be4d82ba2b9d42e5415d0c738263
33,648
def get_reachable_observed_variables_for_inferred_variables(model, observed=set()): """ After performing inference on a BayesianModel, get the labels of observed variables ("reachable observed variables") that influenced the beliefs of variables inferred to be in a definite state. Args mode...
a693d6c57969b38b357a4a57fe2e868650b514b6
33,649
from typing import Dict import logging def load_bias(dataset_name, filtered=False) -> Dict[str, np.ndarray]: """Loads the output of our bias-only model Note that since this produces per-token output, it is only valid on data with the same tokenization as our annotated data. """ if filtered: bias_ids = ...
4cbfa171ac998c7d114f6df04a1ffe14457a98b0
33,650
def isbuildin(name: str) -> bool: """[summary] Checks if name is a keyword or build-in function [description] Arguments: name {str} -- name to be checked Returns: bool -- true if it is a build-in """ blacklist = ["abs", "delattr", "hash", "memoryview", "set", "all", "dict"...
42ac527e1bbc2a50f0fe065fa27c9560eb062448
33,651
def find_dip(pulls): """Find the longest sequence of significant observations in the data""" significant = pulls > 3. if np.sum(significant) == 0: return 0, 0 # Find indices of start and end of each significant sequence changes = np.diff(np.hstack(([False], significant, [False]))) sign...
0f6a7bd33092605cf851b8b10fbb151a9854cb02
33,652
def clip_weights(model, weight_constraint): """ Clip weights of a keras model to be bounded by given constraints. Parameters ---------- model: keras model object model for which weights need to be clipped weight_constraint: Returns ------- model: keras model object ...
9b6fd73b0f04a9889c96a6d823260ce008cab50d
33,653
def scatter_wrapper( self, func, *args, s=None, size=None, markersize=None, c=None, color=None, markercolor=None, smin=None, smax=None, cmap=None, cmap_kw=None, vmin=None, vmax=None, norm=None, norm_kw=None, lw=None, linewidth=None, linewidths=None, markeredgewidth=None, markeredgewidths=Non...
093172b28492864c4462cfc5a8a1e90c89abe1b1
33,654
from datetime import datetime def _coerce_loc_index(divisions, o): """Transform values to be comparable against divisions This is particularly valuable to use with pandas datetimes """ if divisions and isinstance(divisions[0], datetime): return pd.Timestamp(o) if divisions and isinstance(...
818504516d60c3822ac8f2c0e8fda38a2664ea2e
33,655
def triplet_loss(anchor_vector, positive_vector, negative_vector, metric='cosine_dist', margin=0.009): """Computes the triplet loss with semi-hard negative mining. The loss encourages the positive distances (between a pair of embeddings with the same labels) to be smaller than the minimum negative distance ...
6120f3b2ddd581b6dbde427c66643a8d0cc3f6e4
33,656
import hashlib def get_file_hash(filepath: str, blocksize: int = 2**20) -> str: """Return the hash of the given file, with a default blocksize of 1MiB.""" _hash = hashlib.md5() if not isfile(filepath): return _hash with open(filepath, "rb") as f: while True: buffer = f.re...
d1ed17e5d1eb1c38b44b313b245a9244a787014d
33,657
def get_stopwords(): """common stopwords to skip when checking for article names (derived from nltk) """ return [ "i", "me", "my", "myself", "we", "our", "out", "ours", "ourselves", "you", "your", "he", "...
861037bad40204961f205f03399b4b6bbe0e6b2d
33,658
def test_io_dataset_to_in_dataset(fixture_lookup, io_dataset_fixture): """test_io_dataset_to_in_dataset""" args, func, data_func = fixture_lookup(io_dataset_fixture) def f(v): dataset = tf.data.Dataset.range(1000) dataset = dataset.batch(15) dataset = dataset.map(tf.strings.as_string) dataset = d...
f15bfe02e1c89c73c45b36a54800d941c8317172
33,659
def convert_operation_to_task(operation): """Converts an Operation to a legacy Task.""" result = _convert_dict( operation['metadata'], { 'createTime': ('creation_timestamp_ms', _convert_timestamp_to_msec), 'updateTime': ('update_timestamp_ms', _convert_timestamp_to_msec), 'startT...
886cb37a29b8d4de5fc15e9a98946d0a7c3ddebb
33,660
def augment_with_derivatives(V=None, theta=None, M=None, tol=1E-8, symm=True, deflate=True): """ Make a linear basis containing the subspace spanned by V and a third order tensor theta e.g. from modal derivatives by deflation. Parameters ---------- V : ndarray linear basis theta : n...
caa1639f7c0b8c3ae24d633ff3d89bceffccfc2e
33,661
from typing import Union def fomc_statement( dates: Union[str, list[str], None] = None, asDict: bool = False, ) -> Union[pd.DataFrame, dict]: """ Get FOMC statements for given date or dates. `dates`: YYYY-MM-DD, or 'current', or 'previous'. `asDict`: True or False, will return as dictionary i...
356416dee9e68eaed036fcbdeb971f22518e70b0
33,662
def lambda_handler(event, context): """ This is the entry point for the lambda. It will call the main handler, which is within a try/catch so that we can efficiently log any unhandled exceptions to Cloudwatch/Splunk. Args: event (dictionary): contains event data passed in by AWS Lambda ...
dc03440c4bc54a9142cff726d26ae802ed659c2e
33,663
from textwrap import dedent def get_device_number(connection_str): """Return the integer device number from the connection string or raise ValueError if the connection string is not in the format "device <n>" with positive n.""" try: prefix, num = connection_str.split(' ') num = int(num) ...
396a13d4449166e0d63e830b17b07b3b22a208e7
33,664
from click.testing import CliRunner def runner(): """Returns a ```click.testing.CliRunner()`` instance.""" return CliRunner()
8bd6dcdfef85e5afa30ea412a7b7c85b243aac17
33,665
import os import sys def generate_ascii(image_path): """ Generate New Config Parameters ---------- image_path : str Path to image file """ if not os.path.isfile(image_path): print("Invalid image path!") sys.exit(1) # art = ascii_magic.from_image_file( i...
8a95c7251894ce4ed90e5b36e249560ecd65681c
33,666
def bent_plume_ic(profile, particles, Qj, A, D, X, phi_0, theta_0, Tj, Sj, Pj, rho_j, cj, chem_names, tracers, p): """ Build the Lagragian plume state space given the initial conditions Constructs the initial state space for a Lagrangian plume element from the initial values for...
24fdf411c69f06c766fe5a7cc59fb64d83dd7992
33,667
def GetMatrixBase(dim, val = 0): """Return matrix base, with a single sand grain in the middle""" m = np.ones(dim) * val SandFalling(m, 1) return m
f22c025d64c532a86c88e0604847f2c1ca79645b
33,668
def are_resize_confirm_logs_created(logs, instance, guest_hb=False): """ Check if resize-confirm logs have been created """ expected_logs = [{'event_log_id': fm_constants.FM_LOG_ID_VM_RESIZE_CONFIRM, 'severity': fm_constants.FM_ALARM_SEVERITY_CRITICAL}, {'event...
4254ae1175efefa4244544961a638b3d11fe822a
33,669
def find_second_largest2(root_node): """ Time: O(h) Space: O(h) h: height of the tree (O(lg n)); n: # of nodes """ def find_largest(node): if node is None: raise ValueError('Tree must have at least 1 node') if node.right is not None: return find_largest(...
6d012a7fce306cc89f63603462991ac9441d0e57
33,670
from bs4 import BeautifulSoup import html def parse_team_totals(page): """ gets only the totals for a team from the box score of a game (i.e. the last row) """ soup = BeautifulSoup(page, features='lxml') scorebox = soup.find('div', {'class':'scorebox'}) teams = [TEAM_NAME_TO_TEAM(item.text...
311eb570a74dc628e504a92b3282be8e6fbec613
33,671
def ball(p, radius, mass=-1): """Creates a ball that reacts to gravity. :param p: The center point of the ball :type p: (int, int) :param radius: The radius of the ball :type radius: int :param mass: The mass of the shape (defaults to 1) :type mass: int :rtype: shape """ return...
8f0da0982ea6f5622a857e96d47c1ba45731437d
33,672
def cas_proxyCallback(request): """ This is a placeholder for a proxyCallback service needed for CAS authentication """ logger.debug("Incoming request to CASPROXY (Proxy Callback):") return HttpResponse("I am at a RSA-2 or VeriSigned SSL Cert. website.")
f26901adf67475c1697c81da66143ef3afe2c637
33,673
import os def get_secret_id(source="~/.vault-id"): """ Reads a vault user-id (UUID) from a file.""" source = os.path.abspath(os.path.expanduser(source)) user_id = None # pylint: disable=invalid-name if os.path.isfile(source): fd = open(source, "r") user_id = fd.read().strip() ...
6d584be71cbc52fe43b826690348441d4f54c5fd
33,674
import torch from typing import List from typing import Any def decode_actions( node_logits: torch.Tensor, parent_label_logits: torch.Tensor, new_label_logits: torch.Tensor, label_vocab: List[Label], ) -> List[Any]: """ Decode the most likely actions from action logits for the attach-juxtapose...
5ef9f875c3e283c935bf50dfec96211737d5e75d
33,675
def timetz_pack(timetup_tz, dl_pack = dl_pack, mktime = mktime): """ Pack a time; offset from beginning of the day and timezone offset. Given a pair, ((seconds, microseconds), timezone_offset), pack it into its serialized form: "!dl". """ (timetup, tz_offset) = timetup_tz return dl_pack((mktime(timetup), tz_off...
5dc027656c8b5f474ac48c9391fcdcce981c1228
33,676
import inspect def authentication_exempt(handler): """Mark the endpoint handler as not requiring authentication. Note: This only applies when the authentication_required_middleware is being used. """ # Can't set attributes directly on a bound method so we need to # wrap it in a fu...
2e817d2adcf4ae1a08c21de4588c796155851470
33,677
def make_scan(headers, light_ROI=[0, np.inf, 0, np.inf], curvature=np.array([0., 0., 0.]), bins=1, ADU_per_photon=1, detector='rixscam_centroids', min_threshold=-np.inf, max_threshold=np.inf, background=None): """ Make 4D array of RIXS spectra with structu...
0a855a8cfe4102d2299e02d0233f07230ba8d6b6
33,678
import functools def print_args(function): """Decorate the given function to print out it's arguments and return val if not None """ @functools.wraps(function) def wrapper(*args, **kwargs): bound_arguments = bind_args(function, *args, **kwargs) print("{name}({call})".format( ...
ffccb7d3fe73167927b8328bf56f150321ef288c
33,679
def load_data(cutoff: float) -> DataFrame: """ Loads descriptors and binding data for given cutoff. """ # Load ECIF ecif = pd.read_csv(f'Descriptors/ECIF_{cutoff}.csv') # Load ligand descriptors ligand_descriptors = pd.read_csv("Descriptors/RDKit_Descriptors.csv") # Load binding affinity...
80a9709f1034abe7f1b3af1f41bdab06a840e68f
33,680
def phys2digital(mvolts): """ Obtains the digital difference value in the signal that corresponds to a certain physical magnitude variation. """ return mvolts * ADCGain
523c06eea2ce23d4ba18e709e185ebb8bae09428
33,681
from typing import Any def resolve_mock_target(target: Any) -> str: """ `mock.patch` uses a str-representation of an object to find it, but this doesn't play well with refactors and renames. This method extracts the str-representation of an object. This method will not handle _all_ kinds of objects, ...
4c7520d2b17daaf79d1de2d9eca4f615e401fb12
33,682
import math import heapq def a_star_dist(start_state: frozenset, end_state: frozenset): """A* algorithm to calculate minimum energy needed to traverse the given states.""" start_node = Node(0, start_state) open_pq = [start_node] g_scores = defaultdict(lambda: math.inf) g_scores[start_state] = 0 ...
b55160bd50e245a0d8236f7c7c402933c8bc665a
33,683
def get_calc_data(stock_code, s, e, fq='qfq', drop_columns=['code', 'preclose', 'adj'], scaler=['amount', 'volume'], scaler_func=sklearn.preprocessing.MinMaxScaler): """获取计算用数据源 Args: fq: 是否采用复权数据。默认使用前复权。如果不需要复权则传''即可。 stock_code: s...
d8d382ff1523cfdc95753dcc2f73c758301a416c
33,684
def encode_add_validator_and_reconfigure_script( sliding_nonce: st.uint64, validator_name: bytes, validator_address: AccountAddress ) -> Script: """# Summary Adds a validator account to the validator set, and triggers a reconfiguration of the system to admit the account to the validator set for the syst...
6a19907eaa0b1e94ec8339f783540f01555bd599
33,685
import numpy def get_microphone(): """Return raw data from microphone as Numpy array Default format will be 16-bit signed mono. Format will match audio playback. You must call tick() every frame to update the results from this function. """ glock.acquire() d = gmicdata glock.releas...
755072e394603f22282328b553a3ada5c101bd1e
33,686
from typing import OrderedDict from typing import ChainMap def _expand_arrays(raw_variables, old_variables={}, compat='identical'): """Expand a dictionary of variables. Returns a dictionary of Variable objects suitable for inserting into a Dataset._arrays dictionary. This includes converting tuples ...
04ce236b447d26e7d7c748dd155c16f83d2b526e
33,687
import os import subprocess def build_and_push_docker_image(args): """docker-py doesn't seem to work, so use subprocess to call Docker""" # This could be configurable, but there isn't much point. HTTP_PORT = 8081 image_name = f"{args.dockerhub_repo}/scpca_portal_api" # Change dir so docker can s...
3878599b53323dcb6dcddced6eda0ec421ba7781
33,688
import logging def redundant_peaks(usrdata): """Remove redundant, often ambiguous peaks by keeping the peak with the highest ion score""" peaks = usrdata.sort_values(by="IonScore", ascending=False).drop_duplicates( subset=["SpectrumFile", "SequenceModi", "Charge", "PrecursorArea"] ) peaks[...
da3413e4239c68168e1c4cd08feafd0320fcb8d5
33,689
import importlib def getattr_in_module(module_name: str, func_name: str): """ 在某个模块中获取属性 Args: module_name: 模块名 func_name: 属性名 Returns: 属性 """ m = importlib.import_module(module_name) return getattr(m, func_name)
e0ceec50c063cea8350c04a4f048ca53d75ab5f6
33,690
def codeblock(request): """Parametrized fixture of each convention codeblock.""" return request.param
52209ca4c84c873a33d9b6b3dc4ba044ebcd9513
33,691
import numpy def cp_ls_cholesky_factor_objective(beta_gamma, norb, nthc, cholesky_factor, calcgrad=False): """cholesky_factor is reshaped into (norb, norb, num_cholesky) Cholesky factor B_{ab,x} Least squares fit objective ||B_{ab,x} - \sum_{r}beta_{a,x}beta_{b,x}gamma_{ab,x}|| This function provid...
cfa02ca214c0d0638243f916afdbfa052dbc9efe
33,692
def volumes(jukebox_name, slot_id=[], as_object=False, p5_connection=None): """ Syntax: Jukebox <name> volumes Description: Returns a list of all volumes currently loaded in the <name> jukebox. To update the list of the volumes in the jukebox, use the inventory method. Return Values: -On Suc...
8c43a598a8d3ec55bcc3fd07b4b0f0ad1c585bcb
33,693
def calculate_psi(cube, cfg): """Calculate temperature variability metric psi for a given cube.""" window_length = cfg.get('window_length', 55) lag = cfg.get('lag', 1) psi_years = [] psis = [] # Moving average for yr_idx in range(cube.shape[0] - window_length): slc = slice(yr_idx, y...
641b55232dc4c845332aac5f28aef78c26783c43
33,694
import torch def _get_product_features(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: """ Get outer product of 2 tensors along the last dimension. All dimensions except last are preserved. The last dimension is replaced with flattened outer products of last-dimension-vectors from input tensors...
cf438a799b749563ea9509184cf117f4075730ab
33,695
def resume_job(args, wording): """ used by fg and bg to resume a job either in the foreground or in the background. """ _clear_dead_jobs() if len(tasks) == 0: return "", "There are currently no suspended jobs" if len(args) == 0: tid = tasks[0] # take the last manipulated task b...
235db36f3d4c59071b53f61777c908eccd86aa5c
33,696
def drop_me(message): """This function removes user/chat id into a database. Parameters ---------- message : telebot.types.Message The message object. Returns ------- msg : str User/Chat alert list addition/removal. """ helpers.start_connection().query(""" DELETE FROM `mooncake-304003.misc.ps5-broa...
dd6c44b42e1809ff887ca6a99d8d3d4ecc63e882
33,697
def cmpd_to_pt(cmpd, els): """ Args: cmpd (str) - chemical formula els (list) - ordered list of elements (str) in triangle (right, top, left) Returns: (x, y) for compound """ tri = [CompAnalyzer(cmpd).fractional_amt_of_el(el) for el in els] return triangle_to_square(...
aafc4d1a1821ee2a5e41f1540f114f8899a8485a
33,698
def si_unit_lookup_table(units=UNITS): """ Creates a lookup table from all possible input unit names and symbols to their corresponding SI unit. """ return { **{ u.name: (u.si_equivalent, u.coefficient) for u in units if u.name is not None}, **{ u.symbol: (u.si_equivalent...
a859dc78dca4cd31728fdda226609d67fccff7b1
33,699