content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
from typing import Optional def format_revision(revision1: str, revision2: Optional[str] = None): """ Formats one or more revisions """ return f"{revision1}..{revision2}" if revision2 else revision1
c716b0e1de0ff6c686397fd994f6210e786bcb05
660,732
def task2(rows, cols): """ Write a program which takes 2 digits, X,Y as input and generates a 2-dimensional array. The element value in the i-th row and j-th column of the array should be i*j. Example: Suppose the following inputs are given to the program: 3, 5. Then, the output of the program ...
13130b7281e209a7fbe6c8cd883bf6c5c39f7f77
660,733
def myAtoi(s): """ :type str: str :rtype: int """ s = s.lstrip() if not s: return 0 sample = '' if s[0] == '-' or s[0] == '+': sample = s[0] s = s[1:] end = len(s) for i, char in enumerate(s): if char not in ['0', '1', '2', '3', '4', '5', '6', '7'...
1dcb14734b8e0c303327b7fb12c260bf4d4adfed
660,734
def my_strip(thing): """Safely strip `thing`. """ try: return thing.strip() except: return thing
42e408437234b010fb01f5c7b56b996f68663b4f
660,735
def red_free(image): """ https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4944099/ The red-free version of this photo shows the new vessels at the optic disc more clearly. Altering the images, e.g. by using red-free, is a valuable tool for detecting retinopathy :param image: :return: """ ima...
2acebeb4ed219539b43246a729eb7d65a1f516ba
660,736
def quadratic_depth(x, point_1, point_2): """ Evaluate a quadratic function for a given value ``x``. The parameters to define the function are determined through the coordinates of two points (:math: (x_1, z_1) and :math: (x_2, z_2)). .. math :: z(x) = - a x^2 + b where, .. math::...
3695b6619d0d3c846be8d6cd41b9dcfa92051fe5
660,737
from unittest.mock import Mock def _get_mock(instance): """Create a mock and copy instance attributes over mock.""" if isinstance(instance, Mock): instance.__dict__.update(instance._mock_wraps.__dict__) # pylint: disable=W0212 return instance mock = Mock(spec=instance, wraps=instance) ...
a8420def2943cf25931234108958546fd4a67857
660,738
import numpy def equal(data, num_breaks): """ Calculate equal interval breaks. Arguments: data -- Array of values to classify. num_breaks -- Number of breaks to perform. """ step = (numpy.amax(data) - numpy.amin(data)) / num_breaks return numpy.linspace(numpy.amin(data) + step, numpy...
8f75f6abf3f0424fe14050867cf5411deb410239
660,739
def validate_salmonella(seq_list, metadata_reports): """ Checks combined metadata for presence of invA or stn in the GeneSeekr_Profile column :param seq_list: :param metadata_reports: :return: dict with pair of SeqID:boolean where True means GeneSeekr confirms the identity """ salmonella_seq...
bdb9238e62d6c4dae08223cb70d6a57316d16304
660,740
from re import VERBOSE import yaml import sys def load_yaml(file_path): """ :param file_path: Full path to a file with configuration in yaml :type file_path: str | unicode :return: dict representation of the yaml :rtype: dict """ try: with open(file_path) as f: if VERB...
8a96d483d8f0a2d957bbaf0a8245552aadd2341b
660,741
def to_string(ilt): """ :param ilt may be int, list, tuple :return: """ if (type(ilt) is list) or (type(ilt) is tuple): return ', '.join(str(i) for i in ilt) else: return str(ilt)
8c2bf3063c6cae62acd5fb8ec2f097b9d49ac621
660,742
def _recursive_to_list(array): """ Takes some iterable that might contain iterables and converts it to a list of lists [of lists... etc] Mainly used for converting the strange fbx wrappers for c++ arrays into python lists :param array: array to be converted :return: array converted to lists ...
f4c6c91855ffc786fd3836d183ae67fc25bcec85
660,743
import sys def import_object(modname, name): """ Import the object given by *modname* and *name* and return it. If not found, or the import fails, returns None. """ try: __import__(modname) mod = sys.modules[modname] obj = mod for part in name.split('.'): ...
e53f323cee3a7697ff154dd09fad59f81f8eb7fa
660,745
def calculate_bmi(weight, height, system='metric'): """ Return the Body Mass Index (BIM) for the given weight, height, and measurement system. """ if system == 'metric': bmi = (weight / (height ** 2)) else: bmi = 703 * (weight / (height ** 2)) return bmi
9d7108b1c23eb91e1362ad13e14b71fff1bac527
660,746
import os def create_file_structure(path, folders_names): """ Creates folders in specified path. :return: dict Mapping from label to absolute path folder, with videos of this label """ mapping = {} if not os.path.exists(path): os.mkdir(path) for name in folders_names: ...
3f5bf62eed152a4e8062b0a0bda65377fc1924ec
660,747
def save(df, name): """ Save a dataframe as a csv and pickle file :param df: (pd.DataFrame) - dataframe to save :param name: (str) - output name :return name: (str) - output name """ df.to_csv('{0}.csv'.format(name)) df.to_pickle('{0}.pkl'.format(name)) return name
4efda71dc0f5dcd0208558b7f211636cbf52bb5d
660,748
import os import unicodedata import re def normaliseName(value): """ Normalises or renames a string, replaces 'something' with 'something else' add anything else you need; examples are commented Order of rules does matter for custom replacements. At the end all remaining invalid characters are r...
f91d58f56caab7d9529aaa4eddcd3aa6cd057bbb
660,749
def rivers_with_station(stations): """returns the list rivers where the stations are located""" river_list = set([]) for each_station in stations : river_list.add(each_station.river) return list(river_list)
84211b528a7e10dd1280c7f08201ab5c687dadfa
660,751
def just_load_sets(load_list): """Remove additional metadata from load list leaving just the load_set""" return [x[2] for x in load_list]
585e544ff49e582ea7fb26c1ff987a4553a0c8f3
660,752
def get_file_name(url): """ 本函数从 url 中提取对应的资源的文件名 """ url = url.replace('https://www.stormlin.com/', '') if url == '': url = 'index.html' return url
41118273ba8c93244af02ddc24b3e64e0bcb98bb
660,753
def handle_root_dev(line): """Handle if it match root device information pattern :param line: one line of information which had decoded to 'ASCII' """ for root_type in line.split(): # only support ext4 rootfs if "ext4" in root_type: return True return False
a1abbb0b7ba70dfad731641c3983e114feccd960
660,754
def extract_int_from_str(string): """ Tries to extract all digits from a string. Args: string: a string Returns: An integer consisting of all the digits in the string, in order, or False """ try: return ''.join(filter(lambda x: x.isdigit(), string)) except:...
30e4dbe2eb0eee7e381c0e7dc1fa2c037bef3637
660,755
def formed_bond_keys(tra): """ keys for bonds that are formed in the transformation """ _, frm_bnd_keys, _ = tra return frm_bnd_keys
dbbdd8aaa62af5c6f2b678799e591c7bcf0da258
660,756
import numpy as np def calc_num_params(net): """ Calculate the count of trainable parameters for a model. Parameters ---------- net : Module Analyzed model. """ net_params = filter(lambda p: p.requires_grad, net.parameters()) weight_count = 0 for param in net_params: ...
7e1e779bedfa9a3fa854d0ff25b706e48812cec0
660,757
import copy def prepare_dataset(df, target, spl_ratio): """ df: dataframe target: target column name (string) of y spl_ratio: split ratio. if 0.7, 70% of the data will be used as train return: (dataframe of train dataset), (dataframe of ORIGINAL DATABASE) (NOTE: target value of test da...
862636e0dc54eb8506ad4a562811403e38eccdd9
660,758
def go_past_duration(interest_area, fixation_sequence): """ Given an interest area and fixation sequence, return the go-past time on that interest area. Go-past time is the sum duration of all fixations from when the interest area is first entered until when it is first exited to the right, includin...
3e4ec3ddadb5d2916bd16cffcdd0bb71a4522142
660,759
import yaml def load_yaml(fileuri): """Load yaml file into a dict""" fd = open(fileuri, 'r') try: return yaml.safe_load(fd) except Exception as e: raise e finally: fd.close()
8f749af4b46d3e8255c6a6ca4af5c3797bbb4bed
660,760
def parse_gpu_ids(gpu_str): """Parse gpu ids from configuration. Args: gpu_str: string with gpu indexes Return: a list where each element is the gpu index as int """ gpus = [] if gpu_str: parsed_gpus = gpu_str.split(",") if len(gpus) != 1 or int(gpus[0]) >= 0...
de8c693862ac8d6dc022bf9cb9b12ed10b52d046
660,761
import requests def send_get_request(query_url, headers): """ Sends a get request using the Requests library It doesn't do anytthing special right now, but it might do some checks in future :param query_url: :param headers: :return: """ response = requests.get(query_url, headers=header...
0a1285a7b74f8ef69cf9775cfac781e359a8865f
660,762
def html(html, css): """ inp: SMD string to parse returns: parsed html string """ return html
a42b54905917a38ecf42fd4add0efa038b088f73
660,763
def get_lane_loc_list(all_anchor_distance, all_anchor_loc, h, w): """Get lane location list. :param all_anchor_distance: the distance of all anchor :type all_anchor_distance: list :param all_anchor_distance: the regression result of all anchor :type all_anchor_distance: list :param h: feature m...
05b9ce4d292dbe91d37dbe19f31eced4b55128a6
660,764
from datetime import datetime import os def last_file_access_time(filename): """ Get a datetime() representing the last access time of the given file. The returned datetime object is in local time """ return datetime.fromtimestamp(os.stat(filename).st_atime)
561445b55850d2e28b50680989dbdebe8ea7f407
660,765
def autotype_seq(entry): """Return value for autotype sequence Args: entry - dict Return: string """ return next((i.get('value') for i in entry['fields'] if i.get('name') == 'autotype'), "")
ff2fb811656577ced76ede843def2ef070c8cd43
660,766
import base64 def file_to_base64(path): """获取文件base64编码""" with open(path, "rb") as f: content = f.read() return base64.b64encode(content).decode()
22e679ed6779cf54edae70a04832bc4e86ddb289
660,768
def format_repository_listing(repositories): """Returns a formatted list of repositories. Args: repositories (list): A list of repositories. Returns: The formated list as string """ out = "" i = 1 for r in repositories: out += (f"{i:>4} {r.get('name', '??')}\n" ...
f046889948889d5a5aaa7e99bce805f1f10f32a3
660,769
def find_peak(list_of_integers): """ Args: list_of_integers(int): list of integers to find peak of Returns: peak of list_of_integers or None """ size = len(list_of_integers) mid_e = size mid = size // 2 if size == 0: return None while True: mid_e = mid_e // ...
7b472bdf44464f785dfa37a8730d73a982d937e9
660,770
def hex_to_ipv6(hex): """ Takes a 128 bit hexidecimal string and returns that string formatted for IPv6 :param hex: Any 128 bit hexidecimal passed as string :return: String formatted in IPv6 """ return ':'.join(hex[i:i + 4] for i in range(0, len(hex), 4))
0e78ac70169bf7fdaa34f2b8f57f6d0f80579d60
660,772
def func_dc400d407d514c66a0f00e41e8c416cc(psum): """mingain = psum for i in range(N): for j in range(i+1): gain = max(S[j],S[i]-S[j],psum-S[i]) mingain = min(mingain,gain) return float(psum-mingain)/psum""" mingain = psum minpgain = psum return minpgain
2338d8940ded5631202a4d3718079e75f92c1454
660,773
def make_instr(t_var, t_op, t_val, d_var, d_op, d_val): """Makes an instruction function using test (t_) and destination(d_) information. t_var = test var; t_op = test operator; t_val = test_value d_var = dest var; d_op = dest operator; d_val = dest_value """ f_tmpl = """def _aoc_func(r): ...
2625ceb213086245daa8c0a30f24727c1254c0c2
660,774
def new_size_keep_aspect_ratio(original_size, target_size, resize_type='inner'): """Return a new size included (if resize_type='inner') or excluded (if resize_type='outer') in the targeted one by resizing and keeping the original image's aspect ratio. """ # Get current and desired ratio for the images ...
b2616d4bb4f4afb1f937e9f588777e899ad55f1c
660,775
import os import time def crt_file_time(fname, path, ext="", **kwargs): """Function: crt_file_time Description: Creates a file name with timestamp along with directory path. Arguments: (input) fname -> File name (input) path -> Directory path (input) ext -> Extension of file ...
8a192d1c5ffef92fa5289ddac673cb96665e4191
660,776
def reconstruct_path(current): """ Uses the cameFrom members to follow the chain of moves backwards and then reverses the list to get the path in the correct order. """ total_path = [current] while current.cameFrom != None: current = current.cameFrom total_path.append(current) ...
85000ca0d9ed4150afc536ff8ac8a500586df5fb
660,778
import random def guess_number(start: int, end: int) -> int: """Return a number in specified range.""" result = random.choice(range(start, end + 1)) return result
f1545fe7264c3a14484450884b47b256756957b5
660,779
import math # only used in this method from typing import Tuple def get_euclidean_distance(start_pos: Tuple[int, int], target_pos: Tuple[int, int]) -> float: """ Get distance from an xy position towards another location. Expected tuple in the form of (x, y). This returns a float indicating the straight l...
a7a5bf3b68a92703040f096ed95c6bd4f2f76098
660,780
def crossover(x, y): """ Last two values of X serie cross over Y serie. """ return x[-1] > y[-1] and x[-2] < y[-2]
90a2f4244b6e018185507920375cab18639e47f7
660,781
def ConvertToEnum(versioned_expr, messages): """Converts a string version of a versioned expr to the enum representation. Args: versioned_expr: string, string version of versioned expr to convert. messages: messages, The set of available messages. Returns: A versioned expression enum. """ return...
831d5b7b80423a27186b1e204dc517a55a0b9f51
660,782
def w_deph_coolwater_real(m_coolwater_deph, rho_deph_coolwater , d_deph_coolwater_real): """ Calculates the real speed of liquid at the tube. Parameters ---------- m_coolwater_deph : float The mass flow rate of cooling water, [kg/s] rho_deph_coolwater : float The density of cool ...
2a8e8ce6961d7c6d05914fb029371908a5cf7381
660,783
def value_error_to_dict(obj): """Serializer function for ValueError.""" return {"__class__": "ValueError", "args": [str(arg) for arg in obj.args]}
bb008c45c8160b915e5511e99f2b161623aee0ce
660,784
import inspect def bound_signature(method): """Return the signature of a method when bound.""" sig = inspect.signature(method) param = list(sig.parameters.values())[1:] return inspect.Signature(param, return_annotation=sig.return_annotation)
b0a426041199f713c73f578b1bacc5567af692cd
660,785
import string def find_words(text): """ Parameters ---------- text : string Parses the long string into separate words Returns ------- LIST of words from the input text """ text = text.replace("\n"," ") # Replaces new lines with a space for char in string.punctuation: #...
2330daaedd02a75d9ebe398d2510a346b9ad77bb
660,786
def _ip_bridge_cmd(action, params, device): """Build commands to add/del ips to bridges/devices.""" cmd = ['ip', 'addr', action] cmd.extend(params) cmd.extend(['dev', device]) return cmd
f6951b42c734660dcb33c76b0d0e4153f4ee53e7
660,787
def archimedes(q1, q2, q3): """ This is the difference between the lhs and the rhs of the TripleQuadForumula. [MF 124 @ 2:23]. The TQF is satisfied when this is zero. Given: TQF: ((q1 + q2 + q3) ** 2) == (2 * (q1 ** 2 + q2 ** 2 + q3 ** 3)) Define: A(q1, q2, q3) = ((q1 + q2 + ...
9fb282f3448628f46501a9f76936e1beb18dc95f
660,788
def basis_function_one(degree, knot_vector, span, knot): """ Computes the value of a basis function for a single parameter. Implementation of Algorithm 2.4 from The NURBS Book by Piegl & Tiller. :param degree: degree, :math:`p` :type degree: int :param knot_vector: knot vector :type knot_vecto...
ea534541df74ab891ce74fc041c9ed950dfe8765
660,789
def GetDocTypeFromFilename(filename): """ Return a string representing given document type """ interactionStrings = ('ints', 'interactions', 'interaction') postStrings = ('posts', 'post') if any(s in filename for s in interactionStrings): return 'interaction' elif any(s in filename for s i...
32a8c486bda34294dac238b00acff8691a2f0c90
660,790
import zipfile import os def dir2zipfile(zipped_dir_path: str, creat_zip_file_path: str, incl_rootdir=False, incl_emptydir=False) -> bool: """ zip directory to given path (STORED) :param zipped_dir_path: path the zipped directory :param creat_zip_file_path: path to zip file :param incl_rootdir: if...
f08ded02021ac563423b1acdc6bf67bd4be581ce
660,792
def append_with_phrases(tokens, phrases): """Append phrases to the tokens. Args: tokens (list of str): A list of tokens. phrases (list of str): A list of phrases. Returns: list of str: A concatinated list of tokens and phrases. """ return tokens + phrases
c411b9d81c44a513a5c26cc52a07802a182ad366
660,793
import json def open_json(filename): """Opens the json file Parameters ---------------- filename: string Full file path for json file Returns ---------------- jsonf: dictionary Json file is opened and ready to be used by other functions in this code Cont...
a9a5af1701d7e3c856753cb6e3c9fb753bccd9f3
660,794
def get_indexed_constraint_body(backend_model, constraint, input_index): """ Return all indeces of a specific decision variable used in a constraint. This is useful to check that all expected loc_techs are in a summation. Parameters ---------- backend_model : Pyomo ConcreteModel constraint ...
fd2603ee06c041f0b06f945c054f63c8cb7671be
660,795
import argparse def make_parser(): """Constructs and returns the argument parser used in this module""" parser = argparse.ArgumentParser(description='<Compare results to known-good ones>') parser.add_argument('--type', dest='type', action='store', default=None, help='The type of results to check') par...
883f61b9da32de05bd6bf00d57629f7c53790480
660,796
import time def sleep(timeout, cancel_event): """ Sleeps until the timeout is reached, or until cancelled through :param:`cancel_event`. """ if cancel_event: cancel_event.wait(timeout=timeout) if cancel_event.isset(): return False else: time.sleep(timeout) ...
5cdacb49392a2d7b0a126e80530e6a66968f6e05
660,797
def get_safe_name(progname): """Get a safe program name""" for c in r'-[]/\;,><&*:%=+@!#^|?^': progname = progname.replace(c,'') if len(progname) <= 0: progname = 'Program' if progname[0].isdigit(): progname = 'P' + progname return progname
98b30794973436467161966c9cce84d68bf367b3
660,798
def ip_to_hex(address): """return a ipv4 address to hexidecimal""" return ''.join(['%02X' % int(octet) for octet in address.split('.')])
689f4068d289aa64956c13b6788320b35bcc8e85
660,799
from typing import OrderedDict def compare_bins(dict_A, dict_B): """(dict,dict) => dict, dict, dict Compares two dicts of bins. Returns the shared elements, the unique elements of A and the unique elements of B. The dicts shape is supposed to be like this: OrderedDict([('1', ...
2c25dd38c6dbaaf2bad1ffeccc5530876ad386cf
660,800
def create_command(base_command, args): """ args is the parser """ run_command = base_command arg_keys= vars(args).keys() assert('exp_group_list' in arg_keys) assert('exp_id' in arg_keys) assert('run_jobs' in arg_keys) for a, v in vars(args).items(): if a == 'exp_group_list...
73cefa8823a2c27b964739694a3591f83cdea095
660,801
def B0_rel_diff(v0w, b0w, b1w, v0f, b0f, b1f, config_string, prefact, weight_b0, weight_b1): """ Returns the relative difference in the bulk modulus. THE SIGNATURE OF THIS FUNCTION HAS BEEN CHOSEN TO MATCH THE ONE OF ALL THE OTHER FUNCTIONS RETURNING A QUANTITY THAT IS USEFUL FOR COMPARISON, THIS SIMPLI...
0241110a46f710e6e91e6eca6a379dcfecf06798
660,802
def binrep_convert(byt): """Returns a binary string representation of an integer. The returned string has '0' padding on the left to make it minimally eight digits in length. """ return bin(byt)[2:].zfill(8)
26acf3ebe6420f9ae829067e4a847eb1e7a048cd
660,803
import base64 def Base64WSDecode(s): """ Return decoded version of given Base64 string. Ignore whitespace. Uses URL-safe alphabet: - replaces +, _ replaces /. Will convert s of type unicode to string type first. @param s: Base64 string to decode @type s: string @return: original string that was encod...
d3333b0204bf7d4f54570eef14e5f9aa2fbd6915
660,804
def all_prime_factors(p: int) -> list: """ Returns a list of distinct prime factors of the number p """ factors = [] loop = 2 while loop <= p: if p % loop == 0: p //= loop factors.append(loop) else: loop += 1 return factors
dbd7135f62719fa061e9dbc3ac4035a8ef25c006
660,805
import csv def csv_file_to_nested_dict(filename, primary_key_col): """ assumes the first line of the csv is column names. loads each line into a dict of kvps where key is column name and value is the value in the cell. Puts all of these kvp dicts into one top level dict, where the key is the...
d4f39fc0f27ca1a1995a78d457a5894e8d03dd37
660,806
def exclude_from_weight_decay(name): """exclude_from_weight_decay """ if not isinstance(name, str): name = name.name if name.find("layer_norm") > -1: return True bias_suffix = ["_bias", "_b", ".b_0"] for suffix in bias_suffix: if name.endswith(suffix): return ...
faa4a793f1fc202d099b766c521583b0c14c6b0e
660,807
import configparser def fixture_update_config(): """Update the config file with kwargs.""" def _update_config(path, **kwargs): config = configparser.ConfigParser() config.read(path) config.read_dict(kwargs) with open(path, "w", encoding="utf-8") as file: config.wri...
bd2e3eec7293a38d0f94d5429f2c7bf3f8c285a0
660,808
def subsample(input_list, sample_size, rnd_generator): """Returns a list that is a random subsample of the input list. Args: input_list: List of elements of any type sample_size: Int. How many elements of input_list should be in the output list rnd_generator: initialized random generato...
888f9d79ada3576d4adf08771d10020fcee1f491
660,809
from typing import Union def modify_str_int_value(value) -> Union[str, int]: """SQL query needs quotes present for string values. Return value if value is integer else return value wrapped in quotes.""" return value if isinstance(value, int) else f"'{value}'"
645f222fb510728b74fe5715fad9673a53eecfc7
660,810
from pathlib import Path import glob def list_temp_files(directory): """List all temporary files within a directory which are marked with *temp* in their name""" try: dir_path = Path(directory) assert dir_path.exists() except Exception: raise Exception(f"Expected absolute path to v...
57490451dd0bb2121a59f3e722d108c213b57a4a
660,811
def retry(limit=1): """ Retry a failing function `n` times or until it executes successfully. If the function does not complete successfully by the nth retry, then the exception will be reraised for the executing code to handle. Example: :: root@710027b06106:/plsnocrash/examples# cat retr...
b44803d64ccf60cd656219906c8ac7cfcea019b0
660,812
import re def fix_text(text): """ Method to fix up bad text from feeds :param text: Text to cleanup :return: Fixed text """ if text is None: text = "" text = re.sub(r"[]^\\-]", " ", text) return text
c72a2013e8067fe9ba4ba31fcae0595fc1f11174
660,813
def get_integer_form(elem_list): """For an element list like ['e1', 'a1_2', 'a1_1', 'a1_3'], return the integer 213, i.e., the 'subscripts' of the elements that follow the identity element.""" return int(''.join(map(lambda x: x.split("_")[1], elem_list[1:])))
68bad294b679866ab78df6db09ae49a424cb254c
660,814
def get_size_contingency_table(X): """Get size of contingency table prior to calculating it""" size = 1 for jj in X.columns: size *= X[jj].nunique() return size
6c992a9a24171baa2a8dd4ce2fdb4c14a8b27d9f
660,816
def genLabn(n,s): """ Generate nth string label from a char set s """ l = len(s) m = n g ="" go = True while go: c= m % l g = s[c] + g m=m//l go = m > 0 m-= 1 return g
30ba8bb7899e6140ed863c5aefc9e8ebfcd2f895
660,817
from typing import List def choose_best_action_id(list_dict: List[dict], cle: str, value: str) -> int: """ Cette fonction est obsolete. Elle est utilisé pour trouver l'action associée à une cellule qui a le plus de probabilité de ne pas conduire à la défaite :param list_dict: liste des actions :pa...
e8892ef9c5804d2d9b689e36064c21f8ccebf3a9
660,818
def java_type_boxed(typ): """Returns the java boxed type.""" boxed_map = { 'boolean': 'Boolean', 'byte': 'Byte', 'char': 'Character', 'float': 'Float', 'int': 'Integer', 'long': 'Long', 'short': 'Short', 'double': 'Double' } if typ in boxed_map: return boxed_...
23ffb7a1bcfd8440bed98552f01210ad08f4eb71
660,819
import argparse def arguments(): """ Process CLI arguments """ description = 'Upload multiple communication plans to Slate.' parser = argparse.ArgumentParser(description=description) parser.add_argument("-l", "--List", action="store", help="CSV of Plans", required=True) return parser.parse_args()
4dcece5dbd348449052cd8cf0b64cb76f29e11c8
660,820
def parse_arguments(arguments): """ Parse string list into list of tuples: command, args, kwargs, hosts, roles. Parses the given list of arguments into command names and, optionally, per-command args/kwargs. Per-command args are attached to the command name with a colon (``:``), are comma-separated...
40ab21ff0bbb6f6e7b7633ef09a2fb0c846cf501
660,821
def filter_spatiotemporal(search_results): """ Returns a list of dictionaries containing time_start, time_end and extent polygons for granules :search_results: dictionary object returned by search_granules :returns: list of dictionaries or empty list of no entries or keys do not exist """ ...
5b97848c7a2f1edb94c01a9a4759d6ef1e0c1070
660,822
import random import math def get_random_point(): """See https://www.cs.cmu.edu/~mws/rpos.html""" z = random.random() * 2 - 1 phi = random.random() * 2 * math.pi theta = math.asin(z) x = math.cos(theta) * math.cos(phi) y = math.cos(theta) * math.sin(phi) return x, y, z
54208ef96d4f10fe7124e665ab5816966d0f4f0a
660,823
import zlib def _decompress(fileobj): """Read and decompress the file content of the file-like object <fileobj>.""" content = fileobj.read() text = zlib.decompress(content[60:]) return text[:-1]
a13704084317a303db4348f1702ab9851ff2db72
660,824
import re def get_grub_entries(): """ Builds JSON from grub menu entries, just the top level ones, like this: { "menuitems": [ { "name": "Ubuntu" }, { "name": "Windows Boot Manager (on /dev/nvme0n1p2)" }, {...
25ad240086ccbbe1ba336a21d4c2c86c1f6fecb5
660,825
def rescale_contours(cnts, ratio): """ Rescales contours based on scalling `ratio`. Args: cnts (list of contour objects): List of `numpy.ndarray` objects representing contours from OpenCV. ratio (float): Float value used to rescale all the points in contours list. ...
5b9c3a30224f4bd8ac33c6aedecae564f5edcf3c
660,826
def turn(orientation, direction): """Given an orientation on the compass and a direction ("L" or "R"), return a a new orientation after turning 90 deg in the specified direction.""" compass = ['N', 'E', 'S', 'W'] if orientation not in compass: raise ValueError('orientation must be N, E, ...
393d80e317b959a33861c5f0b1745c730eb02745
660,827
import re def filter_star_import(line, marked_star_import_undefined_name): """Return line with the star import expanded.""" undefined_name = sorted(set(marked_star_import_undefined_name)) return re.sub(r'\*', ', '.join(undefined_name), line)
9bf4cbeb79550afd5be0863ca85679579b85cb67
660,828
def pathToString(filepath): """ Coerces pathlib Path objects to a string (only python version 3.6+) any other objects passed to this function will be returned as is. This WILL NOT work with on Python 3.4, 3.5 since the __fspath__ dunder method did not exist in those verisions, however psychopy does ...
4cd41579cfa4369d5fad06521723bf970ff6d502
660,829
def get_count(line): """ Return the count number from the log line """ return line.rstrip().split(":")[-1].strip()
00fd310ece12c70641ec76cf17049cf28dd025ae
660,830
import hmac import hashlib def do_hmac(key, value): """Generate HMAC""" h = hmac.new(key, msg=None, digestmod=hashlib.sha384) h.update(value.encode("utf-8")) return h.hexdigest()
3619f6705fe0f0d38467a778653ddf2dc0079c3a
660,832
def first_bad_version(last_version, is_bad_version): """ Finds the first bad version. Runtime: O(n), I should have thought this function as if find the min number in the sorted list. """ for version in range(last_version, -1, -1): print(f"version: {version}") if not is_bad_versi...
9bfe7f7ef8b4b65efbe3e1b0855b41f9e2f23087
660,833
import os import shelve def open_dashboards(path, **kwargs): """ Open Python shelve containing dashboard data in dictionary form. """ os.chdir(path) dashboards_shlf = shelve.open('dashboards.shelve', writeback=True) return dashboards_shlf
c453c40d367b7665c3259be06dc61cba8168b87f
660,834
import torch def squeeze_repr(nodes, edges, seg): """ This functions renames the nodes to [0,..,len(nodes)-1] in a superpixel rag consisting of nodes edges and a segmentation :param nodes: pt tensor :param edges: pt tensor :param seg: pt tensor :return: none """ _nodes = torch.arange(...
657d2bd636b97a013318dde8d7dde5b61ba513e5
660,835
def _majorana_terms_commute(term_a, term_b): """Whether two Majorana terms commute. Args: term_a (Tuple[int]): The indices of a Majorana operator term term_b (Tuple[int]): The indices of a Majorana operator term Returns: bool. Whether The terms commute. """ intersection = 0...
e3abfb3c6d4543be5a96aa77b7d913bde74d77c2
660,836
def if_columns(x): """ This function suffixes '_columns' to a dataframe (when saving it as a file) if columns are specified and suffixes '_dataframe' no columns are specified (i.e. when the user wants to do EDA of the entire dataset). :param x: list of columns :return: '_columns' suffix if list of c...
3d26f4a7f880fe09078e15fa1c0594c4bc47eec1
660,838
def receive(conn, end_token="!END!"): """Return a full message read from a socket connection""" full_message = [] msg = '' while True: msg = conn.recv(4096) if end_token in msg: full_message.append(msg[:msg.find(end_token)]) break full_message.append(msg) ...
85e032c8c58bb93c173b45c87008b5e82c0d9169
660,841
def historical_imagery_photo_type_to_linz_geospatial_type(photo_type: str) -> str: """Find value in dict and return linz_geospatial_type, else return the original value string. """ geospatial_type_conversion_table = { "B&W": "black and white image", "B&W IR": "black and white infrared im...
af244f74254398c52c5bdabf2a8bb5f59dcd5053
660,842