content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
from datetime import datetime def _obstime(fol): """ Python >= 3.7 supports nanoseconds. https://www.python.org/dev/peps/pep-0564/ Python < 3.7 supports microseconds. """ year = int(fol[0]) if 80 <= year <= 99: year += 1900 elif year < 80: # because we might pass in four-digit ye...
ae473c5931f0fb71b5520a087bf6b2e4f595a0b5
663,662
import textwrap def fio_json_output_broken(): """ Example of broken, unparseable json output. """ fio_out = textwrap.dedent( """ { "fio version" : "fio-3.7", "timestamp" : 1584531581, "timestamp_ms" : 1584531581691, "time" : "Wed Mar 18 11:39:41 ...
74532f5e5e85ba7cef244ad6652cc9814f7c175e
663,663
import copy def get_partial_condition(cond, exclude_factors=[], include_factors=[]): """ Gets a subset of a full condition """ new_cond = copy.copy(cond) if isinstance(exclude_factors, str): exclude_factors = [exclude_factors] if isinstance(include_factors, str): includ...
bbba7ca8388ab7ee503f5f8e6ea5b31128493964
663,664
import re def line_to_dict(line, index1_type, index2_type): """ Takes a string which represents a dict, fixes data from line and returns back a dict. """ dct = {} pattern = re.compile('\([^:]*, [^:]*\): \d*') data = re.findall(pattern, line) for item in data: raw_index, value =...
1bb02a24c2d64c187adaec1204e78c6dc232f648
663,665
def serverbase_addr(): """Параметры серверной информационой базы.""" class Result: server = 'server1' infobase = 'infobase1' return Result
0640b9bb101b6c15049ffd506238a57836edae17
663,666
import numpy def normalize(a: numpy.ndarray) -> numpy.ndarray: """ Normalize an array (vector) Note that the type hints specify numpy.ndarray -- this is shorthand for any of the Point or Vector types in this module (as they all derive from numpy.ndarray """ return a / numpy.linal...
e9c11868bfb59db0ca597fc794ed4e5588bcdd69
663,668
import csv def readCSVIntoList(link): """ Reads CSV to list using 'csv.reader()' Params: link (String) - contains link to the file Returns: tweets_list (List) - containing the tweets in vector form (m x 1) """ tweets_file = csv...
9d0afe32a127930869cdc4b91e99d93488f210f2
663,669
import os def get_requirements(file_name): """Returns requirements from the given file.""" file_path = os.path.join(os.path.dirname(__file__), file_name) with open(file_path, 'r') as f: return [line.strip() for line in f]
5044904c9724e2797c10450f8288e89bc0ee9043
663,670
import os def get_files_to_analyze(file_or_directory): """ :param file_or_directory: name of either file or directory of files :return: a list of all files (even if there is only one) """ files_list = [] if os.path.isdir(file_or_directory): # Build list of files from provided director...
b170e664476307240ecf12028741e28f7a2000e1
663,671
def deduplicate_column_names(df): """ Deduplicate column names by adding suffix f"_{i}" """ df.columns = [ x[1] if x[1] not in df.columns[: x[0]] else f"{x[1]}_{list(df.columns[:x[0]]).count(x[1])}" for x in enumerate(df.columns) ] return df
3a97346069e909bdd5ff5dbe2db1bbe1de90e80b
663,672
from typing import Mapping def _turn_iterable_to_mapping_from_attribute(attribute, obj, optional=False): """ Given ``obj`` which is either something that is an instance of ``Mapping`` or an iterable, return something that implements ``Mapping`` from ``getattr(o, attribute)`` to the value of the items ...
d1b3eeea07c48c73b97e6f93759e983f9aa262ba
663,674
import functools import warnings def deprecated(f): """Prints a deprecation warning when called.""" @functools.wraps(f) def wrapper(*args,**kw): warnings.warn_explicit("calling deprecated function %s"%f.__name__, category=DeprecationWarning, ...
2cbf070c902f026acb0df61fcd17f65191139d55
663,675
import requests def get_artist_info(artist): """ Args: artist (str): name of an artist Returns: dict: dictionary of information about an artist {artist_name, artist_genre, artist_biography} """ try: r = requests.get( f"https://www.theaudiodb.com/api/v1/json/...
80628602831609eecd9559fbbe96cda6afab4404
663,676
import ast import sys def open_txt_points(filename): """ Gets latitudes and longitudes from sample/grid point file :param filename: points txt file to open :return: lons, lats """ converted = None with open(filename, 'r') as f: for curline in f: # check if the current l...
44d167c1509e17e3b9126c7b959b290d3e9b100d
663,677
def enable() -> dict: """Enable the WebAuthn domain and start intercepting credential storage and retrieval with a virtual authenticator. """ return {"method": "WebAuthn.enable", "params": {}}
2c69d15fbf0dd07685f5611eeab57deba4dbde21
663,678
def loan_principal(a: float, i: float, n: float) -> float: """ Calculates the loan principal given annuity payment, interest rate and number of payments :param a: annuity payment :param i: monthly nominal interest rate :param n: number of payments :return: loan principal """ numerator = ...
dc5a991a6fc0d6ed9e5e3fd3138a0ed8c9d13fe0
663,679
import string import random def id_generator(size=6, chars=string.ascii_uppercase + string.digits): """Random string generator. Original code from: http://stackoverflow.com/questions/2257441/random-string-generation-with-upper-case-letters-and-digits-in-python Parameters ---------- size : i...
b501dda1c9514671c6a944ee5d61785da51ace08
663,680
def EdgeInside(original_edge): """ """ shape = original_edge.shape extend = original_edge.extend shape.move((0,extend/2.0)) return original_edge
4db3572ccc90b17aae464ffeed9d09c9966ed9a6
663,681
from typing import AsyncIterable from typing import AsyncIterator from typing import NoReturn def empty() -> AsyncIterable[None]: """ Returns an asynchronous iterable that yields zero values. """ class Empty(AsyncIterator[None]): def __aiter__(self) -> AsyncIterator[None]: return ...
f6789e6c62a6713929f589493c41aad6bff6667c
663,682
import os import csv def generateCSV(dll_name, dll_runtimes): """ Write throuput performance data to a csv file to be consumed by measurement.py Args: dll_name (str): the name of the dll dll_runtimes (float[]): A list of runtimes for each iteration of the performance test """ csv_file...
9f36ccd16b699a4a50effa127bc2400f8f7632d7
663,684
def topHat(r,A0=0.2): """Top-hat beam profile as used in Ref. [1]. Args: r (numpy array, ndim=1): Equispaced 1D grid for radial coordinate. A0 (float): Top hat width (default: 0.2). Returns: f (numpy array, ndim=1): Top-hat beam profile. """...
5bb8a71daf3150d45b6120ce9be692e03e4f4e23
663,685
def deep(m, dflt, *pth): """Access to props in nested dicts / Creating subdicts by *pth Switch to create mode a bit crazy, but had no sig possibilit in PY2: # thats a py3 feature I miss, have to fix like that: if add is set (m, True) we create the path in m Example: deep(res, True), [], 'post'...
19f292b7885ac1abc5c0e010933a205ebc700984
663,686
def npv_converter(sensitivity, specificity, prevalence): """Generates the Negative Predictive Value from designated Sensitivity, Specificity, and Prevalence. Returns negative predictive value sensitivity: -sensitivity of the criteria specificity: -specificity of the criteria preval...
7e4199ebdf967650595afcc0b3cfd6c01520b333
663,687
def get_body(msg): """ :param msg: :return: """ if msg.is_multipart(): return get_body(msg.get_payload(0)) else: return msg.get_payload(None, True)
390d183cdae2a92cb377dcb0ee2d1892e1c44d2f
663,688
def _parse_kernel_initrds_value(line): """ Called by "kernel_initrds" method to parse the kernel and initrds lines in the grub v1/v2 config """ return line.split()[0].split('/')[-1]
7aaf61aa0e545192b56425a64b63ca89ca64894b
663,689
def frange(min, max, delta): """ Floating point range. """ count = int(round((max - min) / delta)) + 1 return [min + i*delta for i in range(count)]
06d1d216de2918761c21091027464bb50e28da04
663,690
def read_csv_col(file_path, col_idx=0, row_offset=1): """ This function reads a csv file and returns the column data specified by the col_idx. :param file_path: :param col_idx: :return: """ with open(file_path, 'r') as f_ref: line_list = f_ref.readlines() col_data_list = [] l...
788af0655e3c7b362c4c803722a65301b33cdee5
663,691
def convert_error_code(error_code): """Convert error code from the format returned by pywin32 to the format that Microsoft documents everything in.""" return error_code % 2 ** 32
40197987e46fab5082b7ccad308edbefd472b852
663,692
import os def dataset_name(dataset_dir): """Gets standard dataset name from dataset directory. Args: dataset_dir (`str`): absolute dataset directory. Returns: `'cub'`, `'awa2'` or `'sun'`. """ benchmark = os.path.split(dataset_dir)[1] if not benchmark: benchmark = os...
7ef1aaee88af6708525517de4c9ffe84c51cec20
663,694
def simplify_polyphen(polyphen_list): """ Takes list of polyphen score/label pairs (e.g. ['probably_damaging(0.968)', 'benign(0.402)']) Returns worst (worst label and highest score) - in this case, 'probably_damaging(0.968)' """ max_score = 0 max_label = 'unknown' for polyphen in polyphen_li...
c31334c0526beed5c3506fb121f3b0e4a3fe51ee
663,695
def snake_to_camel(value: str, *, uppercase_first: bool = False) -> str: """ Convert a string from snake_case to camelCase """ result = "".join(x.capitalize() or "_" for x in value.split("_")) if uppercase_first: return result return result[0].lower() + result[1:]
6b5498e997b7a5408e55ef6a8921ffe2df37cd84
663,696
def _expt__CMORvar(self): """Return set of CMORvar item identifiers for CMORvars requested for this experiment""" cmv = set() for u in self._get__requestItem(): ri = self._inx.uid[u] rl = self._inx.uid[ri.rlid] for i in rl._get__CMORvar(): cmv.add(i) return cmv
db40213a4aee047321a6e19647e04228c2c9f084
663,697
def _expand(variant, nts=False): """Expand Variant field into list for iso_5p, iso_3p, iso_add, iso_snp""" list_variant = [] isomir = {} snp_var = [] for v in variant.split(","): if v.find(":") > 0: isomir[v.split(":")[0]] = v.split(":")[1] elif v.find("snp") > 0: ...
e4ad9a8d7776ae0eb1781137413915b38308214b
663,699
def diam_floc_max(epsMax): """Return floc size as a function of energy dissipation rate. Based on Ian Tse's work with floc size as a function of energy dissipation rate. This is for the average energy dissipation rate in a tube flocculator. It isn't clear how to convert this to the turbulent flow c...
c030d1e89052f1c0ee476498627c48cec6bd23e2
663,700
import hashlib def md5(str,upper=True): """ 转MD5 :param str: 要转的字符串 :param upper: 默认True 转大写 :return: """ m5 = hashlib.md5(str.encode("utf8")) m5str = m5.hexdigest() if upper: return m5str.upper() return m5str
cb4eb6b1a1271959308a8842069d5adb99f1bcf6
663,701
import requests def test_ping(src_switch, src_port, src_vlan, dst_switch, dst_port, dst_vlan): """setup our rules for host / switch / switch and see if we can ping""" urlbase = "http://localhost:38080/checkpingtraffic" args = "srcswitch={}&srcport={}&srcvlan={}&dstswitch={}&dstport={}&dstvlan={}".format( ...
6043f92b966a1729d7a2b1cddf36f4ee9486e5fa
663,702
def valid_pdf_attachment(pdf_attachment): """ Given a string representing an attachment link, this function asserts if the link is a valid PDF link. """ invalid_urls = ["https://www.gov.uk/government/uploads/system/uploads/attachment_data/file/522875/BIS-16-22-evaluation-of-24_-advanced-learning-loa...
ef8813cbc2ea7f49d4d423df8099e267398c0ebe
663,703
import argparse import os def parse_args(): """Parses and returns command line arguments.""" parser = argparse.ArgumentParser() parser.add_argument( '-o', '--output', type=os.path.realpath, help='Path to output file') def maybe_list_file(arg): if arg.startswith('@'): retu...
59f08265b84b35f90b18f151e8506ac38b63cae1
663,704
def extract_name_email (txt): """ Extracts the name and email from RFC-2822 encoded email address. For eg. "Jeff Jeff <jeff.jeff@gmail.com>" returns ("Jeff Jeff", "jeff.jeff@gmail.com") """ if "<" in txt and ">" in txt: name, email = txt.split("<") return name[:-1], email[:-...
5226ab6c7fd9cfd3047e6a512f076f1e22a05f8c
663,705
def is_key_valid(key): """Returns True if a Cloud Datastore key is complete. A key is complete if its last element has either an id or a name. """ if not key.path: return False return key.path[-1].HasField('id') or key.path[-1].HasField('name')
019318b00c8843946dbd36b67570f19cbaed137d
663,706
def preprocess( text, min_token_len=2, irrelevant_pos=["ADV", "PRON", "CCONJ", "PUNCT", "PART", "DET", "ADP", "SPACE"], ): """ Given text, min_token_len, and irrelevant_pos carry out preprocessing of the text and return a preprocessed string. Parameters ------------- text : (str) ...
e36a622f748cb3f6900eda3f3e4d5ef8dbf44952
663,707
import datetime def convertto_iso_format(dt_obj: datetime.datetime): """Takes a given datetime object and returns the timestamp in ISO format as a string. Examples: >>> now = get_epoch_time()\n >>> now\n 1636559940.508071 >>> now_as_dt_obj = convertfrom_epoch_time( no...
3034ad46411438efb2abb3848cfaa12e18983aca
663,708
def get_googleanalytics(): """ Get Google Analytics script """ google_anal_id = 'UA-100755106-1' ganal = ' '+\ '<script async src="https://www.googletagmanager.com/gtag/js?id='+\ str(google_anal_id) +'"></script>'+\ '<script>'+\ ' window.data...
2d4cceb1156609333c26f971ac3d07ac3b4361fb
663,711
def convert_units(props, conversion_dict): """Converts dictionary of properties to the desired units. Args: props (dict): dictionary containing the properties of interest. conversion_dict (dict): constants to convert. Returns: props (dict): dictionary with properties converted. ...
ebc90fc3a94dcaab247633913e8a798e0fa298c6
663,712
def process_question(question): """Process the question to make it canonical.""" return question.strip(" ").strip("?").lower() + "?"
0372540179cb1680b7b66b140bb6eb92d2eae9c4
663,713
def healthz(): """ Handles the '/health' endpoint and checks the health status of the flask server. Sends back '200'. """ return "", 200
7b48f7be0a58e197e521b91155bfdd80324b73d7
663,714
import functools import operator def solution(resources, args): """Problem 8 - Version 1 Go through the entire 1000-digit number and calculate the product of each digit in the specified numbers of digits, then find the maximum. Parameters: resources The 1000-digit number ar...
f18b72d9f71491afa79cd7a12641376f937acd37
663,715
def search_red(text, hit_list): """フィルタ検索で、ヒットした文字を赤くする""" if len(hit_list) <= 0: return text hit_list.sort(key=lambda x:len(x), reverse=True) for hit in hit_list: if hit in text: red_tag = '<span style="color:red;">%s</span>' % (hit) text = text.replace(hit, ...
6f43cccfa0f99b5d96c9219565d1f67552cd308e
663,716
from typing import get_origin from typing import Union from typing import get_args def get_possible_types(t): """ Given a type or a Union of types, returns a list of the actual types """ if get_origin(t) == Union: return get_args(t) else: return [t]
e172de92d9dd76b77eaec821d39d84089328b3c6
663,717
import string import re def split(s): """Split string s by whitespace characters.""" whitespace_lst = [re.escape(ws) for ws in string.whitespace] pattern = re.compile('|'.join(whitespace_lst)) return pattern.split(s)
1d911d49776851350aac83532d434b7b9ccb11ba
663,718
import requests def delete_rule(request): """ Delete rule Deletes a rule. --- rule: description: ' Rule id ' in: path required: true type: string """ raise NotImplementedError() user = user_from_request(request) try: ret = requests.delete( ...
0979c394431062075cd463896013b6f78ee3840e
663,719
import re def build_query_dict(query): """ Given a query string, construct index. Args: query - a string to be indexed Returns: a dictionary with key being each distinct word in the query string and value being number of occurrence in query string """ query = query.lower() ...
d028590330230266c270eee26cc98ebdfc34475c
663,720
def is_valid_state(data: dict) -> bool: """Check set state data.""" return data is not None
a4628ac3e2d9166d0469d9eabdaa1768efd3a8b2
663,722
import requests import json def create_scope(api_url, token, scope): """ Creates a scope in Databricks workspace. This will fail if scope already exists. """ r = requests.post(api_url + 'preview/secret/scopes/create', headers={"Authorization": "Bearer " + token}, ...
1b1e1e454505881636ac35b434f25a674b7a5340
663,724
def sort_dict(d, reverse=True): """Return the dictionary sorted by value.""" return dict(sorted(d.items(), key=lambda item: item[1], reverse=reverse))
55a17c1c1b828aa6f72410c9d9bc08d3838ce905
663,725
def reduceWith(reducer, seed, iterable): """ reduceWith takes reducer as first argument, computes a reduction over iterable. Think foldl from Haskell. reducer is (b -> a -> b) Seed is b iterable is [a] reduceWith is (b -> a -> b) -> b -> [a] -> b """ accumulation = seed for value...
edc217ce3a53521e872ad04b461d6ecad9f549d2
663,726
import re def process_mac_ip_pairs(tshark_output): """ Process output from the tshark command with MAC-IP pairs and return parsed array of dictionaries. :param tshark_output: output obtained by running tshark command :return: array of dictionaries with parsed MAC-IP pairs """ # Remove white s...
c95c493b1630c1a9cbcefb2f42703095eb96bf1c
663,727
import collections def _get_network_type(): """Returns the type of the outputs of a value distribution network. Returns: net_type: _network_type object defining the outputs of the network. """ return collections.namedtuple('c51_network', ['q_values', 'logit...
46bc9a295e1c0b61918af03b9ea5ae5f3601d717
663,728
def stringifydict(res): """ """ a = {} for k,v in res.items(): if type(v) is dict: a[k] = stringifydict(v) else: a[str(k)] = v return a
c754b36cae4fc851eae7230b87863c8aa8af4d32
663,729
import getpass def get_system_username(): """ Return the current system user's username, or an empty string if the username could not be determined. """ try: result = getpass.getuser() except (ImportError, KeyError): # KeyError will be raised by os.getpwuid() (called by getuser...
caaf438cd7710c5cb5aa78f3d5e46a643eac61fb
663,731
def remove_duplicates_retain_order(seq): """Code credited to https://stackoverflow.com/a/480227. Args: seq (list): Any list of any datatype. Returns: list: The list in same order but only first occurence of all duplicates retained. """ seen = set() seen_add = seen.add return([x for x in seq if not (x in se...
a928c63a53ddd032ebcafc3d958d4e8efe313844
663,732
from typing import Any import re def get_MD(tag_bytes: bytes, no_tag: Any = None) -> str: """Extract the MD tag from a raw BAM alignment bytestring Parameters ---------- tag_bytes : bytes a bytestring containing bam formatted tag elements no_tag : Any r...
f12b9ac78ba8ed77f26219500dd28a0464b52a90
663,733
def choose(n, k): """ Binomial coefficients Return the n!/((n-k)!k!) Arguments: n -- Integer k -- Integer Returns: The bionomial coefficient n choose k Example: >>> choose(6,2) 15 """ ntok = 1 for t in range(min(k, n - k)): ntok = ntok * (n...
62b80dd620bf10e9058aedfebc32dfdfa34f0ae5
663,734
import requests def get_json(gl,ty): """ Creates a link from gl and ty and retirves the json data for the same [This proprty observed from the NSE Source] """ link = 'http://www.nseindia.com/live_market/dynaContent/live_analysis/'+ gl[:-1].lower() + '/' + ty + gl + '.json' r = requests.get(link) return r.json()
93cd4e1622505ae3ea87288773eca615c1e75ee9
663,736
def indices_of_nouns(tokens): """Return indices of tokens that are nouns""" return [i for i, (_, pos) in enumerate(tokens) if pos.startswith('N')]
d8f3bf620a4272aba3948ce9c82a767e197afdaa
663,737
import math def _lockfile_create_retries(timeout_sec): """Invert the lockfile-create --retry option. The --retry option specifies how many times to retry. Each retry takes an additional five seconds, starting at 0, so --retry 1 takes 5 seconds, --retry 2 takes 15 (5 + 10), and so on. So: timeout_sec =...
f34148d2d9bdb7e994081411fcccd1e55d4ce878
663,738
def _get_constr_list(buildingSurfs): """ Args: buildingSurfs: """ constr_list = [] for buildingSurf in buildingSurfs: constr_list.append(buildingSurf.Construction_Name) constr_list = list(set(constr_list)) constr_list.sort() return constr_list
aa8c94d6fe4a3d27259ee9b37633a5c0d71a0a57
663,739
def not_installed(package=''): """Return a dummy function for the package that is not installed.""" def dummy_fn(*args, **kwargs): raise ImportError('Package <%s> is required but not installed.' % package) return dummy_fn
0339ea5e243b2e2962dd9ed3b2966633063e81d4
663,740
def try_int(x): """ Converts a float to an int if it is already an integral value. Makes the JSON a little smaller. """ as_int = int(x) return as_int if as_int == x else x
8efd65927fe161f3fbc7d9df2cd2b49a19cfd2dd
663,742
import os import time def fuid(filename, max_staleness=3600): """ return a unique id for a file Using just the file's mtime to determine if the file has changed is not reliable - if file updates happen faster than the file system's mtime granularity, then the modification is not detectabl...
205eb08af13c239d0df2b8310dea55ef1f41768e
663,743
def AlignMatches(matches): """ Tallys up each dif's song id frequency and returns the song id with highest count diff Args: matches: list of tuples containing (song id, relative offset) matched from known song Returns: songId (int) """ diffMap = {} largestCount = 0 song...
d6caf440fc374845b72266e8fbef5bc45658cbf1
663,744
import platform def is_os(*args): """Check if current OS is in args Returns: bool """ return platform.system() in args
9643493d93dd13f3b5b6785c25a19f80bde081e9
663,745
def day_of_week_xxx(datetime) -> str: """ :param datetime.datetime datetime: :rtype: str """ days = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'] return days[datetime.weekday()]
d098230271c6702936a16f6fda8e47ba2ad27fde
663,746
def elaborateanswer(question): """ Give an elaborate, realitisc and Michael-Palin-like answer to the question `question`. Examples: --------- >>> elaborateanswer("Do you have some cheddar?") 'No.' >>> elaborateanswer("The camembert is indeed runny.") '<Nods.>' """ if questio...
15dd965ee0d74fe222603227535b8961da0d1883
663,747
def moveTeamBranchUsage(err=''): """ Prints the Usage() statement for this method """ # redo for submitTeamBranch m = '' if len(err): m += '%s\n\n' %err m += 'Moves Task Branches from any Team Branch to another Team Branch\n' m += 'within the same code stream\n' m +...
edadae0fe7dd6c80aa313dd02f7d88daa5ad2de4
663,748
def convert_shelves(element): """Get the names of all the shelves that hold this book.""" # The shelves for a review are returned in the following format: # # <shelves> # <shelf name="read" exclusive="true"/> # <shelf name="fiction" exclusive="false" review_shelf_id="1234"/> # ...
0afb1c0c0f7ff51847584c88d47ded20acfaa3e4
663,749
def poly(x1, x2, degree=3, gamma=1., r=0.): """ polynomial kernel function Parameters ------------ x1 : numpy array, (..., n) the first input feature vector x2 : numpy array, (..., n) the second input feature vector degree : positive double, default: 3 degree of ...
681306c6b6e55019d0103f981a8e478ddf14d4c0
663,750
def element_with_unique_name(self,name): """Returns the element with unique_name This mehtod extends the powerfactor.Application class. It returns the element with the given unique_name. Args: name: The unique name of the element e.g. 'Netz\\Last.ElmLod' Returns: A powerfactory.Da...
7513eded489913fbddbc1083df9fd017f5f2b94d
663,751
def shear(chromosome, start, end): """染色体剪切: [start,end), 染色体首位下标为1""" return chromosome[start:end]
b4653f5f3c98dfdb8bb13e480249c768aa65d8ab
663,752
def get_platos_y_dinero(): """Funcion que obtiene el numero de platos y el dienro a gastar""" platos = input("Cuantos platos se sirven hoy? ") dinero_disponible = input("Cuanto dinero va a gastar?: ") return platos, dinero_disponible
39e4cef3600d44c96472330ec3b77f42bdd8db23
663,753
def _step_to_value(step, num_steps, values): """Map step in performance to desired control signal value.""" num_segments = len(values) index = min(step * num_segments // num_steps, num_segments - 1) return values[index]
af5c4731827ceca84b56917812d43ff9da44a42d
663,754
import functools def qutip_callback(func, **kwargs): """Convert `func` into the correct form of a QuTiP time-dependent control QuTiP requires that "callback" functions that are used to express time-dependent controls take a parameter `t` and `args`. This function takes a function `func` that takes `t...
8d20a3fc75bd673a3b5576e2d147162d13ca19ba
663,755
def calc_decade(years): """A divison of Years // 10 , to determine how many decades passed.\n Returns : Int""" return years//10
39b8fc9b0fd459fce59b4ba3676a0411ff0ab3f5
663,756
def generate_range(start, stop, step=1, pre=None, post=None): """ Generate a range of values with optional stepping. Chars can be prepended or attached to the end of each value that is generated. """ rangevals = range(start, stop, step) values = [] try: if pre and post: ...
3cd04e75ca3c1391d98ee420732cf0a148361dd1
663,758
def get_claims(app_request=None, role: str = 'account_holder', username: str = 'CP0001234', login_source: str = 'PASSCODE'): """Return the claim with the role param.""" claim = { 'jti': 'a50fafa4-c4d6-4a9b-9e51-1e5e0d102878', 'exp': 31531718745, 'iat': 1531718745, ...
457acf6a36edb63c9df376b522a044cf7053f31b
663,760
import os import json def get_json(directory, type_=None): """Gather all json resource files of one type.""" resources = {} for filename in os.listdir(directory): if not filename.endswith(".json"): continue path = os.path.join(directory, filename) with open(path) as f...
447cea3c8c503f673ed7ba6977708fa32535dc84
663,761
def isNum(s) -> bool: """ Checks if its a number >>> isNum("1") True >>> isNum("-1.2") True >>> isNum("1/2") True >>> isNum("3.9/2") True >>> isNum("3.9/2.8") True >>> isNum("jazz hands///...") False """ if "/" in str(s): s = s.replace("/", "", 1) ...
ee16745f54346b7629e6dcd775690b634270d3bd
663,762
import os def app_config(app_config): """Application configuration fixture.""" base_path = os.path.dirname(os.path.realpath(__file__)) logs_dir = os.path.join(base_path, 'tmp/logs/') if not os.path.exists(logs_dir): os.makedirs(logs_dir) app_config['CDS_MIGRATOR_KIT_LOGS_PATH'] = logs_dir...
54ddafd9de4ddf989579cdab1f6f60c0d6ba80c4
663,763
def duplex_consensus(read1, read2): """(pysam.calignedsegment.AlignedSegment, pysam.calignedsegment.AlignedSegment) -> pysam.calignedsegment.AlignedSegment Return consensus of complementary reads with N for inconsistent bases. """ consensus_seq = '' consensus_qual = [] for i in range(read1.que...
9f430f00b54884b76e192f5bc17155d77bd7ff54
663,764
def _compute_average_precision(gold_labels, ranked_lines): """ Computes Average Precision. """ precisions = [] num_correct = 0 num_positive = sum([1 if v == 1 else 0 for k, v in gold_labels.items()]) for i, line_number in enumerate(ranked_lines): if gold_labels[line_number] == 1: ...
f8a81cce428f2c80c9bd2b2be43bb0f312c76916
663,765
def get_language(request): """Get the selected language. English is the default.""" code = request.GET.get("language", "EN") if code == "NL": return "NL", "EN" else: return "EN", "NL"
786524b795ea6b930b758dceee420d8832f4f812
663,766
def crp_fractional_hierarchical_three(a, d, N, p0): """Fractional approximate inference in a three-level hierarchy.""" cw2 = 0 # bottom tw2 = 0 tw1 = 0 # middle tw0 = 0 # top for i in range(N): p1 = (tw1 - d*tw0 + (a + d*tw0)*p0)/(tw1 + a) p2 = (tw2 - d*tw1 + (a + d*tw1)*p1)/(tw2 + a) f2 = (a ...
5dfb106f2de50278c979c5d62aca6cfd2a00fc19
663,767
from typing import Optional def calculate_limit(max_limit: int, given_limit: Optional[int]): """Get the allowed limit on results to return for a particular or type of object If 'given_limit' is given (ie, by the user), this will return min(limit, max_limit) where max_limit is the set value for the table/...
cb3829f586a0caaea255e552e666a2bc9d004a0b
663,768
import string def loops(): """ solve the tasks with loops""" list_a = [] for letter in string.ascii_lowercase: list_a.append(ord(letter)) list_b = [] for number in range(1, 48): if '3' not in str(number): list_b.append(number) return list_a, list_b
eb283eca30e7ec0ba7676925d77c24940747b899
663,769
from typing import Dict from typing import Any from typing import List def format_overview(data: Dict[str, Any]) -> List[Dict[str, str]]: """ Determine and format the overview statistics and insights from plot(df) Parameters ---------- data dictionary with overview statistics """ ...
e2797fc7ebd28128836e8eb5203c3838206e5fd6
663,770
def frames_to_ms(frames: int, fps: float) -> int: """ Convert frame-based duration to milliseconds. Arguments: frames: Number of frames (should be int). fps: Framerate (must be a positive number, eg. 23.976). Returns: Number of milliseconds (rounded to int). ...
04a9c37cc2b6514b432fa773c2215a716e418209
663,771
def get_Theta_dash_HPU_out(): """1時間平均のヒートポンプ最大運転時のヒートポンプユニットの出湯温度 (℃) Args: Returns: float: 1時間平均のヒートポンプ最大運転時のヒートポンプユニットの出湯温度 (℃) """ return 85.0
e1faf002f8241c24c246b29b076046c8d5cfc1cc
663,772
def compare(game, guess): """I think we all remember that feeling when the result of some long-awaited event is finally known. The feelings and thoughts you have at that moment are definitely worth noting down and comparing. Your task is to compare if a person guessed correctly the results of the matche...
a136dea2470ae357f8d25ed0bee5be643a02d3e9
663,773
def mapLists(first, second): """ Make a dictionary from two lists with elements of the first as the keys and second as values. If there are more elements in the first list, they are assigned None values and if there are more in the second list, they're dropped. """ index = 0 dict = {} # Read through every index ...
928b31e0cf636389124f8ba6b4910b9a51539204
663,774
import os def parse_path(pathname): """ Convert a human friendly pathname to an absolute pathname. Expands leading tildes using :func:`os.path.expanduser()` and environment variables using :func:`os.path.expandvars()` and makes the resulting pathname absolute using :func:`os.path.abspath()`. ...
cc9565cb0899861fea4ff17aee07ed73c75430d9
663,775