content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def detect_ecb(input_bytes: bytes): """Takes in a byte string. Determines whether or not it is likely to be an AEC-ECB-encrypted ciphertext""" number_original_chunks = len(input_bytes) // 16 dedupe_chunks = {input_bytes[i: i + 16] for i in range(0, len(input_bytes), 16)} result = False if len(dedup...
4a83f0d34f714d9e55ffa2b93777e214d164211d
644,475
from functools import partial from collections import defaultdict from os.path import join import pandas as pd def _get_qiime_minimal_mapping(prep_template, out_dir): """Generates a minimal QIIME-compliant mapping file for split libraries The columns of the generated file are, in order: SampleID, BarcodeSequ...
c56f659fe30061f7c508edf6462d4bc610a467f7
644,476
def reverse_complementary(sequence): """ Create reverse-complementary sequence""" new_sequence = ''.join([x for x in reversed(sequence)]) new_sequence = new_sequence.replace('A', 'Z').replace('T', 'A')\ .replace('Z', 'T').replace('C', 'Z').replace('G', 'C').replace('Z', 'G') return new_sequence
dd411f00f00304ac5323ba7ebc66213438449e8f
644,477
from textwrap import dedent def build_brace_pattern(level, separators): """ Build a brace pattern upto a given depth The brace pattern parses any pattern with round, square, curly, or angle brackets. Inside those brackets, any characters are allowed. The structure is quite simple and is recursiv...
35c1fe4f0b86d5b459c9c504a67f12274a68e308
644,478
import os def read_pval_file(targetdir): """Read the quantile information from a file.""" with open(os.path.join(targetdir, "pvals.txt"), 'r') as fp: pvals = {} for line in fp: parts = line.split("\t") # formated as "key:\tvalue" try: pvals[parts[0][0:-1...
7a8373f700fd26af3e6596855aa6e064620ea620
644,479
import itertools def choose_n(total, sample_size): """Given a number of items N and a sample size S, returns all possible unordered S-tuples of integers up to N.""" return list(itertools.combinations(range(1, total + 1), sample_size))
b032ba2a4d044de23aff0093c15b4f47e59df6ea
644,481
def decode_varint_py(buffer, pos=0): """ Decode an integer from a varint presentation. See https://developers.google.com/protocol-buffers/docs/encoding?csw=1#varints on how those can be produced. Arguments: buffer (bytearry): buffer to read from. pos (int): optional position...
e51e7f9f225ce0edd7d157239f1db9e051518bdc
644,482
def expand_year(year): """Convert 2-digit year to 4-digit year.""" if year < 80: return 2000 + year else: return 1900 + year
6a9b47a09493523554c123dc7c3a92897d8464b3
644,483
def write_transfer(x, player_names): """Write into a string the transfers made for a gw Args: x (array): _description_ player_names (pd.DataFrame): player names Returns: str: transfered players """ if len(x['Transfer in']) == len(x['Transfer out']) == 0: return 'Rol...
736fabedbdc4b1c16dcf500dabc80d665e6f66cd
644,484
def readList(infile, column=0, map_function=str, map_category={}, with_title=False): """read a list of values from infile. Arguments --------- infile : File File object to read from columns : int Column to take from the file. map...
e9708a136f248dc3579fcd06fdc52527e9260e54
644,485
def fix_url(url): # type: (str) -> str """ Fix a url to be used in the rest of the program example: api.gdc.cancer.gov -> https://api.gdc.cancer.gov/ """ if not url.endswith("/"): url = "{0}/".format(url) if not (url.startswith("https://") or url.startswith("http://")):...
3af6974f36ec3d1d5bdf8d773eb05ae9c3d49a8f
644,486
def _consume_topics(pubsub_client): """Consume entire iterator. :type pubsub_client: :class:`~google.cloud.pubsub.client.Client` :param pubsub_client: Client to use to retrieve topics. :rtype: list :returns: List of all topics encountered. """ return list(pubsub_client.list_topics())
d9908a84caacd1b0ab58e27cf2c6858de77daf56
644,487
def is_file_covered(file_cov): """Returns whether the file is covered.""" return file_cov['summary']['regions']['covered']
39458fd70145772e1dddc978fd825ba0287c0b72
644,488
import string import random def random_string(len: int) -> str: """ Generate a _random string of desired length. :param len: Desired character length for generated string. :return: Generated _random string. """ alphanumeric_alphabet = ''.join([string.ascii_letters, string.digits]) generated_s...
af7a32425325490a01f8c7e4e72ac295b3e0a910
644,489
def is_multi_label(labels_list): """Whether labels list provided is a multi-label dataset. Parameters ---------- labels_list : list list of labels (integers) or multiple labels (lists of integers) or mixed Returns ------- True if multi-label """ return any([isinstance(l, li...
7c51f84639cc68f263b55b0a71bb5f62d0dffdfd
644,490
def deprecated_somaEspessuras(l, k): """ Soma as espessuras das camadas passadas por parametro ate a camada k """ summ = 0. for i in range(0, k): summ += l[i].espessura return summ
40fee3b20fbb26beedb2f24e8ba5a1d727acd5df
644,491
import random def leet_converter(message): """ Converter to leet https://v2.cryptii.com/text/leetspeak """ replacement = ( ('hacker', 'haxor'), ('otherf', '*therf'), ('uck', '*ck'), ('hacker', 'HaX0R'), ('elite', '1337'), ('a', '4'), ('e', '3'), ('l', '1'), ('o', '0'), ('t', '7'), ('i...
9a0e70c92c85d54d28043762d1402e73128109f5
644,492
def prettify_user_info(data: dict): """Returns a prettified version of get_user_info.""" stats = data["stats"] return { "stats": { "achievements": stats["achievement_number"], "active_days": stats["active_day_number"], "characters": stats["avatar_number"], ...
4bbccacd1100db3e422508a25455bf1194d14f1c
644,493
def valid_operation(x: str) -> bool: """ Whether or not an opcode is valid :param x: opcode :return: whether or not the supplied opcode is valid """ return not x.startswith("__") and not x == "bytecode_format"
947f1f1e7b58f0d56d772c017c100657a84ba5ca
644,494
import argparse import os def get_input_params(): """ Gets input parameters from command line :return: """ parser = argparse.ArgumentParser(description='Generate swagger.json files for apis on vcenter') parser.add_argument('-m', '--metadata-url', help='URL of the metadata API') parser.add_...
006341aa79f3904c3c222ca403240ca74536446a
644,495
def _sort_recitations_dict_into_lists(dictionary): """ Helper method that simply converts a dictionary into two lists sorted correctly. :param dictionary: Dict of two lists :type dictionary: dict :return Sorted dict :rtype dict """ if not dictionary: return zip([], []) surah...
b29c485e9af8b3014f8e8e8ec75a32280cf16e9d
644,496
def generate(G, source): """ 画像データを生成 # 引数 G : Keras model, 生成器 source : List or Image # 戻り値 images : Numpy array, 画像データ """ input_dim = G.input_shape[1] images = G.predict(source) images = images * 255 return images
79281bfea0ad7d3ee170aee4b06e70e619c3c8a6
644,497
import click def validate_soft(ctx, param, value): # pylint: disable=unused-argument """Convert a soft option into a set of acceptable ranks""" if value is None: return None try: vals = set() for triplet in value.split(","): fields = triplet.split(":") ...
dde7a3f14a5fb171c5342ebe1a5cca7ba012db02
644,498
import pwd def parse_uid(uid): """Parse user id. uid can be an interger (uid) or a string (username), if a username the uid is taken from the password file. """ try: return int(uid) except ValueError: if pwd: return pwd.getpwnam(uid).pw_uid raise
602d133647ab58dfc3363bea30df46bcd398fceb
644,499
from typing import List from typing import Dict import os import csv def get_specified_test_cases(filename: str, tests: List[str]) -> Dict[str, List[str]]: """Get test cases from a specified test case file. Usually exported manually or through CI system.""" if not os.path.exists(filename): print( ...
699bb42c2b0b3dfcdb8a9ac3f878f0ef2aacec5c
644,500
def input_data(): """ Спрашивает у пользователя два значение и проводит проверку типов и возвращает список для построения диапазона, либо отрецательный результат проверки типов введенных пользователем данных :return: list Список чисел; bool False - пользователь ввёл текст или околесицу """ rng ...
09c8f7bb61c11154ef1600f541fd11a5b28835a0
644,501
def get_latest(group): """ Get the latest run in this group: """ s = group.sort_values(by=['date','run_number'], ascending=False).iloc[0] s['run_id'] = s.name return s
31e51d340603215240fd4096266184e7950d182d
644,503
def ngrams(iterable, n=1): """Generate ngrams from an iterable l = range(5) list(l) -> [0, 1, 2, 3, 4, 5] list(ngrams(l, n=1)) -> [(0,), (1,), (2,), (3,), (4,)] list(ngrams(l, n=2)) -> [(0, 1), (1, 2), (2, 3), (3, 4)] list(ngrams(l, n=3)) -> [(0, 1, 2), (1, 2, 3), (2, 3, 4)] """ ...
d3a4cbbc87ae6135de663d7e71f4385292732898
644,504
def counter(string): """ Calculate count of elements in string. """ result = [f'Count of {elem} = {string.count(elem)}\n'for elem in set(string)] return "".join(result)
5a14b0894e5c0690eed267cd3dcaf267349d47d1
644,505
def parse_nodelist(fh): """ Return a list of node identifiers which maps the list index to the identifier """ rv = [] for line in fh: line = line.rstrip() words = line.split() for word in words: rv.append(word) return rv
b7a26560e6e319eb8732ccb9d834debe5ff09052
644,506
def try_key(dictionary, key, default): """ Try to get the value at dict[key] :param dictionary: A Python dict :param key: A key :param default: The value to return if the key doesn't exist :return: Either dictionary[key] or default if it doesn't exist. """ try: return dictionary[...
e83b181d8b70a62ca819f8d0356198fbd07b2548
644,507
def generate_coordinate_rect(x_start, x_finish, y_start, y_finish): """ Generate tuples for coordinates in rectangle (x_start, x_finish) -> (y_start, y_finish) """ coords = [] for i in range(x_start, x_finish): for j in range(y_start, y_finish): coords.append((i, j)) return c...
e7e950b455dc74e483bcf401e1a5998c3f4cf088
644,508
def detect_cycle(head): """ Question 8.4: Detect a cycle in a singly-linked list. Return None if there is no cycle. If there is, return the first node in the cycle. """ slow = head fast = head cycle_length = 0 while fast and fast.next and fast.next.next: slow = slow.next ...
636884bd0e595cd37c814bb8e215b43d6b48a131
644,509
def pipe_flatten_names(keywords): """Obtiene una lista con las keywords separadas por un pipe | extrayéndolas del json. Args: keywords (json): keywords de la película Returns: str: keywords de la película juntas """ return '|'.join([x['name'] for x in keywords])
6263c7fec0b277b01e32654418541b4aab4eddf6
644,510
def equalSpacedCoordinates(n, a, b): """n , a and b are integer parameters. n is the number of spaces you want. a and b make the interval to space. This function will take the input parameters and then output a list with its memebers being the coordinates on the x-axis where the spaces are located.""" coorList...
fb0a823ec0d55e80be62c2f7f1b0a3cb41597ead
644,511
def stdDevOfLengths(L): """ L: a list of strings returns: float, the standard deviation of the lengths of the strings, or NaN if L is empty. """ if (len(L) == 0): return float('NaN') # compute mean first sumVals = 0 for s in L: sumVals += len(s) meanV...
51883d29bf078c5a974a92fb9289fa5e07fea2c9
644,512
def get_add_llil(src): """ Returns llil to add :param src: source of operation :return: generator for llil expression for add """ def add_llil(il, instr): return il.set_reg(4, 'a', il.add(4, il.reg(4, 'a'), src(il, instr))) return add_llil
62d35ccbfdf976bb6d301a0010c3a30f91af1bf5
644,513
from unittest.mock import Mock def mock_store(): """Minimal mock store """ store = Mock() store.read_model_run = Mock(return_value={ 'sos_model': 'test_sos_model', 'narratives': {}, 'scenarios': {} }) store.read_sos_model = Mock(return_value={ 'name': 'test_sos_...
ffacad3b3eb3361dc421c9bc833445af4c6efbad
644,514
import json def ReportJson(build_statuses): """Generate the json description of a given build. Args: build_statuses: List of build_status dict's from FetchBuildStatus. Returns: str to display as the final report. """ report = {} for build_status in build_statuses: report[build_status['build...
3ea482787541ee962e1d48e23614143c235974d3
644,515
def get_static_data(modelSpec): """ Return a dictionary of static values that all objects of this model have. This applies only to kubernetes resources where ``kind`` and ``apiVersion`` are statically determined by the resource. See the `Kubernetes OpenAPI Spec Readme`__. For example for a...
6b06d3fc05bc53ed0a6436f57ff7a1f89ef46b65
644,516
def usernameslist(data): """ Returns list of usernames of all users. """ return [u['name'] for u in data['users']]
6efd89d2c63af074ebf2a7133a8680be40c08679
644,517
def power_set(elements): """ recursive version """ if not elements: return [[]] else: result= [] first = elements[0] subsets = power_set(elements[1:]) for subset in subsets: result.append(subset) new = [first] + subset ...
812f59515d765f67e5e96ee69c56631a82eb9f14
644,518
import threading def synchronized(name): """ Function that creates a lock object and stores in the callers __dict__. Wrappes method for synchronized execution :param name: name of the callable to wrap Returns: :obj:`function`: the wrapped function """ def synchronized_method(method):...
817be5c45b896e78e7d26bd58efee759f55c3df3
644,519
def gen_hf_bitstring(n_orb, n_elec): """Generate the bit string representation of the Hartree-Fock determinant. Parameters ---------- n_orb : (unsigned int) the number of spatial orbitals in the basis n_elec : (unsigned int) the number of electrons in the sys...
4c2feb5b827decdafdee109c680f9d78fc952ad8
644,520
import math def distATT(x1,y1,x2,y2): """Compute the ATT distance between two points (see TSPLIB documentation)""" xd = x2 - x1 yd = y2 - y1 rij = math.sqrt((xd*xd + yd*yd) /10.) tij = int(rij + .5) if tij < rij: return tij + 1 else: return tij
ce704b491d401998afc3dc394452f10825c4afbd
644,521
def reply(): """Mock reply callable.""" class _Reply: def __init__(self): self.replied = None async def __call__(self, msg: bytes): self.replied = msg return _Reply()
5bc80fbd1cee11301446dd157aad60410487e252
644,522
import os import io def get_line_cnt_from_cols(file_path: str, offset: int) -> tuple: """Gets a line count and columns offset from a file's absolute offset. :param str file_path: Path to file. :param int offset: The byte offset to translate Returns: A `tuple` of 2 `int` numbers: - I...
d9f3fc7acef1e74222f4539d718ff6f4c0f590e5
644,523
import time def gen_filename(sample, dist, temp): """ Function to generate the string to use as the filename of the output file. The information contained in the filename are hardcoded to match our requirements, but can be easily changed. Parameters ---------- sample: str Str...
062f8bf59f25bf8f6948666bee1ee458b8ccffb6
644,524
import random def roll(sides): """ Roll a (sides) sided die and return the value. 1 <= N <= sides """ return random.randint(1,sides)
aea500961fad3612cf4e42507776a6f754480081
644,525
import re def splitCIGAR(SAM_CIGAR): """ Split CIGAR string into list of tuples with format (len,operator) """ CIGARlist = list() for x in re.findall('[0-9]*[A-Z|=]',SAM_CIGAR): CIGARlist.append((int(re.findall('[0-9]*', x)[0]),re.findall('[A-Z]|=', x)[0])) #174M76S --> [(174,M),(76,S)...
d2fbe4e4280c52ad4673f4928fcce39b06f54818
644,526
import typing import types import sys def get_module(name: str) -> typing.Union[types.ModuleType, None]: """ Retrieves the loaded module for the given module name or returns None if no such module has been loaded. :param name: The name of the module to be retrieved :return: Either...
7d580ac40e994f914ddfa6de5266fdd3a6ec7d57
644,527
def get_state_data(details): """returns bordering states for a state Arguments: details {list} -- details of each state """ return {"name": details[0].upper(), "bordering_states": details[1:-1]}
5112787dae5e506b777ef2cc22d44603cc839116
644,529
def get_middle_points(x_points): """ Get the middle point of an interval """ middle_points = {} if len(x_points) == 0: middle_points[(0, 1)] = 0.5 elif len(x_points) == 1: value = x_points[0] middle_points[(0, value)] = value / 2 middle_points[(value, 1)] = (value...
e0d8c2f54d9f0c31dd86293296a3e313ff0785ae
644,532
def preprocess(df): """pre-processed the data frame.new filtering methods will be implement here. """ df.drop_duplicates(subset=df.columns[0], inplace=True) #drop duplicate gene_names. df.set_index(keys=df.columns[0], inplace=True) df.dropna(how='all', inplace=True) ...
66d4b606116e600605e6e95efcd41233f5c213c5
644,533
def get_count(res, suffix): """ The function helps to obtain relevant information for the given hashed password """ # The data has a ':' delimiter separating the hashed password and its count results = (line.split(':') for line in res.text.splitlines()) for hashed, count in results: # ...
b1fd661eb2fb9a2a5d1edf6a99d7352df04698aa
644,534
def actionToGcdType(actionType) : """Returns the gcdType matching a given actionType """ if actionType == 'gcdSkill': return 'global' elif actionType == 'instantSkill': return 'instant'
67090086864cae075561c04e26f05f30631ff4fd
644,536
def FitnessStatsCriteria(ga_engine): """ Terminate the evoltion based on the fitness stats Example: >>> ga_engine.terminationCriteria.set(GSimpleGA.FitnessStatsCriteria) """ stats = ga_engine.getStatistics() if stats["fitMax"] == stats["fitMin"]: if stats["fitAve"] == stats["fitMax"]: ...
bcb8c56247840b7e3de5f21b6b846d81b4ffe671
644,538
import numpy def RotMatAxis(v,t): """ Return transfomation matrix u for rotation by t (radian) around vector v. :param lst v: axis vector, [x(float),y(float),z(float)] :param float t: rotation angle :return: u(lst) - transformatiom matrix """ eps12=1.0e-12 u=numpy.identity(3) if ...
3a2f6edca1b64b957fcd7d2fd62cf9516f1ba985
644,539
def add_forms_to_formset(request, formset, extra: int): """Add additional forms to formset.""" # Generate copy of request.POST dictionary formset_dictionary_copy = request.POST.copy() # Update formset management form with additional forms formset_dictionary_copy['form-TOTAL_FORMS'] = int(formset_d...
5df441df5fd171200608e20caf65a08ee1a1a357
644,540
import math def radians_to_degrees(radians): """Convert radians to degrees.""" return 180.0 * radians / math.pi
63d166846ba9bd21a665e74ffbfea8bf2c1cc5be
644,542
def largefeed(): """ Provide a larger feed """ test_feed = { 'channel': { 'title': u'99% Invisible', }, 'items': [ { 'published': u'Tue, 19 May 2015 04:47:53 +0000', 'title': u'1 - title one', 'links': [ ...
db5b508a17607cb3a87f50fb4f463251c3aa1852
644,543
def convert_txt_bits(txt): """ converts byte to bits """ bits = ''.join(bin(ord(c)) for c in txt).replace('b','') return bits
0bcdf0080e9db31b5209bfbbdffa22edb275ebcc
644,544
def bob_public_key(b_pr_k, a, p): """Bob calculate his public key with his private key. This is open to public""" return pow(a, b_pr_k) % p
216ebb8ee479fe6396135bda4aa76c6f8dc2d77b
644,545
def getGantryInfoFromPath(filepath): """Get dataset info from path.""" parts = filepath.split("/") # First check whether immediate parent folder is a timestamp or a date if parts[-2].find("__") > -1: # raw_data/scanner3DTop/2016-01-01/2016-08-02__09-42-51-195/file.json j_timestamp = part...
50e3ca33121f5fbf13e1bcfb4d1908c51cc4d442
644,547
def ask(prompt, type_=None, min_=None, max_=None, range_=None): """Get user input of a certain type, with range and min/max options.""" if min_ is not None and max_ is not None and max_ < min_: raise ValueError("min_ must be less than or equal to max_.") while True: ui = input(prompt) ...
76d7e9b9b4623867b4a1d12328fdb7022618cac3
644,548
import typing def _decode_object(pairs: typing.List[typing.Tuple[str, typing.Any]]) -> typing.Any: """ 'object_pairs_hook' callback for json.decode. If a fieldname is an integer literal convert it to 'int'. Field names and values that are of type 'unicode' will be converted to 'str', mostly becau...
9b44a7755df5f79f00b290dddecea096af6937d4
644,549
def _unit_dict(unit): """ Makes a dictionary to match unit label """ return { 'f' + unit : 1e-15, 'p' + unit : 1e-12, 'n' + unit : 1e-9, 'u' + unit : 1e-6, 'm' + unit : 1e-3, '' + unit : 1e0, 'k' + unit : 1e3, ...
e58d16b1cb1856037f93baa8bee8638a3899c1de
644,550
def form_metaquast_cmd_list(metaquast_fp, outdir, input_fasta): """format argument received to generate list to be used for metquast subprocess call Args: metaquast_fp(str): the string representing the path to metaquast executable outdir(str): the string representing the path to the output dire...
9a6d2e1419db4c8e630e7bf6577ac02f5c7bf7a8
644,552
def drop_null_fields(dataset, dropna_threshold=0.7, ignore_cols=[]): """ Usage: [arg1]:[pandas dataframe],[dropna_threshold(default=0.7)]:[What percentage of nulls should account for the column top be removed],[ignore_cols]:[columnd that shouldn't be dropped] Description: Drop columns t...
d5148c682e0e53bd5bd54e25093bb45390176815
644,553
def get_periodicities(pnt): """ Get periodicities for pointings Parameters ---------- pnt : list of dict Pointings Returns ------- periodicities : list of float Periodicities """ # Initialise periodicities periodicities = [] # Loop over pointings fo...
8e458d7db61100d762b7d60d293d4a0f67690448
644,554
def robots(environ): """Returns robots.txt""" status = "200 OK" responseHeaders = [("Content-type", "text/plain")] with open("robots.txt", "r") as f: output = f.read() return status, responseHeaders, output
af505f736841057db8b16070b58a8131267445d8
644,555
import os def path_splitall(path): """Split all components of a path into a list.""" outpath = [] while True: (head, tail) = os.path.split(path) if not head: break path = head outpath.append(tail) outpath.append(path) outpath.reverse() return outpath
abc8c1dfcd22fc958235c606307511a3ac43c042
644,557
def train(data, length=50): """Return average of last n data samples. Args: data (np.ndarray): Time series data length (int, optional): Length of used window (last n values). Defaults to 50. """ return data.ravel()[-length:].mean()
eb68064433489b7fe933ce8cc6d7c6839b2b9179
644,558
import platform def _is_shared_object(filename): """Check the file to see if it is a shared object, only using extension.""" if platform.system() == 'Linux': if filename.endswith('.so'): return True else: index = filename.rfind('.so.') if index == -1: return False else: ...
0429abb86399655f07b6ddc04d59f50c51a00782
644,559
def find_location(index, SIZE): """ Finds the x and y coordinates in a square grid of SIZE**2 given an index. It is assumed that we are counting from left to right on a set of rows top-down, and that area is square. Rows and columns start from 0 given Python indexing conventions. e.g. 0...
5120079db5e720df7373e186d8235da189b108c0
644,560
def extract_golden_standard(path_to_standard): """ Extracts the golden standard associations into a dict :param path_to_standard: str, path to the golden standard associations :return: list<(word<str>, meaning<str>)> tuples """ lexicon = set() with open(path_to_standard) as f: for l...
9b49188f19e147a30d19583afe1f5051bc8a3de0
644,561
def search_max_credit(score_table, max_credit): """ Search credits smaller than 'max_credit'. 'max_credit' is a float that between 0.0 and 8.0. 'min_credit' should be better smaller that 'max_credit'. """ return {v for v in score_table if v[2] <= max_credit}
127d6058a463c7fa2d589dc5a1eccec59b478e83
644,562
import json def read_json(filename): """ Opens the file, reads the data, closes it and turns it into a dictionary. Parameters ---------- filename : string The filename of a JSON file to be opened and read. Returns ------- Dictionary The JSON data in the file as a Pyt...
9ad68d5605162b22e67a4706f212e25d4d826cc0
644,563
def ultratio(fregion, uniqreate): """ ultraio = chrlength * uniqueratio / chr_total_reads """ genomelength = 0 adjreads = fregion.adjreads for chromosome in fregion.chrs_length: genomelength = genomelength + int(fregion.chrs_length[chromosome]) ultratio = genomelength * uniqreate...
63ce13856e0aa6c6ec9ed795249c58f54667d7ed
644,564
def solution(A): """ https://app.codility.com/demo/results/trainingBY9CAY-RBU/ :param A: :return: """ len_ar = len(A) + 1 sum_length = int(len_ar * (len_ar + 1) / 2) return sum_length - sum(A)
d3fb9946118f22465d3fa25e38f406cd0f824037
644,565
def dot(v1, v2): """Return the dot product of two vectors. Args: v1 (complex): First vector. v2 (complex): Second vector. Returns: double: Dot product. """ return (v1 * v2.conjugate()).real
4fe7a504512f07df16d816cfbed4067a485c6490
644,566
def calc_shift(func, in_data, **kwargs): """[Shift](https://docs.chainer.org/en/v4.3.0/reference/generated/chainer.functions.shift.html) Shift only conducts memory read, index calculation and memory write. There might be unnecessary memory read around corners, but for simplicity chainer-computational-c...
3edcddc41b342f2fe6a3d923f38025a0cb6ad4d9
644,567
def empty_units(number: int, from_unit: int) -> int: """ Puts zeros on all digits from the from_unit num being 152 and from_unit being 1 gives 100 """ mask: int = int(10 ** (from_unit + 1)) return number - (number % mask)
d85797380ea17297aa0a7df79d7c80e875b33803
644,568
def subtract(a, b): """ Returns the result of subtracting b from a >>> subtract(2, 1) 1 >>> subtract(10, 10) 0 >>> subtract(7, 10) -3 """ return a - b
a64b604490905fc967230fb8cc9e8359f0b489f7
644,569
def to_celsius(temp): """Converts temperature in Kelvin to Celsius""" temp_in_c = round(temp-273.15) return temp_in_c
e59c9c94ba42c369c7eb9721c8017baa340512aa
644,570
import torch def logistic_rsample(mu_ls): """ Returns a sample from Logistic with specified mean and log scale. :param mu_ls: a tensor containing mean and log scale along dim=1, or a tuple (mean, log scale) :return: a reparameterized sample with the same size as the input mean ...
9d66a21865b051fc919b0c179b928d1aab60a53f
644,572
def make_record(type_name, attributes, defaults=None): """Factory for mutable record classes. A record acts just like a collections.namedtuple except slots are writable. One exception is that record classes are not equivalent to tuples or other record classes of the same length. Note, each call to `make_rec...
3ee5f454890779e8a32658a25a437767ceecb1f9
644,573
def n_max_matchings(A, B): """ Compute the number of maximum matchings in a complete bipartite graph on A + B vertices. A and B are required to be nonnegative. Corner Case: If at least one of the sides has zero vertices, there is one maximal matching: the empty set. """ a = min(A, B) b = max...
32ee6e331e48a8ee2b7d5234a6ca033b895f6d75
644,575
def minify(value): """ remove unneeded whitespaces perhaps add fancypancy html/js minifier """ value = ' '.join(value.split()) return value
e8772d8b4ba6675df23d3cd895acf02ec0738056
644,576
def generate_product_instance_id(vm_fqn, product_name, product_version): """ Method to generate instance id for installed products (product instances) :param vm_fqn: FQN (where product has been installed) :param product_name: Product name (instance) :param product_version: Product release (instance)...
d9c5d3aecff66f7263955e400ba98d5625f783fc
644,577
def calculate_percentages(amount: int, attributes_count: dict) -> dict: """ Based on the calculated counts, creates a frequency table this time with the percentage a trait occurs - rounded to three decimal places. """ attribute_percentages = dict() # lambda func to calculate percentage def pe...
1d71dd9c5d7b630260140c9e771f12104da7bc22
644,578
from datetime import datetime def get_gldas_start_date(product): """ Get NOAH GLDAS start date. Parameters ---------- product : str Product name. Returns ------- start_date : datetime Start date of NOAH GLDAS product. """ dt_dict = { "GLDAS_Noah_v20_02...
2bbab8ad593bf5030468a11bf673e412e9b5ab32
644,579
from typing import List def adjacent_digits(n: int, digits: str) -> List[str]: """List of all adjacent digits of `n` length in `digits`.""" adjacents = [] while len(digits) >= n: adjacents.append(digits[:n]) digits = digits[1:] return adjacents
2a2f1dabf2b6a48937d70892ceb2054d7f74274b
644,583
def descriptor_target_split(file): """ Split the input data into descriptors and target DataFrames Parameters: file: pandas.DataFrame Input DataFrame containing descriptors and target data. Returns: descriptors: pandas.DataFrame Descriptors...
95d518ee9cce190ed08015986fc5b2d86c33318a
644,584
import codecs import json def dump(data, handle, **kwargs): """Serialize ``data`` as a JSON formatted stream to ``handle``. We use ``ensure_ascii=False`` to write unicode characters specifically as this improves the readability of the json and reduces the file size. """ try: if 'b' in han...
2d8ad1f1693ea3e41ec855934302ac0d396ee996
644,585
def some_func(): """Some random function that can be imported from unit tests. """ return True
945e22976c5b37f86c253eb530ef56744cefd2a4
644,586
import six def create_relax_result_node(**kwargs): """ This calcfunction assures the right provenance (additional links) for ALL result nodes it takes any nodes as input and return a special set of nodes. All other inputs will be connected in the DB to these ourput nodes """ outdict = {} ...
271c845b3624d221a0dec1719384a463724affe6
644,587
def year_week__default(element, compiler, **kw): # return compiler.visit_function(element) """ ## select extract(week from timestamp_event) from table_a; week_num = sqlalchemy.sql.expression.extract('WEEK', CertificateSigned.timestamp_not_before) """ args = list(element.clauses) return "conc...
075ff91e45f7a5be4bb98eb41ba69f27208e8b99
644,588
def format_file_size(size): """according file size return human format Arguments: size {int} -- file size Returns: str -- human format file size """ if size < 1024: return '%i' % size + 'B' if 1024 <= size < 1024 ** 2: return '%.1f' % float(size / 1024) + 'K' ...
15342db32a0b8ca08f5857a1907aecef68e1eb5f
644,589
def run_test_method(method_name, class_object, options, reporter): """Run a test method and return 0 on success, 1 on failure.""" test_object = class_object(method_name) test_object.setUp() test_result = test_object.defaultTestResult() test_object.run(test_result) test_object.tearDown() fq_method_name = "...
881b1e3bf13bddaf333336c0fccf6eadd0d6552d
644,590