content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def csv_announcement_email(df_matched): """ This function returns the df_matched in the format that can be used for the email messaging: Announcing buddies to the participants. Use of the email template email_responses.py. """ df_email_og = df_matched.copy() df_email_og.drop(["id_user_1", "id_us...
f95d4c8502352930051a1929a65a8844e2084cdd
3,610,400
import typing def some_class_from( value: typing.Any, id: str, other_classes_registry: typing.Mapping[ str, some.graph.OtherClass], some_classes_registry: typing.Mapping[ str, some.graph.SomeClass], ref: str, errors: some....
5ed95db2c6fe605b67fa0575a9900c3074ae929b
3,610,401
from typing import List import itertools def multiple( context: mgp.ProcCtx, start_points: List[mgp.Vertex], end_points: List[mgp.Vertex], metrics: str = "m", ) -> mgp.Record(distances=List[float]): """ This distance calculator procedure for multiple entries returns 1 field. * `distanc...
7d2a3e4f1eb754d0b0ab5d4430fb538d9b41bd90
3,610,402
def merge_reads_with_novelty(reads, novelty): """ Given a data frame of reads and a transcript novelty data frame, perform a left merge to annotate the reads with their novelty status. """ merged = pd.merge(reads, novelty, on = "transcript_ID", how = "left") return merged
7f6e90e86fa4f51981e4756d23195353d7ff5608
3,610,403
import tempfile import sys import os import time import signal import traceback def run_with_timeout(command, timeoutSecs, inputStream = "", combinedOutput=True): """ Runs the given process until it exits or the given time out is reached. Returns a tuple: (bool:timeout, str:stdout, str:stderr, int:exitco...
d883ca14a3a765602db8046ca8ed071380eee5e9
3,610,404
def cash (): """*****for retrieving cash data from stock.csv FILE and use it accordingly.*****""" fp = open("stock.csv","r") #*****FILE pointer which is opening the file stock.csv as in read mode***** first = fp.readline() split_line = first.split(",") cash = float(split_line[0]) stockCash.appen...
e40dbe26edf45cd1a7956741169658bc2ba67dd5
3,610,405
import numpy def compute_bin_efficiencies(y_score, bin_indices, cut, sample_weight, minlength=None): """Efficiency of bin = total weight of (signal) events that passed the cut in the bin / total weight of signal events in the bin. Returns small negative number for empty bins""" y_score = column_or_1d(...
18b59376d4930168b97012441713efb3551a7cc9
3,610,406
from math import floor def conv_output_shape(h_w, kernel_size=1, stride=1, pad=0, dilation=1): """ Utility function for computing output of convolutions takes a tuple of (h,w) and returns a tuple of (h,w) """ if type(kernel_size) is not tuple: kernel_size = (kernel_size, kernel_size) ...
938ad68c9999b6255b5b1c0186da7807cabd16ad
3,610,407
import random def random_int(n=5): """ Create a random string of ints :return: """ return str(random.randint(1, 10 ** n))
e5fa29ac6177a5c4f6cdd2ee73a5d72736667505
3,610,408
def generate_dataset(data_dir, train=True, n_noisy=30000, k=5): """generate mnist noisy dataset""" data = [] img_sampler = get_noisy_sampler(data_dir) num_sampler = get_number_sampler(load_mnist(data_dir, 'train' if train else 'test')) for i in range(10): print('Generate for number %d ...' %...
e9d81ef168eadc3ee679c60911cacab4b90f5d55
3,610,409
def always_no_state(function, interval): """ This constraint ensures that a state function is undefined on an interval. This function returns a constraint that ensures that *function* is undefined everywhere on an interval (interval variable *interval* when it is present or fixed interval [*start*, *end*))...
2d07f65275af5465e9e136791827cc18a8e8fe68
3,610,410
def merged_stis_data(filename, extension=1): """Get spectrum data from all STIS spectral orders. If only filename is given, use SCI extension. Returns ------- wavs: numpy array, all wavelengths, sorted flux: all fluxes at these wavelengths errs: all errors at these wavelengths """ ...
cfbd361d66a8f5e1a01d6563438c15c87d5b7157
3,610,411
import itertools import random def generate_tuples(parameters): """ :param parameters: :return: """ if len(parameters.keys()) % 2 != 0: parameters['dummy'] = [] keys = parameters.keys() max_0 = keys[0] max_1 = keys[1] for key in keys[1:]: if len(parameters[key]) >= ...
e10c8326c4bdf95c5df36ceb24a3b2ff439d73c7
3,610,412
def run_augment(*args, **kwargs): """Run augment routines.""" return estims_routine(**init_all(*args, routine='augment', **kwargs))
12d00793f80bc758435e94eea43118029bf3329e
3,610,413
import re import string def normalize_answer(s): """Lower text and remove punctuation, articles and extra whitespace.""" def remove_articles(text): return re.sub(r'\b(a|an|the)\b', ' ', text) def remove_articles_ar(text): return re.sub('\sال^|ال', ' ', text) def white_space_fix(...
f2f7e783676a933fac61d0f0c11fc0212030c4fb
3,610,414
def check_prime(number): """ Checks if the given number is prime :param: number Number to evaluate for primality :rtype: bool True if the number is a prime, false otherwise """ for divisor in range(2, int(number**0.5) + 1): if number % divisor == 0: return False return Tr...
37c7cc341c07d02d4c95bf9b95223368504d79e9
3,610,415
import typing import types def is_higher_version( module_o_version: typing.Union[types.ModuleType, str, tuple[int, ...]], version: typing.Union[tuple[int, ...], str], /, *, sep: str = ".", keep_dev_version: bool = True, semver: bool = False, ) -> bool: """ MODULE_o_VERSION > VERSIO...
e1394d9483b7dbbb28f18d7bc2e6a50f3f85a54d
3,610,416
def get_bot_and_update_from_args(args): """Find bot and update instance in the given args. Args: args(iterable): arguments to search for the bot and update. Returns: tuple. telegram.Bot. instance of bot that found in args. telegram.Upate. instance of update that found i...
6080b1d93b2ed9d4d908e18c53ae43555ba9753d
3,610,417
def tally_date_handler(request: HttpRequest, enclosure_slug): """Called from tally page to change date tally""" # if it's a POST: pull out the date from the cleaned data then send it to "count" if request.method == "POST": form = TallyDateForm(request.POST) if form.is_valid(): t...
2fd6088e3b2c4f86d5c480de605dc56d1091d648
3,610,418
import argparse def parse_args(): """set and check parameters.""" parser = argparse.ArgumentParser(description="BRDNet process") parser.add_argument("--pipeline", type=str, default=None, help="SDK infer pipeline") parser.add_argument("--clean_image_path", type=str, default=None, help="root path of ima...
a545a0cfc9e2ecf4c09e0daa785a962a22159577
3,610,419
import torch def kldiv_normal(y, sigma): """ may be unstable because of often small length of y compared to the number of bins. """ delta = sigma/10 width = 10*sigma x = torch.arange(0, width, delta) x = torch.cat([-x.flip(0)[:-1], x]) p = (y.view(-1)-x.view(-1, 1)).div(delta).pow(...
65e3425844dc87725f2e223a5a395924d6efbf3d
3,610,420
def calcDelta(r, x_e, n_ae): """ Calculate topocentric distance to the asteroid. Parameters ---------- r : float (1) Heliocentric/barycentric distance in arbitrary units. x_e : `~numpy.ndarray` (N, 3) Topocentric position vector in same units as r. n_ae : `~numpy.ndarray` (N...
57b52d19225454cc21c2f01f0271cb8ce976a21f
3,610,421
def ParseModel(model): """Parses a model ID into a model resource object.""" return resources.REGISTRY.Parse( model, params={'projectsId': properties.VALUES.core.project.GetOrFail}, collection=MODELS_COLLECTION)
7c90e02c4d2fb6c8ab4e3a34dbac7130da5b018d
3,610,422
import html def update_accordions(clicks): """create bot accordions""" acc_list = [] pair_count = 0 for i in tg_wrapper.helper.get_all_bot_list(): tg_wrapper.helper.read_data(i) state = "defaulted" if "botcontrol" in tg_wrapper.helper.data: state = tg_wrapper.helper...
37acb543ade2efa268aecd9e8f4d0a0f29aabddd
3,610,423
def is_bootstrap_started(): """Checks to see if bootstrap has started. Returns: True if the bootstrap has started, else False. """ return config_model.Config.get('bootstrap_started')
c1c22018da8fa93637a0e55558fabe7d3422286d
3,610,424
def get_feature(feature, first_stage): """FPN, C4, C5""" cfg = load_yml(feature_yml) key = f'{feature}-{first_stage}' return cfg.get(key, None)
296502d5057a4d68e6e637ebc59a5736ace69337
3,610,425
from .. import sim from ..support.morlet import MorletSpec def plotRatePSD(include=['eachPop', 'allCells'], timeRange=None, binSize=5, minFreq=1, maxFreq=100, transformMethod='morlet', stepFreq=1, NFFT=256, noverlap=128, smooth=0, norm=False, overlay=True, popColors=None, ylim=None, figSize=(10,8), fontSize=12, lineW...
76ac27b163a593a73aade5505c7a3e5ad68f6cd2
3,610,426
import numpy import scipy def _evaluate_airy_function_at_point(x, y, z, wavelength, numerical_aperture, refractive_index): """ Evaluates the Airy point spread function at a point. Args: x: Float, x coordinate, in meters. y: Float, y coordinate, in meters. z: Float, z coordinate, i...
e1c4ce7fa3d467ae776efe37177792e23cf305ab
3,610,427
import json def ge_in_wall_dimmer_switch_state_fixture(): """Load the ge in-wall dimmer switch node state fixture data.""" return json.loads(load_fixture("zwave_js/ge_in_wall_dimmer_switch_state.json"))
133814c8e5ce0af2d6aec83e3468488d9430fd8e
3,610,428
import datasets def synthetic_regression_5k_features(dataset_dir): """ Synthetic regression generator from sklearn http://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_regression.html TaskType:regression NumberOfFeatures:5000 NumberOfInstances:100K """ return dataset...
b7d9f4c759beaf3618a28cdd756dd0b4d78abcd2
3,610,429
def genify(options_list, gen): """ Choose position from interval of discrete parameters based on gen value :param options_list: List of discrete values :param gen: DNA gen value :return: """ # Probability steps for projecting to given gen prob_step = 1 / len(options_list) for i in range(len(options_list)): ...
e0b277da2843cf3d7191bbf0445cd80358e7bdcc
3,610,430
def to_int(value): """Return the absolute value.""" try: return int(float(value)) except (ValueError, TypeError): try: return int(float(value.replace(',','').replace('/','.').replace('\\','.'))) except Exception: return 0
460d4317ee02c9c27a5574f95e9b4cdcc6d55e6b
3,610,431
import os import base64 import struct def read_openssh_public_key(key_file): """ Convert an openssl formatted key into a pkcs#1 formatted key as used by our rsa library """ with open(os.path.expanduser(key_file), 'r') as file_handle: keydata = base64.b64decode(file_handle.read().split(None...
d2f28dcbef297a2bc642ab07dc32c6467102ef6d
3,610,432
def getCharsSegments(rows, bounds): """ Gets the char segments of text row images acording to chars bounds. rows and bounds are list of the same matching sizes. Parameters ---------- rows(list) : The list of segmented text row images bounds(list) : Bounds matching chars iamges sizes in a t...
d9a14ec47e5bc384cb2df1d5e69fc41613dd9d29
3,610,433
def make_lsgst_experiment_list(opLabelSrc, prepStrs, effectStrs, germList, maxLengthList, fidPairs=None, truncScheme="whole germ powers", keepFraction=1, keepSeed=None, includeLGST=True): """ Create a list of all the op...
cfb52bec4cc02855f6ef7ba8e8d5f1d3294911b1
3,610,434
def getArrDiffs(dataSet): """ Compares each successive number in a size n numpy array to its predecessor, generating a list of differences, returning a size (n - 1) numpy array. to a list. :param dataSet: A numpy array of numbers :return: An array containing the differences from the imput array....
34d4640f3e174e9714c339041b70f5ab5974c107
3,610,435
def _decide_indices_order(indices): """ arrange indices such the first entry in list has smallest index, the second has the second smallest index """ indices = list(np.roll(indices, -np.argwhere(indices == np.min(indices))[0][0])) second_entry, last_entry = indices[1], indices[-1] if second_ent...
29b4fcd300fbbcd1c89a9ea22d521b97cff049a6
3,610,436
def figsize(*args, **kwargs): """ Set theme_figsize(...) as global plotnine.options + mpl.rcParams: - https://plotnine.readthedocs.io/en/stable/generated/plotnine.themes.theme.html - http://matplotlib.org/users/customizing.html Can be used either as a global mutation (`figsize(...)`) or a context m...
549014a2bfa381df868cc15727a51930d8d591a8
3,610,437
def percent(mylist, item): """Return the percentage of an item of a list. :param mylist: (list) list of elements :param item: (any) an element of the list (or not!) :returns: percentage (float) of item in mylist """ return 100.0 * freq(mylist, item)
a8c0d9df2af5497fff03dd1e2b66c68c70e71bb6
3,610,438
import json def load_cat_to_name(json_path): """Load Label Name from JSON file.""" with open(json_path, 'r') as f: cat_to_name = json.load(f) return cat_to_name
43c30e9dbe29e29d507a873e6cc37f22bc7984c4
3,610,439
def dtc(messages): """ converts a frame of 2-byte DTCs into a list of DTCs """ codes = [] d = [] for message in messages: d += message.data # look at data in pairs of bytes # looping through ENDING indices to avoid odd (invalid) code lengths for n in range(1, len(d), 2): # ...
ae141efef0ec7cb7a5a32f9f3882cacd67018118
3,610,440
def id_overlap_count(input_ids: ListColumn, matching_ids: ListColumn): """ Returns the number of overlaps between two lists of ids Parameters --------- input_ids: First list of ids matching_ids: Second list of ids Examples ------- >>> import torcharrow as ta >>> from torcharrow...
d565fac45ca99a1617f4521b98840d4f29dda68f
3,610,441
def BLVGG(input_tensor, first_filter, hidden_filter, first_dilation, num_classes): """ Build the baseline VGG model :param input_tensor: input tensor :param first_filter: number of first filters :param hidden_filter: number of hidden filters :param first_dilation: number of first dilati...
524b10b649b0e4177bfa146a8e551334949f2afe
3,610,442
import os import json def get_plot(request): """Return a PNG plot of the requested PBS Daily QA data.""" # Get the primary key for the test instance and obtain the filenames pk = get_value_from_request(request, 'id', 0) tests = models.TestInstance.objects.filter( test_list_instance_id=pk ...
5fc86ed1962d0d10e4f39e9d912f208002362bcd
3,610,443
def _mined_attributes_required() -> bool: """Returns True if mined attributes will be required for this batch. Returns: True if mined attributes will be required for the optimizers being run in this batch, false otherwise. """ for optimizer_parameter in _OPTIMIZERS_THAT_USE_MINED_ATTRIBUTES: if _ex...
47c6373769a448f441100f40e9ae04b591d8fbcf
3,610,444
def multi_blend(arrays, colors, alphas=None, modes=None, input_max=1, color_max=1): """Composite one or more one-channel images atop one another, colorizing each. The arrays will be blended in reverse order: arrays[0] will be the base and arrays[-1] will be the top image. Parameters: arrays: l...
92db9b23a203a27c8970ec08ddebeb692ab8c735
3,610,445
def plot_3d(df, target_variable): """ 3d plot of data frame columns :param df: pandas.DataFrame :param target_variable: pandas.Series :return: None """ unique_labels = target_variable.unique() ordinal_encoding = [np.where(unique_labels == label)[0][0] for label in...
967ab3a90a674e1c7bc008825864025fea29d01a
3,610,446
def user_albums_query(user_id: str, page_number: int) -> dict: """ Build User albums query. :param user_id: User id :param page_number: page number :return: Query """ return { "id": 8, "operationName": "AlbumList", "query": "query AlbumList($input: AlbumListInput!) {album {list(input: $input) ...
ca490875a999215bd9cfc7f71a5763c8518f5289
3,610,447
import typing def _consts(fn: typing.Callable) -> tuple: """ Returns a tuple of the function's constants excluding the docstring. """ return tuple(x for x in fn.__code__.co_consts if x != fn.__doc__)
bd60a35cf5243fd158d6e65df6e0a16f6fd9051b
3,610,448
import inspect import sys import unittest def suite(): """ This method must be included at the end of all sub-test modules. To use in other modules, copy this entire method to the new module. :return: (unittest.TestSuite) Test suite for this sub-test """ tests = inspect.getmembers(sys.modules[...
725ab5a006f0ebb9ffc1334bb3d7ec2c7b8afb38
3,610,449
def x_y_to_name(x, y) -> str: """ Make name form x, y coords Args: x: x coordinate y: y cooridante Returns: name made from x and y """ return f"{x},{y}"
40ae99a789fdf029407ab0290ae58e85e911833c
3,610,450
def database(): """ Get all raw database details.""" data = db.DB().db_get() return data
50cdbefc8e07fab2c2619b4252826d364aa8777d
3,610,451
def indice_PM10(fila, columna): """Cálculo del índice de calidad del aire para el PM10 (usando datos de micro gramo sobre metro cúbico). Las operaciones que se realizan aquí son una normalización para que cada contaminante se mida de acuerdo al índice de calidad del aire. Esta función se ocupa de calcular ...
f571b67b4ce939325775dd12a3f93911e1b724a8
3,610,452
def sigmoid_cross_entropy_balanced_back(logits, label, name='cross_entropy_loss'): """ Implements Equation [2] in https://arxiv.org/pdf/1504.06375.pdf Compute edge pixels for each training sample and set as pos_weights to tf.nn.weighted_cross_entropy_with_logits """ y = tf.cast(label, tf.float32...
6d2fda3ace17516b0278e0a3f9c589ef123509ca
3,610,453
def infer_table_schema_type_from_rdf_term(term_type, term_datatype): """Map an RDF literal type to Table Schema field type :param term_type: type from RDF term :param term_datatype: datatype from RDF term """ if (term_type == 'literal' and term_datatype is not None): return _RDF...
5e75c3aa78fff179c88d464fddb66140912f1cc0
3,610,454
def _is_relative_length_valid(acro: str, full: str) -> bool: """ Check whether the relative length of acronym to full form are within reasonable bounds. A full form can be up to 20 times longer than the acronym and the acronym has to be at most 60% of the full form. According to analysis of `acro_...
925fd8bc7bd4f38b3403930dc121bb434aa845c7
3,610,455
def _lvl_error(level): """Get the lng/lat error for the hilbert curve with the given level On every level, the error of the hilbert curve is halved, e.g. - level 0 has lng error of +-180 (only one coding point is available: (0, 0)) - on level 1, there are 4 coding points: (-90, -45), (90, -45), (-90, 4...
52f8653252de1120d34c9a0377e85c07111874d6
3,610,456
def make_lowshelf( frequency: int, samplerate: int, gain_db: float, q_factor: float = 1 / sqrt(2) ) -> IIRFilter: """ Creates a low-shelf filter >>> filter = make_lowshelf(1000, 48000, 6) >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE [3.0409336710888786, -5.60887099222...
53a1f69182f60fe668435bca3e7a0b2638ed4f83
3,610,457
def pixelplt( array, xmin, xmax, ymin, ymax, step, vmin, vmax, title, xlabel, ylabel, vlabel, cmap, fig_name, ): """Pixel plot, reimplementation in Python of GSLIB pixelplt with Matplotlib methods. :param array: ndarray :param xmin: x axis minimum...
fd431bf6b9a2bb6d1b5848b1a499b80d17631bfd
3,610,458
import random def prepare_wikidata_completion(qid=None, pid=None, is_category=False): """ Get the subject's label, Wikipedia article, and get property's label to construct the question :param qid: Entity Id starts with Q :param pid: Property Id starts with P :param is_category: flag indicates ...
50f963d52204a5d9b91f06577b04ac9558d5aaa2
3,610,459
def _kron_1d(a, b): """This function is for internal use. Returns a⊗b for 1d array. """ nb = b.size d = np.repeat(a, nb).reshape(-1, nb) d *= b return d.reshape(-1)
76973d7f676c7bfeb132958ad20e2bf6ec285cb4
3,610,460
def micromanager_metadata_to_coords(summary, n_times=None, z_centered=True): """ Given the 'Summary' dict from micromanager, parse the information into coords for a corresponding DataArray. Parameters ---------- summary : dict Micromanager metadata dictionary. n_times : int ...
2f8cf96d59ab34465fb7fb5a550126356beb617e
3,610,461
def problem1(limit, mod1, mod2): """Problem 1""" result = 0 for cur in range(0, limit): if cur % mod1 == 0 or cur % mod2 == 0: result += cur return result
e0be92fc6e2be4730606f02256e59018420655e6
3,610,462
def arrayuniqify(X, retainorder=False): """ Very fast uniqify routine for numpy arrays. **Parameters** **X** : numpy array Determine the unique elements of this numpy array. **retainorder** : Boolean, optional Whether or not to return in...
35a6297da42881b7a67b5e968da0f857afd6f79c
3,610,463
def atmDensPoly6th(ht, dens_co): """ Compute the atmosphere density using a 6th order polynomial. This is used in the ablation simulation for faster execution. Arguments: ht: [float] Height above sea level (m). dens_co: [list] Coeffs of the 6th order polynomial. Return: a...
653b134d513c3fd9b55e72ee37a4c7116aadf8cf
3,610,464
def render_product(context, product): """ Render a product snippet as you would see in a browsing display. This templatetag looks for different templates depending on the UPC and product class of the passed product. This allows alternative templates to be used for different product classes. ""...
c9c856ae58c6e0d26c7b1452e47d33bb1108d5a0
3,610,465
import re def filter_exitrons(exitrons, reads, bamfile, genome, db, skip_realign, mapq=50, pso_min=0.01, ao_min=2, cluster_purity=0, jitter=10): """ Parameters ---------- exitrons : list list of unfiltered exitrons from exitron_caller. reads : dict Each intron is a key, and the val...
f580ec6163c811bd139746a44034024a76c93fb3
3,610,466
def get_bias_initializer(name: str, dtype=jnp.float32) -> WeightInitializer: """Get a bias initializer.""" validate_bias_initializer(name) return INITIALIZER_CONSTRUCTORS[name](dtype=dtype)
db49bfbc39860d0abed1d058dfffd473a6f6e8f6
3,610,467
def raw_fashion_train_images_file(): """ Train images of MNSIT. :return: filepath :rtype: str """ return data_file('fashion/train-images-idx3-ubyte', GZIP_EXT)
0579a844332609b70483bc6dda3e6f3422c4ccfa
3,610,468
def comment_staticman(github_token, ci_data): """Sequence of functions to get data from github for staticman comment and then write the comment to github """ return sequence( pr_url, requests_get(github_token), lambda x: x.json(), get("body"), archieml.loads, ...
379a6b32245cf6f9f49bf6b0cb4f9b183dab6fd1
3,610,469
import uuid def get_file_name() -> str: """ Creates a unique file name for datastore by appending timestamp to the file name :return: """ uniq_append_string = uuid.uuid4().hex return "LOCAL_STORAGE_{}".format(uniq_append_string)
a865199dc688dfcbb7077d9cf0a30aa9f5199849
3,610,470
def requires_auth(function): """ :param function: :return: the validity of a request """ @wraps(function) def decorated(*args, **kwargs): p_access = False auth_token = False if not auth_token: auth_token = request.header.get('Authorization') if not aut...
22841d539043dcf944ed53a9bcc059e5489a4d1c
3,610,471
import torch def xyxy2xywh(box2d): """ input : [n, 4] [x1, y1, x2, y2] return : [n, 4] [x, y, w, h] compatible with both pytorch and numpy a faster dedicated numpy implementation can be found at lib/fast_util/bbox2d.py """ center_x = 0.5 * (box2d[:, 0] + box2d[:, 2]) ...
54002a422ba762c5797f375be27aa4ee9e0b224c
3,610,472
from sosia.processing.querying import base_query def auth_npubs_retrieve_insert(auth_id, year, conn): """Retrieve an author's publication count until a given year, and insert.""" q = f"AU-ID({auth_id}) AND PUBYEAR BEF {year+1}" npubs = base_query("docs", q, size_only=True) tp = (auth_id, year, npubs)...
c1561cd7af9f43a1aa6e660cbefbef4f15512724
3,610,473
def back_url(request): """后台通知地址 :param request: :return: """ return HttpResponse("Hello back_url")
d90a9374aa53efbc032d0556268033b332e5e361
3,610,474
def SignedCharCast(value): """Explicitly cast a value to type 'signed char'.""" shift = ConstInt(24) return RShift(LShift(value, shift), shift)
0638524bd2835e375bc520d903ee303b5c9c12c7
3,610,475
def get_nested_plot_frame(obj, key_map, cached=False): """Extracts a single frame from a nested object. Replaces any HoloMap or DynamicMap in the nested data structure, with the item corresponding to the supplied key. Args: obj: Nested Dimensioned object key_map: Dictionary mapping bet...
45aa0017c23fc91bfb1cfe142b1db10b735c2e41
3,610,476
import hashlib def __str_to_hash(string_to_hash: str, errors: str = 'ignore') -> str: """ Encodes the given string and generates a hash from it. """ string_hash = string_to_hash.encode(encoding="utf-8", errors=errors) return hashlib.md5(string_hash).hexdigest()
e7c0c419f9fa39bf5884198ec1dbfe4816fb7383
3,610,477
def zeros(shape, dtype, force_cpu=False): """ The OP creates a tensor of specified :attr:`shape` and :attr:`dtype`, and fills it with 0. Its :attr:`stop_gradient` will be set to True to stop gradient computation. Parameters: shape (tuple|list): Shape of output tensor. dtype (np.dtype|co...
793e82b855b0aa60e612bd5149fd00d3abbd38dc
3,610,478
def get_editors(ref_string): """ returns list of editors, which can appear anywhere in the reference :param ref_string: :return: """ if isinstance(ref_string, unicode): ref_string = unidecode.unidecode(ref_string) lead_match = LEADING_INIT_AUTHORS_PAT.search(ref_string) trail_m...
2424fc7be73e337ab9d2212dc8a9a7b42f65c953
3,610,479
def extract_ta_features(stock_df): """Compute features using TA's technical indicators.""" initial_len = len(stock_df) stock_df = ta.add_trend_ta(stock_df, high="High", low="Low", close="Close") stock_df = ta.add_momentum_ta( stock_df, high="High", low="Low", close="Close", volume="Volume" ...
ca1b70d594dcdba0c3fae3a7589ed4b048cd7440
3,610,480
import six def user_pk_to_url_str(user): """ This should return a string. """ User = get_user_model() if (hasattr(models, 'UUIDField') and issubclass( type(User._meta.pk), models.UUIDField)): if isinstance(user.pk, six.string_types): return user.pk return us...
8216bf095262e28b0baa87b91349f6b7a05c71b2
3,610,481
def _get_coords(xedges, yedges): """Get coordinates given the edges of the histogram.""" global XBUFFER, YBUFFER if XBUFFER is None: xcenters = (xedges[:-1] + xedges[1:]) / 2 ycenters = (yedges[:-1] + yedges[1:]) / 2 X, Y = np.meshgrid(xcenters, ycenters) XBUFFER = X ...
678e6d9461388735cbdbc7771e1d5cd22c3c105f
3,610,482
def get_information_from_certificate(certificate): """ Extract user information from a client certificate :param certificate: The certificate :return: """ if not certificate: return None, None # open certificate cert_chain = X509CertChain() try: cert_chain.parsePemLi...
3652ef25db3bc978426bc1f7212d6face1385b63
3,610,483
def create_model_helper(base_model_fn, sequential_inputs, is_training): """Helper function for creating model function given base model function. This function creates a model function that adaptively slices the input features for improved running speed. Note that the base model function is required to have i...
2cbd3c22703c313bce4ec60a029110ae332d9bcd
3,610,484
def check_not_finished_board(board: list) -> bool: """ Check if skyscraper board is not finished, i.e., '?' present on the game board. Return True if finished, False otherwise. >>> check_not_finished_board(['***21**', '4?????*', '4?????*', '*?????5', '*?????*', \ '*?????*', '*2*1***']) False ...
546d68c77f17cca0a418a7852cc671ac2184ea8e
3,610,485
def transform(params): """Convert from ConfigSpace params to Orion params""" return {k: (v if v is not _NoneValue else None) for k, v in params.items()}
e9bf968719f801544b1cd5e1fa90c9d36cebde4f
3,610,486
import json def get_orphan_users(email_to_user_profile, user_emails, source_priority): """ Gets all users that don't exist in the Workday report anymore and terminate them in XSOAR. """ events = [] orphan_users = [email for email, user in email_to_user_profile.items() if email not in ...
d670d94200b1c2d736686497db1fdff78121a6b3
3,610,487
import glob import os def get_postmasters_directories(): """ detect all postmasters running and get their pids """ pg_pids = [] postmasters = {} pg_proc_stat = {} # get all 'number' directories from /proc/ and sort them for f in glob.glob('/proc/[0-9]*/stat'): # make sure the particul...
82d7c312f1b1862b623b4307fccffce29b56f4b4
3,610,488
def template_test(): """Return a test template""" return render_template_string( templates.TEMPLATE, my_string="Wheeeee!", my_list=[0, 1, 2, 3, 4, 5] )
87a641e02c8a94c3a0aebe6a972ebdd3b1342657
3,610,489
def find_overlap_percentage(nominator, denominator): """This function is used to find overlap percentage between 2 lists""" common_skills_set = set(nominator).intersection(denominator) common_skills_list = list(common_skills_set) if common_skills_list: overlap_percentage = len(common_skills_list...
605f55e4698255a97a800d8a183078b25e6c2a34
3,610,490
import os import argparse def extant_file(value): """ 'Type' for argparse - checks that file exists but does not open. """ if not os.path.exists(value): # Argparse uses the ArgumentTypeError to give a rejection message like: # error: argument input: x does not exist raise argpa...
841181c254a7ac760e60cabb77ff56f3cf4eca16
3,610,491
def report_withot_driver_part(): """Returns part from correct final report""" return [" 10. Pierre Gasly | SCUDERIA TORO ROSSO HONDA | 0:01:12.941", " 11. Carlos Sainz | RENAULT | 0:01:12.950"]
0117401194c9c36f86b6b8f1572f06f673a8b085
3,610,492
from typing import Union from typing import Tuple def get_rationed_resizing( resized: Union[int, float], length: int, other_length: int ) -> Tuple[int, int]: """ Get resized lengths for `length` and `other_length` according to the ratio between `resized` and `length`. Parameters ---------- ...
dde1ce579c192178090fe07c145fd3e153d92599
3,610,493
def pyprep_reference(matprep_artifacts): """Get the robust re-referenced signal for comparison with MATLAB PREP. This fixture uses an artifact from MATLAB PREP of the CleanLined EEG signal right before MATLAB PREP calls ``performReference``. As such, the results of these tests will not be affected by a...
71fa40eab30d6893a5d8d2451f0e5049843e4005
3,610,494
def list_average(value_list: list[int|float]) -> None: """Return the average of a list of ints or floats.""" return list_sum(value_list) / len(value_list)
181bae83e129708efae4579bce4f62d70db599e5
3,610,495
def data_context_connectivity_context_connectivity_serviceuuid_include_nodetopology_uuidnode_uuid_get(uuid, topology_uuid, node_uuid): # noqa: E501 """data_context_connectivity_context_connectivity_serviceuuid_include_nodetopology_uuidnode_uuid_get returns tapi.topology.NodeRef # noqa: E501 :param uuid: ...
bcad7bb85ecb2d9f89f9f6c7dd228612532e785d
3,610,496
def delete_restaurant(request, id): """ Delete dish. Roure for 'remove/d/<int:id>'. """ Restaurant.objects.get(id=id).delete() messages.info(request, "Deleted") return redirect(f"/management")
805ad0a3a0728afc40ddeb29e0b8ce6244eadf84
3,610,497
def is_part_of_branch(action): """ Checks if action is part of branch action. :return: Boolean """ try: branch_action = get_parent_by_tag(element=action, tag="steps_Behaviour") except AttributeError: # parent with tag="steps_Behaviour" cannot be found --> is not in branch return...
bd8d55f120b18d2f01c5a48011884d4bffb99e80
3,610,498
def get_sprite_pos(map_dim, sprite_dim, clip_sprites): """Returns a sprite position for a given map and sprite.""" map_w, map_h = map_dim sprite_w, sprite_h = sprite_dim if clip_sprites: x_pos = randint(-sprite_w, map_w) y_pos = randint(-sprite_h, map_h) else: x_pos = randin...
e3d6554758db6268167fd4e335032bd66dc622bb
3,610,499