content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import platform def select_platform(): """Selects for the cell tracking challenge measure the correct executables.""" sys_type = platform.system() if sys_type == 'Linux': return 'Linux' if sys_type == 'Windows': return 'Win' if sys_type == 'Darwin': return 'Mac' raise V...
7edfe8d98174d14cc72709af761a2b802c7cc547
683,175
def solve_normal_eqn(x, y): """Solve the normal equations to produce the value of theta_hat that minimizes MSE. Args: x (ndarray): An array of shape (samples,) that contains the input values. y (ndarray): An array of shape (samples,) that contains the corresponding measurement values to t...
0e44dee26a614066378f463d5975094a9442e99b
683,176
def rolling_score(d1, d2, alpha=0.5): """computes rolling scores, decaying the past by alpha. the past metrics are identified by the `prev` key. any keys present in the update dict that are not in the past dict are carried over.""" # figure out which dict is the previous metrics if 'prev' in d1...
1ee025f7610021cf1461935c8c901e135d13b393
683,178
def solve_3ac3eb23(x): """ Required transformation: position of non-black cells in the first row and their colors are noted. Then in each following row, alternating 2 cells and 1 cell of each of those colors are placed till the end of the grid. The 2 cells in subsequent rows are placed such that they are space...
d7cba03edc2f1328925e1719227e2a7de89e4c26
683,179
def is_bit_set(a, offset): """ Checks whether the offset bit in a is set or not. Returns bool, True if bit in position offset in a is 1 """ return a & (1 << offset) != 0
0eba6b8253ed83bc927cc6c8615225074e4b8c94
683,180
def avoid_hazards(future_head, data): """ Return True if the proposed future_head avoids the hazards, False if it means you will hit a hazard. """ result = True # Get the list of hazards hazards = data["hazards"] # If the future head is in a hazard, return False to mean you'll hit ...
2116295b6ebf2333a5177940bed6fd66c759b8ea
683,181
import copy def lay_wire(current_net, current_option, grid): """ Lay wire on grid, add it to net and change current coordinates. """ current_net.add_wire(current_option) grid.add_wire(current_option, current_net) return copy.deepcopy(current_option)
eca9735f770f24da42e40b1de2ed1aef010ef37e
683,182
import math def dimensionality_factor(dimension: int): """ Given a state dimension estimate the minimum number of points that cover the main directions. Each dimension has a canonical vector, so an heuristic to account for the possible directions between canonical vectors is to number the pairing comb...
1d087ff8512467ea8d9c97ba20bf97a9fc9e7194
683,183
def __io_addr_reg(op): """ Return the i/o port address 'A' and register Rr/Rd from a 2-byte IN or OUT opcode sequence """ AVR_IO_IN_ADDR_MASK = 0x060F # mask for 'A' address for opcode `IN Rd,A`. nb non-contiguous addr_part = op & AVR_IO_IN_ADDR_MASK addr = ((addr_part >> 5) & 0x0030) | (addr_p...
b9e9ed0f2c426cc0f6a0fa37b30371228e81d445
683,184
def ship_size(bf, position): """ :param bf: 2D list representation of a battlefield: list(list) :param position: Coordinates of a position on a battlefield: tuple :return: length of ship, part of which is on that position: int """ x, y = position[0], position[1] up, down, left, right = 0, 0,...
b33242b458ca04d0462293c6045d19b4afd117b2
683,185
import argparse def argument_parser(): """Arguments that may be used when starting the app from command prompt""" parser = argparse.ArgumentParser() parser.add_argument('-src', '--source', dest='video_source', type=int, default=0, help='Device index of the camera.') parser.add_...
b83e19095c44599d5694cf1340dda11ce370d11f
683,187
import random import string def random_four(): """Returns a random 4 charactors""" return ''.join(random.choices(string.ascii_uppercase + string.digits, k=4))
6c4d5ab446f0b201cdcf28eceff8b526d104bf59
683,188
import string def remove_punctuation(text: str) -> str: """ Removes punctuation from text :param text: The string being searched and replaced on :return: Text without the punctuation characters """ punctuation = string.punctuation + '¿¡' table = str.maketrans('', '', punctuation) words = t...
7b1ce1e4bc54b1a18f443aeda9346ea9e6ac84e2
683,189
def identify_quantity(row, key=''): """Identify the quantity if present in a given string.""" return row[key]
cef0a72943a447f28ebb4317e53aedc972ca4297
683,190
def newton_exact( f, fprime, x0: float, parms: tuple[float, float], maxit: int, tol: float, verbose: bool = False ) -> tuple[float, int, bool]: """ 1D Newton solver, tweaked for dipole coordinate conversion problem, parms arg corresponds to fixed (vs. iterations) function parameters """ derivto...
1362a69dedb50dd7e8096ce2ac132ac3e43b95d0
683,191
import crypt def generate_mosquitto_user_line(username, password): """Generates a line for a mosquitto user with a crypt hashed password :username: username to use :password: password that will be hashed (SHA512) :returns: a line as expected by mosquitto """ password_hash = crypt.crypt(passw...
7b9b3b52306233b91e20665f62a7d203b543b90f
683,192
import torch def make_cuda(model): """Use CUDA if available.""" if torch.cuda.is_available(): model = model.cuda() return model
d2c5a55acd3d3adedb2bbdc60dbb5594bb5a0a81
683,193
def isPower2(num): """ Check if num is power of two """ return ((num & (num - 1)) == 0) and num > 0
46160f29e78252f3e2e195d97c23d2b647450de5
683,195
def nut_params() -> dict: """ Change host and port to real IP of your UPS before run test. :return: """ return {"host": "127.0.0.1", "port": 3493}
d9ab26cc1abf71533af3a2c55817af16922e3d59
683,196
def is_indexable_but_not_string(obj): """Return True if ``obj`` is indexable but isn't a string.""" return not hasattr(obj, "strip") and hasattr(obj, "__getitem__")
40c35dd3f800a0b7f7ccee8f1164426626a48e00
683,197
def convert_to_one_hot_labels(input_, target): """Convert labels to one-hot encoding Function taken from the course prologue """ tmp = input_.new(target.size(0), max(0, target.max()) + 1).fill_(0) tmp.scatter_(1, target.view(-1, 1), 1.0) return tmp.long()
e114d7f22033c2da9a68cb52fb79a3de9632334c
683,198
import numpy def lazy_matrix_mul(m_a, m_b): """multiplies 2 matrices""" return (numpy.matmul(m_a, m_b))
b54f69eb3dc2008a1810e44892eb3a019cff04c1
683,199
import os def is_python_script(path): """Check whether path points to a file ending with .py extension.""" return os.path.splitext(path)[1] == ".py"
093703adf08a0aa27178bbd4c6c99a173b446fe7
683,200
def shares_memory(a, b, max_work=None): """ shares_memory(a, b, max_work=None) Determine if two arrays share memory. .. warning:: This function can be exponentially slow for some inputs, unless `max_work` is set to a finite number or ``MAY_SHARE_BOUNDS``. If in doubt, use `numpy....
6257ff21bcd2d67ebcd473741d796f5528a995dc
683,201
def _key_for_segment(segment, topic_words): """A segment may have a single number of an iterable of them.""" segment_key = tuple(segment) if hasattr(segment, '__iter__') else segment return segment_key, topic_words
32ba494317648c7828657c295a3cab0d167c1897
683,202
def multiply(value, arg): """multiplies value and arg""" return int(value) * int(arg)
6613dc8c3a36155bb6a1037ee358f50fed13aeaf
683,203
def _process_keys(left, right): """ Helper function to compose cycler keys Parameters ---------- left, right : Cycler or None The cyclers to be composed Returns ------- keys : set The keys in the composition of the two cyclers """ l_key = left.keys if left is not...
684f93fe9f18e0a91de3f1293f9a8a98ec71191f
683,205
def delete(delete_query): """ Create delete function @param delete_query the query for the new delete function """ def delete_clojure(store, obj): """ Delete an event from the store @param store the database store @param obj the event that will be deleted ""...
d48ecdefc4c0c2e2dcd511319bd665c1f94782ad
683,206
import platform import os def get_hosts_path(): """ Function to get hosts file path :return: str, points to hosts file. :raises: Exception('Unsupported Platform') """ if platform.system() == "Linux": return "/etc/hosts" elif platform.system() == "Windows": # use environme...
214b73080a5c6c0a1fa040781c25e3582589c37f
683,207
from typing import List import ipaddress def is_ip_allowed(ip: str, allowed_networks: List[str]) -> bool: """Return True if the ip is in the list of allowed networks Any IP is allowed if the list is empty """ if not allowed_networks: return True try: addr = ipaddress.ip_address(ip...
ff9ced7303d7eb8fd588407c6c2c550778375bd8
683,208
def calculate_boundaries(dist_args1, dist_args2, dist_type, shift): """ Calculate minimum and maximum reward possible for certain distribution types. For normal distribution take 3 times standard deviation. These minimum and maximum are used to determine the bin sizes. :param dist_args1: parameter o...
dca0d09aa5dd15e1ff3b18a0befb7f4ed0c71d87
683,209
import os import glob import csv import json def prepare_data_corpus(new_dir= os.path.join('data', 'base_data')): """ This method reads all the individual JSON files of both the datasets and creates separate .tsv files for each. The .tsv file contains the fields: ID, article title, article content and the...
186d975ab9825a2aae7ce24b57b999a61493bb68
683,210
def device(portnum): """Turn a port number into a device name""" return 'COM%d' % (portnum+1)
2fd900d723346154b5934d5aa40fb40305235ee7
683,211
def func(a): """This is a function that just returns `a`.""" return a
93746f98321eb957b9c830222f7da5211f00982b
683,212
def T0_T(M, gamma): """Ratio of total to static temperature for adiabatic flow (eq. 3.28) :param <float> M: Mach # at area A :param <float> gamma: Specific heat ratio :return <float> Temperature ratio T0/T """ return 1.0 + 0.5 * (gamma - 1.0) * M ** 2
3a7b6877d07727282d8247a229a57b38f1460967
683,213
def flip_ctrlpts2d(ctrlpts2d, size_u=0, size_v=0): """ Flips a list of surface 2-D control points in *[u][v]* order. The resulting control points list will be in *[v][u]* order. :param ctrlpts2d: 2-D control points :type ctrlpts2d: list, tuple :param size_u: size in U-direction (row length) :t...
0f68efcab4a6c08e697492f7c8cc7aaf4e03d397
683,214
def lerp(x, from_, to): """Linear interpolates a value using the `x` given and ``(x,y)`` pairs `from_` and `to`. All x values must be numbers (have `-` and `/` defined). The y values can either be single numbers, or sequences of the same length. If the latter case, then each dimension is interpolated li...
c389d8c6f6db684420518dceeb510c985b4eee5c
683,215
import itertools def pairs(list1,list2): """ :param list1: list of elements :param list2: list of elements :return: pairs of elements with no repetition """ temp = list(itertools.product(list1, list2)) # output list initialization out = [] # iteration for elem in temp: ...
4b42e4ff3776d552c584ef47367f5b4797f34d96
683,216
def make_goal(nb_columns: int = 3) -> str: """ Define the goal expressed in LDLf logic. E.g. for nb_columns = 3: <(!c0 & !c1 & !c2)*;c0;(!c0 & !c1 & !c2)*;c1;(!c0 & !c1 & !c2)*;c2>tt :param nb_columns: the number of column :return: the string associated with the goal. """ labels =...
401dd04090e5ffdb7b4337e770897a4d52525a2b
683,217
def synonyms(term): """helper to extract synonyms""" if term.data is None or len(term.synonyms) == 0: return [] return list(term.synonyms)
0c6b9ba375bdd9a3cb9da4ef598f75f93ecf65ad
683,218
def _export_flatjson(d: dict, path) -> str: """ JSON文字列でファイル出力する。 1音素1行 """ s = ',\n'.join([f' {str(d_line)}' for d_line in d['labels']]) s = s.replace('\'', '"').replace('{', '{ ').replace('}', ' }') s = '{\n \"labels\": [\n' + s + '\n ]\n}\n' with open(path, mode='w', enco...
75b8577cb9a12abc9195f85a808f476717dc3842
683,219
def _get_from_f(word: dict, key: str): """HELPER: extracts the key from the word dictionary :param word: dictionary from the json word :type word: dict :param key: key that needed to be found in the f dictionary that in word :type key: str :return: value of key in the f key in word dictionary ...
62262ad9bd2bd592bab193c88d5d0d206d781943
683,220
import base64 def save_b64_image(base64_string): """Decodes a b64-encoded image and saves it locally to disk to be displayed in the Monitoring Station GUI Args: base64_string (str): encoded image string Returns: (str): filename for decoded image """ image_bytes = base64.b6...
7acdcd6f6924d0df74bfeb0e1a2d03be9688840d
683,221
def epc_calc_common_mode(reg_dict): """ Returns True if common mode is enabled, False otherwise Parameters ---------- reg_dict : dict The dictionary that contains all the register information Returns ---------- bool True if common mode enabled, false otherwise """ ...
3b59f645f7dca7b1ba3a66e26f7ab38136201274
683,222
import os import fnmatch def _MojomFiles(build_dir, suffixes): """Lists all mojom files that need to be included in the archive. Args: build_dir: The build directory. Returns: A list of mojom file paths which are relative to the build directory. """ walk_dirs = [ 'gen/components', 'gen...
d07f212d98c94043165e9b072d3ac3f0af6aaf04
683,223
def get_item(tbl:dict, key): """ Looks up an item in a dictionary by key first, assuming the key is in the dictionary. Otherwise, it checks if the key is an integer, and returns the item in that position. :param tbl: The dictionary to look in :param key: The key, or integer position to get th...
0f46bee75a0c289d9603696f6b3476542b1e9dcf
683,224
def cli(ctx, email, first_name, last_name, password, role="user", metadata={}): """Create a new user Output: an empty dictionary """ return ctx.gi.users.create_user(email, first_name, last_name, password, role=role, metadata=metadata)
3e1875f4d21cc4eaa6fd59feae2a28d8e7ab594e
683,225
import pandas as pd def add_month_year_column_function(dta, column_name): """ add a year and year-monthcolumn to the dataframe for easier date useage """ dta["column_name"] = pd.to_datetime(dta["column_name"]) dta["year_month"] = pd.to_datetime(dta["column_name"]).dt.strftime("%Y-%m") dta["ye...
4efec73d0445f875d5e50c35cb37b5bfb3b7aa59
683,226
import re def filter_blanks(user, str): """ Replace more than 3 blank lines with only 1 blank line """ if user.is_staff: return str return re.sub(r'\n{2}\n+', '\n', str)
47cfe5d058d7672f64281bbb8f6ff5101298a8b6
683,227
def rcomp(s): """Does same thing as reverse_complement only cooler""" return s.translate(str.maketrans("ATCG","TAGC"))[::-1]
6712717a5f4827cf25c0bac5541adccad5205a70
683,228
import argparse def parse_cli_arguments(): """Return an argparse.Namespace with relevant command-line parsing.""" parser = argparse.ArgumentParser() parser.add_argument("wordlist", default="data/diceware-fr-5-jets.txt") parser.add_argument("words_count", type=int) parser.add_argument( "--n...
79f01a62a7e9141b446f8839ad711747331bacf4
683,229
import collections def _list_to_dicts(list_of_values, keys): """Restores a list of dicts from a list created by `_dicts_to_list`. `keys` must be the same as what was used in `_dicts_to_list` to create the list. This is used to restore the original dicts inside `host_call_fn` and `metrics_fn`. Transforms a...
e32592187866140d3cac152c5402e4645d2e3e1d
683,230
def hms2decimal(RAString, delimiter): """Converts a delimited string of Hours:Minutes:Seconds format into decimal degrees. @type RAString: string @param RAString: coordinate string in H:M:S format @type delimiter: string @param delimiter: delimiter character in RAString @rtype: float @r...
23b52256efbe60435286582837678922de6a97e8
683,231
def rotate270_augment(aug=None, is_training=True, **kwargs): """Rotation by 270 degree augmentation.""" del kwargs if aug is None: aug = [] if is_training: return aug + [('rotate270', {})] return aug
50e1f1878ede857a1b203cd1ebf8384bdd4e80bc
683,232
def create_deets_message(time, size, image): """Creates message of image details for the GUI client Image details returned include the time the image was uploaded or processed and the image size in pixels. If the image was original, the upload time is returned. If the image was inverted, the process...
f9989d85f1cdd10df7901c2cfd879fe25fc6cf39
683,233
import numpy def _ll_simplex0(y, x, beta, ln_s2): """ The function calculates the log likelihood function of a simplex regression. Parameters: y : the fractional outcome in the range of (0, 1) x : variables of the location parameter in simplex regression beta : coefficients of the location ...
8832d28216c1a4bb22c88718b37c81913dea8440
683,234
def _get_venue_storage(districts): """Initializes a dict for storing venues, organized by district. """ # This ensures districts are included even if they have no rated venues. res = {district['name']: [] for district in districts} res[None] = [] # Hack: avoids exception if venue has no district. ...
8ab3ea6cbdc5e329e878361fc964c0b39687634a
683,235
import re def create_form_data(data): """ Convert all keys in data dictionary from camelCaseFormat to underscore_format and return the new dict """ to_lower = lambda match: "_" + match.group(1).lower() to_under = lambda x: re.sub("([A-Z])", to_lower, x) return dict(map(lambda x: (to_under(...
cdd0183407a86bae41195a99bac09ca50d32f8a4
683,236
def find_my_friend(queue: list, friend_name: str) -> int: """ :param queue: list - names in the queue. :param friend_name: str - name of friend to find. :return: int - index at which the friends name was found. """ for i, name in enumerate(queue): if friend_name == name: ret...
7ce266b119f4045a54ed2c0f9963378467c0d8cc
683,237
from jmespath.visitor import TreeInterpreter def patch_jmespath(key_not_found_sentinel): """Patch JMESPath in order to know when a key does not exists in JSON. Default behavior is to return None but this does not mean that key was not found in JSON Args: key_not_found_sentinel (object): s...
ba7ddca57da64cd7d0d5b4fcbf3cbc8a7bb07b33
683,238
import os import glob def find_run_number(workdir, fl_app_name="prostate_central"): """Find the first matching experiment""" target_path = os.path.join(workdir, "*", "fl_app.txt") fl_app_files = glob.glob(target_path, recursive=True) assert len(fl_app_files) > 0, f"No `fl_app.txt` files found in workd...
8a12db1e54b8fa964b07784b118154f190c081a6
683,239
import networkx as nx def OeMolToGraph(oemol): """ Convert charged molecule to networkX graph and add WiberBondOrder as edge weight Parameters ---------- mol: charged OEMolGraph Returns ------- G: NetworkX Graph of molecule """ G = nx.Graph() for atom in oemol.GetAtoms()...
caab6359b8afd3e53b5c9d782e0ea522de9af449
683,240
import os def get_host_port_socket(): """ Returns values from the environment """ try: host = os.environ['LOGSTASH_SERVER'] port = int(os.environ['LOGSTASH_PORT']) socket_type = os.environ['LOGSTASH_PROTO'] except KeyError: raise RuntimeError("LOGSTASH_SERVER, LOGST...
1ffcdd74a2455b9debb0e47dbe832fa83976fc8f
683,242
import pathlib def return_file_extension(_path): """Return string of file extension. Example: .txt; .py""" return pathlib.Path(_path).suffix
ac19fe9d77a2cd4dc64a5a0b21fe21f624f09232
683,243
def read_csv(filepath): """ Simple CSV reader function required for blast function to output results as a dictionary Input ----- filepath = str, path to the CSV file containing blast results Output ------ dictionary = dict, keys = column names, values = columns. ...
d70e3507541d2cc34422a6805c9c89db2bb6e8cf
683,244
def _set_kwarg(f, fixed_kwargs): """Closure of a function fixing a kwarg""" def f2(*args, **kwargs): fixed_kwargs2 = {k: v for k, v in fixed_kwargs.items() if k not in kwargs} return f(*args, **fixed_kwargs2, **kwargs) return f2
d05a5be04a01827b3595d411defb77afa8660b27
683,245
import typing def get_effective_capabilities() -> typing.Optional[int]: """Read CapEff from /proc/self/status Returns None if file is missing, for example non-linux systems. """ try: for line in open("/proc/self/status", "r"): if line.startswith("CapEff:"): return ...
b54c8d9cbaac2bb13979caf40d6a7a31ce9248c2
683,246
def array_find(arr, obj) -> int: """A helpher function which finds the index of an object in an array. Instead of throwing an error when no index can be found it returns -1. Args: arr : the array to be searched obj : the object whose index is to be found. Returns: int: The i...
df8733b073d24d47f7be8f3b01b3f9e2d78f51bc
683,247
def isStaticIpAvailable(ipaddr, chuteStor, name): """ Make sure this static IP address is available. Checks the IP addresses of all zones on all other chutes, makes sure not equal.""" chList = chuteStor.getChuteList() for ch in chList: # Only look at other chutes if (name != ch...
6cd38333d9b7c4fdb53c8ffcf834713dc6686a36
683,248
def __calculate_waterfootprint(wf_ing, quantity): """ Calculate the right water footprint of a ingredient from its (l/kg) water footprint and the quantity provided (in gr). :param wf_ing: the water footprint of the ingredient. :param quantity: the quantity of the ingredient. :return: the water ...
eb675f718dfdf619cf874c8a1fb2cca2f55ed0a5
683,249
import re def _contains_number(obj_in: str) -> bool: """ Checks list to see if it has a number in it anywhere.""" _pattern = r'\d' if isinstance(obj_in, str): return bool(re.search(_pattern, obj_in)) else: raise TypeError
0033f2f9a82108eb494e3b17eb2127a69b387d21
683,250
def _is_extended_mux_needed(messages): """Check for messages with more than one mux signal or signals with more than one multiplexer value.""" for message in messages: multiplexers = [ signal.name for signal in message.signals if signal.is_multiplexer ] ...
61e5c93136a47fcf636da753e3e94304a9e57963
683,251
from typing import Optional def termcolor( logstr: str, color: Optional[str] = None, bold: Optional[bool] = False ) -> str: """Return the passed logstr, wrapped in terminal colouring.""" # For terminal colouring termcolors = { "BLACK": 0, "RED": 1, "GREEN": 2, "YELLOW":...
90861497a1ceaebbb52b7accafae48160b31f465
683,252
def parse_int(arg): """ Parse an integer of an unknown base. The supported bases are 2, 8, 10 and 16. """ arg = arg.lower() base = 10 if arg.startswith('0x'): base = 16 elif arg.startswith('0b'): base = 2 elif arg.startswith('0o'): base = 8 return int...
60d201517280733566d467e4cc31d17f9a588363
683,253
def _combine_external_inputs_with_precursor_nodes(node, external_inputs): """ User_provided_input_nodes. Args: node (OnnxGraphNode): Node instance. external_inputs (list[str]): Inputs in onnx ir. Returns: list[str], precursor nodes list. """ inputs = set(node.ir_node_in...
1d24dee3a1829f6b69f6863c0a74236de4dd8124
683,254
import random import string def generate_name(length=8): # type: (int) -> str """Generate and return a random name.""" return ''.join(random.choice(string.ascii_letters + string.digits) for _idx in range(length))
2814628523c6a7512eac7418970022fe70be7beb
683,255
def initialize_counters(): """ Initialize variables that will count through the whole task the success of each process """ global_counters = { 'metadata': { 'success': 0, 'error': 0, }, 'file': { 'success': 0, 'error': 0, }, 'delete': { 'success': 0, 'error': 0, },...
376da289faf0ac470cddc840d289b15428321cbf
683,256
import random import string def generate_client_token_by_random(): """ The alternative method to generate the random string for client_token if the optional parameter client_token is not specified by the user. :return: :rtype string """ client_token = ''.join(random.sample(string.asci...
beb5122d4a3b44e64ac30266eabd7615e1e3b729
683,257
def check_if_se_coordinate_valid(img, se, x, y, i, j): """Given a structural element, an image, an x-y coordinate for the image, and an i-j coordinate for the structural element, checks to see whether the element needs to be operated on.""" x_adjusted = x + i - se.shape[0] // 2 y_adjusted = y + j - ...
44ec0b6eb305cfcdc5f3382c8b322bc4e8c05ea5
683,258
def _elem2idx(list_of_elems, map_func): """ :param list_of_elems: list of lists :param map_func: mapping dictionary :returns list with indexed elements """ return [[map_func[x] for x in list_of] for list_of in list_of_elems]
234c3bbb1571ec8b3b44ad53e26fb853e14de8b6
683,259
import re def check_mixed_digits(value): """ Checks if an string has mixed digits :param value: String to be checked :type value: String :returns: True if there are mixed digits in the string :rtype: Boolean Examples: >>> check_mixed_digits('Lorem ipsum dolor sit amet, consec...
3bff1aaec761eaf84894156ab54d89da9b93ae02
683,260
def _channel_first(sig): """Use the hack that maximum channel number is 5""" return sig.T if sig.shape[1] > 5 else sig
ca4fc893b18d92afd8c09d24b03fae0970b9963e
683,262
import argparse def get_args(): """ Get arguments for file setup. """ help_description = """ Microcontroller setup script for the Pheeno robot. You must use either --all or --file option. Not using an option will result in nothing getting done. """ parser = argparse.ArgumentParser( ...
f504bc1d6045c4189a84453a78dcddf51270026b
683,263
def get_tree_deep(tree): """ 获得树的深度,以在绘制树的时候分配空间 :param tree: 决策树 :return: 树的最大深度 """ if isinstance(tree, dict): deep = 0 root = list(tree.values())[0] for node in root.values(): temp_deep = get_tree_deep(node) if temp_deep > deep: ...
344a54bf211995b770443e1c02006a0a9d5c7aa5
683,264
import os def get_auth(): """get authentications for transcription service""" # print('AUTH') # print(os.environ.get('IBM_SPEECH_TO_TEXT_APIKEY')) apikey = str(os.environ.get('IBM_SPEECH_TO_TEXT_APIKEY')) return ("apikey", apikey)
86d6452addecacc0446df34c8e896f6b1a8debd7
683,265
def file_fzp_start(filename): """ finds the start of the fzp data :param filename: string of the fzp file name :return: number of lines to skip at top of file """ with open(filename) as in_f: c= 0 cols = [] #find start of VISSIM data line = in_f.readline() ...
ce502de052cb2f16cc4be96dcb5053f790376065
683,267
import numpy def CalculateMZagreb2(mol): """ ################################################################# Calculation of Modified Zagreb index with order 2 in a molecule ---->MZM2 Usage: result=CalculateMZagreb2(mol) Input: mol is a molecule object Output: result ...
a7b6aeaa25f5e91470daf264673b6f28594d8184
683,268
def distance_jaccard(arr1: list, arr2: list) -> float: """ Description: Calcule la distance Jaccard entre deux listes. Paramètres: arr1: {list} -- Première liste. arr2: {list} -- Deuxième liste. Retourne: {float} -- Distance Jaccard entre les deux listes. ...
ef90501d10e08bc76a4ea7b1d2cbee99921bc935
683,269
import re def do_trim_comments(pydot_cfg): """ Remove assembly comments """ # Avoid graph and edge nodes, which are the 1st and 2nd nodes nodes = pydot_cfg.get_nodes()[2:] for n in nodes: c = [] l = n.get_label() if not l: continue lines = l.split(r...
c9d51950e6194dd8d39c51d71962eb043091a28b
683,270
def emphasis_sub(match): """Substitutes <strong>, <em>, and <strong><em> tags.""" level = len(match.group(1)) content = match.group(2) if level == 3: return '<strong><em>{0}</em></strong>'.format(content) elif level == 2: return '<strong>{0}</strong>'.format(content) elif level =...
ad38b3e12fa6876f6c7f15d06c4eb72aa579d7e3
683,271
def find_indices_longer_than_prot_seq(df, TMD): """ Finds indices that are longer than the protein sequence. Small lambda-like function used to determine where the TMD plus surrounding exceeds the length of the protein sequence Parameters ---------- df : pd.DataFrame Dataframe containing t...
9a81ea60ed14f9fb42a686bbbbda014146669127
683,272
import math def calculate_distance(coord1, coord2, box_length=None): """ Calculate the distance between two 3D coordinates. Parameters ---------- coord1, coord2: list The atomic coordinates Returns ------- distance: float The distance between the two points. ...
a43eb15406ea4eaf3c59bb27953b3d55f166a037
683,273
import re def isurl(value): """ Return whether or not given value is an URL. If the value is an URL, this function returns ``True``, otherwise ``False``. Examples:: >>> isurl('http://foo.bar#com') True >>> isurl('http://foobar.c_o_m') False :param value: string ...
746f82809d4c196b56192fe8401c4efb8bc8a7c9
683,274
def longest_common_subsequence(x, y): """longest common subsequence Dynamic programming :param x: :param y: x, y are lists or strings :returns: longest common subsequence in form of a string :complexity: `O(|x|*|y|)` """ n = len(x) m = len(y) # -- compute o...
fcc2b046a965d09e76bd867b32c8744fa1c25bc9
683,275
def FilterInteger(param, value): """ Filter: Assert integral number. """ if value.isnumeric () == False: return "parameter --" + param.name + " expectes an integer as value" return None
bd4ab48793771caea81cd831b62539bd05992e61
683,276
def chunk_list(a, n): """ chunk list a into n sublists """ k, m = divmod(len(a), n) return list((a[i * k + min(i, m):(i + 1) * k + min(i + 1, m)] for i in range(n)))
db6a12d7a1d072cc8aa42630e0e4bc62d0b4cc02
683,277
def consume_whitespace(s: str, offset): """ This also deals with comments. """ while True: while offset < len(s) and s[offset].isspace(): offset += 1 if offset >= len(s) or s[offset] != ";": break while offset < len(s) and s[offset] not in "\n\r": ...
73b93ae79c0babdb8dd912b69654f7be806bffa6
683,278
def find_factors(x): """ """ factors = [] for i in range(1, x + 1): if x % i == 0: factors.append(i) print(factors) return factors
852c39d18a07b4badc34280693824577bf371115
683,279
import torch def get_charges(node): """ Solve the function to get the absolute charges of atoms in a molecule from parameters. Parameters ---------- e : tf.Tensor, dtype = tf.float32, electronegativity. s : tf.Tensor, dtype = tf.float32, hardness. Q : tf.Tensor, dtype = tf....
519b3ee62d4ff17247215eb77100366407338dfc
683,280
def _update_absQfield(qfield, dist, inds, astep, Qp_water, dx): """Update norm of water flux vector.""" for i, ii in enumerate(inds): if astep[i]: qfield[ii] += Qp_water / dx / 2 return qfield
95dccbf5417257ef9806df5749a45476f51d0f3b
683,281