content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def add_total_and_padding(src, field ,name): """ src - rows to add field - dict field to use as total name - name to display in total row return - list with total row added to the last and a 1 empty row for padding at top and bottom """ total = list(filter(lambda...
63ee44de0e32e013bae0173ea5bcf98bf04396e4
645,043
def convert_keywords_to_uppercase(instring): """ Converts any SQL special keywords to uppercase """ # convert string to list of individual words MyInWords = instring.split(' ') MyOutWords = [] # list of SQL keywords to treat differently keywords = 'absolute action ada add all allocate a...
f571cf943620d735d96a25a1df51c72d16fa27f5
645,044
def compute_accuracy(predictions, labels): """ Compute classification accuracy with a fixed threshold on distances. """ labels = predictions < 0.5 accuracy = (labels==predictions) return accuracy.mean()
c683ce3d5d7c93da220d5fd1425a959a77acf66a
645,045
def fpr(fp: int, tn: int) -> float: """False Positive Rate computed from false positives and true negatives.""" return fp / (fp + tn) if fp + tn else 0.0
455610e45cad46e56dae87a71f0ec842763cbc05
645,046
import requests def paste(content): """Make a paste to hastebin.com.""" response = requests.post('http://hastebin.com/documents/', data=content.encode('utf-8')) response.raise_for_status() return 'http://hastebin.com/' + response.json()['key']
d3a80cc5f9e894dae54475720bc6e7af24f8bf44
645,047
def conv_packed_binary_string_to_1_0_string(s): """ '\xAF' --> '10101111' """ r = [] for ch in s: x = ord(ch) for i in range(7,-1,-1): t = (x >> i) & 0x1 r.append(t) return ''.join(map(lambda x: chr(x + ord('0')), r))
348cc84d483706cc764801384f0a52d9b3729d3b
645,048
import os import json import click import sys def load_template(): """ Load the default template for the python package """ skeleton = os.path.join(os.path.dirname(__file__), 'templates', 'default_structure.json') try: with open(skeleton, 'r') as template: ...
a83cb9ddddcb1f56072d73b2eeb0a697bdaff673
645,049
def rollout(env, render_mode=False): """ play one agent vs the other in modified gym-style loop. """ obs = env.reset() done = False total_reward = 0 while not done: # action, _states = policy.predict(obs, deterministic=True) obs, reward, done, _ = env.step(0) total_reward += reward if ren...
915c576b8c5e6d8aa3d73c86c2daf55715131592
645,050
def make_row(table, row, model_name): """ Parameters: ----------- table : `collections.defaultdict` The dictionary to fill. row : `pandas.DataFrame` The dataframe to get the data from. model_name : `str` The model name. Returns: -------- table : `collecti...
e0537ee89dfc8162c6576a9236b5c31e2030a3a7
645,051
def ascii64_paths(tnum): """ Return components of the path to the data for trigger `tnum`, both at the COSSC FTP site and locally: (group, fname, remote). group name of the group directory containing the trigger directory rfname name of the remote ASCII data file, "cat64ms.<tnum>" r...
133cd0e400c1cc215cb2c2f203cd4dc94f00018d
645,052
from typing import List import itertools def generate_partitions(num_elements: int, num_parts: int) -> List[List[int]]: """Generates partitions of num_elements into num_parts nonnegative parts. Args: num_elements: The number of things to permute (a nonnegative integer). num_parts: The number of groups to...
98fe5f3ed600d3b6a44174808f384896086fadc1
645,053
def dict_from_int(version_int): """Converts a version integer into a dictionary with major/minor/... info.""" d = {} rem = version_int (rem, d["pre_ver"]) = divmod(rem, 100) (rem, d["pre"]) = divmod(rem, 10) (rem, d["alpha_ver"]) = divmod(rem, 100) (rem, d["alpha"]) = divmod(rem, 10) ...
485cab922275f37c24d63bf672a22e639f4b2dcb
645,054
import requests def getInfo(router): """Extract the WAN information from the details page. GET /getpage.gch?pid=1002&nextpage=IPv46_status_wan2_if_t.gch """ info = requests.get(router + 'getpage.gch', params={ 'pid': 1002, 'nextpage': 'IPv46_status_wan2_if_t.gch' }) assert inf...
fe7e21d99f3f2ef4b49caa57dff8906ff1579e2e
645,055
def is_state_error(state_meta): """ Determines if the state resulted in an error. """ return not state_meta['result']
e8054b69257f15064fcd392ba33ad0f0c76fed37
645,056
def contact_sequence(data, pIDs): """ Given a pd.DataFrame with variables ['gID', 'pID', 'begin', 'end'], generate a contact sequence of events (j, i, t) where j is the group member being interrupted, i is the group member doing the interrupting, and t is the start time of the interruptive speech. Ignores non-i...
bb36b4bddefc094f036a32319a5cdf47b146005d
645,057
def choose_alt(attr, ob, kwargs): """If the declared class attribute of ob is callable then use that callable to get a default ob instance value if a value is not available in kwargs. @param attr: ob class attribute name @param ob: the object instance whose default value needs to be set @param...
24eeb51c907091190de1ee65be1e1c95d4ff0fa7
645,058
import time import copy import torch def train_model(nb_epoch, dataloaders, model, opt, criterion, device, scheduler=None): """ Function to train a model. Args: nb_epoch: number of epoch to train train_dsld: dataset loader for training model: model to optimize ...
f9cbbbf63c779d075bf4caaa56cae45a867b91c4
645,059
def split_param_filter_index1(s): """ Split a parameter name into the <string><number> components where <string> is the parameter name and <number> is the filter index (1-based). If there is no number at the end for a filter index, then return None for the second argument. Returns ---------...
b5c3356184c9bee35cbbeaf81c3de2915c67435b
645,060
def get_diffs(pulse_times, pulses): """ Returns a list of time differences between the pulse times given, corresponding 1 - for - 1 *** PARAMS *** pulse_time (list of strings): list of strings containing the exact time of the pulse. pulses (list of floats): list of floats of the exact time (...
5611be3d0a54e86beff2d115e49703f84be6a3c9
645,061
def get_maxdepth(input_table_A,input_table_B): """Get maximum depth between tables""" #gaps and overlaps maxlist=[] a= input_table_A['todepth'].unique().tolist() maxlist.append(a[-1]) b= input_table_B['todepth'].unique().tolist() maxlist.append(b[-1]) maxl=float(max(maxlist)) return ...
da62d281c611c08663ee3e9a05b3b0afba6d891a
645,062
import numpy def homog_scale_mtx(scale): """Generate a 4x4 numpy scaling matrix. :param float scale: scale multiplier """ return numpy.array([[scale, 0, 0, 0], [0, scale, 0, 0], [0, 0, scale, 0], [0, 0, 0, 1] ...
b6c54c0c7c8cf33d22c13221b48bf54d22d15b70
645,063
def comp_exact_match(refs, hyps): """ @param refs (list[list[str]]): list of reference sentences @param hyps (list[list[str]]): list of predicted sentences (hypotheses) @return em (float): average exact match value """ assert len(refs) == len(hyps) match = 0 for ref, hyp in zip(refs, hyp...
23a6425052b2ee3b1e9447459fae0cbbf47ac68d
645,064
def GetLeftEye(points): """ Returns left eye points. Args: points: Points Returns: Points """ eye = [] for i in range(6): eye.append(points[i + 36]) return eye
ca6b9a20084f913686ed4b642f6c168e348717ac
645,065
import torch def concat_without_padding(text_idx, cand_idx, use_cuda, null_idx=0): """ Concatenate two right padded tensors and move padding to the right. For example, if text_idx = [[1, 2, 3, 4, 0, 0 ]] and cand_idx = [[5, 6, 7, 8, 0, 0 ]]: Then result = (tokens, segments) where ...
59ae9ba64c9bee926b0d530043709f74f8ec2db7
645,068
def convtograyscale(rgb): """Conversion of RGB to grayscale. http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale :keyword seq rgb: sequence of rgb float values (0 to 1) :returns: Float for grayscale value """ return (rgb[0]*.3 + rgb[1]*.59 + rgb[2]*.11)
64666d8144189015805722bd35873351aca4707e
645,069
def get_hps(data): """ Get the name of all columns corresponding to hyperparameters """ return [c for c in data.columns if c.startswith("hp.")]
b600c2b5d79af3ae24c791c8723255d80baa1093
645,071
def compareDicts(dict1, dict2): """ Compare two dictionaries, returning sets containing keys from dict1 difference dict2, dict2 difference dict1, and shared keys with non-equivalent values, respectively. Parameters ---------- dict1 : dict dict2 : dict Returns ------- set, set, ...
3f1897193118d8ff16022b55570396dec2c289e9
645,072
import re def XmlTupleString_to_Dictionary(tuple_line): """Takes a line in the form of <Tuple key1="value1" key2="Value2" ...KeyN="ValueN" /> and returns a dictionary""" stripped_string=tuple_line.replace("<Tuple","") stripped_string=stripped_string.replace("/>","") pattern="(?<=\")(?<!,|:)\s+(?!,...
b2d1a09afb364d0ed953691ca412f0d223304e7f
645,073
import os def get_changing_percentileFiles(side, precision): """ Find the files which correspond to change percentiles Args: side (string): min/max, referring to the largest negative/positive changes, respectively precision (string): string representation of percentile precision Returns:...
39601803c3d9264b54fa92ae6f11cb0ac39a8a55
645,074
def API_fatal(description): """Create an API fatal error message.""" return {"status": "fatal", "error": description}
92b258f30c18c3cea6c8a462c729eca9c2e9da2d
645,076
def power(a, n: int): """Return `a` to the n-th power, uses exponentiation by squaring i.e square and multiply """ # Shortcuts are evaluated here to avoid code duplication if a == 0: if n > 0: return 0 # 0^n = 0 for n > 0 if n == 0: return 1 # a^0 = 1 (0^0 = 1 is a co...
9343404bf8c3a438e953f1fdedcf213318249e86
645,077
import unicodedata async def _get_all_intents(skills): """Get all skill intents and concatenate into a single markdown string.""" intents = [skill["intents"] for skill in skills if skill["intents"] is not None] if not intents: return None intents = "\n\n".join(intents) return unicodedata.n...
f498d90e5dca49350579ab882dfc3ed069cb31dd
645,078
def usage(pyfile): """ Usage """ return 'Usage: {} <groupname>'.format(pyfile)
4e5e8e31bd7e4fbc1f47a8fc58038334ecb884c9
645,079
def total_gross_income(responses, derived): """ Return the total gross income of both claimants """ try: claimant_1 = float(responses.get('annual_gross_income', 0)) except ValueError: claimant_1 = 0 try: claimant_2 = float(responses.get('spouse_annual_gross_income', 0)) exc...
8ca58266794d6b6ce1166ac50ad318ceafa8d30c
645,080
def gross_count(spec, c1, c2): """Returns total number of counts in a spectrum between two channels""" if c1 > c2: raise ValueError("c1 must be less than c2") if c1 < 0: raise ValueError("c1 must be positive number above 0") if c2 > max(spec.channels): raise ValueError("c2 must ...
154f0e45463d38bd8dfb6ab1f678ef2d1980410c
645,081
def get_app_full_path(app_path): """ Import app views module and get path, app_path like module.module or module ** Attributes ** * ``app_path`` (str): Module path: ``module.module``or ``module`` ** Returns ** application full path: like ximpia.xpsite """ parts = app_path.split('.') ...
fed0d7007b3cba4a6c09faff59e5d49fc7859faa
645,083
def get_check_class(id): """ Find check class matching `id` in the various registers. :param id: identifier for check (matches class name) [string] :return: class """ try: assert id.endswith("Check") return eval(id) except Exception: raise Exception("Cannot identify ...
1fad6c4aab10cbecb02cadb491c6561d82c3d2e6
645,084
import argparse def parse_args(): """ Creates the help menu and the command line options. """ parser = argparse.ArgumentParser( description = ''' Tool to get informations about domains from the database.''') parser.add_argument('domain', help = 'the domain to search f...
aedcf001007ee2306f9ae22bbdad6003da37fd45
645,085
def asbool(value, true=(b'true', u'true'), false=(b'false', u'false')): """Return string as bool if possible, else raise TypeError. >>> asbool(b' False ') False """ value = value.strip().lower() if value in true: # might raise UnicodeWarning/BytesWarning return True if value in fa...
3b043be4e6c479a16c9bc22f068ff47bc36ec11b
645,086
import os def GetModelPath(): """ Helper function: Get the relative /saved_models/ path Returns ../../saved_models/, or ./saved_models/, as appropriate """ # Try from the implementation directory: modelPath = "../../saved_models/" if not os.path.isdir(modelPath): # Try from the pr...
d9c88ae08b2f420bd6a8df49b75d7aa2d296c6d0
645,087
import re import copy def _getZoneData(line): """ Extract TecPlot formatted zone data from a line, return as two lists of keys and matching values. Attributes ---------- * ``line`` (`string`): string representation of a line in a TecPlot file Returns ---------- * `list` with all the names of zone properti...
3e69178dbaef3ffb9997462cbe97f6dd48be4d56
645,088
def SumMultipleDigits(ll,nd): """ sum of multiple digits >>int32, each number is put in a row list """ s=[] sumStr='' #make sure it is NOT same name with funciton sum!!! base=10 for col in range(len(ll[0])): s.append( sum([ll[row][col] for row in range(len(ll)) ]) ) for i in range...
e22204eafd258e7de0b4a0878924ca0b09143428
645,089
import hashlib def get_hash_string_of_numpy_array(array): """ Returns a 32 character long string that is a deterministic hash of a numpy array's data. """ return hashlib.md5(array.data.tobytes()).hexdigest()
62dd603c246f7351ddecf2f76c49a4f55becc285
645,090
import argparse def options(**kwargs): """Create an argparse.Namespace instance.""" kwargs.setdefault("color", "auto") kwargs.setdefault("output_file", None) kwargs.setdefault("tee", False) return argparse.Namespace(**kwargs)
7a7ebc7c2087450bd03762e7a1f84148b30544d4
645,091
def maskAngLT452(image): """ mask out angles >= 45.23993 Parameters ---------- image : ee.Image image to apply the border noise masking Returns ------- ee.Image Masked image """ ang = image.select(['angle']) return image.updateMask(ang.lt(45.23993)).set('sy...
2b310c0542b770858595c5fa027bddbb1c43da33
645,092
import re def is_interface_changed_state_log(device, interface): """ Verify interface didn't flap in the log Args: device (`obj`): Device object interface (`str`): Interface name Returns: result(`str`): verify result """ result = [] out = device.par...
931cce31e3e5c6a4c87a834fbb9173e063d84781
645,093
def prettyPrintResults(evaluationResults): """prettyPrintResults returns a string formatting the results of a simulation evaluation result""" output = "" for er in evaluationResults: message = ( f"Evaluated Action Name: {er['EvalActionName']}\n" f"\tEvaluated Resource name: {...
637846fb2e54922d20d912170cadd1b9552d43a9
645,094
def plot_wrapper(self, func, *args, cmap=None, values=None, **kwargs): """ Calls `~proplot.axes.Axes.parametric` if the `cmap` argument was supplied, otherwise calls `~matplotlib.axes.Axes.plot`. Wraps %(methods)s. Parameters ---------- *args : (y,), (x, y), or (x, y, fmt) Passed to `~m...
fcec48a978da8b653f71a1980032af88170cb551
645,095
from typing import List def max_profit(prices: List[int]) -> int: """ Find the maximum profit that can be made from buying and selling a stock once """ if prices is None or len(prices) < 2: return 0 min_price = prices[0] current_max_profit = 0 for price in prices: if pric...
a411fde1659aa187484e6fbea7633d41ffae8868
645,096
def element_to_apparent(element): """Create an apparent element from an element. Parameters ---------- element The element. Returns ------- A tuple (ElementType, Direction). """ return (element.element_type, element.direction)
9f9e3a6ce870e6aeef33dbe4fd1b6c8502a7458f
645,097
from operator import inv def perform_kron_reduction(z_primitive): """ Reduces the primitive impedance matrix to an equivalent impedance matrix. We break z_primative up into four quadrants as follows: Ẑpp = [Ẑaa, Ẑab, Ẑac] Ẑpn = [Ẑan] [Ẑba, Ẑbb, Ẑbc] [Ẑ...
b3f4616a6c3e5333bbda066cc9de27059000480c
645,098
def _fmt_string(array, float_format="{}"): """ makes a formatting string for a rec-array; given a desired float_format. Parameters ---------- array : np.recarray float_format : str formatter for floating point variable Returns ------- fmt_string : str formatting...
05f687ef5cd0121198e7e7fce74480fe9867e05a
645,099
def get_user(session): """Retrieve handle of logged in user.""" response = session.get("https://api.github.com/user") response.raise_for_status() user_data = response.json() user = user_data["login"] return user
b261e4aabfdb3a641a20ec3a6992f502f3b1b03e
645,100
import argparse def parse(options): """ Initialize the parser to read input """ # Initialize parser = argparse.ArgumentParser(description="Search the filesystem and summarize the existance of files output from "+ "the daily processing pipeline. Can specify spec...
43e1d11538744672df95143877e5919e2f45eab6
645,101
def subsample_leaf(any_df, x_df, split): """Reduces dataframes to data in leaf. Parameters ---------- any_df : Dataframe. Policyscores, indices or any other of same length as x. x_df : Dataframe. Policy variables. split : dict. Split information. Returns ------- polscore_df_red : D...
842c8ed67439fa21198d5e44caf0cb6a1e30cabf
645,102
def merge(left, right): """Merges two sorted sublists into a single sorted list.""" ret = [] li = ri =0 while li < len(left) and ri < len(right): if left[li] <= right[ri]: ret.append(left[li]) li += 1 else: ret.append(right[ri]) ri += 1 ...
88f8550ad67941d1956e67b28d9ed29017975dfb
645,103
def matrix_max(matrix): # SYFPEITHI NORMALIZATION """Returns the maximum attainable score for a pssm""" return sum([ max(value.values()) for _, value in matrix.items() ])
60f166ce15b844d3bf958d66ec6452e318a49561
645,104
def padding(corpus, logger=None): """ Performs padding on the already tokenized documents Args: corpus (list): A list of strings where elements are the tokens from your document. logger (Logger): Returns: A list of strings where elements are all at equal length """ ne...
bb160b021c5f8d92afe758cc2bf605837e060974
645,105
import random def random_colors(N): """ Generate random colors. To get visually distinct colors, generaate them in HSV space then convert it to RGB (Red Green Blue) param: N : Nomber of classes in the Frame """ random.seed(0) all_colors = [] for i in range(N): x, y, z = random.randint(0,255), random.ran...
9cdd91fafb1b38607bc7890004015e661f769a1f
645,106
def singleton(c): """ very simple singleton :param c: :return: """ instance = None def init(*args, **kwargs): nonlocal instance if not instance: instance = c(*args, **kwargs) return instance return init
38d3de12eeafa69439e20f54eef49992a06a9592
645,107
def create_pos_haplotype(chrom, a1_start, a1_end, a1_seq, a2_start, a2_end, a2_seq, ref, buf_len=0): """ Create haplotypes of two regions that are assumed to be overlapping """ start = min(a1_start, a2_start) end = max(a1_end, a2_end) buff = int((end - start) * buf_len) start -= buff end...
c7063f5671f4400059a015a4660a2a8132ed6819
645,108
import pickle def top_n_bigrams(pkl_file_name, N, shift=0): """ Returns a dictionary of form {bigram:rank} of top N bigrams from a pickle file which has a Counter object generated by stats.py Args: pkl_file_name (str): Name of pickle file N (int): The number of bigrams to get ...
8bcffa98c3c585e4da11650890d1f936fca040d9
645,109
import requests def resolve_ch(validated_chs, print_msg=True, server="http://localhost:5279"): """Resolve input channels to see if they in fact exist.""" resolved_chs = [] out = [] for num, validated_ch in enumerate(validated_chs, start=1): channel = validated_ch["claim"] ...
50e26c80fc82f914077392053393ce6b93030654
645,110
def welcome(): """List all available api routes.""" return ( f"Available Routes:<br/>" "<br/>" f"Information about precipitation from Aug 2016 to Aug 2017:/api/v1.0/precipitation<br/>" "<br/>" f"Information about stations: /api/v1.0/stations<br/>" "<br/>" ...
d1a2266fca7fa9bfc58df9bb9a06cf3057ab2e48
645,111
import os def get_dist_status(): """ 得到磁盘使用情况 :return: """ disk_status = os.popen('df -h').readlines() return ''.join(disk_status)
2be93bd75e646c4fa7f1eece774313bf4ce6c0c0
645,112
def list_is_nested(input_list: list) -> bool: """This function checks whether the input_list is nested (i.e. it is a list of lists). Args: input_list (list): the input list Returns: is_nested (bool): True if list is nested, False if it isn’t """ is_nested = any(isinstance(i, list) fo...
ed3eccd77ae8a53d75f040ee6ba44c932dbf1cf3
645,114
from typing import Tuple import subprocess import sys def run_aea_subprocess(*args, cwd: str = ".") -> Tuple[subprocess.Popen, str, str]: """ Run subprocess, bypassing ClickRunner.invoke. The reason is that for some reason ClickRunner.invoke doesn't capture well the stdout/stderr of nephew processes ...
6cf638febb87d7dc7c7cbafb04930f6e940ecb52
645,115
def recursive_fold(left, right): """ Recursively folds (reduces) two records. Parameters ---------- left : dict The "left-hand", or current, record. right : dict The "right-hand", or next, record. Returns ------- left : dict The folded (reduced) record. "...
f93f836a1351806f9691cfd5fbe1ca7ee6058bae
645,116
def load_labels_file(file_path): """ Reads the 'classes.txt' file and returns a class dictionary. Args: file_path: Full path to the 'classes.txt' file. Returns: classes: Dict in the format: 'classes[class_name] = class_id'. """ classes = {} with open(file_path, 'r') as file: ...
f26484546cec1c41a86614def5f969f10c57e5d3
645,117
def to_numpy(ts, xx, yy, msk, scaler): """Function to convert multi-user dataframes to ndarrays""" t = [] x = [] y = [] m = [] for i,_ in ts.groupby(level=0): # timestamps t.append(ts.loc[i].values) # features x.append(scaler.transform(xx.loc[i].values)) ...
8c22a6a26457f332273d0cd9130f0428679a613a
645,118
def epsilon_schedule(eps: float, n_frames: int) -> float: """ Epsilon is annealed linearly from 1 to 0.1 over the n_frames """ change = (1 - 0.05) / n_frames eps -= change eps = max(eps, 0.05) return eps
556424fa4e6277ed397b09710078f5353fdaa073
645,119
def gcdr(a, b): """Recursive Greatest Common Divisor algorithm.""" if b == 0: return a if a<b: a,b = b,a print(a,b) return gcdr(b, a%b)
7edd0742f2f57dbed839b345067df734ec5e4544
645,120
def NDWI(image): """A function to compute NDWI.""" ndwi = image.normalizedDifference(['G', 'N']) ndwiViz = {'min': 0, 'max': 1, 'palette': ['00FFFF', '0000FF']} ndwiMasked = ndwi.updateMask(ndwi.gte(0.05)) ndwi_bin = ndwiMasked.gt(0) patch_size = ndwi_bin.connectedPixelCount(500, True) large...
286ac1e5b55fbf228fb28639403112c2ebf64cb9
645,121
def get_empty_marker_error(marker_type): """ Generate error message for empty marker. """ msg = ( "no configuration file is specified in " "``@pytest.mark.gdeploy_config_{0}`` decorator " "of this test case, please add at least one " "configuration file file name as a par...
92bb8c554d1d84ec64395ff6d7d749bde5a8d5b6
645,122
def find_value(keys, d, create=False): """Return a possibly deeply buried {key, value} with all parent keys. Given: keys = ['a', 'b'] d = {'a': {'b': 1, 'c': 3}, 'b': 4} returns: 1 """ default = {} if create else None value = d.get(keys[0], default) if len(keys) > 1 and ty...
c4b4e039bf6a2f159deee510b79ca8aaa7d179a7
645,123
def convertir(hora: str) -> str: """Convierte una hora en notación de 24 horas a 12 horas. :param hora: Hora a convertir :hora type: str :return: Hora en notación de 12 horas :rtype: str """ hora_24 = int(hora[:2]) hora_12 = 12 if hora_24 % 12 == 0 else hora_24 % 12 return f"{hora_1...
d274761c151908b3013b5973047d25781136f053
645,125
def path_concordance_jspecies(path_fixtures_base): """Path to JSpecies analysis output.""" return path_fixtures_base / "concordance/jspecies_output.tab"
8dbeb6296a050555eaf520a3d2e563ecadcc12a4
645,126
def int_to_bin(data_string: str) -> str: """Returns the binary representation of a integer string First, casts the string to int and calculates from there args: data_string: Incoming string composed of values from 1 to 9 return args: binary_data: Binary representation of the integer ...
ee4fd35646785f7141a149fa0b14b9dbf6fa743a
645,127
import os def current_file(repos_path): """Return triple of (revision, next_node_id, next_copy_id) from REPOS_PATH/db/current .""" return open(os.path.join(repos_path, 'db', 'current')).readline().split()
e32486b763b21f1b20c34adcfcd6e5b700d9b6c4
645,128
def _is_early_stopping(all_losses, patience, threshold): """It decides if training must stop.""" # get current and all past (validation) accuracies accuracies = [x[4] for x in all_losses] if len(all_losses) > (patience + 4): # running average with window size 5 average = (accuracies[-...
616dc6bfaf30207904ec2a1389e621292c4ecaf8
645,129
def normal_from_ineq(s_ineq): """ Get the normal stored in the phase surface inequalitie vector :param s_ineq: A phase data surface vector (see SL1M output doc) :return: The surface normal, as an array of size 3 """ return s_ineq[2]
2e5c5e839407cff51880bc9b30b6107fd7f372c3
645,130
def _get_from_onclick(node, index): """Private function to grab a value in the "`onclick`" attribute. Grabs the value in the specified index of the "`onclick`" attribute of a selectolax `Node`. Args: node (:class:`Node`): A `Node` containing the "`onclick`" attribute. index (:obj:`int`...
aa41f9a3234c3d53f92f22feed6af4f853efb7bf
645,131
def _img_name(pk, device): """ File name """ if device == True: img_name = '/device_qr/d-' + str(pk) + '.png' else: img_name = '/rack_qr/r-' + str(pk) + '.png' return img_name
1d1926a49ca9a6eea8579e13686b70da777c3f8c
645,132
def timeConversion(s): """ Given a time in 12-hour AM/PM format, convert it to military (24-hour) time. Note: Midnight is 12:00:00AM on a 12-hour clock, and 00:00:00 on a 24-hour clock. Noon is 12:00:00PM on a 12-hour clock, and 12:00:00 on a 24-hour clock. Link: https://www.hackerrank.com/challe...
dc310babf11fbf651f6e726c29e0f3e9768b0a32
645,133
def string_to_list_only_last_digit(word): """ The negative index allows to select only the last digit from the new list :param word: parameter :return: list """ return [c for c in word if c.isdigit()][-1]
689934fad6f8f128810c4bec9b2a49357180a57e
645,135
from typing import Dict def parse_host_key(host_key: str) -> Dict: """ 解析主机唯一标识 :param host_key: 三段式:127.0.0.1-0-tencent 或者 1024 :return: {"ip": "127.0.0.1", "bk_cloud_id": 0, "bk_supplier_id": "tencent"} """ try: ip, bk_could_id, bk_supplier_id = host_key.split("-") except Value...
088768e6b1f7d935d71f3cac48096da25aeb8779
645,136
import os def SavePlot(fig,path,title): """ Parameters ---------- path : string folder path in which the figures needs to be saved in. This needs to be created before title: string Name of the figure, this is also what the figures is saved as. This does not need to be created ...
4b53f0a79e891e2e1f2d4773f6957ff602974973
645,137
import typing def is_basic_iterable(obj: typing.Any) -> bool: """Checks if an object is a basic iterable. By basic iterable we want to mean objects that are iterable and from a basic type. :param obj: Object to be analysed. :return: True if obj is a basic iterable (see list below). False otherwi...
48a87ea430021fe7086ba9c17d973da1ef5f7fdd
645,138
import argparse import os import subprocess def parse(argv=None): """Parse command-line arguments.""" parser = argparse.ArgumentParser() pw_root = os.environ.get('PW_ROOT', None) if not pw_root: try: with open(os.devnull, 'w') as outs: pw_root = subprocess.check_ou...
e4c07fd4e4154fe367ea8f63c8a73fbd88963c44
645,140
def _parse_common(row): """Parse common elements to TF Example from CSV row for non-spans mode.""" example = {} example['id'] = row['id'] example['text'] = row['comment_text'] example['parent_text'] = row['parent_text'] parent_id = row['parent_id'] or 0 example['parent_id'] = int(float(parent_id)) examp...
942caa66524af65d1cb5838fcafe1fc52b4d69d4
645,141
def set_data_types(data_types=["userAcceleration"]): """ Select the sensors and the mode to shape the final dataset. Args: data_types: A list of sensor data type from this list: [attitude, gravity, rotationRate, userAcceleration] Returns: It returns a list of columns to use for cr...
4a08ba2d33ce77a4fa8a33b8d4c2f02174c6cefb
645,142
import os def get_unique_dir(base_dir, choice_dir): """ :param base_dir: :param choice_dir :return: """ target_dir = os.path.join(base_dir, choice_dir) curr_count = 1 while os.path.exists(target_dir): target_dir = os.path.join(base_dir, choice_dir + '_' + str(curr_count)) ...
922fba637fa93bdd347a57e0356aadc568933cf3
645,143
from typing import List def render_report_toc() -> List[str]: """Render table of contents for the overall report.""" return [ "<a name='top'></a>" "<h2>Table of Contents</h2>", "<ul id='toc'>", "<li><a href='#reportables'>Reportables</a></li>" "<li><a href='#map'>Map</a></li>",...
f0de15e8021285221bbd07cd2a04d22b19670781
645,144
def false_to_none(ctx, param, value): """Convert a false value to a None""" if value: retval = True else: retval = None return retval
3c25c725473ff7c271c1819170e0332db3810dd8
645,146
from typing import List def _common_substring_table(f1: str, f2: str, hifi: bool = False) -> List[List[int]]: """Builds matrix of common substring lengths.""" matrix = [[0] * (1 + len(f2)) for i in range(1 + len(f1))] for x in range(1, 1 + len(f1)): for y in range(1, 1 + len(f2)): # O...
810ff0003a17d2c1f2629d5c990828702863dff4
645,147
def respuesta(cells, cell_data, phy_lin): """Extracts the nodes located at the physical line phy_line Parameters ---------- cell : dictionary Dictionary created by meshio with cells information. cell_data: dictionary Dictionary created by meshio with cells dat...
cbc14f81183406b6a31e1efa542326b35f8e7a85
645,148
import random def face(x, y): """ Calculates points to fill in order to plot a smiley-face on a graph of x and y dimensions Parameters ---------- x: x-axis resolution (how many points desired in x-axis) y: y-axis resolution (how many points desired in y-axis) ...
504bcb68a511a2cfad57a12d2dc480757891e8ad
645,149
def convert_big_str_numbers(big_num): """Convert big number written with numbers and words to int. Args: big_num (str): number, written with numbers and words. Returns: int: same number as an int. Examples: >>>print(convert_big_str_numbers('101.11 billions')) 101110000...
44699108d1ebac79d55df620ce851a6ecf96376d
645,150
def sub_entry(ynew: float, s: float, s2: float, n: int, calc_var: bool): """Subtracts an entry from the metrics, s, s2, and n. s: previous value of sum of y[] s2: previous value of sum of y[]*y[] n: previous number of entries in the metric """ n = n - 1 s = s - ynew s2 = s2 - ynew * ...
5feec73c2cf460759071b69d734a3be149033817
645,151
import argparse def parse_args(): """Parse command line arguments""" parser = argparse.ArgumentParser() parser.add_argument("font_path", help="Path to ttf font file or directory containing ttf files") parser.add_argument("--loss", help="'ctc' or 'warpctc' loss [Default 'ctc']", default='ctc') pars...
b95d174741f760ba2ff988dee7f98634a5a4f903
645,152