content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def stddev(data, ddof=0): """Calculates the population standard deviation by default; specify ddof=1 to compute the sample standard deviation.""" n = len(data) if n < 2: raise ValueError('variance requires at least two data points') ss = _ss(data) pvar = ss/(n-ddof) return pvar**0.5
3ec3576aa14965b98d9ef44a3d77b69d9a2913a6
3,614,700
def build_model_with_cfg( model_cls, variant: str, pretrained: bool, default_cfg: dict, model_cfg= None, feature_cfg= None, pretrained_strict: bool = True, pretrained_filter_fn = None, pretrained_custom_load = False, kwargs_filter = None, ...
4d127be55ecbc557c5a146ecf87d23307cb785e5
3,614,701
def load_data_and_labels_lemonde(filepathXml): """ Load data and label from Le Monde XML corpus file the format is ENAMEX-style, as follow: <sentence id="E14">Les ventes de micro-ordinateurs en <ENAMEX type="Location" sub_type="Country" eid="2000000003017382" name="Republic of France">France</E...
a1d624d12a1f4ceda49c62cb2608f48301e62dd2
3,614,702
def view_user_issues(username): """ Shows the issues created or assigned to the specified user. :param username: The username to retrieve the issues for :type username: str """ if not pagure_config.get("ENABLE_TICKETS", True): flask.abort( 404, description="Tic...
dfbbc5932080a7e0fa18ebb04d2b553fe57d9862
3,614,703
def i0(x): """ Modified Bessel function of the first kind, order 0. Usually denoted :math:`I_0`. This function does broadcast, but will *not* "up-cast" int dtype arguments unless accompanied by at least one float or complex dtype argument (see Raises below). Parameters ---------- x : ...
665861f872be896553b2b57f5de8ca09b6dc7bfb
3,614,704
def generate_registers_sifive_clic0_clicintip(intr, addr): """Generate xml string for riscv_clic0 intip register for specific interrupt id""" return """\ <register> <name>clicintip_""" + intr + """</name> <description>CLICINTIP Register for interrupt id """ + ...
d3260a11f670a90affaf0284c2f74afac9f6c4a4
3,614,705
import json import time def close_poll(): """ Closes a poll. """ form = DeletePost() if form.validate(): try: post = SubPost.get(SubPost.pid == form.post.data) except SubPost.DoesNotExist: return json.dumps({'status': 'error', 'error': _('Post does not exist')}) ...
1514e0430f808a6e9e9a7f0b377767bdc2436c2b
3,614,706
def TUInt_JavaUIntToCppUInt(*args): """ TUInt_JavaUIntToCppUInt(uint const & JavaUInt) -> uint Parameters: JavaUInt: uint const & """ return _snap.TUInt_JavaUIntToCppUInt(*args)
3d845fab201781d2d23a7d5d6dab2cedc94863cf
3,614,707
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry): """Unload a config entry.""" if hass.data[DOMAIN].get(DISPATCHERS) is not None: for cleanup in hass.data[DOMAIN][DISPATCHERS]: cleanup() if hass.data[DOMAIN].get(DATA_DISCOVERY_INTERVAL) is not None: hass.dat...
bc862de99608e8f8668ddf5d22bc4cb526277447
3,614,708
def extract_pdbs(input_filelines): """ Given a list of lines from SSM output txt, returns a list of upper case PDBs The input file should have a range of lines enumerating the PDBS that looks like this: ..... ..... ## Structure Nres Nsse RMSD Q-score 1 PDB 5cxv...
52270f03ba2a4eca6308327583467bc391346bea
3,614,709
def result(): """Route to results page after submitting form on index page""" # declare form from form.py form = pathToVideo() # user option selections from form saved as sessions to be accessible via different routes session['firstPath'] = form.firstPathSelect.data session['secondPath'] = form...
c4f73bbdd749360c99d64d9106020b61da904235
3,614,710
def is_conv2d(module): """Determine Conv2d.""" # depth-wise convolution not in pruned search space. return isinstance(module, Conv2d) and not is_depth_wise_conv(module)
db7b1d883900a532e183332998ade2723d98f681
3,614,711
def make_date(d_str: str) -> Date: """ Returns new Date instance from given date string REQUIRES: d_str is in format 'yyyy-mm-dd' """ year = int(d_str[:4]) month = int(d_str[5:7]) day = int(d_str[8:]) return Date(year, month, day)
ea09489abba828edcdbc33ff545bf09b88b019ec
3,614,712
def get_device_id(): """ GEt unique id for device""" flash_id = '{0:x}'.format(esp.flash_id()) manufacturer = flash_id[-2:] device_id = flash_id[2:4] + flash_id[0:2] return (manufacturer, device_id)
1f7ecc90b8ef6c844d64ee7acab79c69e7727a07
3,614,713
import torch def view_complex_native(x: torch.FloatTensor) -> torch.Tensor: """Convert a PyKEEN complex tensor representation into a torch one using :func:`torch.view_as_complex`.""" return torch.view_as_complex(x.view(*x.shape[:-1], -1, 2))
14e74f1c8b5e6de673c962e4381e74026d3d3db2
3,614,714
def cross_corr_norm(patch_0, patch_1): """ Returns the normalized cross-correlation between two same-sized image patches. Parameters : patch_0, patch_1 : image patches """ n = patch_0.shape[0] * patch_0.shape[1] # Mean intensities mu_0, mu_1 = patch_0.mean(), patch_1....
213100b174993baa07ea685b23541d3dfe49ace8
3,614,715
from docopt import docopt import logging import os def main(args=None): """Run program.""" args = docopt(__doc__, version=__version__) if args.get('--verbose'): log.setLevel(logging.INFO) elif args.get('--quiet'): log.setLevel(logging.ERROR) elif args.get('--debug'): log.s...
1a7482ecb441dcf89c2b6d3236828120ae83a71d
3,614,716
from datetime import datetime def datetime_to_W3CDTF(dt): """Convert from a datetime to a timestamp string.""" return datetime.datetime.strftime(dt, W3CDTF_FORMAT)
debdce838987c8815fec977761f760a4fba62aa1
3,614,717
def get_device_value_oid(ip, oid, community_string="public"): """ Get value from specified device with OID Args: ip: The device's IP address oid: SNMP OID community_string: The community string for the network. Usually 'public' or 'private' Returns: ...
bf5ecb3519fca3d2d6343e35a540d37a70e698e6
3,614,718
def get_flip_set(index): """Make flip set""" n = 1 while n <= index: n *= 2 def get(n, j): if j <= 1: return {b for b in range(j)} n_half = n // 2 if j < n_half: return get(n_half, j) f = {b + n_half for b in get(n_half, j - n_half)} ...
3174b9bab59ae67e9f869fddd9c0a6669f742a45
3,614,719
def cosineDistance(a, b): """ Calculates the cosine distance between lists of numbers `a` and `b`. Args --- `a : float[]` The first list of floats (or ints) `b : float[]` The second list of floats (or ints) Returns --- `distance : float` The distance between `a` and `b` """ n =...
a697e17c2483441995c3a04652edd2bcac287539
3,614,720
def tensor2sparse(tensor): """Convert pytorch tensor to sparse csr matrix.""" return sparse.csr_matrix(tensor.detach().cpu().numpy())
dbd33450abd534eafa48fdae896afefcf6bdefad
3,614,721
from typing import Any from typing import Callable import click def optional(*decls: str, nilstr: bool = False, **attrs: Any) -> Callable[[FC], FC]: """ Like `click.option`, but no value (not even `None`) is passed to the command callback if the user doesn't use the option. If ``nilstr`` is true, ``-...
dae9c0b60d4d7f0bdbab4966e30f8b237c6af17a
3,614,722
def get_model_base() -> dict: """The base model for running a WLTC experiment. It contains some default values for the experiment but this model is not valid - you need to override its attributes. :return: a tree with the default values for the experiment. """ instance = { "unladen_ma...
cfa1bb87a6f6ffb6c88863a27d75fd9bf2a13cff
3,614,723
def triplet_loss(y_true:tf.Tensor, y_pred:tf.Tensor, alpha:float = 0.2): """ -- Explanation : this function compares the triplet loss () -- Args: y_true -- true labels, y_pred -- python list containing three objects: anchor -- the encodings for the anchor images, of shape (None, 12...
c46161f5253a9969110d2867c309982d1f1db119
3,614,724
def x_view_function(): """ underspecified library view """ return Response(1.234)
a85460fd90978277cfc5c9c4253e2d056c8115c2
3,614,725
def mkXRDTag(t): """basestring -> basestring Create a tag name in the XRD 2.0 XML namespace suitable for using with ElementTree """ return nsTag(XRD_NS_2_0, t)
c770afdcf21576d761e111afc8556f7c37745099
3,614,726
def auth( func=None, roles=None, permissions=None, requires=None, login_redirect=None, should_remember_referrer=True): """Guards a controller action against unauthorized and unauthenticated access. Args: roles (list|string): A list of roles that are able ...
43916198f76f2e840ba6b4535117a35a54d70294
3,614,727
def site_stat_stmt(table, site_col, values_col, fun): """ Function to produce an SQL statement to make a basic summary grouped by a sites column. Parameters ---------- table : str The database table. site_col : str The column containing the sites. values_col : str T...
c704d5687effd3c12abb3feecde9041eb88aae7a
3,614,728
def to_time_units(obj, freq): """Multiply each element with `freq_delta` to get result in time units.""" if not checks.is_array(obj): obj = np.asarray(obj) return obj * freq_delta(freq)
86ca6c833d32e9e03b4afcba8462f69fa42670d4
3,614,729
import random def perform_learning_step(epoch): """ Makes an action according to eps-greedy policy, observes the result (next state, reward) and learns from the transition""" def exploration_rate(epoch): """# Define exploration rate change over time""" start_eps = 1.0 end_eps = 0....
e10ccdaeffeb37800ca52db193dbfd6426ebc9dd
3,614,730
def read_bhrc(filename, **kwargs): """Read the Iran BHRC strong motion data format. Args: filename (str): path to BHRC data file. kwargs (ref): Other arguments will be ignored. Returns: list: Sequence of one StationStream object containing 3 StationTrace objects...
3d86478e22189b3910ca6e509911437fb2bfbb58
3,614,731
def random_pdf(x, dx, seed_i=False, n_iter=1000, silent=True): """ Created on 24/06/2016 Modified on 29/06/2016 to reverse shape """ len0 = len(x) if not silent: print(len0) # Mod on 29/06/2016 x_pdf = np.zeros((len0, n_iter), dtype=np.float64) # x_pdf = np.zeros((n_iter, l...
aa5940ae6913ab40aeb10d319b7e0bdab01a0453
3,614,732
import itertools def vertical_split(im): """ Split an image vertically. This works for member list as well as (well, most times) scouting screenshots :param im: screenshot data :return: the ratio for resizing the screenshot, a list of (start, stop) chunks to use when looping """ im_gray = cv2...
78b2c423f72f0c75ce7712ee8f74a1564caa2990
3,614,733
def interp2d(image): """ Bilinear interpolation method to be used for upscaling Args: tensor_nchw (tensor): tensor of shape (N, C, H, W) Return: tensor of shape (N, C, Hout, Wout), where Hout and Wout are computed by applying the scale factor to H and W """ # return ...
14a40dcf0b3a22d9493b99c0cf5c96e41f37fd2e
3,614,734
def create_app(config_object="chaos_genius.settings"): """Create application factory, as explained here: http://flask.pocoo.org/docs/patterns/appfactories/. :param config_object: The configuration object to use. """ app = Flask(__name__.split(".")[0]) app.config.from_object(config_object) regis...
d3dab2a874518b1f942d91b3c0c76f2ddc50e212
3,614,735
def get(cls, key): """ Get an entity by key """ return build_key(cls, key).get()
58113088582c61dc67bb4d0366a9f4f35256c959
3,614,736
def page_not_found(__=None): """ What to return if a user requests an endpoint that doesn't exist. """ print(app.root_path) return transiter_error_handler(exceptions.PageNotFound(flask.request.path))
21dd68dc51607bee937f327c5c8ac864d5309029
3,614,737
import copy def rational_diagonal_form(self, return_matrix=False): """ Returns a diagonal form equivalent to Q over the fraction field of its defining ring. If the return_matrix is True, then we return the transformation matrix performing the diagonalization as the second argument. INPUT: ...
9bee64eabd0a4550455e99542ff7db3c89526892
3,614,738
def _format_source_error(filename, lineno, block): """ A helper function which generates an error string. This function handles the work of reading the lines of the file which bracket the error, and formatting a string which points to the offending line. The output is similar to: File "foo.py", li...
32d093e53811415338877349ca8e64b0e9261b1d
3,614,739
def calc_exposure(k, src_rate, bgd_rate, read_noise, neff): """ Compute the time to get to a given significance (k) given the source rate, the background rate, the read noise, and the number of effective background pixels ----- time = calc_exposure(k, src_rate, bgd_rate, read_noise, neff) ...
993853d244cfa5c6619300def02294a2497d78df
3,614,740
def decode_image(contents, channels=None, name=None): """Convenience function for `decode_gif`, `decode_jpeg`, and `decode_png`. Detects whether an image is a GIF, JPEG, or PNG, and performs the appropriate operation to convert the input bytes `string` into a `Tensor` of type `uint8`. Note: `decode_gif` return...
2d875772abbd02b716922880c88b63b8c080eed8
3,614,741
import os def exec_mkdir(dirname): """ Create a directory. Parameters ---------- dirname: str The full path of the directory. Returns ------- bool: True on success, False otherwise. """ _logger.debug('__ Creating %s.', dirname) try: if not o...
179d8aeb13c53710904ccc824046636ba38253aa
3,614,742
def get_all_round_info_from_cache(): """Returns a dictionary containing all the round information. example: {"rounds": {"Round 1": {"start": start_date, "end": end_date,},}, "competition_start": start_date, "competition_end": end_date} """ rounds_info = cache_mgr.get_cache('r...
e996b97290112116c65c66d9db3fe7c19f9b242c
3,614,743
def type_or_null(names): """Return the list of types `names` + the name-or-null list for every type in `names`.""" return [[name, 'null'] for name in names]
72cbefcbba08c98d3c4c11a126e22b6f83f4175b
3,614,744
def scratch(request, slug=None): """ Get or create a scratch """ if request.method == "GET": db_scratch = get_object_or_404(Scratch, slug=slug) return Response(ScratchSerializer(db_scratch).data) elif request.method == "POST": data = request.data if "target_as...
d7c13689f7f7a4bb97c1c4d8e2fb20636f1cbf7a
3,614,745
def variables_pool(variable, question='Variable to analyze'): """ :param variable: the variable chosen from variable pool in your dataframe :param question: default parameter ("Variable to analyze") don't :return: """ def guide(diz): """ function that guides user to chose the ri...
fcff9eaa1467d96251ba08eaa433aa05b7b769f2
3,614,746
from sys import path def add_topic(): """ Endpunkt `/topic`. Route zum hinzufügen eines Themas. """ try: if "config" not in request.files: err = flask.jsonify({"err_msg": "Missing File"}) return err, 400 if "name" not in request.form: err = fla...
f42ff7a64f85672ccb3cd151fbb9967b74de02fa
3,614,747
import torch def quadratic_matmul(x: torch.Tensor, A: torch.Tensor) -> torch.Tensor: """Matrix quadratic multiplication. Parameters ---------- x : torch.Tensor, shape=(..., X) A batch of vectors. A : torch.Tensor, shape=(..., X, X) A batch of square matrices. Returns ----...
78335f6a57f34701f3f1fe9b8dd74e9b8be686a3
3,614,748
def get_global_step(estimator): """Return estimator's last checkpoint.""" return int(estimator.latest_checkpoint().split("-")[-1])
11b4a96f74d029f9d9cc5a0fcc93da7504729eb7
3,614,749
from src.priorityq import PriorityQ def test_q(): """Test fixtures of priority qs.""" q0 = PriorityQ() q1 = PriorityQ() q1.insert('sgds', 10) q1.insert('another', 9) q1.insert('another', 8) q1.insert('another', 7) q1.insert('another', 6) return q0, q1
fd5e9cb0a0110b96c34bbc9b85e44596d1180dc5
3,614,750
def make_mlb_classifier_and_data_with_feature_extraction_pipeline(): """Create data set and classifier for testing a multi-label classification scenario with a feature extraction pipeline. """ newsgroups_train = fetch_20newsgroups(subset="train") X, Y = newsgroups_train.data, newsgroups_train.targe...
478077dbecde141e7d92f00cfe9e8d961d14a1b0
3,614,751
def read_volume(filepath, dtype=None, return_affine=False): """Return numpy array of data from a neuroimaging file. Args: filepath: path-like, path to volume file. dtype: dtype-like or str, data type of the volume data. return_affine: boolean, if true, return tuple of volume data and ...
d581155c06599b6e987db5a7fdc2f62e4918e25b
3,614,752
import traceback import json def Import(context, request): """ FOSS FIAStar analysis results """ infile = request.form['data_file'] fileformat = request.form['format'] artoapply = request.form['artoapply'] override = request.form['override'] sample = request.form.get('sample', ...
7536c920b36c8158976b02f6c75cbce1ac8e3bf7
3,614,753
def meantime_blockedby_pp_hat(arr_rate, pp_mean_svctime, pp_cap, pp_cv2_svctime): """ Approximate unconditional mean time blocked in ldr or csect waiting for a pp bed. Modeling pp as an M/G/c queue and using approximation by Kimura. """ pp_svcrate = 1.0 / pp_mean_svctime meantime = qng.mgc_mean...
5c7e8de26b1f131e7e9a02743f51e2c62ef5023d
3,614,754
def _combine_grad(evoked, picks): """Create a new instance of Evoked with combined gradiometers (RMSE).""" def pair_and_combine(data): data = data ** 2 data = (data[::2, :] + data[1::2, :]) / 2 return np.sqrt(data) picks, ch_names = _grad_pair_pick_and_name(evoked.info, picks) th...
5469cc60f27be8646f9f20fa28b3e305d6d1bf38
3,614,755
def each_segment(time_ci, energy_ci, rate_ref, meta_dict,\ start_time, end_time): """ Turns the event list into a populated histogram, stacks the reference band, and makes the cross spectrum, per segment of light curve. Parameters ---------- time_ci : np.array of floats 1-D array of...
043fa5e18021f54ddc4eb7da1e1c45c50453ee8c
3,614,756
import torch def box_iou(boxes1, boxes2): """Compute pairwise IoU across two lists of anchor or bounding boxes. Defined in :numref:`sec_anchor`""" def box_area(boxes): return ((boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1])) # Shape of `boxes1`, `boxes2`, `a...
c358c15b99d0e742487a92630ff927606ad6d896
3,614,757
import os def getBranchPath(path): """Get a path rooted in the current branch. @param path: A path relative to the current branch. @return: A fully-qualified path. """ currentPath = os.path.dirname(__file__) fullyQualifiedPath = os.path.join(currentPath, '..', path) return os.path.abspath...
57897e58b57c704cea63549d437f22f96830d226
3,614,758
import horovod.torch as hvd import horovod.torch as hvd from typing import Tuple from typing import Optional import torch def _get_train_sampler(val_ratio:float, val_fold:int, trainset, horovod, target_lb:int=-1)->Tuple[Optional[Sampler], Sampler]: """Splits train set into train, validation sets, stratifi...
3cf56ed690a4f43795d961f0eb669bc3d133baf5
3,614,759
def feature_reconstruction_loss(base, output): """ Compute the content loss for style transfer. Inputs: - output: features of the generated image, Tensor with shape [height, width, channels] - base: features of the content image, Tensor with shape [height, width, channels] Returns: - scala...
aab47546c68a83e687eeabe77d89fdb7aa51ab8b
3,614,760
import time def attempt_to_acquire_lock(s3_conn, lock_uri, sync_wait_time, job_name, mins_to_expiration=None): """Returns True if this session successfully took ownership of the lock specified by ``lock_uri``. """ key = _lock_acquire_step_1(s3_conn, lock_uri, job_name, mins...
714eb9daaaa242aeb6d877a10b1fffaf353a606e
3,614,761
import torch def multiclass_nms( multi_bboxes, multi_scores, score_thr, nms_cfg, max_num=-1, score_factors=None, multi_attrs=None, multi_feats=None, ): """NMS for multi-class bboxes. Args: multi_bboxes (Tensor): shape (n, #class*4) or (n, 4) multi_scores (Tenso...
4f7075c93b0c4c7fc5d4905237a35bb48f445314
3,614,762
import torch def get_device(): """ Get the device on which running.""" return torch.device("cuda" if torch.cuda.is_available() else "cpu")
9ab3e98a98f9f6c1630ee4bd76c170efae029d68
3,614,763
def make_png_thumbnail(): """Make a thumbail of the first page of a PDF and return it. :return: A response containing our file and any errors :type: HTTPS response """ f = request.files["file"] max_dimension = int(request.args.get("max_dimension")) with NamedTemporaryFile(suffix=".%s" % "pd...
fefc14618bea13693878983c9630280b32584115
3,614,764
import uuid def rand_uuid(): """Generate a random UUID string :return: a random UUID (e.g. '1dc12c7d-60eb-4b61-a7a2-17cf210155b6') :rtype: string """ return str(uuid.uuid4())
fc35e154eeab62988bcd96799ce0f688f4ec427a
3,614,765
import logging def get_logfile_name(): """ Return the current logfile name """ return logging.getLoggerClass().root.handlers[0].baseFilename
28b5d6628890a6cccb09a68f24e6257d425c3833
3,614,766
def sign(x, y): """Fortran's sign transfer function""" return x * tf.math.sign(y)
05f44a6f8955b50318e65e3ad0a633c2acaf8d8d
3,614,767
def filter_linksearchtotals(queryset, filter_dict): """ Adds filter conditions to a LinkSearchTotal queryset based on form results. queryset -- a LinkSearchTotal queryset filter_dict -- a dictionary of data from the user filter form Returns a queryset """ if "start_date" in filter_dict: ...
96a7e816e7e2d6632db6e6fb20dc50a56a273be9
3,614,768
def mean(samps): """ Find the mean point forecasts. """ return np.mean(samps, axis=0)
8821fe547e1b1f12626544ca2d8056b725cf00e1
3,614,769
import os def merge_data(path_data, filename_participants): """ Merge the different datasets. :param path_data: string :param filename_participants: string :return: dataframe, dictionary """ d = {} d_features = {} for i in os.listdir(path_data): path0 = os.path.join(path_d...
fa72cf58f008d8d79dbf56664edd10163d53cbf9
3,614,770
def all(): """ Returns all W2S Scenarios in [GWh/a] :return: """ sc = (read("szenarien_w2s.xlsx") .pipe(start_pipeline) .pipe(NaNtoZero) .pipe(format_df) .pipe(convert_PJ_to_GWH) ) return sc
7cac87baf53c7bfeda5bd2158801628c989178ce
3,614,771
def test_download_cache_hit(mocker): """Check that download is not repeated on cache hit.""" data = b"Hello, world" data_checksum = "4ae7c3b6ac0beff671efa8cf57386151c06e58ca53a78d83f36107316cec125f" cached_path = cache_path(f"downloads/{data_checksum}") # Tidy up from a previous test, if applicable...
244e483ccef50c877e5023d0dd857e2f92ca34b9
3,614,772
import transformers import torch import tqdm def eval_two_span( val_data: data.DataLoader, model: transformers.PreTrainedModel, loss_func: nn.modules.loss._Loss, dev: torch.device=None ) -> float: """Evaluate a two span edge probing model. Args: val_data: valid...
6873dc6e5dcbd5d19ee7321b42f5bac7aa63d2f8
3,614,773
import json import logging def gen_tensorflow_client_string(generated_tensor_data, model_name): """ Generate TensorFlow SDK in Python. Args: generated_tensor_data: Example is {"keys": [[1.0], [2.0]], "features": [[1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1]]} """ code_template = """#!/usr/...
63f197459d1995f4621523973ade157838836b7f
3,614,774
import csv def get_column(path, c=0, r=1, sep='\t'): """ extracts column specified by column index assumes that first row as a header """ try: reader = csv.reader(open(path, "r"), delimiter=sep) return [row[c] for row in reader] [r :] except IOError: print('list_rows: f...
036a1630417224474e8bfe7a9c038a04bd3ea0d5
3,614,775
def part2(lines): """ >>> part2(load_example(__file__, "24")) 19 """ return run(lines, Part2)
bfd2aaf0aff01365c3825a1b4608670739f56875
3,614,776
import uuid def get_example_comments(): """ returns example comments on a submission. """ user1 = 24601 user2 = 42 user_ids_to_uuids = {user1: uuid.uuid4(), user2: uuid.uuid4()} user_ids_to_names = {user1: 'Atlassian_bot', user2: 'Cool_McJones_ASE'} return {'tester_messages': [ { ...
b64b9878f375440cd6745e98f064175e80145610
3,614,777
def add_md_padding(data, endian='big'): """Merkle-Damgard padding Args: data(string) Returns: data+padding(string) """ size = len(data) & 0x3f # len_in_bytes % 64 if size < 56: size = 56 - size else: size = 120 - size p = bytes(b'\x80') + bytes(b'\x00'*63) p = p[:si...
6138c66f854b8746db78ba5e8979e88d831d3a84
3,614,778
def list_fridge(): """ List all items in the frigde. :return: dict with all items and amounts :rtype: dict """ return MOCK_FRIDGE
56988ae3f27e92b2afdfcd404f15ab396c89468b
3,614,779
def evaluate_hessian_val(A, point, direction): """ Returns the value of Hessian function in the given direction. """ hess_p = (A - np.diag((A.dot(point)).dot(point.T))).dot(direction) return np.sum(hess_p * direction)
92c9c62d2e80bf172b2e04c3e533b0cbf021e244
3,614,780
import numpy def frustrated_loop(graph, num_cycles, R=float('inf'), cycle_predicates=tuple(), max_failed_cycles=100, planted_solution=None, seed=None): """Generate a frustrated-loop problem. A generic frustrated-loop (FL) problem is a sum of Hamiltonians, each generated from a single ...
f1e7bccdb17c9703c9b4fa78bc3da4ce583c88a9
3,614,781
def _projection_unit_simplex(x: jnp.ndarray) -> jnp.ndarray: """Projection onto the unit simplex.""" s = 1.0 n_features = x.shape[0] u = jnp.sort(x)[::-1] cssv = jnp.cumsum(u) - s ind = jnp.arange(n_features) + 1 cond = u - cssv / ind > 0 idx = jnp.count_nonzero(cond) threshold = cssv[idx - 1] / idx.a...
9d0cae071d27b2a105da9be945f59c50d5462e60
3,614,782
def channel_id_str_to_bytes(channel_id_str): """ Args: channel_id_str: string representation of channel id Returns: bytes representation of channel id """ assert type(channel_id_str) in [str, bytes] if isinstance(channel_id_str, bytes): return channel_id_str qid_byte...
2267fa7d810ca09a6498c8ab9cfffc0d6c8fcb9e
3,614,783
from typing import Optional def compiled( model: tf.keras.Model, loss=None, metrics=None, optimizer=None, run_eagerly: Optional[bool] = None, # steps_per_execution: Optional[int] = None, ) -> tf.keras.Model: """Mutate model in-place by compiling and return the model for convenience.""" ...
809497352df4ac3ed609e525c3916bf6e506b80a
3,614,784
def vtkVariantExtract(v, t=None): """ Extract the specified value type from the vtkVariant, where the type is in the following format: 'int', 'unsigned int', etc. for numeric types, and 'string' or 'unicode string' for strings. You can also use an integer VTK type constant for the type. Set the ty...
9d34e1b0e989d6b36b78f97eab7bbc9d1e49740e
3,614,785
import collections import itertools def _create_region_groups(const_regions, psvs, genome, max_dist=1000): """ Groups closeby const regions if they have the same CN even if there is a region with a different CN between them. """ psv_ix = 0 n_psvs = len(psvs) # Key: copy_num, value: list of Pl...
5f75d088d31ea5b889ab5f77dbd7ee7abbe18dad
3,614,786
import imp def _LoadConfigModule(name: str, path: str): """Loads a script from external file specified by path. Unprefixed path is looked for in the current working directory using regular file open operation. This should work with relative config paths. Args: name: Name of the new module. path: Pat...
cd2d15bdd357c5efcfe15648a5fca437f3cdda8b
3,614,787
def _parse_icq(fileobj): """Parse a International Comet Quarterly (ICQ) format file.""" df = pd.read_fwf(fileobj, colspecs=list(ICQ_COLUMNS.values()), names=ICQ_COLUMNS.keys(), header=None) return df
40bd2302991e40e014caff6e3b4e4020ff1fa82b
3,614,788
def IperfTCP(target_src, target_dst, dst, length, window=None): """Convenience method for starting a TCP IperfSet. See IperfSet for more details. Args: target_src: A single host or list of hosts. target_dst: A single host or list of hosts (1:1 with target_src). dst: A single address/hostname or a li...
98a94718e29d116acfaadd18bf20855fa2dfadb5
3,614,789
def plot_riemann(states, s, riemann_eval, t, fig=None, color='b', layout='horizontal',conserved_variables=None): """ Take an array of states and speeds s and plot the solution at time t. For rarefaction waves, the corresponding entry in s should be tuple of two values, which are the wave speeds that bou...
af1a53cd84e4e51ee0934c2fe303465fab338636
3,614,790
def find_in_list(list_one, list_two): """Find and return an element from list_one that is in list_two, or None otherwise.""" for element in list_one: if element in list_two: return element return None
9376b38a06cadbb3e06c19cc895eff46fd09f5c1
3,614,791
from typing import List from typing import Tuple def getElementById(idName: str, fileName: str) -> List[Tuple[int, str]]: """Returns first matching tag from an HTML/XML document""" nonN: List[str] = [] with open(fileName, "r+") as f: html: List[str] = f.readlines() for line in html: ...
e0888a41c7cbdf4a0ef449bbbfb23ed650e2ab12
3,614,792
def skip_after(timeout: int or float): """ Creates an async pool with an associated timeout, but without raising a TooSlowError exception. The pool is simply cancelled and code execution moves on """ assert timeout > 0, "The timeout must be greater than 0" mgr = TaskManager(timeout, False) ...
1015389638164a2d1131c6a634e918e66645b2d2
3,614,793
from pathlib import Path def read_peak_correlations(file_name): """ Read in the custom peak correlation Excel file provided by JAX. """ df = pd.DataFrame(pd.read_excel(file_name)) tab = Table.from_pandas(df) #read(file_name, format="ascii.csv") # tab.rename_column('\ufeffMm_chr', 'Mm_chr') ...
f1fc20cfec167cf9aaa0284e4cb08e7cf4fdb74e
3,614,794
import sys import pickle def load_pickle(fname): """Loads a pickle file to memory. Parameters ---------- fname : str File name + path. Returns ------- dict/list Data structure of the input file. """ assert fname, 'Must input a valid file name.' if sys.version...
d5890aec8fd491b89b81e9e6c01ee658b1a843bd
3,614,795
import torch def sample(model, block_size, x, steps, temperature=1.0, sample=False, top_k=None): """ take a conditioning sequence of indices in x (of shape (b,t)) and predict the next token in the sequence, feeding the predictions back into the model each time. Clearly the sampling has quadratic compl...
7d5888a961b9f29c7345fe207f71e26aaf646eef
3,614,796
def explore_result_coverage_detail(): """Get coverage detail info Get coverage detail info loading from disk :return: a list, each element is dict map in list, if coverage file not exist, will return [],for example: [{ "fileName": "1.jpg", "sampleNum": 5, ...
e7a6cf085414743f59d24da790d8115c36a35047
3,614,797
def gradient_dx(fx: tf.Tensor) -> tf.Tensor: """ Function to calculate gradients on x-axis of a 3D tensor using central finite difference. It moves the tensor along axis 1 to calculate the approximate gradient, the x axis, dx[i] = (x[i+1] - x[i-1]) / 2 :param fx: shape = (batch, m_dim1, m_dim2, m_d...
452bb2240db6d155f072288aa32751167f7eb943
3,614,798
from ..main import app def form_edit_permissions(formId): """Set form permissions of a particular user to an array. POST request, with body: (either userId or email is required.) { "userId": "cm:cognitoUserPool:.....", "email": "a@b.com", "permissions": ["Responses_Edit", "Responses_View", ""] or st...
02c53a057176150484c8b76e787b89b97b976ba7
3,614,799