content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def _worker(data_type): """ Worker to grab data from certain data type for a specific query :param data_type: The desired data type :return: A helper function able to process a query for that specific data type """ def _helper(data_query): st = data_query.start_date end = data_...
cf2846a1e672b88d00c90836cd99fdc584e02c17
677,781
import argparse def parse(): """Parse command line""" parser = argparse.ArgumentParser() parser.add_argument('-b', '--brokers', default='kafka:9092', help='Kafka bootstrap brokers') parser.add_argument('-t', '--topic', default='test-topic', help='Name of topic to consume from') return parser.par...
e478009948846c259d6f6f27199653947fe0ffde
677,782
def follow_course(course): """Both parts can be done in one pass because aim in part 2 is just depth from part 1.""" horizontal_position = 0 depth = 0 aim = 0 for direction, n in course: if direction == "forward": horizontal_position += n depth += aim * n elif...
5300dcd1d0502b432aefc1a600fae9b51a7c6a78
677,783
from typing import List def connect( graph: List[List[int]], next_ver: int, current_ind: int, path: List[int] ) -> bool: """ Memeriksa apakah mungkin untuk menambahkan berikutnya ke jalur dengan memvalidasi 2 pernyataan 1. Harus ada jalan antara titik saat ini dan berikutnya 2. Vertex berikutn...
7b80205496c99ea86b2f83fd7efa6be81eb2784e
677,785
def A006577(n: int) -> int: """Give the number of halving and tripling steps to reach 1 in '3x+1' problem.""" if n == 1: return 0 x = 0 while True: if n % 2 == 0: n //= 2 else: n = 3 * n + 1 x += 1 if n < 2: break return x
4b09a759293493bf3088e0e28601a20c0dfd0f52
677,786
def _search_max_idx(lst, upper, start_idx=0): """ returns index of the largest element of all smaller than upper in lst; scans from start_idx note that lst has to be a list of elements monotonously increasing """ idx = start_idx while len(lst) > idx and lst[idx] <= upper: idx += 1 re...
431a89bbd9d0f006327bb9dc2b3031d214e146ee
677,787
def addr_alignment(addr): """Compute the maximum alignment of a specified address, up to 4.""" return addr & 1 or addr & 2 or 4
407c937e97807fa6a4f4c3ad7f966145606de15c
677,788
import logging def check_alarm_url_request(url_request): """ """ if not url_request: return url_request if len(url_request) != 16: logging.warning("URL REQUEST FAILURE: Url manually edited") return False if url_request[4] != "-" or url_request[7] != "-": logging....
61ca12e9c3feb442baa9466fbf5ba8ac804a6e14
677,789
def get_entry_ids(entry): """Creates a trakt ids dict from id fields on an entry. Prefers already populated info over lazy lookups.""" ids = {} for lazy in [False, True]: if entry.get('trakt_movie_id', eval_lazy=lazy): ids['trakt'] = entry['trakt_movie_id'] elif entry.get('trakt_...
a86116cdb84154ae80938f854ccc049be5c928f2
677,790
def add(number_x: int, number_y: int): """Adds two numbers.""" return number_x + number_y
70a8f017e84fa1d49afdbc793f34f3b61d63a64a
677,791
def get_instances_for_service(service_id: str, client) -> list: """ Returns list of registered instance for service with id <service_id>""" return client.list_instances(ServiceId=service_id).get('Instances', [])
7e19bd2c85a51671eebb7e31a211f453c2bf2823
677,792
def check_insertion_order(metadict_inst, expected): """ Ensure that the keys of `metadict_inst` are in the same order as the keys in `expected`. The keys case is ignored. """ def normalise_keys(lst_pairs): return [key.lower() for key, _ in lst_pairs] assert normalise_keys(metadict_...
a6ec3e30b2c743ae8c03441884325a8c1d22346b
677,793
from typing import List def up_to_and_including(l: List, matcher) -> List: """ Cut the list after the first matching element. """ def generate(): for element in l: yield element if matcher(element): break return list(generate())
175cbdb0f6df8b2998460da5b1f09780b06d1d44
677,794
def diagonal(matrix, reverse=False): """ Return matrix' diagonal (count from the the back if reverse = True). """ diag = 0 if not reverse: for i in range(len(matrix)): diag += matrix[i][i] else: for i in range(len(matrix)): diag += matrix[i][(len(matrix) - 1) - i]...
c67f8a3698e82a15dba2316891a0783d72a279e0
677,795
def hello(): """ Returns a Hello World ! """ return ("Hello from Simple Python Package")
e826fc31a8f25b15a4fe3e5a0c251c1de17e16ef
677,796
def flatten_whois(whois_record): """ Flattens a whois record result Args: whois_record (dict): A WHOIS record Returns: dict: A flattened WHOIS result """ flat_whois = dict() flat_whois["domainName"] = whois_record["domainName"] if "createdDate" in whois_record: f...
de5c1f480646bcbfc7e409b995c18baaadbe0ef3
677,797
def rel_id_list(rel_list): """Return a list of already added datasets with relationships""" rel_ids = [] for i in range(0, len(rel_list)): rel_id = rel_list[i]["id"] rel_ids.append(rel_id) return rel_ids
b081b9ae276e5cf40b602bdb02d1afda97971ffe
677,798
def _is_closed_by_author(pr): """If the author closed the PR themselves we ignore it.""" if not pr['author']: return False if pr['state'] != 'CLOSED': return False timeline = pr.get('timelineItems') if not timeline: return False open_login = pr['author'].get('login') ...
3001728cb8a62b14df38a62edc6d2c4df5f3aab7
677,799
import os def _find_file_in_paths(paths, exe_basename): """Returns the full exe path for the first path match. @params paths the list of directories to search for the exe_basename executable @params exe_basename the name of the file for which to search. e.g. "swig" or "swig.exe". @return the...
1210c0ea0148cef872564e4319c2446b9d044b59
677,800
def rc_prescription_from_pm_and_imc(efl, f_pm, pm_vertex_to_focus): """Design a Ritchey-Chrétien telescope from information about its primary mirror. Parameters ---------- efl : float system effective focal length f_pm : float focal length of the primary mirror (should be negative) ...
3f4f1b4b02a5b5d9f1105f446c51df79de02bf67
677,801
from typing import Union from pathlib import Path import csv def _preprocess_csv(file_path: Union[str, Path], delimiter: str): """Validates a CSV file and returns the data as a list of lists""" if isinstance(file_path, str): file_path = Path(file_path) if not file_path.exists(): raise Val...
fe06f35872ae2e139d3fdef5ad6b5d1345c54e5b
677,802
def remove_comment(line): """ 与えられた文字列の"::"以降(右)を除去する Args: line: コメントを取り除きたい文字列 Return: 先頭がコメントだった場合(コメントのみの行だった場合): 空文字 それ以外: コメント部分を取り除いた文字列 """ return "" if line.index("::") == 0 else line.split("::")[0]
36e2e86b25e5c35162eeb6ac1e4bcb3ada7faa68
677,803
def optimize_highlight(lst): """Optimize a highlight list (s1, n1), ... by combining parts that have the same color. """ if len(lst) == 0: return lst else: prev = lst[0] new_lst = [] for s, n in lst[1:]: if s.strip() == "" or prev[1] == n: ...
9c31e22ebd69799b96596bbf624be77f3c25b48b
677,804
import random def filter_suite(arr, b): """ A set of tests for the filter operator Parameters ---------- arr: `ndarray` A 3D ndarray used in the construction of `b` (used to check results) b: `BoltArray` The BoltArray to be used for testing """ random.seed(42) # ...
b49fc3bfa1409b6e995c3895e6f77872f1067113
677,805
from typing import Tuple def umbalanced(training: Tuple, testing: Tuple)->Tuple: """Leave data as they are.""" return training, testing
3f23ee3e328b018f6656bc339e1b26080ad63448
677,806
import os def database_path() -> str: """Database file path to use.""" value = os.getenv("DATABASE_PATH") if not value: raise ValueError("DATABASE_PATH environment variable not set") return value
624101d58514bf35ca97d18f4ba7c3659d0f4c31
677,807
def _getitem_from_frame(f_locals, key, default=None): """ f_locals is not guaranteed to have .get(), but it will always support __getitem__. Even if it doesnt, we return ``default``. """ try: return f_locals[key] except Exception: return default
1a6e3b55d553e9febc3bf4a28e2fd34c9fb193c5
677,809
def gen_results_summary(final_unsupported): """ Generates a results summary given the final unsupported nodes dictionary. Args: final_unsupported (UnsupportedNodeDict): The unsupported ops and corresponding errors and node index ranges. Returns: str: A summary of all th...
eb606e9f45de84e8ee5802f1f1b38d2793392f12
677,810
def get_edges(graph: dict) -> set: """ Return a set of couples that represents all of the edges. @input: graph (graph stored in an adjacency list where each vertex is represented as an integer) @example: >>> graph = {0: [1, 3], 1: [0, 3], 2: [0, 3], 3: [0, 1, 2]} >>> get_edges(graph)...
233503494ef8778affc50c99394643d518184944
677,812
import random def SampleNegativeEdges(graph, num_edges): """Samples `num_edges` edges from compliment of `graph`.""" random_negatives = set() nodes = list(graph.nodes()) while len(random_negatives) < num_edges: i1 = random.randint(0, len(nodes) - 1) i2 = random.randint(0, len(nodes) - 1) if i1 == ...
d8676927708b2fc5b7bd70948502573272766319
677,813
def split_train_test(data, test_data_size: int): """Splits data into train and test. Args: data: All data. test_data_size: Size of the `test` data. Size of the `train` will be `len(data) - test_data_size`. """ train_data = data[:-test_data_size] test_data = d...
1217d69d365ba170090a79427ebf96da6922feeb
677,814
def get_bools_of_pheno(ad, pheno): """return list of booleans""" phenotypes = ad.obs[pheno].unique() bool_list = [ad.obs[pheno] == i for i in phenotypes] return bool_list
f0772629bf929dc6b7e0fe17b8caf3620b826531
677,816
import torch def get_best_accuracy(y_true, y_pred, _): """Select threshold that maximizes accuracy""" threshs = torch.linspace(0, 1, 1001) best_perf, best_thresh = 0., 0. for thresh in threshs: perf = (torch.mean((y_pred > thresh)[y_true.type(torch.bool)].type(torch.float32))) if perf ...
71c4f42e8f2bf0979937d349d29a047f907cc8f4
677,818
def _is_dictionary(arg): """Check if argument is an dictionary (or 'object' in JS).""" return isinstance(arg, dict)
fce225835c14d56206ed88d77abf3cd09bcda5f3
677,819
def hand_rank(hand): """ Computes the rank of a hand, a number between 1 and 9, where lower numbers indicate better hands. Assumes the hand is given in ascending order of number. :param hand: a tuple with 5 tuples, each inner tuple representing a card from a standard deck. :return: the rank of the h...
77c6ea5b496cfd41fe73b8342381fa2a2d4607b7
677,820
def _weight(entry): """ Sum a power of frequency. Word frequencies have a skew with a long tail toward infrequent. """ weight = 500 * entry[0] ** 0.25 for i in range(3, len(entry), 2): weight -= (entry[i] / 100.0) ** 4 * 100 return weight
ed47a0aee91c3ef444a1805083411397b8fc7ec3
677,821
def split_nums_chars(str_: str) -> tuple[str, str]: """Splits the numbers and characters from a string Args: str_: The string to split Returns: A tuple containing the characters and the numbers """ nums = "".join([i for i in str_ if i.isnumeric()]) chars = "".join([i for i in s...
0907953184aabef7d3052af27385482ac087fb7d
677,822
def spawn_enemies(enemies, maze_choice): """ Chooses enemies in order to spawn at preset locations for each map :param enemies: A list of enemies in the field :param maze_choice: int index of which maze was chosen :return: N/A """ spawn_rooms = [[], [], []] if maze_choice == 0: s...
faad16b31b9697c28b95b27f62e9fc9d2e7484d2
677,823
def capitalize(text: str) -> str: """ Capitalize the first letter only. >>> capitalize("") '' >>> capitalize("alice") 'Alice' >>> capitalize("BOB") 'BOB' >>> capitalize("alice and bob") 'Alice and bob' """ if not text: return "" ...
cfd13ed974538f8d44b654ca087735fbae3e1c40
677,824
def filter_data(data, f, m=None): """ :type data: list[common.MimicResult] :type f: str :type m: int :rtype: list[common.MimicResult] """ res = [] for d in data: if d.f.title != f: continue if m is not None and m != d.metric: continue res.append(d) return res
7b0b3aeb8fcbd7a4ebef7550e6928c37d63fb832
677,825
import warnings import os import glob def get_tensorrt_op_path(): """Get TensorRT plugins library path.""" # Following strings of text style are from colorama package bright_style, reset_style = '\x1b[1m', '\x1b[0m' red_text, blue_text = '\x1b[31m', '\x1b[34m' white_background = '\x1b[107m' m...
9190de59ebf0239a8e50cea14e1ba311e1323f27
677,826
def TestSuiteName(test_key): """Returns the test suite name for a given TestMetadata key.""" assert test_key.kind() == 'TestMetadata' parts = test_key.id().split('/') return parts[2]
dded191605b6e3738b3e314a0b744d02995ceb85
677,827
import time def retry_ntimes(n, function, *args, **kwargs): """ Parameters ---------- n : function : *args : **kwargs : Returns ------- """ retry = 0 ret_val = None while retry < n: try: ret_val = function(*args, **kwargs) if n...
d6dbf23c474aeb7657b29d0034dea76ec9891a75
677,828
from typing import Any import pickle def deserialize(input_file: str) -> Any: """ Load data stored by ``serialize()``. :param input_file: path to file when data was stored by serialize() :return: list of objects """ with open(input_file, "rb") as f: return pickle.load(f)
18a65ea672abb54ca54e28bd09cd6b6e5ccdf6f7
677,829
def cases(request): """ 用例数据,测试方法参数入参该方法 case即可,实现同样的参数化,目前来看相较于 @pytest.mark.paramtrize 更简洁 :param request: :return: """ return request.param
4d7ca4dc990c629473a55ebeb921858e221efe11
677,830
def _make_compound_key(table, key): """Returns a list of columns from `column_key` for `table` representing potentially a compound key. The `column_key` can be a name of a single column or list of column names.""" if not isinstance(key, (list, tuple)): key = [key] return [table.columns[nam...
5f75c40f79a94bef9fca1a5a2bb2e5d5100b44e6
677,831
def get_region(regions, cluster): """ Gets the region name from the cluster ID Args: regions (dictionary): dictionary of regions where shortname is the key to the long name value. cluster (str): the OCI ID of the cluster in question. Returns a string of the region long name. """ re...
88498615c4f5a1b5a16e7be64d0aec57278889c5
677,832
import sys import subprocess def start_qrscp_cli(args): """Start the qrscp app using CLI and return the process.""" pargs = [sys.executable, "-m", "pynetdicom", "qrscp"] + [*args] return subprocess.Popen(pargs)
39d19416f5552c0d10297827089e75a43ccf943f
677,833
def convert_lanes_to_edges(lanes): """ Convert lanes (iterable) to edges (iterable). Remove lane index from the end and then remove duplicates while retaining order. Also works with single lane str. >>> lanes >>> ['1175109_0', '1175109_1', '1175109_2', '1183934_0', '1183934_1', '1183934_2']...
3e37b7847d3519dfaf8f07e5ced090151a6f6944
677,834
def load_blob(reader): """Given a reader object, such as returned by ExtBoar.get_blob(), fetches all the blocks and returns the reconstructed data. Warning: this means the whole blob will be loaded into RAM.""" return "".join(reader)
5267971fb731d3c86de93d88482633dbbaf55127
677,835
def window_landmark(region, flank_upstream=50, flank_downstream=50, ref_delta=0, landmark=0): """Define a window surrounding a landmark in a region, if the region has such a landmark, (e.g. a start codon in a transcript), accounting for splicing of the region, if the region is discontinuous Paramet...
be361c4625f4bc99612db3c3ebc3a1eb87fa70b8
677,836
def remove_prohibited_characters(prompt_preStr: str) -> str: """ Remove prohibited characters. """ prohibited_chars = ["[", "]", ">", "#", "%", "$", ":", ";", "~", "*", "."] for ch in prohibited_chars: prompt_preStr = prompt_preStr.replace(ch, "") return prompt_preStr
23c545a445ffa107b831f0b38d0505593cb1df76
677,837
def LinearSearch(l: list[int], x: int) -> bool: """ LinearSearch: Finds an element in an array by sequentially comparing each elements present. Args: l (list[int]): Input array x (int): Element to be searched. Returns: bool : _description_ ""...
255955d25a89fd94bb21588f694159be6451e007
677,839
def hex2rgb(hexstring): """ convert #RRGGBB to an (R, G, B) tuple """ hexstring = hexstring.strip() if hexstring[0] == '#': hexstring = hexstring[1:] if len(hexstring) != 6: raise ValueError("input #%s is not in #RRGGBB format" % hexstring) r, g, b = hexstring[:2], hexstring[2:4], hexstring[...
3850a65cc0a8fdcd3239d564e0b2578a412f9285
677,840
import sys import hashlib def md5(s): """Return the md5 sum (as a hex string) of the given string.""" if sys.version_info[0] == 2: return hashlib.md5(s.encode('utf-8')).hexdigest() else: if isinstance(s, str): return hashlib.md5(s.encode('utf-8')).hexdigest() else: ...
adcf73b07960b0d57757e95f5efff1ce84f47268
677,841
def to_serializable(val, db = None): """Used by default.""" hash_val = val.__id_hash__() return hash_val
47aef2003287b5739db55840e53b28549da5eaaf
677,842
def error(msg, value=None) -> str: """Formats msg as the message for an argument that failed to parse.""" if value is None: return '<[{}]>'.format(msg) return '<[{} ({})]>'.format(msg, value)
f8ec6b3b0b1b9f6e1196a91da58ab2f8fc962f98
677,843
import sys def get_backend(): """Consumed by openstack common code. The backend is this module itself. :return Name of db backend. """ return sys.modules[__name__]
afbae32d6f945c6c183fbfbb3cde07221f6050b1
677,844
def find_max(node): """Find max value node""" while node and node.right: node = node.right return node
cc1b7a4fdefbc6e3d6bc7fabfb59f127b37c3c00
677,845
def throw(**kwargs): """Throw (raise) an exception. @keyword throws: An Exception to throw. @type throws: C{Exception} @keyword throws_message: Text to instantiate C{throws} with. @type throws_message: C{str} """ throws = kwargs.pop('throws', Exception) throws_message = kwargs.pop('thr...
a1d2ec0a6b9c7843ab0489736bfccf46cc4ceb98
677,846
def get_python_module_names(file_list, file_suffix='.py'): """ Return a list of module names from a filename list. """ module_names = [m[:m.rfind(file_suffix)] for m in file_list if m.endswith(file_suffix)] return module_names
fa3ed8504304363e061953fb816eabd5852851c0
677,847
def filter_export_payload(): """ Return a function to filter out items which are not computed datas from a given export payload. Arguments: payload (dict): Payload from exporter. Keyword Arguments: keep (list): List of top level item names to keep. Default only keep the...
2bd2b30b70d349c7ad1dfa9c0beb9c14f9e185eb
677,848
def strf (x): """ format time output strf = lambda x: f"{int(x//86400)}D{int((x//3600)%24):02d}:{int((x//60)%60):02d}:{int(x%60):02d}s" """ days = int(x//86400) hours = int((x//3600)%24) minutes = int((x//60)%60) seconds = int(x%60) out = f"{minutes:02d}:{seconds:02d}" if hours or da...
c9fc647d08922959727fa2029c1df80174593291
677,849
def hamming_distance(list1, list2): """calculate hamming distance between two Pandas.Series""" return sum(list1 != list2)
26122f7fffdc61b6c0e6a673640de42a0acc60e9
677,850
def _symplectic_euler_step(state, force, dt): """Compute one step of the symplectic euler approximation. Parameters ---------- state : array-like, shape=[2, dim] variables a time t force : callable dt : float time-step Returns ------- point_new : array-like, shape=[...
786eb9122823338dcf875a87b40488a0dbce1fff
677,851
from typing import List from typing import Tuple def pack_span_idxs(span_locs: List[List[List[Tuple[int, int]]]]): """ packing of span indices :param span_locs: C * P * L * 2 :return: """ all_span_locs = sum(sum(span_locs, []), []) # CPL * 2 loc_tracks = [] for cidx, c in enumerate(sp...
0fdb11fac351d38131a11f8d67de3a88e5bbaea4
677,852
def early_stop(patience, max_factor, vae_loss_val, em_loss_val): """ Manual implementation of https://keras.io/api/callbacks/early_stopping/. :param patience: max number of epochs loss has not decreased :param max_factor: max_factor * current loss is the max acceptable loss :param vae_loss_val: list...
766dd335a2129a39957972e3f2c92c6650360880
677,853
def combinations(n, k): """ Given two integers n and k, return all possible combinations of k numbers out of 1 2 3 ... n. n = 4 k = 2 [ [1,2], [1,3], [1,4], [2,3], [2,4], [3,4], ] """ def find_c...
4f1b7944257b7609ab230f24c270d50d343f7020
677,854
def clean_col_strings(df,col_name,chars = '/\,:%&()-=<>.–;?‘’+~'): """removes specified characters from dataframe (df) column (col_name) Some characters were found to cause issues with folium""" df[col_name]=df[col_name].astype(str) for i in range(len(chars)): df[col_name] = df[col_name].a...
162bc080356dedf652154ba8006db558acf5c9ab
677,855
def source_num_of_longest_river(arr): """ This function will return the source number of the longuest channel by counting the number of occurence of each sources number. It may be an issue if your channel have similar size, I will create a fancier function that calculate the actual lenght of each channel if...
2fc335a296e03281866cea7a36440420e993625c
677,856
def start_basic_html(site_title: str): """ :param site_title: string to be the title of the HTML page, the default is eqaul to no page name :return: string containing HTML content to start a basic site """ if not isinstance(site_title, str): raise TypeError("input must be a string") htm...
97bccb7a5df341803d747d698181a210f25269f0
677,857
import re def humansort(l): """Sort in place a given list the way humans expect. NB: input list is modified E.g. ['file11', 'file1'] -> ['file1', 'file11'] """ def alphanum_key(s): # Turn a string into a list of string and number chunks. # e.g. "z23a" -> ["z", 23, "a"] d...
a3ef9cddc0d4db3814d3f50dcb6c662a6404edcb
677,858
import re def _hack_error_message_fix(message): """ :param message: message to fix by removing u'...' :type message: str :returns: the cleaned up message :rtype: str """ # This regular expression matches the character 'u' followed by the # single-quote character, all optionally preced...
d200ec0e8ee841539d19b12ebbc54127be871e44
677,859
import random def split_data(data, prob): """split data into fractions [prob, 1- prob]""" results = [], [] for row in data: results[0 if random.random() < prob else 1].append(row) return results
146d7d91631502d1c92a194f619056a0f63e8104
677,861
import numpy def euclidean_distance(a,b): """ Calculate the euclidean distance between two vectors. """ a = numpy.array(list(a), dtype=int) b = numpy.array(list(b), dtype=int) return numpy.linalg.norm(a-b)
43fe1e93c12db238d775d41d23e9d6047bf38d04
677,862
import logging def get_config(network, data_shape, **kwargs): """Configuration factory for various networks Parameters ---------- network : str base network name, such as vgg_reduced, inceptionv3, resnet... data_shape : int input data dimension kwargs : dict extra argu...
e3a8830aa8b0f4104277f7ad700c26bdf62075e1
677,863
import os def cwd() -> str: """Return the absolute path to the current working directory.""" return os.path.abspath(os.getcwd())
c7e287ef647b72a0c7f8246fb78de7d618ae8903
677,864
from typing import Any import numpy def is_scalar_int(x: Any) -> bool: """Check if a value is an integer""" return isinstance(x, (int, numpy.integer))
878526ab35748198e2beacab393012bc3f6297ba
677,865
import os def infer_project_name(file_or_buffer, source): """ Infers a project name based on :epkg:`yml` file. @param file_or_buffer file name @param source second output of @see fn read_content_ufs @return name The function can infer a nam...
b7dacf91c620efbb35c53f08ac7bde9302dbe790
677,866
def model_pool(request, db): """Test fixture that parametrizes model records while inserting them into the database first.""" _model = {} for model_class, data in request.param.items(): _model[model_class] = model_class(data) db.add(_model[model_class]) db.commit() return _model
609db743e370a915c6e4a5708fe0a3959956dec0
677,867
def fix_ecm_move_conflicts(conflict_ecm_list, move_order_text): """Get user input to sort out ECMs moved in both directions It is possible that with a given set of active and inactive ECMs and some sets of keywords given by the user to move ECMs in bulk from one list to the other, there wil...
e4a779789f6359dbb4604bc02c5d70ee84039bfd
677,868
import subprocess def create_anchor(anchor_name): """ Creates a new anchor as an addendum to current default pf config :param anchor_name: Name of anchor to create :return: True if anchor created success, False if failure """ CREATE_ANCHOR_COMMAND = '(cat /etc/pf.conf && echo \'dummynet-anchor...
c9a634a7312b80dd3df4cf3894fbdd08556e1d0f
677,869
import re def repair_filename(filename): """ 修复不合法的文件名 """ regex_path = re.compile(r'[\\/:*?"<>|]') regex_spaces = re.compile(r'\s+') return regex_spaces.sub(' ', regex_path.sub('', filename))
5694716c1d4e62288478e63fbda556f6014ce760
677,870
from typing import Tuple def _time(time: float) -> str: """ this function returns time as a HH:MM:SS string """ # hours, minutes, and seconds hours = time // 3600. minutes = (time - (time // 3600) * 3600.) // 60. seconds = time - hours * 3600. - minutes * 60. ...
2e5c56a7bc3b91e8accdc36c40680d724f067b9e
677,871
def extract_value_other_gdf(x,gdf,col_name): """ Function to extract value from column from other GeoDataFrame Arguments: *x* : row of main GeoDataFrame. *gdf* : geopandas GeoDataFrame from which we want to extract values. *col_name* : the column name from whic...
2af4e2ebacf50d7c35203ee365d51806aba2a2e9
677,872
import imp def import_module(name, path=None): """Import test modules and config files""" try: f, fn, d = imp.find_module(name) mod = imp.load_module(name, f, fn, d) return mod except ImportError: print ('Unable to import %s from %s' %(name, path))
9f437b4eb5f4c9b49e678391a393cdaf653b24c7
677,873
import random def DidYouWin(prizeIn: int, yourChoice: int, switch: bool): """ Returns: 1 if you win the game Returns: 0 if you lose the game """ # list of all doors ALL = list(range(1, 4)) # canShow contains the doors which can be shown canShow = [num for num in ALL if (num != ...
a1a74f712ed2246a75ace67417530f804ce99d26
677,874
import os def get_sandbox_path(virtualenv_path): """ Return PATH environment variable value for the sandboxed environment. This function makes sure that virtualenv/bin directory is in the path and has precedence over the global PATH values. Note: This function needs to be called from the parent ...
41cf04e32394169e81998c29dfc71116a20a8343
677,875
def get_dimensions6(o_dim, ri_dim): """ Get the orientation, real/imag, height and width dimensions for the full tensor (6 dimensions).""" # Calculate which dimension to put the real and imaginary parts and the # orientations. Also work out where the rows and columns in the original # image were ...
4d163a9ff26a8c1e7675ce9f251c5fc942fc6760
677,876
import os def GetProvisioningProfilesDir(): """Returns the location of the locally installed provisioning profiles.""" return os.path.join( os.environ['HOME'], 'Library', 'MobileDevice', 'Provisioning Profiles')
2facbbf284b77fe6637ab853685d656f06adb844
677,877
import torch def voxel_box_decode(box_encodings, anchors): """ box decode for pillar-net in lidar :param box_encodings: [N, 7] Tensor, normal boxes: x, y, z, w, l, h, r :param anchors: [N, 7] Tensor, anchors :param encode_angle_to_vector: whether encoding angle to vector :param smooth_dim: whe...
83f6c6cf1b79de144ba3b8d79c3c23ee8b24bd97
677,879
import argparse def parse_arguments(): """Parse command line arguments Returns: argument objects with flags as attributes """ parser = argparse.ArgumentParser() parser.add_argument('--config', help='Location of the configuration file', req...
53ebb70c64719530c15cd004ac60bcff8f7d71fc
677,880
import requests def status(host, workflow_id): """ Retrieves the current state for a workflow :param host: Cromwell server URL :param workflow_id: :return: """ url = '{host}/api/workflows/v1/{id}/status'.format(host=host, id=workflow_id) r = requests.get(url) r.raise_for_status() ...
2acf46c88a168d5892e29ff380056a755e9705b8
677,881
def isIsomorphic(tree1, tree2): """Checks if two rooted binary trees (of type Node) are isomorphic.""" # Both roots are empty: trees isomorphic by def if tree1 == None and tree2 == None: return True # Exactly one empty: trees can not be isomorphic elif tree1 == None or tree2 == None: ...
dd1628475d2f354caf4803b1f06dfd9457a788e9
677,882
def bboxes_to_pixels(bbox, im_width, im_height): """ Convert bounding box coordinates to pixels. (It is common that bboxes are parametrized as percentage of image size instead of pixels.) Args: bboxes (tuple): (xmin, xmax, ymin, ymax) im_width (int): image width in pixels im_heigh...
add33d059d9ba7a9b65688cd27ff0630d4debaf9
677,883
import typing import hashlib def generateAuthcode(paymentParameters: typing.Dict[str, str]) -> str: """ Generates authcode for E2 payment :param paymentParameters: :return authcode: """ authcodeString = "|".join([str(value) for value in paymentParameters.values()]) return hashlib.sha256(s...
20ad6f2b7c0fc52ed5d486505a9c294b6b2fd702
677,884
from typing import Optional from typing import Tuple from pathlib import Path def get_adress( adress_archive_root: Optional[str], corpus_name: str, variant_type: str, archive_name: str, ) -> Tuple[str, Path]: """Get the adress of a archive file and a contents directory of the corpus. Args...
ea33539532fe762a2e044e4519283c6be1c69d88
677,885
import os import json def subscribe_payload_template(): """Returns subscribe payload template loaded from json file.""" template_path = os.path.join( os.path.dirname(__file__), '..', 'templates', 'subscribe_payload_template.json') with open(template_path, 'r') as template_file: ...
c5fbf2cf045d69ddd256d52e2244b1bfc17f92e3
677,886
import hashlib def hash_file(f): """Finds the MD5 hash of a file. File must be opened in bytes mode. """ h = hashlib.md5() chunk_size = 65536 # 64 KiB for chunk in iter(lambda: f.read(chunk_size), b''): h.update(chunk) return h.hexdigest()
7c6f4660961a5bf45d38e918ee82e5c5a2bcb132
677,887
def kev2ang(energy): """ Convert energy [keV] to wavelength [Å] """ wlen = 12.398/energy return wlen
3bb0a19865199a277490f39a96516cd649cb98dd
677,888