content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import html def escape(s): """ Escape normal text into html representation. The only difference between this function and `django.util.html.escape` is that this function also escapes whitespaces into ` `s. :param s: String to be escaped. :return: Escaped string. :rtype: str """ re...
0561c80d103f78c7ad055d6de9252a395daaf015
629,670
from unittest.mock import Mock import click def mock_launch(monkeypatch) -> Mock: """Replaces click.launch() with a mock""" mock_launch = Mock(spec=click.launch) monkeypatch.setattr("click.launch", mock_launch) return mock_launch
ea3594db6abc1b8386503e2f2deb41240019d272
629,671
import requests import json def add_user(env, admin_api_key, env_type, email, role, group_name): """ Adds a user to the new environment. Will only add to a gorup if the user is in a group. Will add functionality around logon rules later. Can't use add_users because users in the same group could have d...
6e66b0bb841ecee52682422f4db6b611cae8dffa
629,672
import re def regex_out_paren(line): """Regex the comma. Quality docstring.""" return re.sub(r'\(', r'\(', line)
5b26f51ef9942ffc78644fb817c34333aa45117b
629,673
def remove_extra_space( text: str, ) -> str: """To remove extra space in a given text. Parameters ---------- text : str The text to clean. Returns ------- str returns text after removing all redundant spaces. Examples -------- >>> from SkillNer.cleaner impo...
1743c8cae32b0b23631a7f7dc3ed25526826fa69
629,674
from typing import List def count_failed_students(student_scores: List[int]) -> int: """ :param student_scores: list of integer student scores. :return: integer count of student scores at or below 40. """ return len(list(filter(lambda x: x <= 40, student_scores)))
c3fb0cc4fecb946a1850465f342e3530012826c1
629,675
def add_bda(base_config): """Add BDA to config file with hard-coded parameter values.""" bda_config = """ bda: max_decorr: 0 pre_fs_int_time: !dimensionful value: 0.1 units: s corr_FoV_angle: !dimensionful value: 20 units: deg max_time: !dimensionful value...
ba28edbff23a08f844cb87d32ea7856cb269fa36
629,676
def out_filename(template, n_val, mode): """Determine the output filename""" return '{0}_{1}_{2}.cpp'.format(template.name, n_val, mode.identifier)
f6bf0b12377ff4363409cd3315bdb0693e1b9fc9
629,677
def find_effective_max_unique_otus(tree): """ the effective maximum number of unique otus is the max seen at the phyla level """ node_level = tree.get_attribute('node_level') #if above phylum in the tree, find the max of the children if node_level in ['root', 'kingdom']: child_maxes...
3411da259a4f90505f2c11dc95bbe639f1015aa0
629,678
def to_solr_query(self, value): """ This turns a list of query spec items into a complete urlsafe query string Parameters ---------- value : dict The query parameters """ _ = self # pylint if hasattr(value, '_as_dict'): value = value._as_dict() stack, root = [(N...
e7c7f5301988f745732034df8c65051b56b332a1
629,680
def getbitlen(bint): """ Returns the number of bits encoding an integer """ if bint == 0: # Zero is encoded on one bit return 1 else: return int(bint).bit_length()
99cfb57c0248aed21747c85dbb270703b184fd48
629,681
import argparse def make_argument_parser(): """ :return: one argument parser """ parser = argparse.ArgumentParser("vcf2paragraph.py") parser.add_argument("input", help="Input VCF / BCF file", nargs=1) parser.add_argument("output", help="Output JSON file", nargs=1) parser.add_argument("-...
8bae4044d941c795074d43159e81621bf377c008
629,682
import configparser import collections def parse_config(filename): """Parse configuration file.""" parser = configparser.ConfigParser() parser.read(filename) cfg = {} venv_dirname = parser.get('VirtualEnv', 'Directory') if venv_dirname: cfg['venv_dirname'] = venv_dirname else: ...
260eaea766e8547c41fa9443b877a74284f1bbdb
629,684
def aggregator_total_cost(k,r,N): """ Calculates the aggregator's total cost. Note that the aggregator is the leader of the network, who decides the reward that each node in the blockchain will get """ TC_ag=[] # total cost of aggregator for c in range(N): TC_ag.append(k + r *c) return T...
87613e09583492bf2d498a3644a8067cda3b5c10
629,685
from typing import Dict import torch def dictionary_to_device(dictionary: Dict, device: torch.device): """Move dictionary values to a torch device, if they support it. :param dictionary: Dictionary, whose values are to be moved to the torch device. :param device: torch device :return: Dictionary, wit...
ba240355c1ae49fc449b82c652663aa4de021492
629,686
def _set_dtype(properties): """Return the dtype of a random model property.""" return list(properties.values())[0].dtype
695b9ca5e7cb48413261e4ce9f04bad362e7ed16
629,687
import math def determine_num_particles(pack_frac, num_vertices): """Return the number of model particles to be created based on the packing fraction""" num_particles = num_vertices * pack_frac num_particles = int(math.ceil(num_particles)) return num_particles
58f49659cc011278786b91938ac4d31630308080
629,688
def stripStopWordsFromText(sent, stop_words): """ Removes stop-words at the start and end of the inputs """ fw_ctr = 0 bw_ctr = 0 for tok in sent.split(' '): if tok in stop_words: fw_ctr+=1 else: break for tok in reversed(sent.split(' ')): if t...
3641efa23394eeaf2de9f86c923285157810eb5a
629,690
def functions_in(module): """ Create a dictionary of the functions in a module Parameters ---------- module : Module module to run on. Returns ------- dict """ return {name: f for name, f in module.__dict__.items() if callable(f)}
26d8b64034eb5cdb236b877c254eaffee57d1093
629,691
def lib_inc(params: dict) -> str: """ Build lib inc for linker settings """ lib_inc = str() if params["library_libft"]: lib_inc += " -L" + params["folder_libft"] + " -lftprintf" if params["library_mlx"] and params["compile_mlx"]: lib_inc += " -L" + params["folder_mlx"] + " -lmlx" if params["library"]: lib...
ed8ac68bffa203f5816110e0a7f9363293ec3ed0
629,692
def reverse_2nd(vec): """Do time-reversal on numpy array of form `B x T` :param vec: vector to time-reverse :return: Time-reversed vector """ return vec[:, ::-1]
cf069e59e680333698582de81b0e9c2e13eec78b
629,693
def GetPatchMetadata(patch_dict): """Gets the patch's metadata. Args: patch_dict: A dictionary that has the patch metadata. Returns: A tuple that contains the metadata values. """ # Get the metadata values of a patch if possible. start_version = patch_dict.get('start_version', 0) end_version = ...
4fa58c5cbcdd457ef7ad92b6b9ad3600264542c4
629,694
import numpy def getSph2CartTransfMat(rvm, ISO=False): """Compute the transformation matrix from a spherical basis to a Cartesian basis at the field point given by the input 'r'. If input 'r' is an array with dim>1 then the last dimension holds the r vector components. The output 'transf_sph2cart' is ...
08505c18ca9095564274511c2b94295958e6b039
629,695
def get_suite_name(nodeid): """Return suitename from nodeid string. Args: nodeid(str): pytest.Item nodeid string Returns: str: test suite name """ names = nodeid.split("::") names[0] = names[0].replace("/", '.') names = [x.replace(".py", "") for x in names if x != "()"] ...
c08133bf7d70a288abaac7f6c15e0c06eb6888dc
629,696
def _binary_search(a: float, b: float, f, precision: float = 1e-6)-> float: """f(x) returns True if threshold is greater than x, False otherwise.""" pivot = (a+b)/2. while b-a > precision: pivot = (a+b)/2. if f(pivot): b = pivot else: a = pivot return pivo...
7cc02a28e279e13acab5cdc1c4fceccb517de564
629,697
def calc_blotchiness(nfans, nblotches): """Calculate the fnotch value (or fan-ness).""" return (nblotches) / (nfans + nblotches)
5e309364dfc8f40df3232bec6b38eea07d9c9c29
629,698
def back_slash_to_front_converter(string): """ Replacing all \ in the str to / :param string: single string to modify :type string: str """ try: if not string or not isinstance(string, str): return string return string.replace('\\', '/') except Exception: ...
f3e6c57a3c984c066088e9faf9f19b5b08f2b53c
629,701
import os import subprocess def make_resample_1mm(file_): """ Resamples input nifti file to 1mm space Parameters ---------- file_ : string Input Nifti File Returns ------- new_fname : string Input Nifti resampled to 1mm space """ remainder, ext_ = os.pa...
5b0280b9f51ebb3268c7ebef3ca27c663e3291d9
629,703
def min_sec(secs): """ Takes an epoch timestamp and returns string of minutes:seconds. :param secs: Timestamp (in seconds) >>> import time >>> start = time.time() # Wait a few seconds >>> finish = time.time() >>> min_sec(finish - start) '0:11' """ secs = int(secs) ...
6c06866c0c44d7662b7b655798fd2f92357af14a
629,704
def find_selected_id_in_history(history, selected_frame, posx, posy): """ Find which one of our ids matches with the selected pedestrian to be tracked, which was in posx and posy at the selected_frame. :param history: :param selected_frame: :param posx: :param posy: :return: """ ...
033426cccee37e5666887f3354ec21789ca69434
629,705
def get_number_of_images(body_response): """ Returns the number of images in the list. :param body_response: Parsed response (Python dic). List of images :return: Length of list """ return len(body_response['images'])
c7034154b379c647739b3f7d52c4a5ba631eafb6
629,706
def char_to_bin(char: str) -> str: """This creates a string representing the binary value of the character. Parameters: ----------- char: string: A single character. Returns: -------- binary: string: The 8-bit binary representation of the character. """ binary = bi...
8a07c944733cf9543e236eb61dadf47571fa6b9b
629,707
def is_indicator(item_type): """Return whether or not the given item_type is an indicator.""" indicator_types = [ 'address', 'emailaddress', 'file', 'host', 'url', 'asn', 'cidr', 'mutex', 'registry key', 'user agent' ] retur...
9f471290f62e3f583cc9b2c1e45604312f9f48bb
629,708
from typing import Tuple def parse(args: Tuple[str, str, str, str, str]) -> Tuple[str, str, str]: """Parser for rd rs rt format instructions.""" return (args[2], args[3], args[4])
9a74a7a98f108d350ca22ae62e0d6ea3769ca720
629,709
def list_daily_cases(list_of_cumulative_cases): """ Given a list of cumulative cases, this function makes and returns a list of daily cases. """ daily_list = [0] for i in range(1, len(list_of_cumulative_cases)): N_daily_case = list_of_cumulative_cases[i] - list_of_cumulative_cases[i - 1...
287d01b2c7a2a8764289c1f5f2e65372fedc35b5
629,710
def is_user_inputs_populated(user_prefs): """ Takes a dictionary of user preferences and returns a Boolean whether all inputs are filled. """ return all(value != '' or value != 'No preference' for value in user_prefs.values())
316769bb352b8f67f6080a4e021ef800f243fcaf
629,711
from typing import Mapping def get_keys_for_dict(d): """ Get all (possibly nested) keys in a dictionary """ out = [] for k, v in d.items(): out.append(k) if isinstance(v, Mapping): out += get_keys_for_dict(v) return out
4ad5a9df77f5fe153c75cc820b3899542990f98b
629,712
def getFibonacciRecursive(n: int) -> int: """ Calculate the fibonacci number at position n recursively """ a = 0 b = 1 def step(n: int) -> int: nonlocal a, b if n <= 0: return a a, b = b, a + b return step(n - 1) return step(n)
f5196709dc7dd66b1f5278b1bc696face28e6e85
629,713
def deltax(firstx, lastx, npoints, **kwargs): """-> (lastx - firstx) / (npoints - 1)""" return (lastx - firstx) / (npoints - 1)
f01df63db4121427bbb800d870f41cbe18227ca0
629,714
import os def get_dir_name_type(out_name, out_type='png', out_dir=None): """ Standardized behaviour for filenames. Parameters ---------- out_name : str output filename. if it contains an extension (e.g. 'MyName.png'), the extension is added to out_ext. out_type : str or itera...
5283b8dc183e5faecb6d1d3358bfdab41d4bad3e
629,715
def average(values): """calculates average from a list""" try: return float(sum(values) / len(values)) except ZeroDivisionError: return 0
103923cba72bb7a1c84577518731ad56e1f4bc4c
629,716
def _parse_action_removals(actions): """ Separates the combined list of keys to remove into webhooks and emails. """ flattened = list({x for sublist in actions for x in sublist}) emails = [] webhooks = [] for item in flattened: if item.startswith('http://') or item.startswith('https://'): ...
7ac597c039c64d22e3dc82b965e4b28b1ddbd8e7
629,717
import requests from bs4 import BeautifulSoup def get_soup(link): """Gets soup from a given website.""" res = requests.get(link) soup = BeautifulSoup(res.text, "html.parser") return soup
e4212b3e95642fc238407b803e5c65ac44d3aeca
629,718
def novlp_cmbtns(variants): """Returns non-overlapping combinations of variants. Variants assumed to be sorted. For example,assuming the following variants:: Ref TTATATT ------- vrt0 AGTCTGA vrt1,vrt3 AGT TG vrt2,vrt4 G A >>> novlp_cmbtns([vrt1,v...
56da55b972734e9423d2f260809f3f70f7452583
629,719
def get_package_name_and_type(package, known_extensions): """Return package name and type. Package type must exists in known_extensions list. Otherwise None is returned. >>> extensions = ['tar.gz', 'zip'] >>> get_package_name_and_type('underscored_name.zip', extensions) ('underscored_name', 'z...
eb7732a16a4f1ca84b25c38c7aec2e4572f1afd3
629,720
def merge(d1, d2, merge_fn): """ Merges two dictionaries, non-destructively, combining values on duplicate keys as defined by the optional merge function. The default behavior replaces the values in d1 with corresponding values in d2. Examples: >>> d1 {'a': 1, 'c': 3, 'b': 2} >>> ...
d1d4b48d5d4048bb7fa99312236a5df1a4e409d0
629,722
import argparse def percent_float(value): """ Floating type for Arguments """ pvalue = float(value) if pvalue < 0.0 or pvalue > 100.0: raise argparse.ArgumentTypeError( "%s not in range [0.0, 100.0]" % pvalue) return pvalue
203d6c19f8ca50fe5d3f2931ae8bfa375786020a
629,723
import random def random_caps(any_case, upper_percent_chance=25): """ Takes a string passed to it in any case, as well as an optional percentage of time you want lower-case letters, and returns a string with randomly capitalized letters. :param string any_case: :param int upper_percent_chance: ...
89c7f83304c51dab10577ae894a43dd935b4497c
629,724
def _perp(t: tuple) -> tuple: """ Obtain the point whose corresponding vector is perpendicular to t. Parameters ---------- t : tuple Point (x, y) Returns ------- tuple: (-y, x) """ return -t[1], t[0]
ed49a4f326f8ef065e72d964bce3b3ce444c25f5
629,725
def solve_me_first(num1: int, num2: int): """Calculate the sum of two numbers.""" return num1 + num2
09c44886cd43d2e0ab7b54bbbcaa058a9e9382ed
629,726
import math def cint(num): """ Returns ceiling of number as type integer :param num: input number :returns: integer ceil number """ return int(math.ceil(num))
46dccd12e93053b4e54f43a498d97a97e202693c
629,727
import hashlib def create_key(notification): """Create the key for status_keys from notification in: notification return: the key """ key = notification.host key += '/' key += notification.plugin if notification.plugin_instance: key += '-' key += notification.plug...
2397430e9198bfbbbe66f83ce0e9eddfc172ec4c
629,728
def zero_cross_down(values, start=0, end=-1): """ Returns the indexes of the values so that values[i] > 0 and values[i+1] < 0 params: - values: list of values to consider - start: index of the first value to consider - end: index of the last value to consider (can be < 0) """ ...
ee86118c23dcb6278d9c86bd50a1915661a2eaf5
629,729
import numpy def copy_array_including_strides(arr): """copy a numpy array, including the strides""" arr = numpy.asarray(arr) if arr.ndim!=2: raise NotImplementedError('only 2D arrays currently supported') newarr_full = numpy.empty( (arr.shape[0], arr.strides[0]), dtype=arr.dtype) newarr_fu...
07b5e7248e6b50b5fed1c87b5f152dd6e2d4a465
629,730
def pascal_case(text): """Returns text converted to PascalCase""" s1 = text.split('_') return ''.join([s.lower().capitalize() for s in s1])
f39c99e2dea707ba1f603d94363c049a2205a34d
629,731
def get_set_intersection(list_i, list_j): """ Get the intersection set Parameters ---------- list_i, list_j: list two generic lists Returns ------- intersection_set: set the intersection of list_i and list_j """ set_i = set(list_i) set_j = set(list_j) interse...
bfba58d6f8b33591208de76c20fee60ac9e56fd8
629,732
import torch def center_crop(layer: torch.Tensor, max_height: int, max_width: int) -> torch.Tensor: """ Crops a given layer to a certain size by removing equal margins all around.""" _, _, height, width = layer.size() xy1 = (width - max_width) // 2 xy2 = (height - max_height) // 2 return layer[:, ...
b9872678c5794fec68e67eb30fec42cf427ca118
629,733
def delete_user_defined_app_address_map( self, ip_start: int, ip_end: int, ) -> bool: """Delete specific user defined application group based on address map .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - applicationDefini...
d783812a6faad1c12bc5e7afc765e44ca23f78e6
629,734
def getMutationIDs(data): """ Function to get uniques mutation IDs from COSMIC data Arguments: data = dataframe containing COSMIC data Returns: list of unique mutation IDs """ return list(set(data["Mutation ID"]))
906f4d4a240373d2476e8a420b9e8df542db70b5
629,735
def get_para_spans(example, orig_to_tok_index, orig_to_tok_back_index, all_doc_tokens, marker): """get paragraphs' spans""" para_spans = [] for title_span, para_span in zip(example.title_start_end_position, example.para_start_end_position): para_start_position = orig_to_tok_index[title_span[0]] ...
95978c5fea3ad0726b0119f99fe1a31f78188646
629,736
def no_duplicate_letters(phrase: str) -> bool: """Check if each word has distinct letters in phrase.""" words = phrase.split(' ') for word in words: if len(set(word)) == len(word): continue else: return False return True
95b7a8e496b6624dee2abb8a98b3cefd8c7aaf10
629,737
def AmOppCreditParts(exact, e87521, num, c00100, CR_AmOppRefundable_hc, CR_AmOppNonRefundable_hc, c10960, c87668): """ Applies a phaseout to the Form 8863, line 1, American Opportunity Credit amount, e87521, and then applies the 0.4 refundable rate. Logic corresponds to Form 8863, P...
36be57cf25ea18d422a522e2a7a1aef36aee7ef6
629,738
import os def fmt_path(path): """格式化地址""" path = os.path.expanduser(path) return path
e8054ca013bd8a9110d3afe7634aef34c060cf94
629,739
def is_string_integer(string: str): """ This function takes in a character value and checks if it is a valid integer. All entries must be strings of length 1 :param string: the string to be analyzed :type string: str :return: true or false, depending on if the character is a valid integer ...
854c86f9eeda717b8a76339d22642e6503069222
629,740
import os def setup_sorting(): """If you don't need to do sorting, simply return None.""" start_dir = os.path.abspath( os.path.join("__dirname__", "muscimol_data", "CanCSR7_muscimol", "2_03082018") ) def sort_fn(x): """ Establish a sorting function for recordings in a containe...
95cd0881d1cf247b9bdeabdfeb8be5bf022f93e2
629,741
import torch import math def attention(query, key, value, atten_mask=None): """ Compute Scaled Dot Product Atten should: d_q == d_k, len_v == len_q, atten_mask.shape equal to scores or can be broadcast :param query: (batch_size, n_heads, len_q, d_q) :param key: (batch_size, n_heads, len_k, d_q) ...
95e4dd0a35d1a82b523e2764e23a5eba5231fb9c
629,742
def delete(redis, task_id): """Delete a given task.""" keyt = "task:" + task_id status = redis.hget(keyt, "status") if status is None: return (False, "task does not exists") if status != "stopped": return (False, "status is not stopped") with redis.acquire_lock(keyt): red...
f3461949d3e0b17ba5ae2fdf7a145678b3cb031a
629,743
def is_valid(utf8_content): """Was the request fulfilled as expected?""" return 'Magnificent!' in utf8_content.decode("utf-8")
008d0e1a30f0eec30b671dc49f25b34fc7a27a62
629,744
def compute_pad(image_shape, kernel_size, enforce_odd=True): """Computes a padding length for a given image shape and kernel. Args: image_shape: A tuple or list of 2 integers. kernel_size: A positive integer. enforce_odd: A boolean indicating whether the padding should result in an image with odd...
a6ca56c99d90942ea55dc6c3b039fb62e4aada22
629,745
def euler31(obj=200, coins=None): """Solution for problem 31.""" if coins is None: coins = [1, 2, 5, 10, 20, 50, 100, 200] nb_ways = [1] + [0] * obj for c in coins: for v in range(obj + 1 - c): nb_ways[v + c] += nb_ways[v] return nb_ways[-1]
4b16a131ea4839ae301f62b3b1383a7598aa6100
629,746
def is_green(fuel_type): """Return a green RGB value if a facility uses a renewable fuel type""" if fuel_type.lower() in ("nuclear", "water", "wind", "hydro", "biomass", "solar", "geothermal"): return [10, 230, 120] return [230, 158, 10]
e5c4a15cb484ffcf676e8b64e52efa4a40112636
629,748
def valid_field_in_tree(arch): """A `tree` must have `string` attribute and an immediate node of `tree` view must be `field` or `button`.""" if arch.xpath('//tree[not (@string)]'): return False for child in arch.xpath('/tree/child::*'): if child.tag not in ('field', 'button'): re...
84b8f67b01929d4a9c6dd89954ea3397a489e9f4
629,749
def one(iterable): """Return the single element in iterable. Raise an error if there isn't exactly one element. """ item = None iterator = iter(iterable) try: item = next(iterator) except StopIteration: raise ValueError('Iterable is empty, must contain one item') try: next(iterator) except StopIteration...
49cbb2e829bccaeb3ba5337b00c8bb19c2842b02
629,750
def checklist(): """Nowcast system state checklist dict data structure; a mock for :py:attr:`nemo_nowcast.manager.NowcastManager.checklist`. """ return {}
e39e5976980ea8a4780f8ae5085a39f64573b0d9
629,751
def GetDetailedHelpForAddIamPolicyBinding(collection, example_id, role='roles/editor', use_an=False, condition=False): """Returns a detailed_help for ...
78d835b89535db5051d8d9a5bd40e31eee7873de
629,752
import argparse def exp_smoothing_weight_test(value): """Require that the weight for exponential smoothing is a weight between 0.0 and 1.0""" fvalue = float(value) if fvalue < 0.0 or fvalue > 1.0: raise argparse.ArgumentTypeError("{} must be a float between 0.0 and 1.0".format(value)) return f...
14a1f77636175cb7334556368488dbcc7682ad66
629,753
def twochannel10(tb10v, tb10h): """Simple 2 channel algorithm 10 GHz """ ct=1.33313-0.01686*(tb10v-tb10h) return ct
928178be7e0defe40da79a4421f407b664408cee
629,755
def flatten(image, char): """ Given a layered image (typically (y, x, RGB)), return a plain 2D image (y, x) according to a spec. Args: image (np.ndarray): The image to flatten char (char): One of (R, G, B, or V (=value)) Returns: np.ndarray - The 2D image. """ if im...
6cc504876032ab78350d42d24d475302cfc2bb5f
629,756
def get_translation_data(struct, key): """Returns translation data set by set_translation_data(). Args: struct: type. A Struct class. key: any object. Raises: KeyError: Translation data for the key is not defined. """ return struct._translation_data[key]
4af9f908be917a6c13c563ddb62766728cb472e3
629,757
import re def lowercase (text): """Создаёт из текста список слов в нижнем регистре""" # Переводим текст в нижний регистр: text = str(text.lower()) # Регексп вытаскивает из текста слова: words = re.findall(r"(\w+)", text, re.UNICODE) # Восстанавливаются ссылки: urls = re.findall('http[s]?:/...
3a78f534c1327c24679a56658c785fabb28c7825
629,758
def guess_multi_value(value): """ Make the best kind of list from `value`. If it's already a list, or tuple, do nothing. If it's a value with new lines, split. If it's a single value without new lines, wrap in a list """ if isinstance(value, (tuple, list)): return value if isinstanc...
a742a9f37f84bbcc04f550fc3525a8df0fce43b9
629,759
def calc_us_in_name(name): """ calculate how many underscore is in name. :param name: a string. :return: a number """ cnt = 0 for ch in name: if ch == '_': cnt += 1 return cnt
0c5f25de0718e615350a49176859a5b987276f84
629,760
def flowfile(): """NiFi's FlowFile Stream v3 Pack/Unpack.""" return 0
a0e806ef3b3c941286d957dde66b9eb55f636d3d
629,761
import os def has_merlin_error(path='.'): # type: (str) -> bool """Check if it has Merlin flow error""" return (os.path.exists('{0}/.cmost_flow_has_error'.format(path)) or os.path.exists('{0}/.merlin_flow_has_error'.format(path)))
278393002ba387915ea62bd6ad8a26044be22012
629,762
from typing import List import sys import csv def read_csv() -> List[List[str]]: """ Reads in the data from the data argument and returns a nested list of strings """ with open(sys.argv[1], newline='') as csvfile: reader = csv.reader(csvfile, delimiter=',') return_val = [] for ...
ac4aafc342cc64ad30365f5e7ac18a82aad85c9d
629,763
def convert_numpy_to_scientific_string(numpy_array): """ converts a numpy array in a string composed of scientific notation numbers """ list_strings = [] for value in numpy_array: list_strings.append("%e" % value) list_strings.append(",") string_result = "".join(list_strings) ...
074693dba01889dfc89b0528a750939a30bae705
629,764
def cal_add(val1, val2): """ 足し算を行う関数 """ return val1 + val2
ea9400d7468ee4b293a91515f82b097c29a447de
629,765
import os def test_data_folder(request): """ This fixture returns path to the folder with the shared test resources """ return str(os.path.join(request.fspath.dirname, "test_data"))
2f98c45385727420b522aa7cae741b6fe210091c
629,766
import re def process_text(text): """ This method is responsible for performing all pre-processing steps for the text. It converts text to all lower case and performs some basic cleanup using regex. """ text = text.encode('ascii', errors='ignore').decode() text = text.lower() text = re.su...
a49fe0861b00f7e92612cc265c5c19dfd935ecb1
629,767
def recall_particle_parameter_measurements(): """returns a tuple of measurements I made from the kinematics of the full models using ordinairy least squares. see main manuscript for details. Example Usage: a_hat_FK, D_hat_FK, a_hat_FK_long, a_hat_FK_vlong, a_hat_LR, D_hat_LR, a_hat_LR_long=recall_particle_...
8760e1d99e47d6fe228e2a689f85e176eb2699c2
629,768
def read_gems(directory, file_name): """ Read a GEM file of the form "PlinePgem". Args: directory (str): directory of the file location (ex: '/Users/kimm/') file_name (str): name of the file (ex: 'SHG0008H.Fragnum_PlinePgem') Returns: in_gems (list): tab-separated lists of lists ...
d583cc9f8d3b53fb42dd4e45f2d74531716e8ab5
629,769
def aggregate_count(items, col): """ Function to use on Group by Charts. accepts a list and returns the count of the list's items """ return len(list(items))
4053079bc0c0623c549c178a65e4b5af9a8b7d09
629,771
def _replace_and_save(md, fns, replacing_fn): """ Replaces functions in `fns` list in `md` module with `replacing_fn`. Returns the dictionary with functions that were replaced. """ saved = dict() for check_f in fns: try: fn = getattr(md, check_f) setattr(md, chec...
a57fdca4ffad6a3f5d4567e47e14d40cb59c7ea7
629,772
def as_list(val): """ Helper function, always returns a list of the input value. :param val: the input value. :returns: the input value as a list. :Example: >>> as_list('test') ['test'] >>> as_list(['test1', 'test2']) ['test1', 'test2'] """ treat_single_value = str i...
d696d22233c853d180e4eefba59be81e4e7f783f
629,773
def find_date_event(source_table): """ convienience function to return the source field of a date event for a destination table from the current source table Paramaters: - source_table (ScanReportTable): object for the scan report table Returns: - ScanReportField : the source_f...
f971b64eec63be8299bfb7d0c3d5acbc2ffee915
629,774
import subprocess def _user_has_root_privileges(): """Determine whether the user currently has root privileges. Returns ------- bool Whether the user currently has root privileges. """ try: subprocess.run( ["sudo", "-ln"], check=True, stder...
1ad72d0a89d1ca0aff6cda5dd40776b4d77aef4d
629,775
def quantize_dequantize(quantization, tensor): """Simple helper to quantize and dequantize.""" quantized_tensor, context = quantization.quantize(tensor) dequantized_tensor = quantization.dequantize(quantized_tensor, context) return quantized_tensor, dequantized_tensor, context
435e14a99b61c4cdb88dc7927280e0322e880ffc
629,776
import numpy as np def lcs_distance(sa, sb): """insertions and deletions only""" sa_s, sb_s= len(sa)+1, len(sb)+1 # 表,从0个字符开算 t = np.zeros((sa_s, sb_s)) for m in range(sa_s): t[m, 0] = m for n in range(sb_s): t[0, n] = n for m in range(1, sa_s): for n in range(1,...
7f27ea21eb8a2dc1c50ff007ad4fa6d8e314fa83
629,777
from typing import Dict from typing import Union from typing import Any def get(doc: Dict, key: str) -> Union[Any, None]: """Gets the value for key from the dictionary. Example get("a", {"a": 1, "b": 2, "c": 3}) # => 1 """ if not isinstance(doc, dict): return None if not isinstance(key, str): ...
04231cfe7c236b3332935814d6b099d0bba24a58
629,778
import platform def get_current_prefab_platform() -> str: """Get the name of the running platform. Throws a RuntimeError on unsupported platforms. """ system = platform.system() machine = platform.machine() if system == 'Darwin': # Currently there's just x86_64 on mac; # will ...
b81158e0364a98f288f81c73c37878113719be43
629,779