content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def safe_sum(v1, v2): """Sum two integers (string type) accounting for the possibility that one or both is missing; returns an integer.""" if v1: if v2: return int(v1) + int(v2) else: return int(v1) if v2: return int(v2) return 0
2fcae1373ce981079ccc50472e4e1e3d27d52c60
626,713
def render_services(args, df): """ replace service number with service name, for common services""" for col in ['srcport', 'dstport']: df[col][df[col] == '22'] = 'ssh' df[col][df[col] == '23'] = 'telnet' df[col][df[col] == '53'] = 'domain' df[col][df[col] == '80'] = 'http' ...
adee9b81f84cb91e23b9c6797864fb350e7a4c3e
626,714
def tuple_add(tuple_a: tuple, tuple_b: tuple) -> tuple: """Return the result of the addition of two tuples.""" return tuple(map(lambda x, y: x + y, tuple_a, tuple_b)) # Source: https://stackoverflow.com/questions/497885/python-element-wise-tuple-operations-like-sum
0ffa95ce1f47ef87687ac675b750348f6985f631
626,715
def signal_percent_to_dbm(percent: int) -> int: """ arbitrary conversion factor from Windows WiFi signal % to dBm assumes signal percents map to dBm like: * 100% is -30 dBm * 0% is -100 dBm Parameters ---------- percent: int signal strength as percent 0..100 Returns --...
83b6ce9c47c6966d0bc97b76a5dc28280e4e26f5
626,716
import re def singleline_replace(content: str) -> str: """singleline_replace performs simple replacements""" content_new: str = "" for line in content.splitlines(keepends=False): line = line.replace("equals", "eq") line = line.replace("starts_with", "eq") line = line.replace("ends_...
aeb11d473cb494ac9dd1a5570f122bcde7164f85
626,717
def fibonacci(n): """ This is the original function, it will be used to compare execution times. """ if n <= 1: return n return fibonacci(n - 1) + fibonacci(n - 2)
1ca15b9bfd259712b924f7f2f67f34183a701555
626,719
def getObjectName(objectData, objectLabel): """ Returns the object label specified in object_data.yaml :param objectLabel: :return: objectName """ for objectName in objectData: if objectData[objectName]['label'] == objectLabel: return objectName raise ValueError('there i...
55f2b9eee60beca79e5551fd613b49d615d54d51
626,720
def get_names(chemkin_names,inchis): """ Get the names of the species from the original mechanism """ names = ['' for inchi in inchis] for chemkin_name in chemkin_names: chemkin_inchi = chemkin_names[chemkin_name] for i,inchi in enumerate(inchis): if inchi == chemkin...
5420f5818e7d98f7a85d896216a1ed2b3a7ecddf
626,721
def find_by_name(name, items): """ Find the object with the specified name attribute. :param name: str: name to look for :param items: [object]: list of objects to look for :return: first item matching name or None if not found """ for item in items: if item.name == name: ...
7b12dde6ca985143ce8eca86baf7884acfb85657
626,723
import time def time_function(func, params): """ Returns the approximate run-time of a function, in milliseconds """ start_time = time.time() result = func(*params) end_time = time.time() return end_time - start_time
b49d27fe5fb4a122ecb6ca245a073831c70e3ebc
626,724
import torch def estimate_implicit_moments(config, shared, task_id, hnet, hhnet, num_samples, device): """Estimate the first two moments of an implicit distribution. This function takes the implicit distribution represented by ``hnet`` and estimates the mean and the variance...
a84751baecc1a23b3f3911075e193bc72a867d6b
626,725
def kleene_closure(the_state_machine): """Creates a state machine that is repeated any number of times (zero is also accepted). See: Thomson construction. """ # (*) clone the machine result = the_state_machine.clone() # (*) add additional initial state prev_init_state_index ...
2f153841f72a9719740602330015cec9a22bde32
626,726
import os def get_extension(path): """ Returns the exctension of a file path (wihtout the period) :param path: str, valid path to a file :return: str """ return os.path.splitext(path)[1][1:]
a5d08a512a8b7f5c055dc0c1f299e4c04b6c52e9
626,727
def disc(x): """ Returns 'x' rounded to the nearest integer. """ return int(round(x))
726d08f3d1b02fdce809ef53b936b87f84628b29
626,728
def _read_filepath(source: str) -> str: """ Read file contents """ with open(source, 'r', encoding='utf-8') as infile: contents = infile.read() return contents
cb22c6eee9a5fc54c513b751e36440f9b86e4522
626,729
def extract_task(line): """ Tries to return the task name being called in the line. """ stripped = line.lstrip() temp = stripped.find("(") if temp == -1: return None return stripped[0:temp]
7b635e3c7af3ba65c73c4bb6c6d2864f28300bec
626,730
import math def camera_location(azimuth, elevation, dist): """get camera_location (x, y, z) you can write your own version of camera_location function to return the camera loation in the blender world coordinates system Args: azimuth: azimuth degree(object centered) elevation: el...
14111282ce733bc2db23de49d440b829df1d9c42
626,731
import collections def Event(): """Create a subclass for simulating vispy mouse events. Returns ------- Event : Type A new tuple subclass named Event that can be used to create a NamedTuple object with fields "type", "is_dragging", and "modifiers". """ return collections.named...
a80ebe2c3ef7e2810c0ab88095811e28a2dcd08d
626,732
def is_podcast_series_id(item_id): """Validate if ID is in the format of a Google Music series ID.""" return len(item_id) == 27 and item_id.startswith('I')
e17f7a5419d40689c6a0ac8a99da7260aca48774
626,733
import torch def format_abstract_tensile(cycles, predictions): """ Format abstracted tensile test data, where only the yield strength and ultimate tensile strength are available. This method relies on the input cycles being: * 0: in the elastic regime * 1: for the first 1/2 of the remaining t...
e59116b10c34a9106b2b004613eaf4814f6333a6
626,734
def assert_nested_field_allows_type_key(schema, field_name, type_key, negated=False): """Assert that the nested field allows a type key.""" is_in = type_key in schema._declared_fields[field_name].nested._declared_fields return negated != is_in
39b4078021a823fcc63b45ade110e92ecf82e6a5
626,735
def get_set_vertices_u_0(g_or_n): """Get indexes for the belief vector:" 0: capture 1,...n: vertices""" if isinstance(g_or_n, int): n = g_or_n else: n = len(g_or_n.vs) V = list(range(1, n + 1)) V_ext = [0] + V return V_ext
a9e31c1b7bcd60a77bb5befebd8976507915b108
626,736
from typing import List from typing import Dict import yaml import os import json def config_to_cc(template_dir, config_file, additional_context: List=[]) -> Dict: """Converts a yaml config file to a cookiecutter json Returns: A dictionary holding the configuration info. """ with open(config_...
7b228adc90bbab32e1c0f1871b68ee5986b816bd
626,738
def instance_dist(novel, word): """ Takes in a particular word, returns a list of distances between each instance of that word in the novel. >>> from gender_novels import novel >>> summary = "Hester was her convicted of adultery. " >>> summary += "which made her very sad, and then her Arthur was als...
bcc6f92754567fdfeee7e7005857919c5e62bc2e
626,739
def define_constants_for_fixed_srht_with_momentum(n, d, m): """ As defined in Jonathan Lacotte, Mert Pilanci, Optimal Randomized First-Order Methods for Least-Squares Problems (https://arxiv.org/abs/2002.09488) Args: n: Number of rows of data matrix d: Number of columns of data matrix ...
984192fb26a475900c08e9beab26a8661290ed2b
626,741
def _get_action_profile(x, indptr): """ Obtain a tuple of mixed actions from a flattened action profile. Parameters ---------- x : array_like(float, ndim=1) Array of flattened mixed action profile of length equal to n_0 + ... + n_N-1, where `out[indptr[i]:indptr[i+1]]` contains play...
ffeb0a38f07d16079723beddf73ce090135af43c
626,742
from dateutil import tz def _localize(time): """private method for relocalizing This is a bit of a hack and only works for things in our local time zone""" aware = time.replace(tzinfo = tz.tzutc()) return aware.astimezone(tz.tzlocal())
8ee699068e4c80bea64124053ff2d6cc0a75408c
626,743
def fromSI(value: str) -> float: """converts from SI unit values to metric Args: value (str): a value in SI units, e.g. 1.3u Returns: float: the value in metric units. """ return float(value.replace("u", "e-6"))
1b63ec8453deace7583d9919519de4feda44e0dd
626,744
def _get_jsonld_property(jsonld, property, default=None): """Return property value from expanded JSON-LD data.""" value = jsonld.get(property) if not value: return default if isinstance(value, list) and len(value) == 1 and isinstance(value[0], dict) and "@value" in value[0]: value = valu...
5cda221bc065b53411f460ab226d99200c68a148
626,746
def dfa_word_acceptance(dfa: dict, word: list) -> bool: """ Checks if a given **word** is accepted by a DFA, returning True/false. The word w is accepted by a DFA if DFA has an accepting run on w. Since A is deterministic, :math:`w ∈ L(A)` if and only if :math:`ρ(s_0 , w) ∈ F` . :param dict df...
fdc85a810d79c715c6fbeffc65248495ea551ffb
626,747
def avseth_gassmann(ksat1, kf1, kf2, kmin, phi): """ Applies the Gassmann equation. Args: ksat1 (float): Ksat1. kf1 (float): Kfluid1. kf2 (float): Kfluid2. kmin (float): Kmineral. phi (float): Porosity. Returns: float: Ksat2. """ s = ksat1 / (km...
738f2c91517b5a225c5d397c2b983f96cedb6a7c
626,748
import re def snakify(name: str, *, sep: str = '_', _re_upper=re.compile(r'([A-Z])')) -> str: """Lowercase ``name`` adding ``sep`` before in-word-uppercase letters. >>> snakify('CamelCase') 'camel_case' """ return (name[:1] + _re_upper.sub(rf'{sep}\1', name[1:])).lower()
72adb24ad471e89828c1170a3afb3f649fb4288f
626,749
def cap_length(tweet): """ Shortens the tweet to 140 characters. """ if len(tweet) >= 140: return tweet[0:139]+'…' else: return tweet
980e36bbf95a1a7aea07e6d93ed2a645247cf07e
626,750
def model_values(model): """Get the values out of a Z3 model. """ return { d.name(): model[d] for d in model.decls() }
7a4d70e73d34e670c47b8a16d024165746b14e8f
626,752
def add_suffix(string,suffix): """if suffix, appends suffix to string with underscore. otherwise return it unchanged.""" if suffix is None: return string else: return "{}_{}".format(string, suffix)
d0c1818f4c2b987c378ed81ac0539d75926894f3
626,753
import torch def _collate_fn(batch): """ Custom collate function to manually specify how samples are batched from the DataLoader. See https://pytorch.org/tutorials/beginner/data_loading_tutorial.html#iterating-through-the-dataset for an introduction. In particular, the batch represents a collection of ...
1364fb58d4963b42821c72e49d8790ada8babf7e
626,754
def findTerm(ont,name): """ Searches an ontology for a specific term name and returns the first hit Args: ont (pronto Ontology): Ontology to search name (str): Search query Returns: pronto Ontology: Term that matched name or None if not found """ for term in ont: if term.name == name: return term re...
7cbf24cfb111cca31d89381d932df5dd4d0ce1d1
626,755
from typing import Union from pathlib import Path def find_file(path="~", file="LabRecorderCLI.exe") -> Union[Path, None]: """find a file recursively args ---- path:str the root folder file:str the file name returns ------- filepath: Union[Path, None] ...
73f8ef7ca9ba74ea688f98cb46ef33093c39c5dd
626,756
def radixsort(lst): """Integer only""" finished = False low_order = 1 while not finished: buckets = [[] for _ in range(10)] for elem in lst: digit = (elem // low_order) % 10 buckets[digit].append(elem) j = 0 finished = True for i in range...
08ff638af84d1a379bac29a973a62e7035525c16
626,758
async def check_shutter_closed(command, spectro: str): """Check the open/closed status of the shutter""" shutter_status_cmd = await command.actor.send_command( "lvmieb", f"shutter status {spectro}" ) await shutter_status_cmd if shutter_status_cmd.status.did_fail: return "Failed to r...
a205da275b61a709ce5ee7da5ad03ac287583375
626,759
def make_strategy_id(strategy): """ Return a string that will identify a strategy - just concatenate the numbers of transfers per gameweek. """ strat_id = ",".join([str(nt) for nt in strategy[0].values()]) return strat_id
50dea9aa8724a974ba22790e191c88d9eb6e0bae
626,760
def dm_fibonancci(n): """ The following function determines the Fibonacci Sequence using a Recursive Function. Finding the dm_Fibonacci sequence with seeds of 1, 1, 2 for n = 0, 1, 2 respectively. The sequence is 0,1,1,2,3,5,8,13,..., where the recursive relation is dm_fibonancci(n) = dm_fibonancci(n-1) + 2* dm...
cf52f503fbf6763ce8cd8b597fb8e986674291f8
626,761
def parse_grep_out(segment): """ Parse the grep output segment, get the file name, starting line number and codes. """ # The difficulty is that grep use different format for matching lines and context lines. # for example: # # /home/zhenlei/projects/pydocx/pydocx/export/html.py-231- ...
5a28d3678c0c66ace81914ea4cf8219b1c8a5067
626,762
import torch def focal_loss(input, target, reduction='mean', beta=0.5, gamma=2., eps=1e-7, **kwargs): """ Focal loss, see arXiv:1708.02002 input: [B, 1, H, W] tensor that contains predictions to compare target: [B, 1, H,...
d698fffeb252ae8c2f4a43a45094ac75532f3ce2
626,763
def driver(): """ Make sure this driver returns the result. :return: result - Result of computation. Example ______ _n = int(input()) arr = [] for _ in range(_n): arr.append(int(input())) result = solve(arr) """ result = "This is a template!" print(result) ...
791c06d62659d9eb12a2f92c70ca7543fa53e9de
626,764
import argparse def _parse_args() -> argparse.Namespace: """Parses arguments.""" parser = argparse.ArgumentParser( description='Analyze a list of images that failed to download or crop.') parser.add_argument( 'failed_images', metavar='URL_OR_PATH', help='URL or path to text or JSON...
dc0d4d8955d8ec7a764cbded19b7db12a2e2f70e
626,765
import shutil from pathlib import Path import os def executable_not_executable(monkeypatch): """ Mocks an executable path that does not point to an executable file, but does point to a file. """ def mock_which(*args, **kwargs): """Mock an absolute file path.""" return args[0] ...
849c87108281ed1241d0b292b205a2af76e35d43
626,766
def reorder(class_list): """Reorder the class list based on the location of its refs and deps.""" # build list of all class names defined in file all_class_names = [] for c in class_list: all_class_names.append(c.name) # find direct references for each class in list for n, c in enumerat...
28eac76dd9a80b5bcbd78259749e9c158e35a9e8
626,767
import torch def evaluate(model, iterator, criterion, device): """Evaluate model and calculate mean loss""" model.eval() losses = [] with torch.no_grad(): for _, (source, target) in enumerate(iterator): source, target = source.to(device), target.to(device) outpu...
2d5b821a631bc7b98a991dbb280382129b2c6563
626,768
import os def path(path=""): """ Will return the specified path joined with os.getcwd(). """ return os.path.join(os.getcwd(), path)
cc827caa4ee655d554ac80ee8749dcd46b4bccca
626,769
import torch def create_xyz_tensor(sl): """ Return an 32 x 32 x 32 x 3 tensor where each len 3 inner tensor is the xyz coordinates of that position """ incr_t = torch.arange(sl, dtype=torch.float64) z = incr_t.expand(sl, sl, sl).unsqueeze(3) y = incr_t.unsqueeze(1).expand(sl, sl, sl).unsqu...
f410c0cfa1fd121373ec43235e7a6700bec3ac08
626,770
def add(x, y): """ Adds two floats. :type x: float :param x: first summand :type y: float :param y: second summand :rtype: float """ return x + y
c37377bf2f7a9b163c46a85552b491ed0d09b568
626,771
import os def in_untracked(labbook_root: str, section: str) -> bool: """ Query whether the given section for a labbook root dir is tracked in Git. Args: labbook_root: Root directory of labbook section: Section to check if tracked or not Returns: True if the given section is unt...
87f0c045e7a09a9774aff28ddc9553a534d46b65
626,772
def _build_rtw88_config(rtw88_config): """Builds the wifi configuration for the rtw88 driver. Args: rtw88_config: Rtw88Config config. Returns: wifi configuration for the rtw88 driver. """ result = {} def power_chain(power): return { 'limit-2g': power.limit_2g, 'limit-5g-1': po...
10836cbe85003c5b51d5deffbf1cb862525ed67e
626,773
def parse_quality_list(formats, quality): """ Parse the user-given list of qualities they are willing to accept for download :param formats: :param quality: """ selected_qualities = [] quality = quality.lower().strip() selected_quarities = quality.split("/") for q in selected_quari...
2572e2bfb9a1a3ed95f6cdbc870811f6824bf3e9
626,774
def find_header_row(sheet, first_column_value, max_row_range=10, max_col_range=10): """ Procedura poszukuje wiersza nagłówkowego. :param sheet: :class:`xlrd.sheet.Sheet` :param first_column_value: pierwsza poszukiwana wartość :type first_column_value: str :param max_row_range: maksymalny zakres...
425111183900cf154159b63e1d25dd89a83c2259
626,775
import re def get_process_id_and_name(header): """Get process id from header.""" m_process_num = re.match(r'(.*)[(]\s*(\d+)[)]', header) if not m_process_num: return None return int(m_process_num.group(2)), m_process_num.group(1).strip()
2d7412de3865e1a36ea1ff013193a5f2951fc7ab
626,776
def get_n_control_ts(model): """Get number of timesteps in the model's control variable""" return len(model.wells.event_dates)
24b7a3d5ec3b18b4f9025629889a1a3b2ab33492
626,777
import time def get_timestamp(timeStamp): """ :param timeStamp: 时间戳(秒) :return: 根据时间戳获取该天的开始和结束时间戳 """ timeStamp = timeStamp timeArray = time.localtime(timeStamp) otherStyleTime = time.strftime("%Y-%m-%d", timeArray) timeArray = time.strptime(otherStyleTime, "%Y-%m-%d") timeStamp =...
e633adeeb11c828e2be24df53ce5050697437b9f
626,778
def allow(whitelist): """ Decorates a handler to filter all except a whitelist of commands The decorated handler will only be called if message.command is in the whitelist: @allow(['A', 'B']) def handle_only_a_and_b(client, message): pass Single-item whitelists may be ...
c193dddb1a530132d69a8b7d378751430aec0198
626,779
def compss_wait_on_directory(*directory_name): # noqa # type: (*str) -> None """ Dummy compss_wait_on_directory. Does nothing. :param directory_name: Directory/ies name. :return: None """ return None
91962ff2500f375aacd71843a6f12fbf63cfc842
626,781
import re def split_return_line(line): """ Split the return line with format `type: some doc`. Type may contain colons in the form of :obj: or :class:. """ splits_on_colon = line.split(":") idx = 1 while idx < len(splits_on_colon) and splits_on_colon[idx] in ["obj", "class"]: idx += 2 ...
0131e0a719da5c634a347590f3f089382dc46711
626,782
import argparse def get_parser(): """Gets the argument parser""" parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--arm-sysroot', default='/build/arm-generic', help='ARM sysroot directory (default=%(default)s)') parser.add_argument('--aarch...
24cea55c15a1f0b9a96b7fdd0ac5c55553a4c2c1
626,783
def check_tic_tac_toe(): """ This challenge is to take a list of lists that represents a tic-tac-toe board and check who has won the game. """ def check_winner(board): def player_check(player): if player == 0: return "It's a tie" return f"Player {play...
622e5847bf08b40f2ff97003f8e81bdafd793b62
626,784
def stats_file_values(pop_size, gene_number, generation_number, diversity, viability_ratios, viability_ratios_db): """Return a dict usable with csv.DictWriter for stats file""" values = { 'popsize': pop_size, 'genenumber': gene_number, 'generationnumber':generation_number, ...
fa945943fba8368e2ba775eaa629880bf32d483f
626,785
def compress_indices(indices, size): """Return compressed indices. The function is used for compressing COO row indices to CSR compressed representation. The input indices must be sorted. """ nse = len(indices) compressed = [0] * (size + 1) k = 1 last_index = 0 for i in range(nse):...
b6a0b703b5e7fc56e1b190f491e4fd2443dc4668
626,786
def selection_sort_counting(A): """ Instrumented Selection Sort to return #swaps, #compares. """ N = len(A) num_swap = num_compare = 0 for i in range(N - 1): min_index = i for j in range(i + 1, N): num_compare += 1 if A[j] < A[min_index]: m...
783aa83086c38deefd503ddd6767bd759e298721
626,787
def set_per_bc(elements, n, cross_sec, n_in_cross, nel_cross_section): """ Set periodic boundary conditions at front and back sides and their corresponding connected elements and faces. elements : list of elements n : current element number cross_sec : ...
44435e6cf5e4fc96dbef511d2e0ee28783b56289
626,788
def to_fahrenheit(temp): """ Converts a temperature in celsius to fahrenheit. """ return (temp * 1.8) + 32
11e06263f472e79096656373cf190fc86ac1acf9
626,789
import pkg_resources def resource_filename(modulename, resource, basefilename=None): """Locate and return a resource filename. >>> f = resource_filename( __name__, 'somedatafile', __file__) """ return pkg_resources.resource_filename(modulename, resource)
443449d9a67d5934b984b7d8fc1764a4bf59d174
626,790
import re def regression_test_almost_match_file_names(old_fname, new_fname): """Checks whether the two file names match (if the files match up to name_i*.ext, it counts as if they match) """ if old_fname == new_fname: return True if '_i' in old_fname: if re.sub('_i[0-9]*', '', old...
00452a0929552c9ef1da802780a2ec31f61834cc
626,791
import re def correct_flag(flag: str) -> str: """ Fixup slightly misformatted flag input. """ filtered = flag.replace(" ", "").lower() match = re.search(r"[0-9a-f]{32}", filtered) if match: return "__flag__{" + match.group(0) + "}" return flag
d88a71a67e4c62c3485ed612c39ae02b4cbe2217
626,792
def site_client(client, site): """Returns a client tied to a specific site.""" client.config['default_site'] = site['id'] client.default_site = site['id'] return client
6e879a5011fb5b2ed9eb917392e3c22b20e4a6bc
626,795
def color_in_square(colors, color): """Get colors from the given pixel color count""" # There will be some noise - but it doesn't matter, we're looking for our # specific colors return color in colors
d4bfa4085bc26ade51748f7f4956a25c96bf3d14
626,796
import random def random_adjacency_matrix(n): """ Generate random sub-matrix for adjacent matrix :param n: dims of sub-matrix """ matrix = [[random.randint(0, 1) for _ in range(n)] for _ in range(n)] for i in range(n): matrix[i][i] = 0 for i in range(n): for j in range(n): ...
17b2e07237bae6b8bc623df79d690fb9b977be19
626,798
import functools def deprecate_current_app(func): """ Handle deprecation of the current_app parameter of the views. """ @functools.wraps(func) def inner(*args, **kwargs): if 'current_app' in kwargs: current_app = kwargs.pop('current_app') request = kwargs.get('reque...
c065a574dd0c178cc5aeefe36995a7f11235b17f
626,799
def time_frog_jumps(other_side_position: int, leaf_positions: list) -> int: """ Returns the earliest time that a frog can jump to the other side of the river. Uses a Set to store unique values from leaf_positions[]. When the size equals to other_side_position, means the leaves have covered all position...
39f0d52bfe821a3b46380db4b1459fbc06968a11
626,801
def rgb_to_hsb(r, g, b, a): """Simple rgb to hsb conversion. Assumes components specified in range 0.0-1.0.""" maxval = max(r, g, b) minval = min(r, g, b) if maxval == minval: h = 0.0 elif maxval == r: h = ((60 * (g - b) / (maxval - minval) + 360) % 360) / 360.0 elif maxval == g:...
89274fc6fc69138dab26ec73a007977ffc5a3066
626,802
def MI_par_helper_dic(key, value, x, function, name, indicator_string): """ helper function to parallelize edge and KSG estimator creating dictionaries that can then be united key: key of the output dictionary that holds activations value: activation for one layer and one epoch x: input or outpu...
262b8f51324b560d843755dbe039743e9c2d6b0f
626,803
def double(x: int) -> int: """ >>> double(0) 0 >>> double(2) 4 """ return x * 2
c14fbfde514a8b7fe399571ba948b9c31298f484
626,804
import inspect import sys def get(config, sms_carrier=None): """Returns the sender based on the name of the sms_carrier. Here the name of the carrier should match the name of the sender object, that is if the sender object is 'XXSender' the carrier name should be 'XX' """ sms_carrier = sms_carrier or confi...
1adbf87627e2c8a3fa39d44c614c8a9f880b8fa6
626,805
def get_fields(fields, label): """ 搜索DICT中的label 获取值""" for res_dict in fields: if res_dict['label'] == label: return res_dict['value'] return ""
c3631c8c8f44f9cf3fc875b669421043e1ebf855
626,807
from typing import Tuple def calc_pad_value(src_value: int, dst_value: int) -> Tuple[int, int]: """ Calculate a padding values for a pair of source and destination numbers. Parameters: ---------- src_value : int Source number. dst_value : int Destination num...
6231eae061c3a534f0b2fe4a313987dc3d4eed98
626,808
import shutil import sys import os def execute(executable, args): """ Run container command with execve(2). Use manually execve to run the process as same pid and avoid to fork a child. """ executable_path = shutil.which(executable) if executable_path is None: print(f"{sys.argv[0]}: {...
7214dbfd76ce55b2252a6e55a07482c3cfad76f7
626,809
import os import configparser def _parse_file(filename): """This function opens a file with the given filename and creates a dictonary of all parameters in the file. The keys of the dictionary are the parameter names. Sections are completely ignored and have no effect on the returned dict.""" if not os.path.is...
13ce04c302976a643730ec5b69b029da3c1b3daa
626,810
import configparser def tox_ini(): """Parse tox.ini file.""" ini_parser = configparser.ConfigParser() ini_parser.read("tox.ini") return ini_parser
2764232850fd25c2fe863866b6ab67b84fd1db99
626,811
from typing import Dict def base_user() -> Dict[str, str]: """A user that is not in the database""" return { "email": "anewemail@domain.com", "password": "avalidpassword_99!" }
7393bb7e46cb9eef12f93ec4b428c4b318902bee
626,814
import re def parse_line(line): """ parse model.js line-by-line using voodoo-regexp: '{title: "Bungeejumper", url: "modellen/Bungeejumper.xml"},\n' => ["Bungeejumper", "modellen/Bungeejumper.xml"] [\"|'] --> match " or ' (.[^'|\"]*) --> group: match anything except " or ' [\"|'] ...
b28ca8d4c9622c54d11970b6c407b8d07f37b8ec
626,815
async def readyz(): """ Readyz endpoint. """ return {"status": "ready"}
7f089fc63ee74ce8eec872d80eeb5129fc267272
626,816
def IoU(boxA, boxB): """ Computes the Intersection over Union (IoU) metric, given two bounding boxes. Input: "boxA": bounding box A "boxB": bounding box B Output: "score": IoU score """ # Compute the intersection points of the two BBs xLeft = max(boxA[0], boxB[0]) yLeft ...
b3e026dc40f329e2013102127e0cddcb5832b697
626,817
def requires_secret(request_handler): """request must have your app's mobile_secret in params to continue""" def decorated(): raise NotImplementedError() if 'mobile_secret' in request.params and request.params['mobile_secret'] == _config['mobile_secret']: request_handler() e...
2d8e78f619b21d1696013a36fda9d5e0377a0651
626,818
def is_transition(allele1, allele2): """Is the pair of single bp alleles a transition? Args: allele1: A string of the first allele, must be 1 bp in length. allele2: A string of the second allele, must be 1 bp in length. Returns: True if allele1/allele2 are a transition SNP. Raises: ValueError...
0fe36568156029fef42808e78f8bec8fcb116b7e
626,819
def update_identifiers_dict(formula_identifiers,formula_unit_dimension,identifier_unit_dimensions): """Update identifiers dict with units.""" updated_formula_identifiers = [] unit_dimensions = [formula_unit_dimension] unit_dimensions.extend(identifier_unit_dimensions) identifier_index = 0 for i...
0acddc444539035512102df14a131917e56a85a1
626,820
def edges_to_adjacency_matrix(mesh): """ compute the adjacency matrix of a mesh adja(i,j) = 2 if the edge (i,j) is in two faces adja(i,j) = 1 means that i and j are on the boundary of the mesh adja(i,j) = 0 elsewhere :param mesh: :return: """ return mesh.edges_sparse.astype('int8')
e505b69834c2e526aa0ee41f56208806836f568d
626,821
import sys def _reload(mod, _larch=None, **kws): """reload a module, either larch or python""" if _larch is None: raise Warning("cannot reload module '%s' -- larch broken?" % mod) modname = None if mod in _larch.symtable._sys.modules.values(): for k, v in _larch.symtable._sys.modules....
20349d2dc86c366b1b6d68b565bab74a79b86674
626,822
import math def _normalize( vec, ): """Return a normalized version of vec""" return vec / math.sqrt(sum(vec ** 2))
152667b617d964aa1f29d2a3d62e9bcbaabf587d
626,823
def example_choices(field, arg=3): """ Returns a number (default: 3) of example choices for a ChoiceFiled (useful for CSV import forms). """ examples = [] if hasattr(field, 'queryset'): choices = [(obj.pk, getattr(obj, field.to_field_name)) for obj in field.queryset[:arg + 1]] else: ...
5206254abc339b8941596ccb29538cd4fcc1e8a1
626,824
def f1(x): """ A simple quadratic function. """ y = x**2 - 3.*x + 5. return y
fa29c665b314ae2731cd395148ee3dffc3423572
626,826
def arithmetic_sum_n(a_1, d, n): """Calculate the sum of an arithmetic series. Parameters: a_1 The first element of the series d The difference between elements n The number of elements in the series to sum Return: The sum of n numbers in the arithmetic seri...
3a391886a0ecab60b35632c1bf429131d3f08373
626,827
def apply_text_replacements(path, text, text_replacements): """ If path appears in text_replacements, replace each old value with new value in order. """ if path in text_replacements: for old_val, new_val in text_replacements[path]: text = text.replace(old_val, new_val) retur...
1618f8ea395bd930c448e2ce6524762d1df1f111
626,828