content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def seqcomp(s1, s2): """ Compares 2 sequences and returns a value with how many differents elements they have. """ p = len(s1) for x,y in zip(s1, s2): # Walk through 2 sequences. if x==y: p -= 1 return p
1ef0e7fddc751225ba2030804b360daf8bf10abd
670,035
import torch def abs2(x: torch.Tensor): """Return the squared absolute value of a tensor in complex form.""" return x[..., -1] ** 2 + x[..., -2] ** 2
186387791dec899a775dc6d3bbb1987a5433898f
670,036
import argparse def get_args(): """ Get command-line arguments """ parser = argparse.ArgumentParser( description="""Rabbits and Recurrence Relations. Given two positive integers, n <= 40 and k <= 5, this program returns the total number of rabbits pairs present after n months if we be...
8906b284d65ee8a848ee1741175b80f17b2b2d84
670,037
import argparse def construct_args( task: str, config: str, ground_truth: str, result: str ) -> argparse.Namespace: """Construct command-line arguments for tests.""" return argparse.Namespace( task=task, config=config, gt=ground_truth, result=result, nproc=1, ...
653d480d6cca5bc850063ca0e70494dc27a4ea67
670,038
import numpy def vdot(x,y, z = None): """ vectorized dot z = vdot(x,y) Rationale: given two iteratable containers (list,array,...) x and y this function computes:: z[i] = numpy.dot(x[i],y[i]) if z is None, this function allocates the necessary memory Warni...
487b958770b5a438c31760a4a09eb4f2e1a07637
670,039
from typing import Iterable def _reconstruct_conll_from(sentences: Iterable[str]) -> str: """Reconstructs CoNLL-U format file content from sentence annotations.""" return "\n\n".join(sentences)
56833f9e373a53e047900e6650678c85e92679e2
670,040
def get_features(words, word_features): """ Given a string with a word_features as universe, it will return their respective features : param words: String to generate the features to : param word_features: Universe of words : return: Dictionary with the features for document string """ ...
a78bd6a83b9b3ea340a22c8696778b289539dd78
670,041
def _djangofy_choices(input): """ Convert a list of tuples into the required format :param input: :return: """ return [x[:2] for x in input]
1ed151217c2f72d8a51d4ab199b20e3a66cdc88b
670,042
def make_key(app_id, app_key, task_id): """This is a naming convention for both redis and s3""" return app_id + "/" + app_key + "/" + task_id
688b3a9103ee7bf3315df4650f44a0204e0c2368
670,043
def clip_box(box, shape): """ Clip box for given image shape. Args: box (array_like[int]): Box for clipping in the next format: [y_min, x_min, y_max, x_max]. shape (tuple[int]): Shape of image. Returns: array_like[int]: Clipped box. """ ymin, xmin, ymax, xm...
7cb329c630dc5eef47e87a8e32dab4d5a97739ae
670,044
def laplace_noise_parameter(k, num_attributes, num_tuples, epsilon): """The noises injected into conditional distributions. Note that these noises are over counts, instead of the probability distributions in PrivBayes Algorithm 1. """ return (num_attributes - k) / epsilon
b7503e43a3122f356b674c4cee786327a6f71d26
670,046
def get_workflow_object(workflow_name, settings, logger, conn, token, decision, maximum_page_size): """ Given a workflow_name, and if the module class is already imported, create an object an return it """ full_path = "workflow." + workflow_name + "." + workflow_name f = eval(full_path) # Cr...
d033fa384072800f05af09be42ff2c1e397f5bc7
670,047
def postfunct(INDIR, FUNCTION, OUTDIR, ARGS, intranet): """ Description ----------- Function executed after processing all files. Current working directory is "dat". example "collects all data from all files and summarizes it in one file" """ #if intranet = [], postfunct does not write ...
98fea3a8639c0e980d40683eb9fd1cce438fd4d1
670,048
import os def get_doc_dir(root_dir_): """Remove the old "docs directory and return an empty one. Returns: A "doc directory" by it's absolute path. """ doc_dir = os.path.join(root_dir_, 'docs') if not os.path.isdir(doc_dir): os.mkdir(os.path.join(root_dir_, 'docs')) return doc_...
99d4d22a2ef2e089237e11ba09faa076e00f8e1c
670,049
import torch from re import S def labels2tensor(labels): """ Build Groundtruth tensor S*S*5. :param labels: list of labels with bounding box classification and position for each image. :return: T: Groundtruth tensor S*S*5. format <x> <y> <w> <h> <class name> """ T = torch.zeros...
196260660ac732f3eff79259d48c878082108c0f
670,050
def get_embedding_dict(filename): """ Read given embedding text file (e.g. Glove...), then output an embedding dictionary. Input: - filename: full path of text file in string format Return: - embedding_dict: dictionary contains embedding vectors (values) for all words (keys) """ ...
07d5501c1eb71114488af913d012d2511f4a5439
670,051
def week_cal(cal: str, current_day: int) -> str: """Function used to transform a HTML month calendar into a week calendar. Args: `cal`(str): the html calendar to transform. `current_day`(int): the current day to select the current week. Returns: `str`: the calendar transformed. ...
11cad36d9c92e38f10152b2c97039a9d5d16c344
670,052
def sol(n): """ Standard DP problem The width is 4 always, so we need to worry only about the length which can be reduced either by 1 or by 4 i.e keeping the tile horizontally or vertically """ dp = [0]*(n+1) if n < 4: return 1 dp[0] = 1 # If the length is 0, there is no so...
d0c92e1416d3edc1d120ad28dd2139233756e955
670,053
import torch def safe_log_prob(tensor, eps=1e-12): """Safe log of probability values (must be between 0 and 1)""" return torch.log(torch.clamp(tensor, eps, 1 - eps))
1fe21914d421a7af25aff1a094f3203c70bdbdf7
670,055
import os def check_env(env_var_name): """ Check and return the type of an environment variable. supported types: None Integer String @param env_var_name: environment variable name @return: string of the type name. """ try: val = os.getenv(env_var_name) ...
485cac6a4e4ee9223f565a7d2b96d2757ea4d366
670,056
def check_unique_scores(score_list): """Method that checks if the scores presented are unique. Returns true if only unique, false if there are duplicates""" return len(score_list) == len(set(score_list))
7e8aad11e8680a3c6339283a191227647095e643
670,057
def ReadFile(filename): """Returns the contents of a file.""" file = open(filename, 'r') result = file.read() file.close() return result
3d8700a50a511c578902142519011d6adf2ddded
670,058
def get_add_customer_params(request_data: dict) -> tuple: """This method is used to get form data""" c_email = request_data["c-email"] c_full_name = request_data["c-full-name"] c_address = request_data["c-address"] c_city = request_data["c-city"] c_postal_code = request_data["c-postal-code"] ...
ce27bb1b2453aa8221a8324db7f18535a6a6671c
670,059
def _subsample(name, indices, doc=""): """Create an alias property for slices of mesh data.""" def get(self): return self.vectors[indices] def set(self, value): self.vectors[indices] = value get.__name__ = name return property(get, set, None, doc)
be10649e75823da2b89a4fd01227d32b9535cf40
670,060
from datetime import datetime def create_human_timestamp(): """Generates human timestamp for the date of day in format (yearmonthday): e.g. 20191011""" now = datetime.now() timeprint = now.strftime("%Y%m%d") return timeprint
109c5a4133b67dca1f5bc69a720594e37ea8b68d
670,061
import requests import json def CoinNames(n=None): """Gets ID's of all coins on cmc""" names = [] response = requests.get("https://api.coinmarketcap.com/v1/ticker/?limit=0") respJSON = json.loads(response.text) for i in respJSON[:n]: names.append(i['id']) return names
206246314b8dab7c5d86ba6109a59e9060ad1ffa
670,062
def dot(a, b): """The dot product between vectors a and b.""" c = sum(a[i] * b[i] for i in range(len(a))) return c
5ba6e253a2408c79c9f1edd0e98a84904e966050
670,064
def extract_ligand_residues( pdb_hierarchy, ligand_code, atom_selection=None, only_segid=None): """ Extract the atom_group object(s) with given 3-character residue name. :param pdb_hierarchy: input model :param ligand_code: 3-letter residue ID :param atom_selection: optional flex.bool object ...
64442c29db5204c7b3510fd773638d4408c84722
670,065
import pickle def read_Docs(path): """ This function will return a list which includes documents as string format. Parameters: path: path for the pickle file we will provide. """ with open(path,'rb') as P: Docs = pickle.load(P) return Docs
e6209add58a8067430e0308f0cb24a04449f99f0
670,066
def translator(en:str)->str: """ Translate English into Simplified Chinese :param en:English text :return:Simplified Chinese text """ zh = '' return zh
e63c7d6a0b56741ea9b2b003c1880a7f19f39968
670,067
import os import errno def create_dir(entry, section, domain, output, flat_output): """Create the output directory for the entry if needed.""" if not flat_output: full_output_dir = os.path.join(output, section, domain, entry['assembly_accession']) else: full_output_dir = os.path.join(outpu...
529cdb866f517346ae298d168ec7e9c0f3d64434
670,068
def for_in_empty_nested_listcomp(): """ >>> for_in_empty_nested_listcomp() [] """ return [x for _ in [] for x in [1, 2, 3]]
399c74a1c46a3772a29faf593959ecfb8f66d595
670,069
import argparse def parse_args(): """Parses arguments.""" parser = argparse.ArgumentParser() parser.add_argument('--model_name', type=str, default='styleganinv_ffhq256', help='Name of the GAN model.') parser.add_argument('--mode', type=str, default='man', help='Mode...
0ce7910080e8b11648a3fd211e088296a91fe39b
670,070
def PercentileOfList(List, Percentile, Ascending=True): """ :param List: list of values [value1, .... , valueN] :param Percentile: desired percentile of List (inclusive) :return: """ n = len(List) k = int(Percentile*n) # Number of data points ascending_list = sorted(List) if Ascend...
194867b7505ce1818c03bff95805b98d6abdd254
670,071
def molar_concentration_water_vapour(relative_humidity, saturation_pressure, pressure): """ Molar concentration of water vapour :math:`h`. :param relative_humidity: Relative humidity :math:`h_r` :param saturation_pressure: Saturation pressure :math:`p_{sat}` :param pressure: Ambient pressure :m...
e5d8a416bb1a598f84d9749c95cbb9d08013b805
670,072
def mean(values): """ Compute the mean of a sequence of numbers. """ return sum(values)/len(values)
d474df419d99a9de5d142284f5faa4a8e862d8e3
670,073
def build_dir_list(project_dir, year_list, product_list): """Create a list of full directory paths for downloaded MODIS files.""" dir_list = [] for product in product_list: for year in year_list: dir_list.append("{}\{}\{}".format(project_dir, product, year)) return dir_list
38683b30fac0b944f17a27351384066670afda11
670,074
from typing import List def epub_metadata_filter_language(language: List[str]) -> List[str]: """Filter language field""" language_filtered = [] for lang in language: if lang.lower() == 'pt-br': lang = 'pt_BR' language_filtered.append(lang) return language_filtered
4376cb3b4265924d86bc17c2ba40846256ef0f3e
670,075
def str_to_bool(s): """ Convert multiple string sequence possibilities to a simple bool There are many strings that represent True or False connotation. For example: Yes, yes, y, Y all imply a True statement. This function compares the input string against a set of known strings to see if it ...
b7483c833a62a39df852bdafc0a02b106f22d7a3
670,076
import six def optionalArgumentDecorator(baseDecorator): """ This decorator can be applied to other decorators, allowing the target decorator to be used either with or without arguments. The target decorator is expected to take at least 1 argument: the function to be wrapped. If additional argume...
f018db3ed927e33640ad2b4b570f9fd374834164
670,077
def get_decimal(instance): """ Wrapper which just calls the .getDecimal method of the passed instance of unitsclass :param instance: type unitsclasses :return: float """ return instance.feetDecimal
2b5a91941d9d06e898fd67d979d10cd52ba8d96e
670,078
import os def doc_folder_with_code(doc_folder): """Return Doc folder with Javascript example source code. """ js_source = os.path.join(doc_folder, "example") with open(os.path.join(js_source, "index.js"), "w") as f: f.write( "/**\n" " * A function\n" " *\n"...
bdf7d78ae808cbe86f13a3218355b332d99237ab
670,079
def unit_can_reach(unit, location): """ Return whether a unit can reach a location. Arguments: unit: the unit location: the location Returns: whether the unit can reach the location """ x, y = location return unit.partition[y][x]
6597ca30ea1041fd3f6dadf0f1f5e6e5b5ad2ae8
670,080
def smallest_square(n: int): """ returns the smallest int square that correspond to a integer example: smallest_square(65) returs 8 (8*8 = 64) """ n = abs(n) i = 0 while i**2 <= n: i += 1 if n - (i-1)**2 < i**2 - n: return i - 1 else: return i
c7c8d80d9cf70ac2a1e9c87ddaf2fb651307d763
670,082
from typing import List def split_lines(*streams: bytes) -> List[str]: """Returns a single list of string lines from the byte streams in args.""" return [ s for stream in streams for s in stream.decode('utf8').splitlines() ]
78104f09d44f7998035d37abc8dc80a2dc8c9385
670,083
def get_pred_text(eval_dict, example_ids, pred_starts, pred_ends, probs, use_official_ids=False): """Get text of predicted answers for a number of predicted starts, ends, and the corresponding example_ids. If use_official_ids is True, the returned dictionary maps from official UUIDs to predicted (answer text, p...
7651c651065a2f4b12fbc54b5b0e0426c9fcb8d8
670,085
import math def time_since(s): """compute time Args: s (float): the amount of time in seconds. Returns: (str) : formatting time. """ m = math.floor(s / 60) s -= m * 60 h = math.floor(m / 60) m -= h * 60 return '%dh %dm %ds' % (h, m, s)
87a3411515350d3d802df0e13532c2120736bd5b
670,086
def invert_rule_hierarchy(rule_hierarchy): """Get inverted rule hierarchy (swapped lhs and rhs).""" new_rule_hierarchy = { "rules": {}, "rule_homomorphisms": {} } for graph, rule in rule_hierarchy["rules"].items(): new_rule_hierarchy["rules"][graph] = rule.get_inverted_rule() ...
b42e98f6bc424803c0c364be8d20b22c375478dd
670,087
def _get_euclidean_dist(e1, e2): """Calculate the euclidean distance between e1 and e2.""" e1 = e1.flatten() e2 = e2.flatten() return sum([(el1 - el2) ** 2 for el1, el2 in zip(e1, e2)]) ** 0.5
c29777c9f17a099d97984711f2f5d261c86276da
670,088
def P(g): """Shortcut for П""" mult = 1 for i in g: mult *= i return mult
50a5d28160514c8d424b393b607614830cfa277b
670,089
def is_block_structure_complete_for_assignments(block_data, block_key): """ Considers a block complete only if all scored & graded leaf blocks are complete. This is different from the normal `complete` flag because children of the block that are informative (like readings or videos) do not count. We on...
5974bef0449b019a68092a1e630bb4395513d270
670,090
def _call_string(call): """Converts the provided call to string.""" positional_args = call[0] keyword_args = call[1] arg_strings = [] if positional_args: arg_strings.append(', '.join([str(arg) for arg in positional_args])) if keyword_args: arg_strings.append(', '.join( [f'{k}={v}' for (k, v...
3c993eb2be2b7a564ff5f65587c207e475b2bd4b
670,091
import torch def log_density(x: torch.Tensor) -> torch.Tensor: """Computes the density of points for a set of points Args: x (torch.Tensor): set of points (N x D) Returns: torch.Tensor: density in # points per unit of volume in the set """ hypercube_min, _ = torch.min(x, dim=0) ...
237981f584b1f7f2db5ccd38b80e13b57b688b61
670,092
def unit_step(t): """ Takes time as argument and returns a unit-step function """ return 1*(t>=0)
3fc46c615250c905e3cb2f816550aaf435862427
670,093
def docstrings(code, to_double = True): """ Converts between 3x' and 3x" as long as only one of them occurs in the file. """ single, double = "'''", '"""' if single in code and double in code: print('skipping docstrings because both %s and %s appear' % (single, double)) return code if to_double: code = code...
524f8ec2cc2292f7f8558b0a3bafe692943d86a2
670,095
def is_clique(graph): """ A clique is a set of nodes in which each node is connected to all other nodes. """ #for n1 in graph.nodes: # for n2 in graph.nodes: # if n1 != n2 and graph.edge(n1.id, n2.id) == None: # return False if graph.density < 1.0: return Fals...
bdd5560f1b02028914a2549bcef45c0c0290fe49
670,096
def _ascii(s): """ A helper function for converting to ASCII """ if isinstance(s, str): return s.encode('ascii', 'backslashreplace') elif isinstance(s, bytes): return s else: raise ValueError("Expected unicode or ascii string, got %s" % type(s))
59a94181914ae73c3d5124765ac4168245b84c6c
670,097
def substitute(arg, value, replacement=None, else_=None): """ Substitute (replace) one or more values in a value expression Parameters ---------- value : expr-like or dict replacement : expr-like, optional If an expression is passed to value, this must be passed else_ : expr, optional...
6f3d8e0e72dc16c15cbb0c769d5bb1b14f17df27
670,098
def delete_elem(s, elem): """delete a item in set""" r = set(s) r.remove(elem) return r
7ec9d60a3e08a6279a9408bd521329db87b1506e
670,099
def readMDL(filename): """ Read the MDL file in ASCII and return the data. """ filehandle = open(filename,'r') data = filehandle.read() filehandle.close() return data
53a190912e7c0a3ad78706cdbc7b7a95981ecbd5
670,100
from bs4 import BeautifulSoup def scrape_cards(soup): """ Scrape cards in deck list page. """ cells = soup.find_all("td") cards = BeautifulSoup(str(cells), "lxml").find_all("td", {"class": "deck-col-card"}) quantities = BeautifulSo...
a68a2cf181d3b23dbd111231107649fd898c2a49
670,101
def _plot_scatter(*, x, y, z, axis, norm, **kwargs): """ Plot scatter subplot """ return axis.scatter(x=x, y=y, c=z, norm=norm, **kwargs)
d8919f0dbf8fc37c8c81f8b08581fa3338ce627d
670,102
def check_previewUrls(search_results): """ Checks if a result provides a previewUrl for thumbnails. Otherwise a placeholder will be set. This function is needed to avoid too much logic in template rendering. Args: search_results: Contains all search results Returns: search_results ...
4f78f3d14167970a7988aea310fe2eaeae498ec3
670,103
import re def starts_with_auth(s): """Checks is string s starts with standard name type Args: s (str): WhatsApp message string Returns: bool: True if matches regex for name, False if not """ patterns = [ r'([\w]+):', # 1st Name r'([\w]+[\s]+...
a910375fb82151e938f4a2cb8b897002d24cb14e
670,104
def get_html_tr(case_id, passing_state, img_path, per, device_log, filter_log): """ :param case_id:编号 :param passing_state: 文本 :param img_path:图片地址 :return: html tr部分 """ tr = """ <tr bgcolor="MintCream"> %(case_id)s %(pass)s %(img)s %(per...
78a8a7dee1de063f7dcc2f28b7e781264ec28adc
670,105
import socket def is_port_open(host, port): """ determine whether `host` has the `port` open """ # creates a new socket s = socket.socket() try: # tries to connect to host using that port s.connect((host, port)) # make timeout if you want it a little faster ( less accur...
5c974c912196d02fa5ae536998f380f1f2fac90c
670,106
import random def generateGoldenApple(): """ This function returns if a golden apple should be generated or not. :return: """ return random.randint(1, 15) == 1
bdba94bda2fd56f7831193b0b17849c1f1e1c635
670,107
def format_num_3(num): """ Format the number to 3 decimal places. :param num: The number to format. :return: The number formatted to 3 decimal places. """ return float("{:.3f}".format(num))
94cbb801539dd72538ffb39bdbfab4675d9e8eed
670,108
import secrets import string def generate_secret_key() -> str: """Securely generate random 50 ASCII letters and digits.""" return "".join(secrets.choice(string.ascii_letters + string.digits) for _ in range(50))
efd23fd8e572f86372c3765ebb946e666370fce0
670,109
import sys import os import re def split_paired_reads (infile, extension, pair_identifier=None): """ Select paired-end reads from input interleaved files This function will select paired end reads from the interleaved files Args: infile (string): A interleaved read file (with or without the full paths) exten...
9a14c6d131d35b944df046dc1c57dceb81f0b33e
670,111
import tarfile import os def compress(data_type, output_file="archive.tar.gz", output_dir='', root_dir='.', items=[]): """compress dirs. KWArgs ------ output_file : str, default ="archive.tar.gz" output_dir : str, default = '' absolute path to output root_dir='.', absolute pat...
c77ae4331024c648285e92f37da526efa06324af
670,112
import random def quicksort(lyst): """ quicksort implementation, return a new sorted version of the input list. Faster quicksort in that it relies on built-in list comprehensions and concatenation. Inspired from Vitalii Vanovschi: http://www.parallelpython.com/component/option,com_smf/Item...
091bde65e325d9fd13fc3119dca06343fa99c8dc
670,113
import os def find_file_starting_from_reference_file_directory(reference_file, file_to_find): """Attempts to find file_to_find by navigating through directories from reference_file's parent directory.""" file_path = os.path.realpath(reference_file) folder_path = os.path.dirname(file_path) for root, un...
f1621d960592fe1be35b6dcfa2be3a0a0e27653a
670,114
import re def camelcase(value): """ Convert a module name or string with underscores and periods to camel case. :param value: the string to convert :type value: str :returns: the value converted to camel case. """ return ''.join(x.capitalize() if x else '_' for x in re....
9e751cb4d3cc8fc5a43733e9a5e0cafa98f18584
670,116
import math def _compute_effect_size(slice_metric: float, slice_std_dev: float, base_metric: float, base_std_dev: float): """Computes effect size.""" metric_diff = abs(slice_metric - base_metric) slice_var = slice_std_dev * slice_std_dev base_var = base_std_dev * base_std_dev return...
f7865beff061b7df61a39bfdf968e0db63ce5fd9
670,117
def if_handler(code): """Prevents player from using indefinite while loops by breaking loop after pre-defined amount of iterations. :param code: Source code string block. :type code: str :returns: The modified user source code string block is successful or -1 if failure. """ print("if handler"...
d904a6686d3ecf11b131c0e27fd088394778a499
670,118
def hex2dec(s): """return the integer value of a hexadecimal string s""" return int(s, 16)
7f97aabe590c1e434f03870c3d43af33cbf113a1
670,119
def return_nearest_relation_str(sim_sorted_ind, rev_rel_vocab, rel, k=5): """ helper method to print nearest relations :param sim_sorted_ind: sim matrix sorted wrt index :param rev_rel_vocab: :param rel: relation we want sim for :return: """ print("====Query rel: {}====".format(rev_rel_v...
723c3e9bc3db0e9611d0ad936d6e97dc02453496
670,120
def isNumber(string): """ check if a string can be converted to a number """ try: number = float(string) return True except: return False
40916ab8a206e4fdb068b2986146dde0d0cb64dc
670,121
def uniqueValues(aDict): """ Write a Python function that returns a list of keys in aDict that map to integer values that are unique (i.e. values appear exactly once in aDict). The list of keys you return should be sorted in increasing order. (If aDict does not contain any unique values, you should ...
5663dcdc7c11df3902ebe5f35ef400e2542dddc1
670,122
import string import random def generate_random_string(size=6, chars=string.printable): """ generates a random printable string of the given size using the given characters :param size: length of the string to be generated :param chars: set of characters to be used :return: a random string """...
80b5fec638e3865434bbc0af2503a66507a3b486
670,124
import numpy def msavi(b5, b8): """ Modified Soil-Adjusted Vegetation Index (Qi et al., 1994). .. math:: MSAVI = (2 * b8 + 1 - sqrt((2 * b8 + 1)^2 - 8 * (b8 - b5))) / 2 :param b5: Red-edge 1. :type b5: numpy.ndarray or float :param b8: NIR. :type b8: numpy.ndarray or float :returns ...
6f761c05c1126bd3d60d585294caa3ff78de93c0
670,125
def find_mode(x): """ find the mode (most common value reported) will return median (center of sorted list) should mode not be found """ n = len(x) max_count = 0 mode = 0 bimodal = 0 counter = 0 index = 0 while index < (n - 1): prev_count = counter count...
2e52ac1805901f61a6bca07f895eb5a5262f08c2
670,126
from datetime import datetime def create_cid(): """Create a new Client order id. Based on timestamp multiplied to 100k to make it improbable that two actions are assigned the same cid. Returns ------- int A integer number equal to the current timestamp * 10 mill. """ now = datetim...
6efdd8487f12198ebf0b66d117d9a843baa98f08
670,129
def subset_df(df, nrows=None, ncols=None, row_seed=0, col_seed=0): """Randomly subset a dataframe, preserving row and column order.""" if nrows is None: nrows = len(df) if ncols is None: ncols = len(df.columns) return (df .sample(n=nrows, random_state=row_seed, axis='rows') ...
c7933fd5609982b1eae01ef2e6cfb1d057f6acb3
670,130
import torch def knn(ref, query): """return indices of ref for each query point. L2 norm Args: ref ([type]): points * 3 query ([type]): tar_points * 3 Returns: [knn]: distance = query * 1 , indices = query * 1 """ mp2 = ref.unsqueeze(0).repeat(query.shape[0], 1, 1) tp...
ca999c7085f62d742c454f1bd9a25a58926a24f3
670,131
import time def check_log_timestamp(log_entry, date_filter_second, nowtime_second): """ check the log_entry's Created timestamp. If timestamp is within date filter, return True, else return False """ try: log_date_time_string = log_entry['Created'].split('.')[0].strip() log_second = int(time.m...
af7363c8258313650f6f3246de76b1d56fb23ae7
670,132
def get_bucket(timestamp, resolution): """ Normalize the timestamp to the given resolution. """ return resolution * (int(timestamp) // resolution)
67985fa9d875211c5a55749d353d93de0f2df670
670,133
import codecs def decode(text): """ Recognize string encodings: \t etc """ return codecs.decode(text, 'unicode_escape')
a9bf0146c95f38cc09f867215862e247d2a8ba1b
670,134
def get_data(features, labels_aud, labels_foc, files, indices): """Return features, labels and files at given indices """ features = [features[idx] for idx in indices] labels_aud = [labels_aud[idx] for idx in indices] labels_foc = [labels_foc[idx] for idx in indices] files = [files[idx] for idx in i...
5da68f72a17084a019e2bf2971023187aaff1ba1
670,136
def model_app_name(value): """ Return the app verbose name of an object """ return value._meta.app_config.verbose_name
c4fd7b138b4edeceb957beb2dbe1a1f28ebe4f95
670,137
import yaml def pretty(d): """Pretty object as YAML.""" return yaml.safe_dump(d, default_flow_style=False)
058b55f31f127cf932679312b14c4034f2bd5ed0
670,138
def locale_dict_fetch_with_fallbacks(data_dict, locale): """ Take a dictionary with various locales as keys and translations as values and a locale, and try to find a value that matches with good fallbacks. """ # try returning the locale as-is if data_dict.has_key(locale): return dat...
f81e37a4dcb5286619308832bd01b8740218ee6d
670,139
def filter_urls(new_urls, filter_words, args_filterand): """Returns filtered list of URLs based on URL filtering""" filtered_urls = [] if args_filterand != None: for i in new_urls: if all(x in i for x in filter_words): filtered_urls.append(i) filtered_urls = list(...
5f98edef97a18f7ffacf200ab9f391d53cac71ca
670,140
import math def _ceil_partial(value, grid_spacing): """Ceil to next point on a grid with a given grid_spacing.""" return math.ceil(value / grid_spacing) * grid_spacing
4876dc28c5281315ed467e8f0d11fa8145e82e44
670,141
import os import fnmatch def findfile(indir, inmask): """ literal_directory, basename_pattern (simple shell-style wildcards), includes dot-files no regex, but constructs like e.g. L5_[!a-f]*.tif , are possible """ filelist = [] for root, dd, files in os.walk(indir): for ff in f...
67d4e0aec6030d2e22a98e69ad8b8855dc08c358
670,142
import copy def swap_variables(self, r, s, in_place = False): """ Switch the variables `x_r` and `x_s` in the quadratic form (replacing the original form if the in_place flag is True). INPUT: `r`, `s` -- integers >= 0 OUTPUT: a QuadraticForm (by default, otherwise none) EX...
9a8fb0e6e0424efb39cf7861949961e88a147ad8
670,144
import unittest def test_suite(): """Allows testing of only this module with the command: python setup.py test -m desitarget.test.test_geomask """ return unittest.defaultTestLoader.loadTestsFromName(__name__)
961b12005fcf9007b65c623eb15cae9c5fa9c9bf
670,145
def totuples(data): """ Convert python container tree to key/value tuples. """ def crawl(obj, path): try: for key, value in sorted(obj.items()): yield from crawl(value, path + (key,)) except AttributeError: if not isinstance(obj, str) and hasattr(obj, '__...
e44b404dff2bc9d552d510f386dcc4793ad5e0b7
670,146
def _wrap_around(value, min_, max_): """Literally does what it says.""" width = max_ - min_ while value < min_ or value > max_: if value < min_: value += width else: value -= width return value
48a1e302524fc079d919fee81cfa7fe221ade7c9
670,147