content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import timeit import os def _training_timing(): """ Runs training.py script and measures execution time Returns: float: running time """ start_time = timeit.default_timer() os.system(f"python training.py") # _ = subprocess.run(['python', 'training.py'], capture_output=True) ti...
21ac59b6d08ef33f3bd19a7619a6a2f0cb4a4d92
639,691
def is_pow2(n): """ Check whether a number is power of 2 Parameters ---------- n: int A positive integer number Returns ------- bool """ return n > 0 and ((n & (n - 1)) == 0) # Solution 2 # return math.log2(n) % 1 == 0
6f386513eb4931339faf61c2552a3a8b7cde3053
639,692
def reward_func(observations): """Computation of the reward from the observations of the inverted pendulum env. The observations are also the ones predicted by the model. For compatibility with other environments the actions should be appended to the inputs observations as the reward can be a funct...
ed517a76d972d34ff822a1dc835ca0c84387dc89
639,693
def get_court_circuit(c): """Convert a court variable to the circuit it's on.""" dmap = {1: 13, 2: 13, 3: 13, 4: 14, 5: 14, 6: 13, 7: 13, 8: 13, 9: 22, 10: 99, 12: 9, 13: 99, 14: 13, 15: 99, 16: 99, 17: 99, 18: 99, 19: 0, 20: 22, 21: 1, 22: 2, 23: 3, 24: 4, 25: 5,...
5edb98bc10202eeb72216c09dda20a8ce5dec134
639,694
import sys def _get_user_input(): """ Get user's input, which will be transformed into encoder input later """ print("> ", end="") sys.stdout.flush() return sys.stdin.readline()
3ed39edef25893743dabf5121a5073a647728a66
639,695
import difflib def gen_ndiff(a, b): """ Return a binary diff result of the byte sequence as a YARA signature. :param list a: First buffer representing code block as hexlified bytes. :param list b: Second buffer representing code block as hexlified bytes. :return: YARA compliant hex string sequen...
f5f251fbf7f11ac2c90ab48a8a9108715eb5c3d9
639,696
def allocated_size(allocation_unit, requested_size): """ Round ``requested_size`` up to the nearest ``allocation_unit``. :param int allocation_unit: The interval in ``bytes`` to which ``requested_size`` will be rounded up. :param int requested_size: The size in ``bytes`` that is required. :...
f25a55f3cf96194c5357e106642b89f6aefba65c
639,699
def rotate_word(s, r): """ Rotate each char in a string by through the alphabet by the given amount. Wrap around to the beginning (if necessary). """ r_s = '' for c in s: num = ord(c) r_num = num + r r_c = chr(r_num) r_s += r_c return r_s
64d19c0cece0c57b2806d8e547944fee6fb3b0d5
639,700
def assign_constant_points(projects, default_task_value=10): """ Takes in parsed project tree, with one level of tasks Outputs project tree with constant points assigned """ for goal in projects: for task in goal["ch"]: task["val"] = default_task_value return projects
5f0865e0a60de866f3acdca62614d51bc4e8b324
639,701
import argparse as ap def parse_hr(): """This function allows the user to run the script in the command window and specify arguments. The arguments are for the data file to be run, one argument to allow for either ecg data or both ecg data and pp data, one argument to specify bradycardia, another to spec...
b81fd3b6ab46056e5c28f92143e5fb6b683e0e39
639,702
def count_gender(data_list): """ Esta função têm o objetivo de contar as inserções de gênero feminino e masculino no arquivo argumento: parâmetro1: trata-se do arquivo ao qual será verificada a inserção de gênero através do laço for. """ male = 0 female = 0 x=0 for n in ...
01fb5a98ed158d394cea34215442b730b566c80e
639,703
def default_cmdline_options(config): """ Return default command line options required for every run of terraform. Args: config: dictionary containing all variable settings required to run terraform with Returns: cmdline_options: list of command-line arguments to run ...
85f3e74049ae744f4a5b46eb382f293a3c9126d6
639,704
from datetime import datetime def utcnow_timestamp_ms() -> int: """UTC timestamp in milliseconds. Returns: timestamp (int): UTC time in milliseconds """ return int(datetime.utcnow().timestamp() * 1000)
bb8e5700c5e2a180e7a49e20e997f0a7d8958cc0
639,705
def genty_repeat(count): """ To use in conjunction with a TestClass wrapped with @genty. Runs the wrapped test 'count' times: @genty_repeat(count) def test_some_function(self) ... Can also wrap a test already decorated with @genty_dataset @genty_repeat(3) @g...
968b30740174f3b40532be0992aa7e7467463436
639,706
import click def check_hybrid(tags): """Check whether or not the release has mixed precisions/sample rate.""" first_tag = next(iter(tags.values())) if not all( t["precision"] == first_tag["precision"] and t["sample rate"] == first_tag["sample rate"] for t in tags.values() ): ...
820132b755657b775599023e98e7ffdf2c5a1233
639,708
def time_string(seconds): """Returns time in seconds as a string formatted HHHH:MM:SS.""" s = int(round(seconds)) # round to nearest second h, s = divmod(s, 3600) # get hours and remainder m, s = divmod(s, 60) # split remainder into minutes and seconds return "%2i:%02i:%02i" % (h, m, s)
24635313218b40646fcefd9b1e5d11d294736696
639,709
import os import json import logging def import_smtp_from_json(path,test=False): """A helper function to set the SMTP configuration for send_email from a json file Args: test (bool): Indicates whether this is just a test run (True), or (False) in prod path (str): The path to the smtp configura...
497b881ef0a1998e54e03ec9d5c6c3de9a4af1b6
639,710
def get_input_output_filenames_from_args(args): """Return strings inserted to input and output filenames.""" input_filename = args.input_filename output_filename = args.output_filename if args.input_output_filename is not None: input_filename = args.input_output_filename output_filename ...
ec955bc6f3d872abbb14b6734b2c1abcb9b676cf
639,711
def humanise_seconds(seconds): """ Takes `seconds` as an integer and returns a human readable string, e.g. "2 hours, 5 minutes". """ units = [] unit_table = [('hour', 3600), ('minute', 60)] for unit in unit_table: quotient, seconds = divmod(seconds, unit[1]) if quotient: ...
c2f6e1395699efa585102288f791011ac45affaa
639,712
def v_str(v_tuple): """turn (2,0,1) into '2.0.1'.""" return ".".join(str(x) for x in v_tuple)
479dd7d1af4a9f23a49ff7d0fe7bdcc9b8bc4411
639,713
def suffix_opt(opt_arg=''): """ return suffix for backup file """ suffix = '' if len(opt_arg) != 0: suffix = '.' + opt_arg return suffix
0a099756bb0b6054ff1c50faad5f44976c82a398
639,714
def dumps_utf8string(obj): """ Convert the specified L{dbus.types.UTF8String} to bpickle's representation for C{unicode} data. """ return "u%s:%s" % (len(obj), obj)
8d3b8b68689e1caad65436ac271012d0c5b20100
639,715
def sort_network(n_df): """ Sort the network. Parameters: n_df (list): the data Returns: list: the modified data """ return sorted(n_df, reverse=True)
d8b64cd1b351b89ff9ddab017294bc8b33409e3d
639,717
import itertools def nonzero_entries(array, eps=1e-7): """Extracts sparse [(value, *indices), ...] array representation. Args: array: The numpy array to obtain a sparse representation for, eps: Threshold magnitude. Entries <= `eps` are skipped. Returns: List of (coefficient, index0, ..., indexN) tu...
42967a7ee827f91a963d69a412754aec2319af3c
639,718
def _digest_via_trypsin(graph): """ Digestion via Trypsin. Each edge from a node with the aminoacid K or R as source gets cleaved (marked as TRUE) except when a P is followed (-> set as target). Additionally two new edges are added: 1: One edge from __start__ to the next nodes target (Beginnin...
1fd375f6d9e383826a6a4e4895942a20695e46b8
639,720
def flatten_batch_X(X): """ Flattens images """ return X.reshape(len(X), -1)
8a4499c72d7a36ae0c545a855713ebc2e12a0559
639,721
def verbatim(s, delimiter='|'): """Return the string verbatim. :param s: :param delimiter: :type s: str :type delimiter: str :return: :rtype: str """ return r'\verb' + delimiter + s + delimiter
379aa393af41e0a97ed3b1d66aa4620f2fb7682c
639,723
import argparse def load_args(): """Load the argument parser object""" parser = argparse.ArgumentParser(description='htseq tools') sp = parser.add_subparsers(description='Select a tool', dest='choice') sp.required = True # Get Gene Lengths glen = sp.add_parser("gene_lengths", ...
33737465d7df6d702c733cccd0605f4b67c9c393
639,724
def read_mol_dict(file): """ Read dict of molecules from file. Returns ------- molecules : :class:`dict` of :class:`dict` Dictionary of molecule definitions with `key` = name. """ with open(file, 'r') as f: lines = f.readlines() molecules = {} for line in lines: ...
a435dfea35d8e88587dfa782575c13fd420426ca
639,725
def get_command(nbapp): """Get the command to run""" terminalsAvailable = nbapp.web_app.settings['terminals_available'] # Compatibility with Notebook 4.2. token = getattr(nbapp, 'token', '') cmd = ['mocha', '--timeout', '20000', '--retries', '2', 'build/integration.js', ...
4b6d35cdfa48df66d8cfc3748bf7253e66188ebd
639,726
def speak(): """ A typical Hodor response """ return ("Hodor")
209dec7d0adc133c03bfbd623eb91d295bbc1e55
639,727
import os def is_file_and_json(json_file): """Validates that the file exists and is a JSON file.""" return os.path.isfile(json_file) and json_file.endswith('.json')
441ec8ea4ca0b02879371427ad9e69c0034777c6
639,728
import os import codecs def read(filename): """Read and return `filename` in root dir of project and return string""" dirname = os.path.abspath(os.path.dirname(__file__)) return codecs.open(os.path.join(dirname, filename), "r").read()
eca21142275adb7d5dcaf035c54eed3c7ee39192
639,729
from json import load import logging def read_json(filename): """ Reads input from a JSON file and returns the contents. :param str filename: Path to JSON file to read :return: Contents of the JSON file :rtype: dict or None """ try: with open(filename) as json_file: re...
6f0b4589207430f3325eef4536640711e684df89
639,730
import re def filter_location(location): """ (str) -> str Filter input string from such characters as parentheses and blank symbols >>> filter_location("United Kingdom {(UK)}") 'United Kingdom' """ location = re.sub("[(].*?[)]", "", location) location = re.sub("[{].*?[}]", "", location...
d7a8d2f3ea5a9900aac2df2e601963f8e43da86f
639,731
def get_median_change_tweets(trend_days): """ Function for calculating trend differences between days, based on tweets. @param trend_days: the data to calculate trend graph from. @return: list fo points for a graph. """ keys = sorted(trend_days.keys()) #print keys results = [] for i ...
7e5707e675b8366488480dcbe37adf1d6ac7949a
639,733
def serialize_primitive(obj, spec, ctx): """ Serialize a primitive value. """ return ctx.dumpval('', obj)
63be72a1e8959a75f5b623fa7938e8a369191b54
639,734
def bterm(f,p,pv0,e,B,R,eta): """ For the cubic equation for nu in the four-variable model with CRISPR, this is the coefficient of nu^2 """ return -(e*f*pv0*(pv0*(f + R) + p*(1 + f*(-1 + B*(-eta + (1 + e + eta)*pv0)) - R + B*(eta + pv0*(-1 - e - eta + 2*R)))))
759e3cf058c0d6fe05f3a81e9a5d6dd587365104
639,737
def assert_interrupt_signal(library, session, mode, status_id): """Asserts the specified interrupt or signal. Corresponds to viAssertIntrSignal function of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Unique logical identifier to a session. :param mode: How...
f55af51b3bddd3c113223d1ce9ac94a4d20d64ad
639,739
def get_option_from_user(options): """Give the user options to select :param options: Set of available options for the user :type options: `str` :return: The different options for the user to choose from :rtype: `str` """ return input("Options: 'e'+Enter= Exit {!s}, Enter= Next test\n".form...
e9a283ac3c0e7efd00a43872b80bb5295d2be460
639,740
def extract_sentences(filepath): """ """ sentences = [] with open(filepath) as infile: for line in infile: sentences.append(line) return sentences
6e0ff58d83d4ba16f9cd7b22fb720787f894f9f5
639,743
def build_reagent_vectors(portion_reagents, portion_chemicals): """Write the reagents in a vector form, where the vectors live in the complete portion basis The basis is spanned by all chemicals in all reagents in the portion (sans solvent) :param portion_reagents: a list of all reagents in the portion ...
f8d12ef19e84111dde7a40fa5d1113b4f423ab6f
639,745
def read_dictionary(filename): """ 將所有的單字都視為key,value則為True,往後只要不是在字典內的單字則會被判斷成None (All words are treated as keys, value is True, and any word that is not in the dictionary will be judged as None thereafter.) :param filename: location of dictionary.txt :return: dictionary format:dictionary[word]=[True] """ dic...
08296cea10ae6e1b1282baa229d6730262bcac86
639,746
def translate(tile, offset): """ Move a tile. This returns a moved copy; the original is unchaged. Parameters ---------- tile : tuple containing y and x slice objects offset : tuple translation, given as ``(y, x)`` Returns ------- tile : tuple a copy; the in...
0a43b48147dd2782e8d994da487a3ea020e20006
639,747
def get_finegrained_count(text, gender_dct): """ Count the number of female, male, and neutral gendered words in a string, given the gender dict. """ text = text.lower() f_count = 0 m_count = 0 n_count = 0 for line in text.split('\n'): words = line.split(' ') for word...
fb5e0cdb0768d3b56892431d032e642fb37211f5
639,748
import unittest import os def _discover_test_runner(path, args): """Test runner that looks for tests in *path* :param str path: path to search for tests :param args: parsed arguments :type args: `argparse.Namespace` """ suite = unittest.TestLoader().discover(path) unittest.TextTestRun...
56ddff2f279a4f6dabd43530a61d4baa30d87aa6
639,749
def to_dict(X): """Make dict-like. Parameters ---------- X : dict """ if hasattr(X, "items"): return X elif X is None: return {None: None} else: return {None: X}
758307c47a04b3d4e5da8ae7768ee35df5e035c0
639,750
def CommonChecks(input_api, output_api): """Presubmit checks run on both upload and commit. This is currently limited to pylint. """ checks = [] blimp_tools_dir = input_api.PresubmitLocalPath() def J(*dirs): """Returns a path relative to presubmit directory.""" return input_api.os_path.join(blimp...
8c87d4ba84b6bf647f73139344ed6d8e29716b1b
639,753
def decrypt(m,d,n): """ Returns decrypted message. Parameters: m (int): encrypted message d (int): private key n (int): modulus Output: decrypted message in numeral form """ return(pow(m,d,n))
f06814403f680b60c36f992eb93900d1a70312df
639,754
import os def get_file_name(path): """ Extracts only the filename from the given path. Extension is removed as well. """ base = os.path.basename(path) return os.path.splitext(base)[0]
0cf7beb4e8361506bdf487bc4f71755660d9ff1d
639,756
import os def FindFile(filename): """Return the full windows path to a file in the same dir as this code.""" thisdir = os.path.dirname(os.path.join(os.path.curdir, __file__)) return os.path.abspath(os.path.join(thisdir, filename))
a83a4f9f6f393c75a7f7d51423a1129404aee5cf
639,757
import click from typing import Union from typing import Optional from pathlib import Path from typing import List from typing import Tuple def get_files_to_copy_to_genconf_dir( ctx: click.core.Context, param: Union[click.core.Option, click.core.Parameter], value: Optional[Path], ) -> List[Tuple[Path, Pat...
2167a22c2dc5399ba5b5e9524121c874a99d7f86
639,758
def make_chrom_bounds(cfile): """ :param cfile: :return: """ boundaries = dict() with open(cfile, 'r') as infile: for line in infile: if not line.strip(): continue name, size = line.strip().split() boundaries[name] = {'start': 0, 'end':...
5a7bef0f585f752f1dd7861512f1a70799e039e2
639,760
from typing import Tuple import re def check_email(email: str) -> Tuple[bool, str]: """ Check if the email is true """ if re.search('@', email) is None or re.search('.', email) is None: return False, "Votre email doit contenir un @ et un ." if not re.match(r'^[A-Za-z][A-Za-z0-9_-]+$', email): ...
0e3176e7da9c0b0e55de67a92d29c555e3b2f019
639,761
import re def pascal_francis_conference_zotero_map(PF_notice_elements_list): """ params: PF_notice_elements_list, [[],{},[],[],{},[],{},{}, ...] return: zotero_dict_note_list, [{},{}] """ # zotero_dict = {'DOI': '', 'ISBN': '', 'abstractNote': '', ...
57b73e7f8bfd5966f0a58a3b7d73ba9c0550db74
639,762
def indent_code(code): """ Takes the lines of code in `code` and adds for spaces to each line. :param code: string containing code to be profiled :return: string containing indented code """ return [' ' * 4 + line for line in code.split('\n')]
a3825071b685267a805c72761b597a2d83c1aec4
639,763
import ctypes import os def is_admin(): """ Return True if the current user has elevated admin privileges. Should work on Windows and Linux. """ if os.name == 'nt': # WARNING: requires Windows XP SP2 or higher! try: # Warning: This call fails unless you have Windows X...
207c9da0d14ffedaabb9b49012ffee02b9018e3a
639,764
def A023811(n: int) -> int: """Largest metadrome. (number with digits in strict ascending order) in base n. """ result = 0 for i, j in enumerate(range(n - 2, -1, -1), start=1): result += i * n ** j return result
bbe0f007f6c3fa7975c6c2c440dc77bca6640968
639,765
def _get_percent(status): """ Yardstick util function to calculate success rate """ if status * 100 % 6: return round(float(status) * 100 / 6, 1) else: return status * 100 / 6
bf57db9a0a3073d7737438e66730d58d2df68e58
639,766
import subprocess def change_backlight(dir): """ Function decorator for Qtile to adjust the backlight up or down. @param {str} direction 'up' or 'down' """ process = ['xbacklight', '<amount>'] def inner(qtile=None): if dir == 'up': process[1] = '+10' else: ...
7e8801fec606be77969f91aa2e39ee26820451e1
639,767
def apply_pred(data, cat_model, cat_map, unsupervised): """Suggest labels """ data['pred_id'] = cat_model.predict(data.text) if unsupervised: data['pred'] = data.pred_id.apply(lambda y: cat_map[y]) else: data['pred'] = data.pred_id.apply(lambda y: [list(cat_map.keys())[list(cat_map.value...
f0cd8d8bb1d6daa631d656d60ab5b19021372f30
639,768
def remove_padding(data: bytes, block_n_bytes: int) -> bytes: """Removes 0x80... padding according to NIST 800-38A""" if len(data) % block_n_bytes != 0: raise ValueError("Invalid data") for i in range(len(data) - 1, -1, -1): if data[i] == 0x80: return data[:i] elif data[...
74e904d01448ac9a04b245cb6f8e94bc8a39b67c
639,769
from yaml import dump from typing import Dict def yaml_pep_filter(p, **kwargs) -> Dict[str, str]: """ YAML PEP filter, that returns Project object representation. This filter can save the YAML to file, if kwargs include `path`. :param peppy.Project p: a Project to run filter on """ data = p...
ac9a91827a23d657a2437db037fd7e68e21915cd
639,770
import os def get_evaluation_filename(path, extension='txt'): """Ground truth of test set""" return os.path.join(path, 'evaluation_result.%s' % extension)
9d44cde7817c8c074cccab2999a93c52a2b7baf1
639,771
def freq_wise_bmm(a, b): """ Parameters ---------- a: (..., n_freq, n_channels_1, n_channels_2) op 1 b: (..., n_channels_2, n_freq, n_frames) op 2 Returns ------- The batch matrix multiplication along the frequency axis, then flips the axis back Tensor of shape (...
e54c684106cca842b72b8b2522836815b14aa6ac
639,773
import sys def get_line(): """read a line from sys.stdin""" return sys.stdin.readline().strip()
a4f5f7eaa1469e5231b7bede3f12ccd1b214168c
639,775
def _reconstruct_flattened_structure(structure, flattened): """Reconstruct the flattened list back to (possibly) nested structure. Parameters ---------- structure : An integer or a nested container with integers. The extracted structure of the container of `data`. flattened : list or None ...
54fa02bb70cc62ec48266987c0503ba9df9c6d15
639,776
import math def get_code_len(class_range, mode=0): """ Get encode length :param class_range: angle_range/omega :param mode: 0: binary label, 1: gray label :return: encode length """ if mode in [0, 1]: return math.ceil(math.log(class_range, 2)) else: raise Exception('On...
ff053e24b9cca0cc5298cdd665ac9bd5a6612847
639,777
import os def normalize_path_arg(path_arg: str, may_need_tilde_expansion: bool = False) -> str: """Normalizes a path by using os.path.realpath(). Note that this function is expected to be used with command-line arguments. If the argument comes from a config file or GUI where tilde expansion is not do...
85351c20d8f3f7920250b47555eacaa05f468bfc
639,778
def mergesort(input_list): """ Takes in a list and splits it into halves recursively, then compares parts of the list to each other and merges them sorted into another list """ output = [] if len(input_list) > 1: mid = len(input_list) // 2 first_half = input_list[:mid] second...
9f13c283c8997ef544035998faae4750af899332
639,780
import shlex def shlex_join(argv): """Undo enough of the "shlex.split" to log its work reasonably well""" rep = " ".join((repr(_) if (" " in _) else _) for _ in argv) if '"' not in rep: # like don't guess what "'$foo'" means try: if shlex.split(rep) == argv: return r...
a0c79de964e53fe6346bf6c858f94c54138e46a5
639,781
def get_better_name(book_name): """ Sometimes book name is slightly different than entered. This will try find more suitable book name using google search. """ return book_name
4fb6a94a513a26aacf96cfe99b248b5aa3805cf4
639,782
def logical_right_shift(n: int , shifted_by: int)-> str: """ Take in 2 positive integers. 'n' is the integer to be logically right shifted 'shifted_by' times. i.e. (number >> shifted_by) Return the shifted binary representation. """ if n < 0 or shifted_by < 0: raise ValueError('The ...
d213f60bba3e41ca9c2e9e7fed85aca1c7757da3
639,783
import json def smtp_json(): """Return an SMTP JSON.""" return json.loads( """{ "name": "RVXXX1-SP", "from_address": "Camp1 Phish<camp1.phish@bad.domain>", "host": "postfix:587", "interface_type": "SMTP", "ignore_cert": true }""" )
40620b34a277bbb234949a1fe4f209290aa3f86d
639,784
def _first_label(label_list): """ Find first non-blank label """ llist = [lobj.get_text().strip() for lobj in label_list] for label_index, label_text in enumerate(llist): if label_text not in [None, '']: return label_index
b6e49ea2c9c1847ae5efb098a2e6d2b3903524a8
639,785
import logging def sqrt(number): """ Calculate the floored square root of a number Args: number(int): Number to find the floored squared root Returns: int: Floored Square Root """ if not isinstance(number, int): logging.error("Invalid input type. Should be integer.") ...
d142e4c4ad86815284bde71ca23ff20e47fe7bf3
639,786
import os def _resolve_file(file_name): """ Checks if the file exists. If the file exists, the method returns its absolute path. Else, it returns None :param file_name: The name of the file to check :return: An absolute path, or None """ if not file_name: return path = o...
bca3bcdc798a29cd68a67967ac5b870ebb08433f
639,787
def is_hamiltonian_path(G, route): """Determines whether the given list forms a valid TSP route. A TSP route must visit each city exactly once. Parameters ---------- G : NetworkX graph The graph on which to check the route. route : list List of nodes in the order tha...
83dfb42171e6ecc5a51953b54ec4e7ccd9356d3c
639,788
import math def utilityY(c1,c2,rho): """Compute the utility of the young agents Args: c1 (float): consumption of the young generation c2 (float): consumption of the old generation rho (float): discount parameter Returns: (float): utilit...
6efd01d4a8f85a61f05eb12efca31b63f9f8aeaf
639,790
import operator def _sortIssues(issues): """ Helper function from _formatIssues(). Sort a list of issues by issue number and then by comment creation date. GIVEN: issues (list) -- nested list of issues and their comments RETURN: new_issues (list) -- the given 'issues' list, but sorte...
c43e388c07b398b9532b97c2ea73b22f8e96d428
639,791
def beam_centre_mosflm_to_xds(x, y, header): """Convert a beam centre for image with header information in header from mm x, y in the Mosflm cordinate frame to pixels x, y in the XDS frame.""" # first gather up some useful information from the header width, height = tuple(map(int, header["size"]))...
7cab1b505942a2460d2b21dd426d7a7be4a3a604
639,792
def time_to_string(time: int) -> str: """Convert time to string representation Args: time (int): Time in seconds Returns: str: Time in MM:SS format """ if time < 0: raise ValueError("Negative integer not supported") return "%02d:%02d" % (time // 60, time % 60)
3d6f639467c216e9fe9cec3b89e65f617cd89cba
639,793
def rgb_hex_to_rgb_list(hex_string: str): """Return an RGB color value list from a hex color string.""" return [ int(hex_string[i: i + len(hex_string) // 3], 16) for i in range(0, len(hex_string), len(hex_string) // 3) ]
f760ae986a1d98d4bc159e88d1c84776cebb6947
639,794
import binascii def bytes_to_hex(seq): """Converts seq from byte array to hex string""" return str(binascii.hexlify(bytes(seq)), 'ascii')
7c332852a066d738719db0fbe4ae7466f0973e7a
639,795
def check_inequality(left_version, right_op, right_version, **_): """ Checks for version compatibility when the dependency for 'left_version' has specified an explicitly disallowed version Args: left_version (packaging.version.Version): The version on the left side of the comparison...
8e783c265d04c06b85f3676f4c168b934f260f4e
639,796
def is_to_play(game, user_id): """Checks if the specified user is to play this turn in the specified game. game - the game to check if the user is in user_id - the ID of the user for which to check if playing """ return game.get_player_id_to_move() == user_id
307e714d761f35041802bf83698a0a5d25ccf046
639,797
def thermal_energy(particles): """ Returns the total internal energy of the (gas) particles in the particles set. >>> from amuse.datamodel import Particles >>> particles = Particles(2) >>> particles.u = [0.5, 0.5] | units.ms**2 >>> particles.mass = [1.0, 1.0] | units.kg >>> particles.th...
91aad749b8523ca8adfc4e8951d3b774b9222c5f
639,799
def normalized(name, feed_entries, start): """Returns a list of normalized kvstore entries.""" data = [] for feed_entry in feed_entries: if 'indicator' not in feed_entry or 'value' not in feed_entry: continue # Make the entry dict. entry = feed_entry.copy() entry...
04cd81291c52b9d5114d0e26176bf6836467bff8
639,800
def filter_args(arg_dict, fields=None): """only pass to network architecture relevant fields.""" if not fields: # if arg_dict['net_type'] == 'resnet': fields = ['net_type', 'num_scales', 'in_channels', 'mid_channels'] # elif arch['net_type'] == 'densenet': # arch_fields = ['net...
d9df810efca673bf9a36ba4ab58801bb03b353ce
639,801
def ensure_existence(f): """ Ensures that method is not marked as non_existent Parameters ---------- f Method Raises ------ NotImplementedError if the method is marked as non existent Returns ------- Method f """ if getattr(f, 'not_existing', False): raise Not...
18410fe298fcb5dab3114dea1632010d4778417c
639,802
from typing import Dict from typing import List def get_evaluations(data: Dict[int, List[int]]) -> Dict[int, float]: """ Turns a dictionary with float lists into a dict with mean values. :param data: Input dictionary with float lists :return: Output dictionary with float mean values ...
c986e360d6434871baf08d18abc6cb1ffa03547f
639,803
import os def Home(): """ Home directory """ return os.path.expanduser('~')
a913005733483992505fc57f1cb24b6e52ef7f63
639,804
def has_all_dims(dp_or_event, dims): """ Tests if `dims`'s are all in a certain datapoint or event """ return dims.items() <= {d.key: d.value for d in dp_or_event.dimensions}.items()
435374511a4d57c07374f1038a6821b837164edc
639,805
def compound_noun_list(token): """Find compound nouns. :param token: token for which to generate potential compound nouns :type token: :class:`spacy.token` :return: list of potential compounds :rtype: [string] """ nouns = [token.text] for nc in token.lefts: if nc.dep_ == "compou...
9bb3bae0f3b9cb1fd13a82c39f9d2123d179da17
639,806
def find_num_player_in_group(group): """ find the number of players in a group :param group: A Group object :return: number of players in the group """ players = group.players.all() return (len(players))
3a1f470bf64fe9409237da7afe1c0692a7b68d53
639,808
import multiprocessing import time def batch_process(func, iter_input, num_cores=multiprocessing.cpu_count()): """ Takes in a function, independent inputs to the function in a list, and the number of desired parallel cores and parallelizes the computation across the number of cores desired, returning ...
7334c42406e1d6d9f196b30546ada966a02c5446
639,810
import json async def _sendLambdaRequest(session, lambdaUrl, anomalyServiceObj): """ Async method to send anomaly detection request to lambda :param session: ClientSession instance for aiohttp :param lambdaUrl: AWS Lambda invocation endpoint :param anomalyServiceObject: Dict containing parameter d...
46403e12d0bd277f893c0c5d3e2547ddc8acadd7
639,811
def inject_port_module(self, *args, **kwargs): """"inject_port_module""" return None
16be69b08fde6343acb891465a778aa891b25caa
639,814
def csv_to_list(x): """Converts a comma separated string to a list of strings.""" return x.split(",")
55b97bb93ac6315718ad5b140650be39083c6714
639,815
import torch def balanced_positive_negative_sampler(matched_idxs, batch_size_per_image, positive_fraction): """ Arguments: matched idxs: list of tensors containing -1, 0 or positive values. Each tensor corresponds to a specific image. -1 values are ignored, 0 are considered as ...
72faec5a1ce651c98f0f2ff87ebb88abaa3d8d65
639,816