content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
from typing import Mapping def _mixin(d, u): # noinspection SpellCheckingInspection """ if value x in "keyx:valuex" pair is list, it's will be replaced :param d: :param u: :return: """ u = u or {} d = d or {} for k, v in u.items(): if isinstance(v, Mapping): ...
5285d1efa1eabc9c64ace95a02b37f6ee50d7470
682,611
import functools def wait_while(toggle_attr): """Returns a decorator that waits for an instance attribute to be false.""" def wait_while_decorator(instance_method): """Waits on a toggle attribute before executing an instance method.""" @functools.wraps(instance_method) def wrapper(self...
0152b10e5ec42f270c89c7ab35fd60706ee4c8db
682,612
import random def mutate_agent(agent_genome, max_mutations=3): """ Applies 1 - `max_mutations` point mutations to the given road trip. A point mutation swaps the order of two waypoints in the road trip. """ agent_genome = list(agent_genome) num_mutations = random.randint(...
130204f0ffa2134a053a55202f26252366eecdba
682,613
from typing import Sequence def strictly_increasing(s: Sequence): """Returns true if sequence s is monotonically increasing""" return all(x < y for x, y in zip(s, s[1:]))
010134cd75c5ca6dc88bfdcb73a7a79d719e83ff
682,614
def get_categories(geneSetFile): """ Makes a dictionary of categories and their corresponding genes for files that a formatted as a list of genes with their categories""" catDict = {} allList = [] catFile = open(geneSetFile, 'r') for line in catFile: line = line.strip() line = li...
63a0d927c5d6fee47e8d030765dcde3dd9b06d5e
682,615
def frac_of_cases(series1, series2=None): """ Description: Compute fraction True cases from given data series Params: series1: an array of True and False cases: series2: it is not used. It is only there, so that the draw_perm_reps can work...
f3dea221af4125af015453a516fd6871b3fe2d8f
682,616
import random def generate_number(digits): """Generate an integer with the given number of digits.""" low = 10**(digits-1) high = 10**digits - 1 return random.randint(low, high)
a123a4312329d446aef8dad25a26c14a2bc24a8e
682,617
def _applescriptify_str(text): """Replace double quotes in text for Applescript string""" text = text.replace('"', '" & quote & "') text = text.replace('\\', '\\\\') return text
591883251dde88c21ec3f01285a113814676c745
682,618
def unpack_spectrum(HDU_list): """ Unpacks and extracts the relevant parts of an SDSS HDU list object. Parameters ---------- HDU_list : astropy HDUlist object Returns ------- wavelengths : ndarray Wavelength array flux : ndarray Flux array z : float Reds...
8536e50ffaea2301519a5a046d54a9d256de05c8
682,619
import re def is_stable_version(version): """ Return true if version is stable, i.e. with letters in the final component. Stable version examples: ``1.2``, ``1.3.4``, ``1.0.5``. Non-stable version examples: ``1.3.4beta``, ``0.1.0rc1``, ``3.0.0dev0``. """ if not isinstance(version, tuple): ...
db5056654dea881d5beec076541d08c129a790c7
682,620
def modify(name): """vboxmanage modify callback property.""" return { "fget": lambda self: self.source.info.get(name), "fset": lambda self, value: self.source.modify(**{name: value}), }
4195322afc50729123a68486a261e4e274882bca
682,621
def read_symfile(path='baserom.sym'): """ Return a list of dicts of label data from an rgbds .sym file. """ symbols = [] for line in open(path): line = line.strip().split(';')[0] if line: bank_address, label = line.split(' ')[:2] bank, address = bank_address.split(':') symbols += [{ 'label': label...
5bfb861cd82424c955984c27cb08631021712d53
682,623
def cert_bytes(cert_file_name): """ Parses a pem certificate file into raw bytes and appends null character. """ with open(cert_file_name, "rb") as pem: chars = [] for c in pem.read(): if c: chars.append(c) else: break # nul...
6d10553832f11d514b62bb206f97ce3c167723d1
682,625
def cupy_cuda_MemoryPointer(cp_arr): """Return cupy.cuda.MemoryPointer view of cupy.ndarray. """ return cp_arr.data
b87e8f0a9952f637817077fcdc621eb6441367ab
682,626
def a1z26_encode(text): """Simple alphabetic text encoding by replacing each char with char number""" text = '-'.join(map(str, map(ord, text))) return text
8293c1ed08c58cd5a54ebd22e4bf23398f34a79a
682,627
def priority(s): """Return priority for a give object.""" if type(s) in (list, tuple, set, frozenset): return 6 if type(s) is dict: return 5 if hasattr(s, 'validate'): return 4 if issubclass(type(s), type): return 3 if callable(s): return 2 else: ...
dae14d0e2958f1b2cdbf85c39897b8b9c5ba07c4
682,628
import torch def estimate_gpnoise(likelihood, verbose=True): """ Estimate true GP Noise under constraints Input Args: likelihood : Optimized GPyTorch likelihood object verbose : default = True (bool) Return: GPnoise : 1x1 tensor """ raw_noise = likelihood.noise_covar.raw_nois...
d588523140083583d2d94cb03bd9081bd0e8d4be
682,629
def extend(*dicts): """Create a new dictionary from multiple existing dictionaries without overwriting.""" new_dict = {} for each in dicts: new_dict.update(each) return new_dict
e5f6e4797eab6cc6c6b2c23f0766b6ff23f5f8e1
682,630
def mult (x, y): """ multiply : 2 values """ return x * y
f4292f0b88be0ee49df3572066a8cef4c3cb11fe
682,631
def msg_to_str(msg, ignore_fields=''): """ Convert ParlAI message dict to string. :param msg: dict to convert into a string. :param ignore_fields: (default '') comma-separated field names to not include in the string even if they're in the msg dict. """ def filter(txt):...
bb855636349f0ceb9f7bdf8f27231da3fa9214a0
682,632
def combine_on_sep(items, separator): """ Combine each item with each other item on a `separator`. Args: items (list): A list or iterable that remembers order. separator (str): The SEPARATOR the items will be combined on. Returns: list: A list with all the combined item...
f57f605c5ba186af992ad8e3818a0b97158f64ec
682,633
def swapPos(list:list, pos1:int, pos2:int): """ Swap two elements in list. Return modified list """ list[pos1], list[pos2] = list[pos2], list[pos1] return list
6977b7f9f7040b63552ae5188eced46c3c2cfdb9
682,634
import csv def team2machine(cur_round): """Compute the map from teams to machines.""" # Get the config with the teamname-source mappings. config_name = f"configs/config_round_{cur_round}.csv" team_machine = {} with open(config_name, 'r') as infile: reader = csv.reader(infile) for r...
e81c7a7321127a70a7ead1fcf6be6feed54a9c40
682,635
import torch def systematic_sampling(weights: torch.Tensor) -> torch.Tensor: """Sample ancestral index using systematic resampling. Get from https://docs.pyro.ai/en/stable/_modules/pyro/infer/smcfilter.html#SMCFilter Args: log_weight: log of unnormalized weights, tensor [batch_shape, ...
6e38e8f8eb37075cae838e7cf8d77aeaf984f7aa
682,636
def get_column_as_list(matrix, column_no): """ Retrieves a column from a matrix as a list """ column = [] num_rows = len(matrix) for row in range(num_rows): column.append(matrix[row][column_no]) return column
0f8f234fa9c68852d1c2f88049e2d0fea0df746d
682,637
from operator import or_ from operator import not_ def null_prop(cls, key): """Provide expression to filter on a null or nonexistent value""" return or_( cls._props.contains({key: None}), not_(cls._props.has_key(key)), )
ff2116e2ff5f0e2c5187e0962cd302711ef66cd6
682,638
def _GetDefault(t): """Returns a string containing the default value of the given type.""" if t.element_type or t.nullable: return None # Arrays and optional<T> are default-initialized type_map = { 'boolean': 'false', 'double': '0', 'DOMString': None, # std::string are default-initialized....
8fadb2db6211fa18fc2dc4d1306bd68113d2bb4f
682,641
import configparser def get_downstream_distgit_branch(dlrn_projects_ini): """Get downstream distgit branch info from DLRN projects.ini""" config = configparser.ConfigParser() config.read(dlrn_projects_ini) return config.get('downstream_driver', 'downstream_distro_branch')
fefde39830b80618606a9b4906b061726ac9b706
682,642
def get_defined_enums(conn, schema): """ Return a dict mapping PostgreSQL enumeration types to the set of their defined values. :param conn: SQLAlchemy connection instance. :param str schema: Schema name (e.g. "public"). :returns dict: { "my_enum": frozense...
eea2f3e533eab4f4059b6c86f67d4683a4cc7644
682,643
def find_valid_edges(components, valid_edges): """Find all edges between two components in a complete undirected graph. Args: components: A [V]-shaped array of boolean component ids. This assumes there are exactly two nonemtpy components. valid_edges: An uninitialized array where ou...
83d6a8237c45c74bd695d2f54371b19ae81e493e
682,644
import torch def collateFunction(self, batch): """ Custom collate function to adjust a variable number of low-res images. Args: batch: list of imageset Returns: padded_lr_batch: tensor (B, min_L, W, H), low resolution images alpha_batch: tensor (B, min_L), low resolution indica...
9d76ee5d2ab6bb079976ef948a5cceab885c50e2
682,645
def find_column_by_utype(table, utype): """ Given an astropy table derived from a VOTABLE, this function returns the first Column object that has the given utype. The name field of the returned value contains the column name and can be used for accessing the values in the column. Parameters ...
e1347af38ecb406cdc9c5c7976422e0606c3efd9
682,646
def sol(s, n): """ If the character is a number and l is not set set it to that index, if it is set the r. If character is not a number set both l and r as None """ l = None r = None mx = 0 for i in range(n): if 48 <= ord(s[i]) <= 57: if l == None: # ...
9cb66cbcab13bfac2175ab6f8cb1519e6485b4f3
682,647
def calc_node_attr(node, edge): """ Returns a tuple of (cltv_delta, min_htlc, fee_proportional) values of the node in the channel. """ policy = None if node == edge['node1_pub']: policy = edge['node1_policy'] elif node == edge['node2_pub']: policy = edge['node2_policy'] else:...
5d0eb77cb233e96ba340d4afa42c4478872735d6
682,648
def coerce_value(value, dtype: str): """ Coerces value into the type specified by dtype and returns the coerced value. Args: value: the value to coerece dtype (str): the data type to coerce/cast value into Returns: the value cast into the data type specified by dtype """ ...
8e90622c33306ecd91d27399340feb912875f356
682,649
def context(doc, result=None): """turn the document into an unpackable format for the render_template context""" if result is None: result = {} if '_id' in doc: doc.pop('_id') doc2 = doc.copy() for key, value in doc.items(): if isinstance(value, dict): for k,...
88b967eca8bc4e2acbbcbf2bff86fff028383f44
682,650
def try_function_on_dict(func: list): """ This method trys the given functions on the given dictionary. Returns the first function, which returns a value for given dict. Main purpose of this is the initialization of multiple Classes from json dicts. Usage: ```python func_list = [func1, func2, ...
625263f12f2d30470999a278e37739d60030b9b3
682,651
def format_mac(mac: str) -> str: """ Format the mac address string. Helper function from homeassistant.helpers.device_registry.py """ to_test = mac if len(to_test) == 17 and to_test.count("-") == 5: return to_test.lower() if len(to_test) == 17 and to_test.count(":") == 5: t...
283fe3c294bbe1eb30017d6a61587e824256bc73
682,652
def apply_properties(vehicle,fuel_tanks): """Apply fuel tank properties from OpenVSP to the SUAVE vehicle. Assumptions: Fuel tanks exists in the fuselage and wings only Source: N/A Inputs: vehicle.fuselages.*.Fuel_Tanks.*.tag [-] vehicle.wings.*.Fuel_Tanks.*.tag [-] ...
4f582707858f2786d2b63c414abb7339816d2524
682,653
def present(element, act): """Return True if act[element] is valid and not None""" if not act: return False elif element not in act: return False return act[element]
872f6b73d873f3c4ef5967e531d2056c151566a8
682,654
def car(f): """ :type f: function :rtype: int """ def first(a, b): return a return f(first)
70cc021ae0bef21ea6632be9d314dd440180f95e
682,655
def format_output(tosave, formatter): """ Applies the formatting function, formatter, on tosave. If the resulting string does not have a newline adds it. Otherwise returns the formatted string :param tosave: The item to be string serialized :param formatter: The formatter function applied to ite...
03ff2ec8b10edbf2a54b21841505cb26e2522617
682,656
def _update_query(table: str, field: str, is_jsonb: bool, from_string: str, to_string: str) -> str: """Generates a single query to update a field in a PostgresSQL table. Args: table (str): The table to update. field (str): The field to update. is_jsonb (bool): Whether ...
1d90246cfd464b40f3235310e97d2ad38c30fcb3
682,657
def reverse_str(str): """ Returns reversed str """ if len(str) == 1: return str return str[-1] + reverse_str(str[:-1])
286ab253216e48f123f835474c429050ab351c6f
682,658
def extract_red_alphashape(cloud, robot): """ extract red, get alpha shape, downsample """ raise NotImplementedError # downsample cloud cloud_ds = cloudprocpy.downsampleCloud(cloud, .01) # transform into body frame xyz1_kinect = cloud_ds.to2dArray() xyz1_kinect[:,3] = 1 ...
058a1a83a327156aa4b88d2e1112fdf189d4100c
682,659
import os def get_data_files_paths(): """ Returns the input file folders path :return: list of strings The input file paths as list [train_jpg_dir, test_jpg_dir, train_csv_file, test_csv_template_file] """ data_root_folder = os.path.abspath("input/") train_jpg_dir = os.path.join(...
ce124c06bf943d4cf1ab596bf65d4a6bb5fa81c4
682,660
import os import logging from unittest.mock import call def filter_aligned_reads(bam_path, output_name=None, paired=True): """ Filters bams for aligned reads :param str bam_path: Path to bam file :param str output_name: Defaults to input bam with '.filtered' inserted before the .bam extension :pa...
53545eaf3a8fc2af0bbc015718db1f37e8744643
682,661
def smart_split(sentences, pos_tags, max): """Smart split makes sure, when you truncate input sequence you dont loose data. To do this, it breaks the input sequence upto MAX_SEQ_LENGTH and the reaming part of the sequence becomes a new sequence. For example, if MAX_SEQUENCE_LENGTH=64, a sentence with l...
05c75072482bca734fc69e0be1fc084c67455b8c
682,662
def generateFilenameFromUrl(url): """ Transforms a card URL into a local filename in the format imageCache/setname_cardnumber.jpg. """ return 'imageCache/' + '_'.join(url.split('/')[1:])
d1541b12edf451636b7c3823061ea13266ee2e0e
682,663
import shutil def move(src_path, dest_path, raise_error=False): """ Moves a file or folder from ``src_path`` to ``dest_path``. If either the source or the destination path no longer exist, this function does nothing. Any other exceptions are either raised or returned if ``raise_error`` is False. "...
77633febeccff8cc9ba6dea4f1ef89c07a471d42
682,664
def unblock_list(blocked_ips_list, to_block_list): """ This function creates list of IPs that are present in the firewall block list, but not in the list of new blockings which will be sent to the firewall. :param blocked_ips_list: List of blocked IPs. :param to_block_list: List of new blockings. ...
74b29a975c530eb22b3f9fc6ed7ce9c924e8baee
682,665
def the_code_should_not_run(flag): """the code should not run.""" @flag def testfun(): return "executed" assert testfun() is None
85b66e60d6c4b4005bb99e0eb466bec355035fac
682,666
import csv import re def get_keys_from_file(file): """ Reads a file and creates a list of dictionaries. :param file: Filename relative to project root. :return: lkeys - a list of dictionaries [{ Key: '00484545-2000-4111-9000-611111111111', Region: 'us-east-1' },...
ae0b89bf216b54e012b26fed3ec7ab0bbb6e288e
682,667
import os def PathSplitToList(path): """Returns the path split into a list by the separator. Args: path: An absolute or relative path (e.g. '/a/b/c/' or '../a') Returns: A list of path components (e.g. ['a', 'b', 'c]). """ lst = [] while True: (head, tail) = os.path.split(path) if head =...
8399c7c580deeed94f9a5affb79b5ba60cd720cc
682,668
from numpy import array, diag def long_range_energy_matrix(X, Rm1, Z, Q, P): """ Extract the matrix of the electrostatic energies of atoms described By their positions, charges and dipoles Args: X (array): the array of the atom positions Q (array): charge monopoles of the electrons ...
328822e1e2a2b798ba0d69916baa8afdf2cf8e5b
682,669
def file_list(redis, task_id): """Returns the list of files attached to a task""" keyf = "files:" + task_id return redis.hkeys(keyf)
422103ae390c47e707cc17ef1bd08d042d433ecc
682,671
def encode(en_sens, cn_sens, en_dict, cn_dict, sort_by_len=True): """ word to number """ out_en_sens = [[en_dict.get(w, 0) for w in en_sen] for en_sen in en_sens] out_cn_sens = [[cn_dict.get(w, 0) for w in cn_sen] for cn_sen in cn_sens] if sort_by_len: sorted_index = sorted(range(le...
6281f9ff5728300d1ed1d7d60807b240c659ef5d
682,673
def _parse_quad_str(s): """Parse a string of the form xxx.x.xx.xxx to a 4-element tuple of integers""" return tuple(int(q) for q in s.split('.'))
79dcb2bffad831a7f60fd471ea5f4b747e693d1e
682,676
def flatten_dict(dct, separator='-->', allowed_types=[int, float, bool]): """Returns a list of string identifiers for each element in dct. Recursively scans through dct and finds every element whose type is in allowed_types and adds a string indentifier for it. eg: dct = { 'a': 'a stri...
ca978d848f1f10c3a92e20e1e93f8ffb461eaff6
682,678
def observe_fn(last_image, last_action, last_reward, state): """the observe_fn for the model.""" del last_action, last_reward, state state = last_image[:, 0] return state
5fff033aa18adf52548669ad194207a2e49b33af
682,679
import torch def gpu_mem_usage(): """ Computes the GPU memory usage for the current device (MB). """ mem_usage_bytes = torch.cuda.max_memory_allocated() return mem_usage_bytes / (1024 * 1024)
5ca56df8e89697ee158974725e176289ba4bad60
682,680
import argparse def get_args(): """Get commandline arguments with argparse. Returns: The args dictionary """ parser = argparse.ArgumentParser(description='Train the network.\n\n' 'This can be done with Google' ...
0334bed7a938d240aaffe2d6de38504bd2928dde
682,681
def is_candidate_word(word): """ check a word is correct candidate word for identifying pronoun """ discarded_words = ["a", "an", "the"] # can enhance this list if len(word)<=2 or word.lower() in discarded_words: return False return True
7f3c609c82f5cf6e8586ec3408ac90e392a1b0c7
682,682
def _parse_tersoff_line(line): """ Internal Function. Parses the tag, parameter and final value of a function parameter from an atomicrex output line looking like: tersoff[Tersoff].lambda1[SiSiSi]: 2.4799 [0:] Returns: [(str, str, float): tag, param, value """ line = line.s...
df984a7e6dafb17b7a90400bc2320765327bbbbe
682,683
def _crop(image): """ Preprocessing: crop """ h = image.shape[0] w = image.shape[1] cropped = image[int(h/5.):h-25,:,:] return cropped
25b46fbfc64dfd71f0afe9a51227893ba6fcb97f
682,684
def find_IPG_hits(group, hit_dict): """Finds all hits to query sequences in an identical protein group. Args: group (list): Entry namedtuples from an IPG from parse_IP_groups(). hit_dict (dict): All Hit objects found during cblaster search. Returns: List of all Hit objects correspon...
ef6f345b12644dd8f4dd0fa8664a304772ff77cc
682,685
def fill_empty(df, config, dataframes): """ Parameter must be either a value or a dictionary. The format of the dictionary is key being the column name, and the value the value to fill the nan. When only a value is sent this will fill the whole dataframe if an empty value is found """ if isinsta...
bab3f6f629e7fdb8b6ad3b2c33f0bfe6913583e4
682,686
def get_mc_filepath(asm_path): """ Get the filepath for the machine code. This is the assembly filepath with .asm replaced with .mc Args: asm_path (str): Path to the assembly file. Returns: str: Path to the machine code file. """ return "{basepath}.mc".format(basepath=asm_...
7eb283e3d231a0217f1c9459b27fdd4f451c46ee
682,687
import os import argparse def is_file(filename): """Checks if a file is an invalid file""" if not os.path.exists(filename): msg = "{0} doesn't exist".format(filename) raise argparse.ArgumentTypeError(msg) else: return filename
31c3f7aeced7ae5b3df42c565695b80a750f2d3a
682,690
import re def dropBody(line): """ Parameter: line:string Function: drop the function body in the string "line". """ return re.sub(r"(\{?.*\}$)|(\{.*\}?$)", "", line)
92a4656460fbab70faef36357f559681d1f829c5
682,691
import ast def parse_param_from_str(text): """Attempt to parse a value from a string using ast Args: text (str): String to parse Return: tuple: value, used_ast Raises: Exception: An error occurred """ text = str(text).strip() value = text used_ast = False ...
bebfc05d6750f4b5cb6f007f35b4d4eff9db558a
682,692
def makeheader(): """ Returns the header information for the Latex document. Currently this just returns the header information. In the future this may have some arguments for introducing extra Latex packages """ return r"""% resume.tex % vim:set ft=tex spell: \documentclass[10pt,letterpape...
ed92b5964303302800f88c210b2f19a19e90f1d4
682,693
import sys def get_block(block_type, in_channels, out_channels, kernel_size, stride, activation, se, bn_momentum, bn_track_running_stats, *args, **kwargs): """ The factory to construct the candidate block Args: block_type (str) in_channels (int) out_channels (int) kern...
d6e67a6d48c81e128b4a91c52c2b6db176f4408b
682,694
def get_interpolated_row(df, time): """ for float types it linearly interpolates between two pandas dataframe rows and returns the interpolated row, for all other types it takes the nearest value; extrapolates the dataframe using first/last row :param df: pandas dataframe or series containing time series profiles ...
1f652680b352ba15d8be43ddcbe17ff9e7f1eec3
682,696
import re def encode(name, system='NTFS'): """ Encode the name for a suitable name in the given filesystem >>> encode('Test :1') 'Test _1' """ assert system == 'NTFS', 'unsupported filesystem' special_characters = r'<>:"/\|?*' + ''.join(map(chr, range(32))) pattern = '|'.join(map(re.es...
1c8df18bde7535b8d7729bc708fd041236bd10fd
682,697
from itertools import tee def pairs(iterable): """ Return a new iterable over sequential pairs in the given iterable. i.e. (0,1), (1,2), ..., (n-2,n-1) Args: iterable: the iterable to iterate over the pairs of Returns: a new iterator over the pairs of the given iterator """ # lazil...
8b33a15cfabff0940a47d1634ea1a9a7c97882be
682,698
def post_node(path, root, request, node): """ Function to post-process requests for node view. It is used to post-process the node. """ return node
275d8341514b4d358ef18cbebd520454d4f8a04b
682,699
import re def convert_spaces_and_special_characters_to_underscore(name): """ Converts spaces and special characters to underscore so 'Thi$ i# jun&' becomes 'thi__i__jun_' :param name: A string :return: An altered string Example use case: - A string might have special characters at the end when t...
1317911480df2d7c93ef02086c747bd126e615ad
682,700
def retrieveHost(): """ Retrieve the 3d host application where the script is running. @rtype: string @return: the name of the host, ie blender, maya or c4d """ global host host='' try : host = 'c4d' except : try : host = '3dsmax' except: ...
1825d3a389c4772f6768dcd4b7010b7f4549c52d
682,702
import subprocess import json def json_from_task_process(task_query): """ read input from taskwarrior via stdin, return list of dictionaries. """ output = subprocess.check_output(task_query.split(' ')) tasks = ','.join(str(output, 'utf-8').split('\n')[:-1]) return json.loads('[' + tasks + ...
0a1739ec9d031a026369a31ed50804401c484499
682,703
def uid_already_processed(db, notification_uid): """Check if the notification UID has already been processed.""" uid = db.document(notification_uid).get() if uid.exists: return True else: return False
81aa82bb9d18188d34dcbb4fb599b90cd741cddf
682,704
def count_matched_numbers(a:list, b:list): """ Write a function that takes two lists as parameters and returns a list containing the number of elements that occur in the same index in both lists. If there is not common elements in the same indices in both lists, return False Example: >>> count_matched_numbers([1,...
23713c31f4eef35feecce17aed82eeb63fe30144
682,706
import binascii def from_bytes(bytes): """Reverse of to_bytes().""" # binascii works on all versions of Python, the hex encoding does not return int(binascii.hexlify(bytes), 16)
55c3984c2b9c9ad8b0ea8c4a821eee27bf2e3f63
682,707
import string def filter_word(word): """https://github.com/gonenhila/gender_bias_lipstick/blob/master/source/remaining_bias_2016.ipynb""" def has_punct(w): if any([c in string.punctuation for c in w]): return True return False def has_digit(w): if any([c in '012345678...
3fc078ce788f479151d6f18b236b9ed8329dec64
682,709
def runningMean(oldMean, newValue, numValues): # type: (float, float, int) -> float """ A running mean Parameters ---------- oldMean : float The old running average mean newValue : float The new value to be added to the mean numValues : int The number of values i...
eb1fc1b59f2f1a81ef01347e6cde968e2bd01bbd
682,710
import math def get_ore(react, sol, amount=1): """return the amount of ore to produce a specific amount of Fuel""" requeriments = {"FUEL": amount} while True: try: need, need_amount = next( (n, i) for n, i in requeriments.items() if n != "ORE" and i > 0) except:...
1db2a39e11f8bb0b2f483dd362ce45e106412965
682,711
from typing import Tuple from typing import Optional def validate_parse_directions(verb: str, direction: str) -> Tuple[Optional[str], Optional[str]]: """Parse north, south, east, west to n, s, e, w and if the user types trash insult them and return a tuple like, (None, some validation message)""" if len(d...
0190c34bb619cd5cf5f56224492c2421b1766b11
682,712
import os def get_absolute_path_of_file(file_name, dir_name=None): """ Filenames in our .json config could be absolute or relative to the current working dir. This method tries to find the valid, full file path. :param file_name: :param dir_name: prefix, for example, the dirname of our .json file...
651c170c5810490e4a22ecd5c72bca7e92033cab
682,713
from pathlib import Path def tutorial_path(): """Path to the directory containing the tutorials.""" return Path(__file__).parents[2] / "tutorial"
924a70bc96dcda4dec2e63b86a1eefcd55178db1
682,714
def read_file_lines(filename): """Reads the lines of a file as a list""" with open(filename, mode="r") as f_in: return f_in.readlines()
c8cfaeddb71c9905125291ef27299b15d6f8e31c
682,715
def get_list_hashes(lst): """ For LZ to be more effective, than worst case 'fresh' raw dump, you need to lz encode minimum 4 bytes length. Break into 4 bytes chunks and hash Parameters ---------- lst : list Input list to form hashes from (lz haystack). Returns ------- enume...
cf8668ff2da8c130bbeb80fdc84ad1b9566fa7b6
682,716
def _parse_files(file_list): """Helper function to parse a list of files into a tuple for storage. :param list[str] file_list: A list of file names to parse and format. :rtype: list[str] :return: A list of tuples where the first value is the file name and the second value is None. """ return [(...
7314870520725864bb9d120e79e2a05ebdc2a36b
682,718
def remove_ext(filename: str, ext: str) -> str: """ Remove a file extension. No effect if provided extension is missing. """ if not ext.startswith('.'): ext = f'.{ext}' parts = filename.rsplit(ext, 1) if len(parts) == 2 and parts[1] == '': return parts[0] else: return...
2951ad8420f8b1b63951b76d976129632fa0b1d6
682,719
def parse_to_dicts(lines, containers): """ Parses a list of lines into tuples places in the given containers. The lists of lines has the following format token1: tval1 key1: val11 key2: val12 token1: tval2 key1: val21 key2: val22 :param lines: :param containers: a dictio...
b696159b7cb651723e18d6d84a0403d4a5513785
682,720
def is_number(s): """ Test if a string is an int or float. :param s: input string (word) :type s: str :return: bool """ try: float(s) if "." in s else int(s) return True except ValueError: return False
82c02c121ac863c9f6cbf034dec95abc7120f7cc
682,722
def get_locale_identifier(tup, sep='_'): """The reverse of :func:`parse_locale`. It creates a locale identifier out of a ``(language, territory, script, variant)`` tuple. Items can be set to ``None`` and trailing ``None``\s can also be left out of the tuple. >>> get_locale_identifier(('de', 'DE', Non...
a1c694d49fee5e021e534cf17b4b434b92207dc7
682,723
def template(text, **kwargs): """ Заполнение шаблона данными """ return text.format(**kwargs)
5b62995c8b54e274ad7162b7ebdbc1776d20d0d0
682,724
def to_channel_last(tensor): """Move channel axis in last position.""" return tensor.permute(1, 2, 0)
ba17da336aab38e6ccf7570cfb13fc36a6f02398
682,725
import base64 def generate_token(secret_key=None): """Generates token based on secret_key""" if secret_key is not None: token = base64.b64encode(secret_key.encode()).decode('utf-8') else: raise ValueError("Secret key cannot be None.") return token
41598a6254e1b9930de2c1d3dd5d8bb5ce381b65
682,726
def calcContactFrac(n, **kwargs): """Return the proportion of contact for a n-residue protein. This proportion is utilized in the DICOV as the prior probability of 3D contact, P(+), by a regression analysis of a training set of 162 structurally known protein sequences. [MW15] Mao W, Kaya C, Dutta A...
032e2749f3d01de53c98de5dc79654f702f0c459
682,727