content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def write(file, lines): """ Write file from an array """ with open(file, 'w') as f: bytes_ = f.write('\n'.join(lines[0:]) + '\n') return bytes_
606e994b674798b853a306816451185884d8c868
681,918
def getQuestionLabels(task_question_answer_labels, task_uuid): """ Gets a list of question labels under the same task uuid """ series = task_question_answer_labels[task_question_answer_labels["quiz_task_uuid"] == task_uuid] return series["question_label"].unique().tolist()
4cb71f70367850d7f0ea4ef16415c3664a9a0356
681,919
import argparse def get_argument_parser(): """Set up command line arguments and usage.""" parser = argparse.ArgumentParser() parser.add_argument( '--test', action='store_true', help='do dry run only, do not update the database' ) return parser
a833235b409c68554f291e9c3db2e2cd20c6ebb7
681,921
def cli_cosmosdb_gremlin_database_throughput_migrate(client, resource_group_name, account_name, database_name, ...
2b768c0e443c4ce4324e2a3bfc2f685693a08d99
681,922
def contrib_xref(contrib_tag, ref_type): """ Given a contrib tag, look for an xref tag of type ref_type directly inside the contrib tag """ aff_tags = [] for child_tag in contrib_tag: if ( child_tag and child_tag.name and child_tag.name == "xref" ...
767a0af81bdfdf1aba16bc835d96597085d7462d
681,923
def array_pair_sum_sort(k, arr): """ first sort the array and then use binary search to find pairs. complexity: O(nlogn) """ result = [] arr.sort() for i in range(len(arr)): if k - arr[i] in arr[i + 1:]: result.append([arr[i], k - arr[i]]) return result
68e459ca35add8a34ae4cd5cc604ef8906b04e1a
681,924
def _neighborsIndexes(graph,node,includeOutLinks,includeInLinks): """ returns the neighbors of node in graph as a list of their INDEXes within graph.node() """ neighbors = set() if includeOutLinks: neighbors |= set(graph.neighbors(node)) if includeInLinks: neighbors |= set(graph.predecessors(node)) r...
af1ca1a60d0a1331fdb9715f0a16f46c5f0a86ad
681,925
def _mbondi_radii(atom_list): """ Sets the mbondi radii """ radii = [0.0 for atom in atom_list] for i, atom in enumerate(atom_list): # Radius of H atom depends on element it is bonded to if atom.type.atomic_number == 1: bondeds = list(atom.bond_partners) if bondeds[0]...
0bcd2b3fd113e69523a75514a28abdf3d1f424a9
681,926
def fill_queue(task_queue, start_slice, end_slice): """Fill the queue""" for i in range(start_slice, end_slice+1, 1): task_queue.put([i]) return task_queue
f1738db5997b6718ed0676731f2b8919453c7e18
681,929
from typing import List import random import itertools def get_model_nncf_cat() -> List: """Test helper for getting cartesian product of models and categories. Returns: List: Returns a combination of models with their nncf support for each category. """ model_support = [ ("padim", Fal...
bf3db7892f3d1a2243a4fb7f324092e9ffeba1ef
681,930
def get_hyperhdr_device_id(server_id: str, instance: int) -> str: """Get an id for a HyperHDR device/instance.""" return f"{server_id}_{instance}"
fd89cfaf3a6e921924bf84d8da5f5c13336cbae0
681,932
def strict_forall(l, f): """Takes an iterable of elements, and returns (True, None) if f applied to each element returns True. Otherwise it returns (False, e) where e is the first element for which f returns False. Arguments: - `l`: an iterable of elements - `f`: a function that applies...
dac9d7e7ca7499475aa8daba52a71185f2e47d5b
681,934
def data_env_2(default_data_env, client_2): """Fixture with pre-existing assets in second node.""" return default_data_env.filter_by(client_2.node_id)
aafb8fcd6e63afa962f2559813c097977e001be2
681,935
import os def ensure_dir(file_path, create_if_not=True): """ The function ensures the dir exists, if it doesn't it creates it and returns the path or raises FileNotFoundError In case file_path is an existing file, returns the path of the parent directory """ # tilde expansion file_path = o...
8e98b571966bee3f332f6c38082b24eabc3cc095
681,936
import copy import sys import platform def get_extra_cmake_options(): """ Parse CMake options from python3 setup.py command line. Read --unset, --set, -A and -G options from the command line and add them as cmake switches. """ _cmake_extra_options = [] opt_key = None has_generator = Fal...
c6886355ca073a9304cee03c1f029aa2ef1ddf29
681,937
import pyclbr def is_handler_subclass(cls, classnames=("ViewHandler", "APIHandler")): """Determines if ``cls`` is indeed a subclass of ``classnames`` This function should only be used with ``cls`` from ``pyclbr.readmodule`` """ if isinstance(cls, pyclbr.Class): return is_handler_subclass(cls....
631ff0c02b005d8127d2b76c505cd032ce8a29bf
681,939
def create_label_column(row) -> str: """ Helper function to generate a new column which will be used to label the choropleth maps. Function used to label missing data (otherwise they will show up on the map as "-1 SEK"). Parameters ---------- row : Returns ------- str C...
b790eb3614859ecb557d8e76a7075d7c42fa841f
681,940
def virus_test(name): """Tests whether "virus" is in a species name or not. Written by Phil Wilmarth, OHSU, 2009. """ return ('virus' in name)
822af656a03575d6ca6e5784b82109f5b9740866
681,941
import pathlib def derive_filepath(filepath, append_string='', suffix=None, path=None): """Generate a file path based on the name and potentially path of the input file path. Parameters ---------- filepath: str of pathlib.Path Path to file. append_string: str String to app...
174c439a5285441fcca7902bfd1c542348f6fb3d
681,942
def gather_pages(pdfs: list) -> list: """ Creates a list of pages from a list of PDFs. Args: pdfs (list): List of PDFs to collate. Returns: list: List of pages from all passed PDFs. """ output = [] for pdf in pdfs: for page in pdf.pages: output.append(pa...
18d80f2204dc6fd7eca51c5f6e83af9ed8403405
681,943
import os import zipfile def unzip(path, cleanup=False, dest=os.path.dirname(os.path.realpath(__file__))): """ Unzips the file with path given in first parameter. Deletes the zip file and puts the new folder in the specified destination, default this file's directory. If cleanup is set to True, then...
71de42786d4d7577dac101670955ae9991cc1ff9
681,944
import json import requests def create_source_connection_profile(source_config, db_password, token, project, location): """ This function will create the source connection profile in Google Cloud DataStream :param source_config: source config from variables.py :par...
dfdf3d6f32e6e1022e2bee7103fbb435fe209a32
681,945
import copy def interval_job_dict(job_dict, interval_trigger_dict): """An interval job represented as a dictionary.""" dict_copy = copy.deepcopy(job_dict) dict_copy['trigger_type'] = 'interval' dict_copy['trigger'] = interval_trigger_dict return dict_copy
6e4effb182bad830567ceedf1d242e8bef66dde7
681,946
def check_for_null(data_frame): """ check if the dataframe is null """ if data_frame.shape[0] == 0: return True else: return False
8860a5655f4cb2167c276a6a8b00b37883cfc606
681,947
import torch def create_alternating_binary_mask(features, even=True): """ Creates a binary mask of a given dimension which alternates its masking. :param features: Dimension of mask. :param even: If True, even values are assigned 1s, odd 0s. If False, vice versa. :return: Alternating binary mask ...
a402a697e7bc0ab6c4249a57e7e3c12ca9873fea
681,948
import sys def get_basedir(): """Return the homek8s base dir on the gateway, default is /homek8s. This parameter is given as a CLI argument by the systemd service. """ return sys.argv[1]
75f6a5f5cd582769a4510ca966f9c903d749d777
681,951
def mac_normalize(mac): """Retuns the MAC address with only the address, and no special characters. Args: mac (str): A MAC address in string format that matches one of the defined regex patterns. Returns: str: The MAC address with no special characters. Example: >>> from netut...
3fde0901726ad7e436b9b2e9add905663b89218d
681,952
def parse_none(*args): """Return tuple of arguments excluding the ones being None.""" return tuple(arg if arg is not None else "" for arg in args)
42e4822d29c3f9c7a62b345f7b64f74b0c16d250
681,953
def remove_dupes(items): """ make sure no item appears twice in list i.e. filter for any duplicates """ clean = [] for i in items: if not i in clean: clean.append(i) return clean
85efbd27be24292454cbc95b6bc465ae9c9ae699
681,954
def wordList(fname = 'dictionaryWords.txt'): """Generate list of possible words from the passed file.""" wordlist = [] with open(fname, 'r') as fin: for word in fin: word = word.rstrip() ; wordlist.append(word) return wordlist
443cb77df3082829091bd9ba4907d969832c43a8
681,955
def test_src_node() -> dict: """Return a DICOM node as a dict that can be used to initiate network queries. """ return {"aetitle": "pacsanini_testing", "ip": 11114}
894cd57f06eb44ddc64d33b9ddd57d255e07edc0
681,956
def calc_electrons_from_photons(photons, quantum_efficiency): """ Calculate the number of electrons generated by incident photons. Returns ------- int : no units, a number of electrons """ return int(photons * quantum_efficiency)
c9538d777bdf2d8ae133c16fdff2af281b940c4f
681,957
def _gutenberg_simple_parse(raw_content): """Clean a project Gunteberg file content.""" content = raw_content # *** START OF THIS PROJECT GUTENBERG EBOOK THE RED BADGE OF COURAGE *** starts = [ '*** START OF THIS PROJECT GUTENBERG EBOOK', '***START OF THE PROJECT GUTENBERG EBOOK', '*** START O...
7927711ef919d08d40e2fd89e77f24c999a6e9ac
681,958
def get_square_length(file): """ Parameters ---------- file : str path to checkersize.txt. Contains square length in centimeters [cm]. Returns ------- float square length in meters [m]. """ with open(file) as f: return float(f.read()) * 1e-2
48b01203f0fb15d65c28ae646fa349cf19a1d7d1
681,959
def counter_mean(counter): """Takes the mean of a collections.Counter object (or dictionary).""" mean = 0. total = 0. for k, v in counter.items(): if k <= 0: k = 200 mean += k * v total += v return mean / total
83c943ac279e515d8e8d6040f906bcd4b0f1e9aa
681,960
import torch def quat_conj(Q): """ Returns the conjugate of the given quaternion Parameters ---------- Q : Tensor the (4,) or (N,4,) quaternion tensor Returns ------- Tensor the (4,) or (N,4,) conjugate quaternion tensor """ return Q * torch.tensor([-1, -1, -...
9e64ea036e25cdd5fc15db6e6e5d672884ed15bc
681,961
def xauth(auth): """Expand authentication token >>> xauth(None) >>> xauth(('user', 'pass')) ('user', 'pass') >>> xauth('user:pass') ('user', 'pass') >>> xauth('apikey') ('apikey', '') """ if auth is None or isinstance(auth, tuple): return auth else: u, _, p ...
3c8be7c7caf7c7442971f28f1892420ef97dcbaf
681,962
import subprocess def get_video_length(video_path, verbose=False): """Returns video length.""" cmd = ( f'ffprobe -v error -select_streams v:0 ' f'-show_entries stream=duration ' f'-of default=noprint_wrappers=1:nokey=1 {video_path}' ) if verbose: print(f'CMD {cmd}') try: res = subprocess...
5070a352ca916e7734ab2ce0412aeadc83813950
681,963
import requests def normalize_id_to_translator(ids_list): """Use Translator SRI NodeNormalization API to get the preferred Translator ID for an ID https://nodenormalization-sri.renci.org/docs """ converted_ids_obj = {} resolve_curies = requests.get('https://nodenormalization-sri.renci.org/get_norm...
e81907eda687319913db827bcb6124e567f9d636
681,964
import json def _get_codes(error_response_json): """Get the list of error codes from an error response json""" if isinstance(error_response_json, str): error_response_json = json.loads(error_response_json) error_response_json = error_response_json.get("error") if error_response_json is None: ...
86e73be80735df115f1d24b5a45f091b62db4d42
681,965
def get_channel_id(data: dict) -> str: """Return channel id from payload""" channel = data['channel'] return channel
74b9ff9ad70bacd25d7ebe9ad93ef3cd827d627e
681,968
def collect_ids(self, res, i): """Used as a callback in a chain or group where the previous tasks are :task:`ids`: returns a tuple of:: (previous_result, (root_id, parent_id, i)) """ return res, (self.request.root_id, self.request.parent_id, i)
489ebd11714c5196c70037001e7c77ca77d66831
681,969
def leap_check(year) -> str: """Check if a year is a leap year. :return: A string telling us weather or not it is a leap year. """ if (year % 4 == 0) and (year % 100 != 0) or (year % 400 == 0): return f"{year} is a leap year!" else: return f"{year} is not a leap year!"
9bb099c063eb119b4b9dbe3ff7c62774db6f6bb6
681,970
def documentize_sequence(seqs, tag, nt_seq): """This function converts raw nucleotide or amino acid sequences into documents that can be encoded with the Keras Tokenizer(). If a purification tag is supplied, it will be removed from the sequence document. """ # setup 'docs' for use with Tokenizer ...
21929282187c020038978f0d3ae7dacbf00d8ca2
681,972
def _alg(elt): """ Return the hashlib name of an Algorithm. Hopefully. :returns: None or string """ uri = elt.get('Algorithm', None) if uri is None: return None else: return uri
ef232715263c72a21ffeefe7105c1f033d5d88d1
681,973
def minSubArrayLen(self, s, nums): """ :type s: int :type nums: List[int] :rtype: int """ b, sum, min_length = 0, 0, 0 for e in range(len(nums)): # Increase the boundary in each iteration sum = sum + nums[e] if sum >= s: # A successful boundary found # See ...
ba73301f7b660da9a5cdf9485c06efcd8f0124fc
681,975
def wavelength_range(ini_wl, last_wl, step=1, prefix=''): """Creates a range of wavelengths from initial to last, in a defined nanometers step.""" return [f'{prefix}{wl}' for wl in range(ini_wl, last_wl + 1, step)]
66e8ea5e53cb6dbe107e4ebcc046c5cc310a9b86
681,976
def _docmd(doc): """Convert a docstring to markdown""" if doc is None: return '' def codeblock(lines): return ['```python'] + [' ' + l for l in lines] + ['```'] md = [] code = [] indent = 0 lastindent = 0 for line in doc.split('\n'): indent = len(line) line = l...
983264bc8f49d1969895d6319f8da40258ddd966
681,977
def make_peak(width:int, height:float=100) -> list: """ This is an accessory function that generates a parabolic peak of width and height given in argments. width: integer width of the peak height: float height of peak Returns: list of values of the peak """ rightSide = [-x**2 for x i...
6153399fc5916339d1733c68a60cfb166d48da45
681,978
def filter_inputs(db, measure_inputs, retry=False): """ Filter a measure_inputs batch based on saved db results Parameters ---------- db: Database database object measure_inputs: Array of MeasureInput measure_inputs as expected in measure_batch retry: bool whether to...
721b7283eb856a8aa0a9f29c6d2034d357f5f636
681,979
import torch def nchw_to_nhwc_tensor(tensor: torch.Tensor) -> torch.Tensor: """ :param tensor: :return: :rtype:""" assert len(tensor.shape) == 4 return tensor.permute(0, 2, 3, 1)
55ce74eb31b6dce97a883e17b81477a66dd031ee
681,980
import os import patoolib def is_archive(filepath): """ Checks if the file indicated by `filepath` is a valid arhive. An exception is raised if the file does not exist or is not readable. This is a best guess checking proceduce and the supported formats are those indicated by `patool`: https://gi...
2258f1e738307f4f211f8d6063b43b89f4fccc30
681,981
def generate_macro_args(): """Generate the value of MACRO_ARGS.""" args = [] for i in range(1, 10): args.append("#" + str(i)) return args
df4cf460e959d31c526e0329d205e250564ce51d
681,982
def consume_next_text(text_file): """Consumes the next text line from `text_file`.""" idx = None text = text_file.readline() if text: tokens = text.strip().split() idx = tokens[0] tokens.pop(0) text = " ".join(tokens) return idx, text
9a0595580a9fa8d6b5f480d218e88c508e5cd197
681,983
def match_device(hu_disk, ks_disk): """Tries to figure out if hu_disk got from hu.list_block_devices and ks_spaces_disk given correspond to the same disk device. This is the simplified version of hu.match_device :param hu_disk: A dict representing disk device how it is given by list_block_devices m...
0fb406eb847af00a151e950a39286ce1e7f51ae4
681,986
def append_suffix(word, suffix): """ 在单词后添加词缀. Args: word: string, 输入单词 suffix: string, 词缀 Return: 修改后的单词 """ if len(word) == 1: print( "We currently fear appending suffix: {} to a one letter word, but still doing it: {}".format(suffix, word)) i...
7c77c4594a391342a80dfae3f463e9449c36f9d1
681,987
def osavi(b4, b8): """ Optimized Soil-Adjusted Vegetation Index \ (Rondeaux, Steven, and Baret, 1996). .. math:: OSAVI = 1.16 * b8 - (b4 / b8) + b4 + 0.16 :param b4: Red. :type b4: numpy.ndarray or float :param b8: NIR. :type b8: numpy.ndarray or float :returns OSAVI: Index value ...
082bc515e9347520454030fb3560ab2496531b2b
681,989
def _build_mix_args(mtrack, stem_indices, alternate_weights, alternate_files, additional_files): """Create lists of filepaths and weights to use in final mix. Parameters ---------- mtrack : Multitrack Multitrack object stem_indices : list stem indices to include ...
4b53b3b636c6d587d0efd756fe5d281929be0727
681,990
def instance_set_private(self, terminate=False): """ Stop a list of Instance and recreate it with only a private ip. Keeps all tags, name and security groups. :param boto.ec2.instance.Instance self: Current instance. :param bool terminate: Terminates the old instance. Default : False. ...
7d525e5d2d204437d326f88e920bdf6ec4832ccd
681,991
def is_str_int_float_bool(value): """Is value str, int, float, bool.""" return isinstance(value, (int, str, float))
9b62a9d89ea5d928db048cd56aa1ee5986fcc79a
681,992
import torch def collate_fn(data): """ :param data: :return: padded inputs and outputs """ xs, inputs = zip(*data) # pad sequences lengths = [len(x) for x in xs] # (b,) xs_ = torch.zeros(len(lengths), max(lengths)).long() for i in range(len(lengths)): end = lengths[i] ...
08dac621f9d0ed256ae731e30b20dd8180becd92
681,993
def get_people_ids_based_on_role(assignee_role, default_role, template_settings, acl_dict): """Get people_ids base on role and template settings.""" if not template_settings.get(assignee_role): return [] templat...
e3706c5c8499801b6e7d31175da9ba6e4dc9761b
681,994
def matchSubdirLevel(absDir, correctRelDir): """ The two input directories are supposed to be to the same level. Find how many directory levels are given in correctRelDir, and return the same number of levels from the end of absDir. Also return the topDir, which is the components of absDir above th...
c9ab7d80a99554f521c9f74e221f2971bc0f1833
681,995
from typing import Any from typing import Union def to_int_if_bool(value: Any) -> Union[int, Any]: """Transforms any boolean into an integer As booleans are not natively supported as a separate datatype in Redis True => 1 False => 0 Args: value (Union[bool,Any]): A boolean val...
984a97ad94b8500c1506c978bde6dcb792d0288c
681,996
def task_reduce_partition(f, partition): """ :param f: :param partition: :return: """ iterator = iter(partition) try: res = next(iterator) except StopIteration: return for el in iterator: res = f(res, el) return res
bc64d35ca764b2eb70bd2a9299d8e4842b23f2d5
681,997
import fnmatch def ExcludeFiles(filters, files): """Filter files based on exclusions lists Return a list of files which do not match any of the Unix shell-style wildcards provided, or return all the files if no filter is provided.""" if not filters: return files match = set() for file_filter in filte...
5a37efa7402da1c6465aea40000266bf1483e454
681,998
def grow_bitmap(mask,count=1): """Extents the area where the pixels have to value 1 by one pixel in each direction, including diagnonal by the number of pixels given by the parameter 'count'. If count is 1 or ommited a single pixel grows to nine pixels. """ from numpy import array,zeros if ...
7d50e5b56f27e4574f73aae8a5d4cbd91154ba69
681,999
def get_object_name(file_name): """ Get object name from file name and add it to file YYYY/MM/dd/file """ return "{}/{}/{}/{}".format(file_name[4:8],file_name[8:10],file_name[10:12], file_name)
437c286b2c14712d80f68f8f7b3d36ccf279da81
682,000
def binto(b): """ Maps a bin index into a starting ray index. Inverse of "tobin(i)." """ return (4**b - 1) // 3
c6744be554f3cee439ed2923490af63387d95af7
682,001
def _list_at_index_or_none(ls, idx): """Return the element of a list at the given index if it exists, return None otherwise. Args: ls (list[object]): The target list idx (int): The target index Returns: Union[object,NoneType]: The element at the target index or None """ if ...
46651d93140b63bcb85b3794848921f8ea42d7bf
682,002
from typing import Counter def chartab(corpus, top= 256, special= "\xa0\n "): """returns the `top` most frequent characters in `corpus`, and ensures that the `special` characters are included with the highest ranks. corpus : seq (line : str) """ char2freq = Counter(char for line in corpus for c...
fdc179c87c6b6c1da456189f78999778e91ee127
682,003
def find_result_node(desc, xml_tree): """ Returns the <result> node with a <desc> child matching the given text. Eg: if desc = "text to match", this function will find the following result node: <result> <desc>text to match</desc> </result> Parameters ----- x...
42ac4958a6b5c45e26a58d09b8e7dfa701f7678e
682,004
def is_valid_date(date): """ validate date format """ return True
0a674db010345dbf869768e48c87e96e965c1a33
682,005
def sort_by_pitch(sounding_notes): """ Sort a list of notes by pitch Parameters ---------- sounding_notes : list List of `VSNote` instances Returns ------- list List of sounding notes sorted by pitch """ return sorted(sounding_notes, key=lambda x: x.pitch)
ddb2485a807608b91925ce84e6be08011803dd12
682,006
from typing import Iterable import six def issequence(arg) -> bool: """ Returns `True` if `arg` is any kind of iterable, but not a string, returns `False` otherwise. Examples -------- The formatter to use to print a floating point number with 4 digits: >>> from dewloosh.core.tool...
4ba2f7691c1f79041a22389739c7f270f190bda8
682,007
def split(t): """ Split a matrix into 4 squares doesn't work well for matrices of size < 2x2 """ midRow = int(t.rows/2) midCol = int(t.cols/2) topLeft = t.subMatrix(0, 0, midRow - 1, midCol - 1) topRight = t.subMatrix(0, midCol, midRow - 1, t.cols - 1) bottomLeft = t.subMatrix(midRow...
a88d8ca1e029cae10d19eac28e18ed2ea0a674f1
682,009
import re def process_gene_data(gene_faas, cluster_reps, gene_bulk='gene_data.bulk'): """ parses faa headers (from prodigal) to generate table of gene data with: gene, contig, start, end, cluster_rep (puled from cluster_reps dict) returns contig gene counts as dict """ contig_counts = {} ...
3fee5f0bf9b15aad632e7dd46c0cf5fd50e0a5dc
682,010
import glob def SetupAll(BasePath): """ Inputs: BasePath - Path to images Outputs: ImageSize - Size of the Image DataPath - Paths of all images where testing will be run on """ # Image Input Shape ImageSize = [32, 32, 3] DataPath = [] NumImages = len(glob.glob(BasePath+...
d8d778c388695a208c9806da8cfadeb0a7350384
682,011
from typing import OrderedDict def get_json(node): """ 递归调用,实现 process: 1.判断传入的节点是否有子节点 有: 判断该节点是否是唯一元素 是: 不生成数组,递归 否: 生成数组, 递归 否: 没有子节点,到达递归出口 # 方式二(感觉有点小问题) ...
e304475b81450bba70ba5a1a0960541cb37099e2
682,012
def check_clusters(labels_true_c, labels_pred_c): """ Check that labels_true_c and labels_pred_c have the same number of instances """ if len(labels_true_c) == 0: raise ValueError("labels_true_c must have at least one instance") if len(labels_pred_c) == 0: raise ValueError("labe...
0ddba08bfa28724143a284017dc905cb4c3210e1
682,013
def observed_species(counts): """Calculates number of distinct species.""" return (counts!=0).sum()
8b534640541b58afc2840322c781be3c9c60d024
682,014
import re import json def extract_schema(script): """Extract schema from script""" schema_regex = r'var schema = (.+)' match = re.search(schema_regex, script) if match: return json.loads(match.group(1))
477948cb689aea6800b63225fea0f5a8d4ba8335
682,015
import heapq def optimized_solution(nums): """ l = len(nums) # find the first maximum/largest number index max_idx1 = -1 for i in range(l): # if index 1 greater than index zero than work if (max_idx1 == -1) or (nums[i] > nums[max_idx1]): max_idx1 = i # find the 2n...
b704d1ebc606b0d9dc5cfc3612d28f575689e985
682,016
import torch def to_numpy(tensor): """ Converting tensor to numpy. Args: tensor: torch.Tensor Returns: Tensor converted to numpy. """ if not isinstance(tensor, torch.Tensor): return tensor return tensor.detach().cpu().numpy()
029f43c3836a6b96931f1992d2a809dd87e1326d
682,017
def check_username(name, address): """ This will check to see if a username is given or if one needs to be asked for Args: name (None|str) : this will be None if no username is given or check to make sure a string otherwise. address (str) : string of the address getting username for retu...
e6ca84de2d999f6cfe376a5bfd3ac066870ce2ac
682,018
def lox_to_hass(lox_val): """Convert the given Loxone (0.0-100.0) light level to HASS (0-255).""" return (lox_val / 100.0) * 255.0
f7c61b8605bf3cd15b24e244b6724334d1128ce4
682,020
def default_format(source, language, class_name, options, md, **kwargs): """Default format.""" return '<custom lang="%s" class_name="class-%s">%s</custom>' % (language, class_name, source)
24b295ce723eb6ece9c0b016130e84e9b959a17b
682,021
def bits_to_int(bits: list, base: int = 2) -> int: """Converts a list of "bits" to an integer""" return int("".join(bits), base)
3cbf131607eb0de8d6b46bc4c88c1414ebf00029
682,022
def get_conditions_join(filters): """The conditions to be used to filter data to calculate the total vat.""" conditions = "" for opts in (("company", " and p.company=%(company)s"), ("from_date", " and p.posting_date>=%(from_date)s"), ("to_date", " and p.posting_date<=%(to_date)s")): if filters.get(opts[0]): ...
e310f094eb87187e274f2c2b6c4df7311fa0e872
682,023
def _date_proximity(cmp_date, date_interpreter=lambda x: x): """_date_proximity providers a comparator for an interable with an interpreter function. Used to find the closest item in a list. If two dates are equidistant return the most recent. :param cmp_date: date to compare list against :par...
2e04a0609e0d46e021f64e24d0d76ed60fd00c13
682,024
def clean_html_of_csrf_for_local_comparison(html_data): """Removes content that is omitted by render_to_string(), for fair comparison between the response and local html. Expects that each logical line also occupies one physical line. (Especially the lines to be cleaned.)""" lines = html_d...
44a8853e5d8047e345d0563131239ced0f2cbf40
682,025
import sys def on_macos(): """Returns ``True`` if the script is running on macOS.""" return sys.platform == 'darwin'
9e2060a4b20a841c5ab0f223bceb81bdf50a35d4
682,026
def hashlib_hash(func): """ Wrapper for hashlib hashes. """ def hash_(data): return func(data).digest() return func().digest_size, hash_
181cc8a0132ed4a5625dfcc7c092dbd5c32e1469
682,027
def rescale(ys, ymin=0, ymax=1): """ Return rescaling parameters given a list of values, and a new minimum and maximum. """ bounds = min(ys), max(ys) ys_range = bounds[1] - bounds[0] new_range = ymax - ymin ys_mid = sum(bounds)*.5 new_mid = sum([ymax, ymin])*.5 scale = float(new_range)...
f3f11b4e8f964dc58b1efc8d6eb8895236ddf066
682,028
from typing import List import shlex def str_command(args: List[str]) -> str: """ Return a string representing the shell command and its arguments. :param args: Shell command and its arguments :return: String representation thereof """ res = [] for arg in args: if "\n" in arg: ...
4820c23472bbff0990932e25751e84ec4f827be4
682,029
from pathlib import Path def res_path(): """Location where test resources are stored on-disk""" return Path(__file__).parent / 'resources'
5ce12d5b70c71d15efd9cc31818f9206f707a821
682,030
import sys import random def rand(bot, trigger): """Replies with a random number between first and second argument.""" arg1 = trigger.group(3) arg2 = trigger.group(4) try: if arg2 is not None: low = int(arg1) high = int(arg2) elif arg1 is not None: ...
c0784c1b32aac8c83efb0c85a1a386c65e573fd8
682,031
def fib_memo(n, memo=None): """ The standard recursive definition of the Fibonacci sequence to find a single Fibonacci number but improved using a memoization technique to minimize the number of recursive calls. It runs in O(n) time with O(n) space complexity. """ if not isinstance(n, int): ...
9222e6d814dea2d6a4af5799080ba5569e93c893
682,032
import os def get_data_file_length(data_file_name): """ Open a file, and read the number of lines in it. Parameters ----------- data_file_name : str A path to the file name to read the length of. Returns ------- file_length : int The number of lines within the...
bd88adf3367633188e58d322cc8bc62cdf2b8c33
682,034
def findBuildDirs(testList): """ given the list of test objects, find the set of UNIQUE build directories. Note if we have the useExtraBuildDir flag set """ buildDirs = [] reClean = [] for obj in testList: # be sneaky here. We'll add a "+" to any of the tests that ...
9da7cfd2f6ed54e76099910d6064a2c1048d6c5f
682,035