content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def parse_ingredients(raw_ingredients): """Parse individual ingredients from ingredients form data.""" ingredients = [] for ingredient in raw_ingredients.split("\r\n"): if ingredient: ingredients.append(ingredient) return ingredients
e76e6dc4183c147870f12f2c4af7b05ae8c1847f
688,554
def S_self_operate_values(_data_list, _step=1, _operation=1): """ Apply arithmetic operation on data samples themselves step parameter is used to define how many data points to skip for calculating accelerated values _operation parameter is used for selecting one of the operations (1: addition, 2: subtr...
8d84dd4138ced3e59974b7f8f7ef3365d055a6d2
688,555
def check_dischar(s): """ ファイル名使用不可文字を含んでいるかチェックする。 """ seq = ('\\', '/', ':', ',', ';', '*', '?','"', '<', '>', '|', '"') for i in seq: if s.find(i) >= 0: return True return False
13b320838a994d5ea6169e5ea45289394fe539a3
688,556
def read(metafile): """ Return the contents of the given meta data file assuming UTF-8 encoding. """ with open(str(metafile), encoding="utf-8") as f: return f.read()
82135a6b680803c01cb9263e9c17b4c3d91d4516
688,557
import hashlib def get_ftp_md5(ftp, remote_file): """Compute checksum on remote ftp file.""" m = hashlib.md5() ftp.retrbinary(f'RETR {remote_file}', m.update) return m.hexdigest()
dc8bc74daba3262c56c969c480e5c1d5e112f2aa
688,560
def flatten_vuln_export(records): """A generator that will process a list of nested records, yielding a list of flat records""" def flatten_dictionary_field(_record, field, recursive=False): """ create new fields in _record for each key, value pair in _record[field] - prefix the new keys wi...
9a09e66858e484ceb4e3c61742e37fa609bab96a
688,562
def usd(value): """ Format value as USD """ return f"${value:,.2f}"
41e53fc59e6d679080a5cf86ce077c49d48d5375
688,563
from datetime import datetime def tic(): """ equivalent to Matlab's tic. It start measuring time. returns handle of the time start point. """ global gStartTime gStartTime = datetime.utcnow(); return gStartTime
d5c95e5c7c3e2f8b807045412898e4c06e06817f
688,564
def get_batch(file_h5, features, batch_number, batch_size=32): """Get a batch of the dataset Args: file_h5(str): path of the dataset features(list(str)): list of names of features present in the dataset that should be returned. batch_number(int): the id of the batch to be re...
0529b24644a23fd92bccb539b976edf799adc16a
688,565
def countingSort (A, k): """ Smarter Counting Sort """ L = [[] for _ in range(k)] for n in A: L[n].append(n) output = [] for i in L: output.extend(i) return output
5fba2f2daf9ac113068a67c0802054c00b56a84d
688,567
def headers(): """Fake Moltin API auth headers.""" return { 'Authorization': 'Bearer test_token', 'Content-Type': 'application/json', }
f81b07b79f77ed15b671184024596d827719cce1
688,569
import platform def is_mac(): """是否mac os操作系统""" return 'Darwin' in platform.system()
c5c810febab6426effe09f69d03611479f9f9723
688,570
import random def randhex() -> str: """Returns random hex code as string""" return "#" + "".join(random.choices("ABCDEF123456", k=6))
8edf53c33bd1264de85616ab836abf652e3d95fe
688,571
def has_log_message(caplog, message=None, level=None): """Check caplog contains log message. """ for r in caplog.records: if level and r.levelname != level: continue if not message or message in r.getMessage() or message in r.exc_text: return True return False
e576c125b2738a0239a86deb49b9a95c5ee07953
688,572
def split_byte_into_nibbles(value): """Split byte int into 2 nibbles (4 bits).""" first = value >> 4 second = value & 0x0F return first, second
082f0526001e5c7b2b6093861250a5d2c2634cf7
688,573
def lombardi(w, r): """ Conservative for low reps. Optimistic for high reps. """ return w * r**0.10
29507dafa43ff3813fbc518b86afffc597a24e87
688,574
def filter_forwards(args, exclude): """ Return only the parts of `args` that do not appear in `exclude`. """ result = [] # Start with false, because an unknown argument not starting with a dash # probably would just trip pip. admitted = False for arg in args: if not arg.startswith('-'): ...
7dbb54b7a31ece597b81e7d29cc7f316d9e51300
688,575
def _count_spaces_startswith(line): """ Count the number of spaces before the first character """ if line.split("#")[0].strip() == "": return None spaces = 0 for i in line: if i.isspace(): spaces += 1 else: return spaces
79276ac710bf290baeeb84a4a064e03308ea6548
688,576
def d2var_type_sort(_entry): """ `(None, None, None)` from d2varmap entry.""" # Sort and type may be provided later in a D2Cvardecs. return (None, None, None)
a2e547c4564c73cc5169a1da0e2b558ec5d16f04
688,577
import json def load_config(file_full_path): """Loads a JSON config file. Returns: A JSON object. """ with open(file_full_path, 'r') as f: conf = json.load(f) return conf
1af1a2f75ad9f1dd2291991c96509a618357d46a
688,578
from typing import Iterable def get_proc_name(cmd): """ Get the representative process name from complex command :param str | list[str] cmd: a command to be processed :return str: the basename representative command """ if isinstance(cmd, Iterable) and not isinstance(cmd, str): cmd = ...
f737faf2866083fd2bbaf65e52effe84a8e86cbc
688,579
import ssl def parse_url(url): """Parse a Elk connection string """ scheme, dest = url.split("://") host = None ssl_context = None if scheme == "elk": host, port = dest.split(":") if ":" in dest else (dest, 2101) elif scheme == "elks": host, port = dest.split(":") if ":" in des...
c07f0582d0a22f95a4818c9dc1aa2e35b0749ab6
688,581
def create_df_quartier(data, data_global, columns_from_global, quartier): """Cette fonction crée et renvoie la dataframe contenant toutes les observations pour un quartier.""" df = ( data[data["Quartier_detail"] == quartier] # Pour pouvoir ensuite grouper sur la date, on la retire de l'index...
57b021e49756c3e4ecb85b16d1de3ddd70030d4d
688,582
import hashlib def generate_idempotency_key(payload): """ An idempotency key is a unique value generated by the client which the server uses to recognize subsequent retries of the same request. This is not the only correct way to generate an idempotency key. You have to make your own implemen...
833fa1955b2b6d86ea3f2e74d1de426a743eb455
688,583
import socket def is_port_open(port_num): """ Detect if a port is open on localhost""" sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) return sock.connect_ex(('127.0.0.1', port_num)) == 0
8ee5e4674a2c4444448208d0e8194809665c8014
688,584
from typing import Union from pathlib import Path from typing import Tuple def get_paths(base_path: Union[str, Path]) -> Tuple[Path, Path]: """ Get fsh input and output paths from base path. :param base_path: Base path :return: FSH input path, FSH output path """ return ( Path(base_pa...
6b4ac2a24a5cdbaec8b39c7232d1cbd14aeb2770
688,585
def multiply(x, y): """ Multiplies two number :param x: first factor :param y: second factor :return: product of two numbers """ return x * y
462da76f8fbabb8b51b0edfacedbab23c44b1b19
688,586
import numpy as np def calc_mean_midstance_toe_angles(toe_angles, mid_stance_index): """ calculated the mean of the three tow angles at midstance""" #print("\nlength of toe_angles: ", len(toe_angles)) if len(toe_angles) > 2: mean_value = np.mean([toe_angles[mid_stance_index - 1], ...
22c348e78b6c45b22883efceefc3560af94c8d51
688,587
import json def inline_json(obj): """ Format a python object as JSON for inclusion in HTML. Parameters: obj: A python object that can be converted to JSON. Returns: An escaped :term:`native string` of JSON. """ return json.dumps(obj).replace("</script", r"<\/script").replace(...
a0062821cd61674b182e41c913bb248b6ade7a35
688,588
from typing import Dict def calculate_score(tf_dict: Dict[str, Dict[str, float]], idf_dict: Dict[str, float]) -> Dict[str, Dict[str, float]]: """Calculates tf*idf score""" for doc_id in tf_dict: for token in tf_dict[doc_id]: idf_value: float = idf_dict[token] tf_value: float = ...
eff4920f53906791844cda5b4fdb1fabfd284ba6
688,589
def readCols(cols_file): """ Read a .cols file (normally correspondingly to a .dm file) and return two dictionaries: word:index and index:word. In the .cols file, the line number is used as index. :param cols_file: str -- file path to a list of words (words' line numbers are their index) :return: {i...
8dc1b9ffb1f339f76aea30675f3b73ace21c51cf
688,590
def documents_return(ordered_matrix, document_dataframe): """ For a given document ID, returns the document file name. :param ordered_matrix: A matrix in row value form tuple :param document_dataframe: The original dataframe with the documents :return: List of the name of the files """ docu...
67d5334de606a2d45d06fe533e2881f9f0fadbbd
688,592
def _MakeDetailedHelp(include_vpn): """Make help, parameterized by inclusion of information about vpn.""" vpn_hop = ' ``--next-hop-vpn-tunnel\'\',' if include_vpn else '' return { 'brief': 'Create a new route', 'DESCRIPTION': """\ *{command}* is used to create routes. A route is a rule that...
0a0dde3bf5e341d7b1e691cccc75521f4abd40c7
688,593
def get_invalid_user_credentials(data=None): """ Returns error response for invalid user credentials :param str data: message :return: response :rtype: object """ response = {"status": 401, "message": "Invalid user credentials.", "data": data} return response
67ee7eec77997a207041d56457c806083d718e14
688,594
def iterate_parameters(parameters, default, count): """ Goes through recursively senstivity nested parameter dictionary. Args: paramters (dict): nested dictionary default (dict): default parameter dictionary count (int): number of scenarios """ for key, value in parameters.items...
2add1e8dacbaf72bf0302ac74c915d5293ce7600
688,596
from typing import Mapping def item_iter(obj): """ Return item (key, value) iterator from dict or pair sequence. Empty seqence for None. """ if obj is None: return () if isinstance(obj, Mapping): return obj.items() return obj
3572377a4debf0e0346f2423f29a527b2e903543
688,597
import torch def mean_std_integrand(fx, px): """Compute the expectation value and the standard deviation of a function evaluated on a sample of points taken from a known distribution. Parameters ---------- fx: torch.Tensor batch of function values px: torch.tensor batch of PDF...
11be2e474090d9c29adf1f4f75db39c54537e51e
688,599
def start_ind(model, dbg=False): """ equation 1 in the paper (called i_0): returns the first index of the w vector used in the random power law graph model """ assert model.gamma > 2 #if gamma=2, this returns 0 num_nodes = model.num_nodes max_deg = model.max_deg avg_deg = model.avg_deg ...
aa8483b666d81840c20ec693fed389529d8c7aac
688,600
import time def test(odrv, axis): #Andrew Byers is trying to work on it :) """ Runs a test function through the ODrive. 50% duty cycle square wave with a 2-second period and 0,2*pi radian amplitude. Runs for 30 seconds. NOTE: must convert from radians to encoder counts! """ for i in range...
8f029b05c745fc7c1e78d1fdb011107606f9d7d7
688,601
def get_nap_starts(db, cl): """returns only the NapStarts rows that are not connected to a Nap""" return db.session.query(cl).filter(cl.nap==None).all()
bac7f1ef46ac646cdf3ad0af3d32390803c94924
688,602
def _GetDisplayRange(old_end, rows): """Get the revision range using a_display_rev, if applicable. Args: old_end: the x_value from the change_point rows: List of Row entities in asscending order by revision. Returns: A end_rev, start_rev tuple with the correct revision. """ start_rev = end_rev =...
ea5d11507fd49b5f29c0954436159ac6b9de669e
688,603
import base64 import six def serialize(obj): """Serialize the given object :param obj: string representation of the object :return: encoded object (its type is unicode string) """ result = base64.urlsafe_b64encode(obj) # this workaround is needed because in case of python 3 the # urlsafe_b...
c7a7d2362d6c4cc194495af77d5f09991ed4b2ed
688,604
def get_transcript(**kwargs): """ get_transcript(parsed=JSON string) parameters: JSON string returns: string containing the transcript """ result = "" # # Run through the json document looking for the results item # parsed = kwargs['parsed'] for k,v in parsed.items(): ...
f196d061e601052f360f95036011cc0ae07adc41
688,605
from typing import Counter def safe_mode(iterable): """ Like taking the mode of the most common item in a sequence, but pick between one of the two most frequent if there is no unique mode. :param iterable: :return: """ items = sorted(Counter(iterable).items(), reve...
64e0adde6cbd3d15c726d8b318c651df19866f72
688,606
def get_vocab_from_counter(counter, min_occur, max_size): """ sort vocab and truncate it based on frequency """ selected_tokens = [w for w in counter if counter[w] >= min_occur] selected_tokens = list( sorted(selected_tokens, key=lambda x: -counter[x])) idx2word = selected_tokens id...
911452c5a0f57747716c08cbeef57f2581f42a1e
688,607
import requests from bs4 import BeautifulSoup def create_soup(url): """ This function takes a url and creates a soup for us to work with""" html = requests.get(url).text soup = BeautifulSoup(html, "html5lib") return soup
87012f1838281e4c82fc71176ec2095301e5c4fc
688,608
def rad2equiv_evap(energy): """ Converts radiation in MJ m-2 day-1 to the equivalent evaporation in mm day-1 assuming a grass reference crop using FAO equation 20. Energy is converted to equivalent evaporation using a conversion factor equal to the inverse of the latent heat of vapourisation (1 ...
7780ca2fc42cbbb1814aa5899aa1c2294453f45d
688,609
import json def to_sentiment_json(doc_id, sent, label): """Convert the sentiment info to json. Args: doc_id: Document id sent: Overall Sentiment for the document label: Actual label +1, 0, -1 for the document Returns: String json representation of the input """ j...
0c8e699df6649a2c5205bbba817cc0bcbe70768f
688,610
def to_ms(ip_str): # FIX ME """Convert a HH:MM:SS:MILL to milliseconds""" try: #ip = ip_str.split(':') hh, mm, ss = ip_str.split(':') hh = int(hh) * 60 * 60 mm = int(mm) * 60 ss = int(ss) except ValueError: hh = 0 try: mm, ss = ip_str.split...
dc865764975984c5d795752a4ac71620daa27dc8
688,612
import sqlite3 def needs_sqlite(f, self, *a, **kw): """return an empty list in the absence of sqlite""" if sqlite3 is None or not self.enabled: return [] else: return f(self, *a, **kw)
78fd36546c26465c9c0fc1abe9c9316dd37ac1b8
688,614
def calculate_seed(zone_1_seed, amplified): """This function calculates the seed based off the first floor seed""" # seed.add(0x40005e47).times(0xd6ee52a).mod(0x7fffffff).mod(0x713cee3f); # Stolen from Alexis :D add1 = int("0x40005e47", 16) mult1 = int("0xd6ee52a", 16) mod1 = int("0x7fffffff", 16) ...
8dc13b6951044af859945dea459d030357d46c7c
688,615
def get_top_matches(matches, top): """Order list of tuples by second value and returns top values. :param list[tuple[str,float]] matches: list of tuples :param int top: top values to return """ sorted_names = sorted(matches, key=lambda x: x[1], reverse=True) return sorted_names[0:top]
53fc953fe528833b8dbf6e4d8ffc6f3437f3b565
688,617
import os def get_world_size(required=False): """Get world size from environment.""" if 'MV2_COMM_WORLD_SIZE' in os.environ: return int(os.environ['MV2_COMM_WORLD_SIZE']) if 'OMPI_COMM_WORLD_SIZE' in os.environ: return int(os.environ['OMPI_COMM_WORLD_SIZE']) if 'SLURM_NTASKS' in os.env...
d980fa850630d04476c7e0fb34be629a834f5d92
688,619
def is_input_topic(topic, device_id, module_id): """ Topics for inputs are of the following format: devices/<deviceId>/modules/<moduleId>/inputs/<inputName> :param topic: The topic string """ if "devices/{}/modules/{}/inputs/".format(device_id, module_id) in topic: return True return...
adab38ad8c7be86b69f0cabf65452706b10453f3
688,620
import os def setResDir(env_var = "SL_RESULTS"): """Set the results directory :param env_var: Environment variable to reference :param type: string :returns: path to results directory :rtype: string """ results_dir = os.environ[env_var] assert os.path.isdir(results_dir), "Results dir...
c592fdb19308c5249346ca26ed5a002191302d4b
688,621
def parseKeyWordArgs( arglist ): """ The function takes a list of strings of the shape bla=2 bli='blub' and sets fills a dictionary with them which then is returned. """ arg_dict = {} for arg in arglist[1:]: # check that argument has the equal sign index = arg.find('=') ...
45839095c6841ae9a0f586ebbdd5bede14bca5d7
688,622
from typing import Set from typing import Tuple from typing import Dict from typing import List def partition(tags: Set[Tuple[str, int, int]], no_frames: int, cost_table: Dict[str, float] = dict(), default_cost: float = 1, penalty: float = 2) -> List[int]: """partition() takes annotations of each frame, penal...
4bfbe8fe96c41adb09aaaed1475238d6e8458fde
688,623
def errmsg(r): """Utility for formatting a response xml tree to an error string""" return "%s %s\n\n%s" % (r.status, r.reason, r.raw)
611f77e7bf8f674189d57ee4090ea4fe8b39daac
688,624
def respond_with_error(func): """Wraps func so that it writes all Exceptions to response.""" def get_func(self): """Handle a get request respond with 500 status code on error.""" try: func(self) except Exception as excep: # pylint: disable=broad-except self.respo...
92e40a7e45fea9d97243753c6834fc0d0338127b
688,625
def list_pretrained_models(workspace): """列出预训练模型列表 """ pretrained_model_list = list() for id in workspace.pretrained_models: pretrained_model = workspace.pretrained_models[id] model_id = pretrained_model.id model_name = pretrained_model.name model_model = pretrained_mode...
7a44d3676d8dc2c11ea9d5bc675038af04159223
688,626
def GetCounterSetting(counter_spec, name): """ Retrieve a particular setting from a counter specification; if that setting is not present, return None. :param counter_spec: A dict of mappings from the name of a setting to its associated value. :param name: The name of the setting of interest. :retur...
86e06b7c023d401150ca3ecaf16dfbbf2ed53288
688,627
def jaccard_similariy_index(first, second): """ Returns the jaccard similarity between two strings :param first: first string we are comparing :param second: second string we are comparing :return: how similar the two strings are """ # First, split the sentences into words tokenize_firs...
43b33620b5c2b93386c297b7131b482189fcac18
688,628
def scale(score, omax, omin, smax, smin): """ >>> scale(2871, 4871, 0, 1000, 0) 589 """ try: return ((smax - smin) * (score - omin) / (omax - omin)) + smin except ZeroDivisionError: return 0
b24373f6cc22fb14a3e7873b242f9ee24a3bafa1
688,630
def add_prefix_un(word): """ :param word: str of a root word :return: str of root word with un prefix This function takes `word` as a parameter and returns a new word with an 'un' prefix. """ prefix = 'un' return prefix+word
f454c3e787b5e64eae55ef86cdc03e1e8b8bb064
688,631
from typing import List import re def parse_dot_argument(dot_argument: str) -> List[str]: """ Takes a single argument (Dict key) from dot notation and checks if it also contains list indexes. :param dot_argument: Dict key from dot notation possibly containing list indexes :return: Dict key and possibl...
cf002a9f8eeca9f54641c5f54145228c9ce65dfd
688,633
def apply_building_mapping(mapdict, label): """ Applies a building map YAML to a given label, binning it into the appropriate category. """ for category in mapdict: #print(mapdict, category, label) if label in mapdict[category]['labels']: return category return "house"
d04c8b012975fa76ed08a1bd160c1322ecaeb3af
688,636
import re from typing import Tuple from typing import List def incorrect_regex(patterns: Tuple[str, ...]) -> List[bool]: """ >>> incorrect_regex([r'.*\\+', '.*+']) [True, False] """ booleans = [] for pattern in patterns: try: booleans.append(bool(re.compile(pattern))) ...
960de206be998da18185a56b0a43a8aad7ad8540
688,637
def preprocess_text(raw_text,nlp): """ Preprocesses the raw metaphor by removing sotp words and lemmatizing the words Args: raw_text: (string) the original metaphor text to be processed nlp: (spacy language object) """ tokens=[] for token in nlp(raw_text): if not token.is_...
6b65f6f97a54980fdb310cf61a98564cfb67f172
688,638
def get_major_version(version): """ :param version: the version of edge :return: the major version of edge """ return version.split('.')[0]
c17e1b23872a25b3ce40f475855a9d1fe4eef954
688,639
def get_min_max_words(input): """ returns the words with the least and maximum length. Use min and max and pass another function as argument """ return (min(input,key=len),max(input,key=len))# replace this calls to min and max #(sorted(input,key=len)[0],sorted(input,key=len)[len(input)-1])------...
0c7afec3956dd6efe7a018826f6903126ca3fbcb
688,640
def ordinal(number): """ Get ordinal string representation for input number(s). Parameters ---------- number: Integer or 1D integer ndarray An integer or array of integers. Returns ------- ord: String or List of strings Ordinal representation of input number(s). Return a string if inpu...
dcd914cbb313859779347c652c4defbaa4d7983d
688,641
import re def remove_accents(text): """Removes common accent characters.""" text = re.sub(u"[àáâãäå]", 'a', text) text = re.sub(u"[èéêë]", 'e', text) text = re.sub(u"[ìíîï]", 'i', text) text = re.sub(u"[òóôõö]", 'o', text) text = re.sub(u"[ùúûü]", 'u', text) text = re.sub(u"[ýÿ]", 'y', te...
e0f80556aff358f8dc1f9f20a43ce00ca190407a
688,642
def valid_scrabble_word(word): """Checks if the input word could be played with a full bag of tiles. Returns: True or false """ letters_in_bag = { "a": 9, "b": 2, "c": 2, "d": 4, "e": 12, "f": 2, "g": 3, "h": 2, "i": 9, ...
4ef648df6147f9d9a593b0459f6e803aff9150e5
688,643
def medal_tally(df): """ this is medal wise tally, duplicates have been removed because in some games there are group medals """ medal_tally = df.drop_duplicates( subset=['Team','NOC','Games','Year','City','Sport','Event']) medal_tally=medal_tally.groupby('region').sum()[['Gold', 'Silver', 'Bronze']...
baf9016bd47bb601a3da5a2d76054012f2a33331
688,644
def get_max_drawdown(c_values): """ 根据累计价值计算最大回撤 Args: c_values (list): 累计价值列表 Returns: float: 最大回撤 """ drawdown = [1 - v/max(1, max(c_values[:i+1])) for i, v in enumerate(c_values)] return max(drawdown)
0329d95b3053b4678d224011f0aecf69c8e31062
688,645
def cluster_list(list_to_cluster: list, delta: float) -> list: """ Clusters a sorted list :param list_to_cluster: a sorted list :param delta: the value to compare list items to :return: a clustered list of values """ out_list = [[list_to_cluster[0]]] previous_value = list_to_cluster[0] ...
5ebde99189c7a9008cf1c362d18f7dff9b2617c0
688,646
def external_pressure(rho, g, d): """Return the external pressure [Pa] at water depth. :param float rho: Water density [kg/m^3] :param float g: Acceleration of gravity [m/s/s] :param float d: Water depth [m] """ return rho * g * d
1b2aea7030561e17f331be0f04b1cfd85072a862
688,647
import struct def bytes_2_long(long_bytes_string, is_little_endian=False): """ 将8字节的bytes串转换成int。 :param long_bytes_string: :param is_little_endian: :return: """ # 小端数据返回 if is_little_endian: return struct.unpack('<q', long_bytes_string)[0] # 大端数据返回 return struct.unpack...
cdf52df95981482f08408f0853b7474be65bbe92
688,649
def get_node_composer_inputs(equivalent_quantity_keys, parsed_quantities, quantity_names_in_node_dict): """ Collect parsed quantities for the NodeCompoer input. When multiple equivalent quantities are found, the first one found in the equivalent_quantity_keys is chosen. """ inputs = {} for...
e907eb8887c5aedee7fece6e0b3c573e602eddcc
688,650
def sort_words(arguments, words): """ Takes a dict of command line arguments and a list of words to be sorted. Returns a sorted list based on `alphabetical`, `length` and `reverse`. """ if arguments.get('--alphabetical', False): words.sort() elif arguments.get('--length', False): ...
a6c0af4fe254c24d0f6d977e3ff80457ca4da2f0
688,651
def dict_to_string(in_dict): """ *** DEPRECIATED *** Converts a dicionary to a string so it can be saved in a hdf5 file. Args: in_dict (dict): Dictionary to convert. Raises: TypeError: If the type of a value of in_dict is not supported currently. Supported types are string, float a...
fb25b050a134ae2e355195f8e22f2a7d6d04c2f9
688,652
def generate_index_list(original_string_list, spoken_string_list): """ The output of this goes to generate_match_indeces to be "permutated" :param original_string_list: list of words :param spoken_string_list: list of words :return: index list """ return [[index for index, value in enumerate...
0476e0931f9a42529311811f0bcfc845bdb3d73d
688,653
def source_from_url(link): """ Given a link to a website return the source . """ if 'www' in link: source = link.split('.')[1] else: if '.com' in link: source = link.split('.com')[0] else: source = link.split('.')[0] source = source.replace('https...
b7b3a88dc4093ba2e793911fb53f14891d22b554
688,654
def _check_type(type_, value): """Return true if *value* is an instance of the specified type or if *value* is the specified type. """ return value is type_ or isinstance(value, type_)
4ff8ce08d75f6256939f98a20b9e85181ee5492d
688,655
import importlib def get_callback_class(hyperparams): """ Get one or more Callback class specified as a hyper-parameter "callback". e.g. callback: stable_baselines3.common.callbacks.CheckpointCallback for multiple, specify a list: callback: - utils.callbacks.PlotActionWrapper ...
1714c5109b278adac6030e2d788800189ff09ebd
688,656
def area_under_curve(x, y): """Finds the area under unevenly spaced curve y=f(x) using the trapezoid rule. x,y should be arrays of reals with same length. returns: a - float, area under curve""" a = 0.0 for i in range(0, len(x) - 1): # add area of current trapezium to sum ...
25f872927add3c74d325b1bf1e2e96c9bef9fdca
688,657
import requests def get_from_gitlab_no_auth_raw(url): """ """ return requests.get(url)
65a8ec76df7f21405b809300752bb6f82790cb5c
688,658
def newman_conway(num): """ Returns a list of the Newman Conway numbers for the given value. Time Complexity: O(n) because the number of calculations performed depends on the size of num. Space Complexity: Space complexity is also O(n) becuase newman_conway_nums array to store sequence valu...
e595fd25e5ed6718339431b20e22b00ae504e5be
688,659
def _get_position_precedence(position: str) -> int: """Get the precedence of a position abbreviation (e.g. 'GK') useful for ordering.""" PLAYER_POSITION_PRECEDENCE = { "GK": 1, "LB": 2, "LCB": 3, "CB": 4, "RCB": 5, "RB": 6, "LDM": 7, "CDM": 8, ...
b86795e5b21f5238e534eca84f5b9a1c683bb5b6
688,661
import torch def img_grid_pad_value(imgs, thresh = .2) -> float: """Returns padding value (black or white) for a grid of images. Hack to visualize boundaries between images with torchvision's save_image(). If the median border value of all images is below the threshold, use white, otherwise black (whi...
02f209e927d55a1505396caa88ca4084c68bfd60
688,662
def is_valid_executor(exe, self_platform): """Validates that the executor can be run on the current platform.""" if self_platform not in exe["supported_platforms"]: return False # The "manual" executors need to be run by hand, normally. # This script should not be running them. if exe["exec...
9e8bd4fe4c1a79edfec431b9bec4ef0869ed2d79
688,663
def scrape_page(driver): """ This method finds all hrefs on webpage """ elems = driver.find_elements_by_xpath("//a[@href]") return elems
739d620d5db061542dedb686f78193b5d39ebd4d
688,665
def v1_deep_add(lists): """Return sum of values in given list, iterating deeply.""" total = 0 lists = list(lists) while lists: item = lists.pop() if isinstance(item, list): lists.extend(item) else: total += item return total
005297fc36dec4dbe471229a100ce822955ff36b
688,666
def get_username_from_login(email): """ Create a public user name from an email address """ return str(email).split('@')[0].lower().replace('.','-').replace('_','-')
e1d0cf28ba21bffb9ccd67a483738f2f75deb09c
688,667
def ngrams(sequence, N): """Return all `N`-grams of the elements in `sequence`""" assert N >= 1 return list(zip(*[sequence[i:] for i in range(N)]))
096a7ed58667889d0be62aa4e0b44133c753c921
688,668
def pollutants_per_country(summary): """ Get the available pollutants per country from the summary. :param list[dict] summary: The E1a summary. :return dict[list[dict]]: All available pollutants per country. """ output = dict() for d in summary.copy(): country = d.pop("ct") ...
88261062fb238a5eea9d01909f0b2be0363ed1f8
688,669
import string def read_cstring(view, addr): """Read a C string from address.""" s = "" while True: c = view.read(addr, 1) if c not in string.printable: break if c == "\n": c = "\\n" if c == "\t": c = "\\t" if c == "\v": c = "\\v" if c == "\f": c ...
7f9fbbe8ca2ae4023ee581bacac1110cc0995e09
688,670
def internal(key, default=None): """ property factory for internal usage fields """ def _getter_(self): if key in self.internal: return self.internal[key] return default def _setter_(self, val): self.internal[key] = val return property(_getter_, _setter_)
e86a8ae590e7438684e3cabb7103292bcdb9ac9c
688,671
def parse(fo): """Parses file-like or file object. Also this method is used in API classes as an imported library. Args: fo: The file-like or file object to parse. Returns: A dict with jobs found. See: https://docs.python.org/3/glossary.html#term-file-object """ j...
eaf14e31968499db45b154ceaba790f845422715
688,672
def make_text(content, css_class=None): """ :param content: :param css_class: :return: """ text = { 'type': 'text', 'text': content } if css_class: text['class'] = css_class return text
1701b211d22f02a5b6980ac81765911673b5a84b
688,673