content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def cube(x): """return x^3""" return x*x*x
df9aa4330b7cfb1946b3c403935c864a2e7fae7a
708,006
import os from pathlib import Path def is_root() -> bool: """ Checks whether the current user is root (or, on Windows, an administrator). """ if os.name == 'nt': try: _dummy = list((Path(os.environ.get('SystemRoot', 'C:\\Windows')) / 'Temp').iterdir()) return True ...
b6fb87fd0a8daab882e506aa5e289d83eb61c242
708,007
from typing import Tuple def load_forcings_gauge_metadata(path: str) -> Tuple[float, float, float]: """ Loads gauge metadata from the header of a CAMELS-USE forcings file. Parameters ---------- path: str Path to the forcings file. Returns ------- tuple (gauge latitude...
c91c3bafb83709967d6dd480afd8e53ac9f94445
708,008
def append_artist(songs, artist): """ When the songs gathered from the description just contains the titles of the songs usually means it's an artist's album. If an artist was provided appends the song title to the artist using a hyphen (artist - song) :param list songs: List of song titles (onl...
b3fbda311849f68ab01c2069f44ea0f694365270
708,010
def get_missing_columns(missing_data): """ Returns columns names as list that containes missing data :param missing_data : return of missing_data(df) :return list: list containing columns with missing data """ missing_data = missing_data[missing_data['percent'] > 0] missing_...
80feccec6148a417b89fb84f4c412d9ea4d0dd37
708,011
def get_function_name(fcn): """Returns the fully-qualified function name for the given function. Args: fcn: a function Returns: the fully-qualified function name string, such as "eta.core.utils.function_name" """ return fcn.__module__ + "." + fcn.__name__
ae186415225bd5420de7f7b3aef98480d30d59f8
708,012
def clean_cases(text): """ Makes text all lowercase. :param text: the text to be converted to all lowercase. :type: str :return: lowercase text :type: str """ return text.lower()
9b0c931336dbf762e5e3a18d103706ddf1e7c14f
708,013
def filter_0_alleles(allele_df, allele_num=2): """Drop alleles that do not appear in any of the strains. """ drop_cols = [] for col in allele_df.columns: if allele_df[col].sum()<allele_num: drop_cols.append(col) allele_df.drop(drop_cols, inplace=True, axis=1) return allele_df
9b76152d6e6fc200c2d80d4721122d3958642286
708,015
def gradient_of_rmse(y_hat, y, Xn): """ Returns the gradient of the Root Mean Square error with respect to the parameters of the linear model that generated the prediction `y_hat'. Hence, y_hat should have been generated by a linear process of the form Xn.T.dot(theta) Args: y...
73a46197f90cf1b9c0a90a8ce2d2eae006c6d002
708,016
def align_down(x: int, align: int) -> int: """ Align integer down. :return: ``y`` such that ``y % align == 0`` and ``y <= x`` and ``(x - y) < align`` """ return x - (x % align)
8144309badf601999f4c291ee3af5cfbd18397ea
708,017
import glob import csv def write_colocated_data_time_avg(coloc_data, fname): """ Writes the time averaged data of gates colocated with two radars Parameters ---------- coloc_data : dict dictionary containing the colocated data parameters fname : str file name where to store th...
2e786c6df8a617f187a7b50467111785342310c5
708,019
def augment_note_matrix(nmat, length, shift): """Pitch shift a note matrix in R_base format.""" aug_nmat = nmat.copy() aug_nmat[0: length, 1] += shift return aug_nmat
a1ff855266e44012e05347a95abfa5324fd6e4e6
708,020
def breed_list(request): """ Фикстура возвращает список всех пород собак """ return request.param
29394d8a97444680acc3a0b7ff0f1b2949a5609d
708,021
def tail(file, n=1, bs=1024): """ Read Last n Lines of file credit: https://www.roytuts.com/read-last-n-lines-from-file-using-python/ https://github.com/roytuts/python/blob/master/read-lines-from-last/last_lines_file.py """ f = open(file) f.seek(0, 2) l = 1-f.read(1).count('\n') B ...
db7443e4af1028565491cb06944717488506b2b7
708,022
def null_count(df): """ df is a dataframe Check a dataframe for nulls and return the number of missing values. """ return df.isnull().sum().sum()
6e3eb91a3eaec456bb828b44be0780b64470e823
708,023
import subprocess def currentGUIusers(): """Gets a list of GUI users by parsing the output of /usr/bin/who""" gui_users = [] proc = subprocess.Popen('/usr/bin/who', shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) ...
69c7b62ea3b3759b5efc64c68fe0110f59fda9db
708,024
import glob import os import csv def extract(func): """ Decorator function. Open and extract data from CSV files. Return list of dictionaries. :param func: Wrapped function with *args and **kwargs arguments. """ def _wrapper(*args): out = [] instance, prefix = args for fn...
2a369596b6b26edc7259f27e7f594bd997d04f48
708,025
import os def list_all_projects(path): """lists all projects from a folder""" project_names = [] for file in os.listdir(path): if not os.path.isfile(os.path.join(path, file)): continue project_names.append(file.split('.')[0]) return project_names
f40c9c5868b49170b2dcd7326e0effe2ce99ee45
708,026
def get_trail_max(self, rz_array=None): """ Return the position of the blob maximum. Either in pixel or in (R,Z) coordinates if rz_array is passed. """ if (rz_array is None): return self.xymax # Remember xycom[:,1] is the radial (X) index which corresponds to R return rz_array[self....
5456c95ba4cb02352aa69398f9fa5307f3dc8e06
708,027
from typing import Tuple from typing import List def create_annotation(annotation_id: int, image_id: int, category_id: int, is_crowd: int, area: int, bounding_box: Tuple[int, int, int, int], segmentation: List[Tuple[int, int]]) -> dict: """ Converts input data to COCO annotation informat...
715a6204ed5dd9b081ac6e87541df3cd46d329a1
708,029
def asset_name(aoi_model, model, fnf=False): """return the standard name of your asset/file""" prefix = "kc_fnf" if fnf else "alos_mosaic" filename = f"{prefix}_{aoi_model.name}_{model.year}" if model.filter != "NONE": filename += f"_{model.filter.lower()}" if model.rfdi: filename...
e7211bec70739e53280ce424e1cb3c4c4304ac54
708,031
def rgb2hex(rgb_color): """ 'rgb(180, 251, 184)' => '#B4FBB8' """ rgb = [int(i) for i in rgb_color.strip('rgb()').split(',')] return '#{:02x}{:02x}{:02x}'.format(rgb[0], rgb[1], rgb[2])
40a01ccc5695266aebaf63a169c1039a6f42a724
708,032
def execute(cursor, query): """Secure execute for slow nodes""" while True: try: cursor.execute(query) break except Exception as e: print("Database query: {} {}".format(cursor, query)) print("Database retry reason: {}".format(e)) return cursor
b46338ab7304737d3b12cb1bd4d4dff9665d0f60
708,033
import zipfile def zip_to_gdal_path(filepath): """ Takes in a zip filepath and if the zip contains files ascii files, prepend '/viszip' to the path so that they can be opened using GDAL without extraction. """ zip_file_list = [] if zipfile.is_zipfile(filepath): try: ...
9e9e44d6eb3022ebe982cc44284da76f56a4ddeb
708,034
def is_eval_epoch(cfg, cur_epoch): """ Determine if the model should be evaluated at the current epoch. Args: cfg (CfgNode): configs. Details can be found in sgs/config/defaults.py cur_epoch (int): current epoch. """ return ( cur_epoch + 1 ) % cfg.TRAIN.EVAL_P...
d8abb04409879b88bdfd32cf323bcbea037ae630
708,035
def _getMissingResidues(lines): """Returns the missing residues, if applicable.""" try: missing_residues = [] for i, line in lines['REMARK 465']: if len(line.split()) == 5 and int(line.split()[4]) > 0: missing_residues.append("{0:<3s} {1}{2:>4d}".format(line.split()[...
071c6d792bc703d0379774eb19c09d9599f17c66
708,036
def get_season(msg, info_fields): """find season in message""" seasonDICT = {'2016':['二零一六球季', '二零一六賽季', '2016球季', '2016賽季', '2016年', '2016'], '2017':['二零一七球季', '二零一七賽季', '2017球季', '2017賽季', '2017年', '2017'], '2018':['二零一八球季', '二零一八賽季', '2018球季', '2018賽季', '2018年', '2018'], ...
8b5dfceafe45d9ba325c519b24dde03a20d37655
708,038
def lsst_exposure_time(bands=''): """ Sample from the LSST exposure time distribution """ dist = {'u': 15.0, 'g': 15.0, 'r': 15.0, 'i': 15.0, 'z': 15.0, 'Y': 15.0} return [dist[b] for b in bands.split(',')]
1374512a73b9a0eaf3b1757b09cfdd519fba520c
708,039
def bin2hexstring(bin_str): """ 二进制串转十六进制串,按照 4:1 比例转换 :param bin_str: 二进制串 :return: 十六进制串 """ bin_len = len(bin_str) left = 0 right = 4 re_str = hex(int(bin_str[left:right], 2))[2:] for i in range(right, bin_len, 4): left = right right += 4 re_str += hex(...
823ba4ef86ebcf7e30a29c3718768c6a654acad5
708,040
def check_dict_word(word, target): """ Check dict word. If one character not in searching word, then not add the word to python_dict. :param word: str, word in dictionary.txt. :param target: str, the searching word :return: True, all character within are in searching word. """ # Level one: c...
91751f580aa74b7340946f0642c24e11dc19ff32
708,041
def get_memory_in_GB(memory_str): """Returns the memory value in GB from a given string in kB""" try: return '{0} GB'.format(int(memory_str[:-2]) / 1000000) except (ValueError, TypeError): return ''
4c94c00a5e800ed807f4c3a31fe89e90f28260fe
708,042
def filehash(thisfile, filesha): """ First parameter, filename Returns SHA1 sum as a string of hex digits """ try: filehandle = open(thisfile, "rb") except: return "" data = filehandle.read() while data != b"": filesha.update(data) data = filehandle.read(...
bb6c965d5a0c5f332320d2426b066b4fa85f77e3
708,043
from sys import getsizeof def object_size(o): """ Calls `getsizeof <https://docs.python.org/3/library/sys.html#sys.getsizeof>`_. @param o object @return size of the object, that excludes references objects. """ return getsizeof(o)
f66dbbd543001b904f960aa75fd26f0c4737f5a5
708,044
import time def current_time(): """ current_time() -> str >>> current_time() 14:28:04 Returns the current local time in 24 clock system. """ return time.strftime('%X', (time.localtime()))
9ab4ed21d1480e1923c8a55b8f213ff47cb8adcc
708,045
def prepare_hex_string(number, base=10): """ Gets an int number, and returns the hex representation with even length padded to the left with zeroes """ int_number = int(number, base) hex_number = format(int_number, 'X') # Takes the string and pads to the left to make sure the number of characte...
e6efeca87d5f0a603c8fdb65fd7e2d07cc491766
708,046
def plotly_figure(figure, id: str): """ :param figure: plotly graph object or px figure :param id: unique id string of format 'id_xxx' with x representin a number :return: html style string containing a plotly figure """ json_figure = figure.to_json() html = """ <div id="""+id+"""></...
949415c70d467c48ee3aa1f028c9e3539099febf
708,047
def _add_resources_to_vault_obj(obj, data, columns): """Add associated resources to column and data tuples """ i = 0 for s in obj.resources: if obj.resources[i].id: name = 'resource_id_' + str(i + 1) data += (obj.resources[i].id,) columns = columns + (name,) ...
3a6dd7541ac853a7c62b638abf4d0eeb21bb6cb2
708,048
def classify_helmet_belt_worn(x): """ This function returns a strinig representation of the int value of the field which specifies whether the person was wearing a setabelt or a helmet. This specification is from the Road Crash Statistics Victoria , 2013 Edition document. :param x: int value represe...
cba05be8d03c933e767a75400032d07e296e0ec3
708,049
import collections def sort_dataset_by_len(dataset): """ returns a dict mapping length -> list of items of that length an OrderedDict is used to that the mapping is sorted from smallest to largest """ sorted_dataset = collections.OrderedDict() lengths = sorted(list(set(len(x[1]) for x in datas...
1e67da963c6d968fba39730cc33e100242fcafca
708,050
import copy import random def select_random_user_goals(user_goals_no_req_slots, user_goals_with_req_slots, cardinality_no_req, cardinality_req): """ Helper method to randomly select user goals """ random_user_goals = {} random_user_goals['all'] = [] # select randomly user goals without reque...
ff51361d45cdbd62cc9ee9e8263d47870435b326
708,051
import click def optional_tools_or_packages_arg(multiple=False): """ Decorate click method as optionally taking in the path to a tool or directory of tools or a Conda package. If no such argument is given the current working directory will be treated as a directory of tools. """ name = "paths" if ...
4a34da51b4a644df70c5ce3ea8afb8b86ae2281d
708,052
import numpy def linear_interpolate_cdf(base_cdf): """Linear interpolate regions of straight lines in the CDF. Parameters: base_cdf (list): n elements of non-decreasing order. Returns: list of length base_cdf where consecutive elements of straight lines are linearly interpolated ...
8f119d1698a44e90253920decf1b3253db9171be
708,053
def hash_str(string: str) -> int: """ Create the hash for a string (poorly). """ hashed = 0 results = map(ord, string) for result in results: hashed += result return hashed
b80c177974437966361e4117ba235c1563fee5c4
708,054
def compare_files(file_name1, file_name2): """ Compare two files, line by line, for equality. Arguments: file_name1 (str or unicode): file name. file_name2 (str or unicode): file name. Returns: bool: True if files are equal, False otherwise. """ with open(file_name1) as f...
3f77cf177ba60ddd121b95648379fff845d9877b
708,055
import os def _get_template_dirs(type="plugin"): """Return a list of directories where templates may be located. """ template_dirs = [ os.path.expanduser(os.path.join("~", ".rapport", "templates", type)), os.path.join("rapport", "templates", type) # Local dev tree ] return templat...
b0c6351d0e346310f5d36c6d010332cc1e1b54ea
708,056
def push_gitlab_event_dict(): """ Cleared version of the push gitlab webhook content. """ return { "object_kind": "push", "event_name": "push", "before": "0e27f070efa4bef2a7c0168f07a0ac36ef90d8cb", "after": "cb2859505e101785097e082529dced35bbee0c8f", "ref": "refs/...
3a0134774f828e233c8b1e3fd2d6b94d6fae699f
708,057
import collections def sort_dict(d, key=None, reverse=False): """ Sorts a dict by value. Args: d: Input dictionary key: Function which takes an tuple (key, object) and returns a value to compare and sort by. By default, the function compares the values of the dict ...
9ca904a5e0df3e3c50b29967adfe9061e778dfc9
708,058
def getReviewRedirect(entity, params): """Returns the redirect to review the specified entity. """ return '/%s/review/%s' % ( params['url_name'], entity.key().id_or_name())
959ff6d0297ec54248ee725e93a79702512d00d7
708,059
import sympy def __sympyToC_Grad(exprs: list, doOpts: bool = False) -> str: """ creates C code from a list of sympy functions (somewhat optimized). source: https://stackoverflow.com/questions/22665990/optimize-code-generated-by-sympy and modified """ tmpsyms = sympy.numbered_symbols("tmp") if do...
33a95d99b19458ac7b8dd8d8e4272485b0f5f206
708,060
def ger(self, y): """Computer an outer product between two vectors""" assert self.dim() == 1 and y.dim() == 1, "Outer product must be on 1D tensors" return self.view((-1, 1)).matmul(y.view((1, -1)))
003dda3dd678fdcf35f63f80c064586320c97d23
708,061
def loadSource(path): """Loads a list of transportReactions. Format: R("Macgamb_Transp") R("Madnb_Transp") R("MalaDb_Transp")...""" file = open(path, 'r') sources = [line.strip() for line in file] file.close() return sources
244e9e5619a5039822ef14dfbb3d99b55cb6cc74
708,062
import ast def transpose_dict(data, data_key): """Function: transpose_dict Description: Transpose specified keys in a list of dictionaries to specified data types or None. Arguments: (input) data -> Initial list of dictionaries. (input) data_key -> Dictionary of keys and data ...
7675ea2f80e9e85993dc99a2a31df04abfeba2c8
708,063
def aligner_to_symbol(calls): """ Assign symbols to different aligners in the input file Set the attribute of the class instances return a list of indices for which each aligner is found uniquely and all aligners sorted by aligners """ symbols = ['o', '+', 'x', 'v', '*', 'D', 's', 'p', '8',...
b9cef3ae33b6ce84daf78a8bc8ce528f97d7a8a6
708,064
def convertCRS(powerplants, substations, towers, crs, grid): """ :param powerplants: :param substations: :param towers: :param crs: :return: """ substations.to_crs(crs) # powerplants = powerplants.set_crs(crs) # powerplants = powerplants.to_crs(crs) # print(powerplants.crs) ...
9fcb8c51323c00935ba2c882502a273f2bf532ff
708,065
def read_number(dtype, prompt='', floor=None, ceil=None, repeat=False): """ Reads a number within specified bounds. """ while True: try: result = dtype(input(prompt)) if floor is not None and result < floor: raise ValueError(f'Number must be no less than...
a528b1f5912ba4bab0b87c87004311778eaa8187
708,066
from copy import copy from numpy import zeros, unique from itertools import product def trainModel(label,bestModel,obs,trainSet,testSet,modelgrid,cv,optMetric='auc'): """ Train a message classification model """ pred = zeros(len(obs)) fullpred = zeros((len(obs),len(unique(obs)))) model = copy(bestMode...
fdf60d23894bfd997cdf7fa82cb59257ad7b2954
708,067
import sys def get_cpuinfo(): """Returns the flags of the processor.""" if sys.platform == 'darwin': return platforms.osx.get_cpuinfo() if sys.platform == 'win32': return platforms.win.get_cpuinfo() if sys.platform == 'linux2': return platforms.linux.get_cpuinfo() return {}
2ac223337d54426d36c9fda8d88f3545c6d4c30a
708,068
def default_thread_index (value, threads): """ find index in threads array value :param value: :param threads: :return: """ value_index = threads.index(value) return value_index
7be2efb6579f2880f53dac11705ba6a068c2d92d
708,069
def isID(value): """Checks if value looks like a Ulysses ID; i.e. is 22 char long. Not an exact science; but good enougth to prevent most mistakes. """ return len(value) == 22
527db9446adc2b88c2117bd35c74474c3e7bad24
708,070
def _extract_codes_from_element_text(dataset, parent_el_xpath, condition=None): # pylint: disable=invalid-name """Extract codes for checking from a Dataset. The codes are being extracted from element text. Args: dataset (iati.data.Dataset): The Dataset to check Codelist values within. parent_e...
45e4ec2a61dc38066ad9a71d41e63a48c6ccde23
708,071
def _do_ecf_reference_data_import( import_method, widget, logwidget=None, specification_items=None, ecfdate=None, datecontrol=None, ): """Import a new ECF club file. widget - the manager object for the ecf data import tab """ ecffile = widget.datagrid.get_data_source().dbhome ...
593b1ac77688c92c9fcd3ea8fafb3f5089849293
708,072
def decrement(x): """Given a number x, returns x - 1 unless that would be less than zero, in which case returns 0.""" x -= 1 if x < 0: return 0 else: return x
56b95324c147a163d3bdd0e9f65782095b0a4def
708,073
def solver_problem1(digits_list): """input digits and return numbers that 1, 4, 7, 8 occurs""" cnt = 0 for digits in digits_list: for d in digits: if len(d) in [2, 3, 4, 7]: cnt += 1 return cnt
d1946d00d368ad498c9bb0a8562ec0ea76d26449
708,074
import decimal def round_decimal(x, digits=0): """This function returns the round up float. Parameters ---------- x : a float digits : decimal point Returns ---------- Rounded up float """ x = decimal.Decimal(str(x)) if digits == 0: return int(...
8670fa1e9063376e012ebbc71df0a19c6205ea9c
708,075
def getPrefix(routetbl, peer_logical): """ FUNCTION TO GET THE PREFIX """ for route in routetbl: if route.via == peer_logical: return route.name else: pass
2ca32a1fd63d6fcefbcc9ac23e8636c73e88455b
708,076
def dump_tuple(tup): """ Dump a tuple to a string of fg,bg,attr (optional) """ return ','.join(str(i) for i in tup)
ffa4838e2794da9d525b60f4606633f8940480bb
708,078
def gen_check_box_idx(): """ Generate a list containing the coordinate of three finder patterns in QR-code Args: None Returns: idx_check_box: a list containing the coordinate each pixel of the three finder patterns """ idx_check_box = [] for i in range(7...
e26d9c5a3b093b52f54eb2c65b844215c40ddab8
708,079
import json def json_formatter(result, verbose=False, indent=4, offset=0): """Format result as json.""" string = json.dumps(result, indent=indent) string = string.replace("\n", "\n" + " "*offset) return string
512847722fa36eff408ac28d6e3dc8fde5c52af1
708,080
from typing import Any from typing import Counter def calc_proportion_identical(lst: Any) -> float: """ Returns a value between 0 and 1 for the uniformity of the values in LST, i.e. higher if they're all the same. """ def count_most_common(lst): """ Find the most common item in LS...
adf467eba11694c5ea4583d7b53029110e59e25a
708,081
import os def getDirectoriesInDir(directory): """ Returns all the directories in the specified directory. """ directories = {} for d in os.listdir(directory): path = os.path.join(directory, d) if os.path.isdir(path): directories[d] = path return directories
8d78571d0ebc4fba58abf98354a7bd2bea018e60
708,082
import numpy def csr_matrix_multiply(S, x): # noqa """Multiplies a :class:`scipy.sparse.csr_matrix` S by an object-array vector x. """ h, w = S.shape result = numpy.empty_like(x) for i in range(h): result[i] = sum(S.data[idx]*x[S.indices[idx]] # noqa pylint:disable=unsupported-assignme...
77e1630cbdd59f53b1b2885b731e73a14fb18b35
708,083
def _singleton(name): """Returns a singleton object which represents itself as `name` when printed, but is only comparable (via identity) to itself.""" return type(name, (), {'__repr__': lambda self: name})()
b07003e1716115864bf1914d4b523b36d0f0471f
708,084
import pickle def fetch_pickle(filename): """ Fetches any variable saved into a picklefile with the given filename. Parameters: filename (str): filename of the pickle file Returns: variable (any pickle compatible type): variable that was saved into the picklefile. """...
172c18520619d102b520658949d2464d5ecfb05c
708,085
def check_clockwise(poly): """Checks if a sequence of (x,y) polygon vertice pairs is ordered clockwise or not. NOTE: Counter-clockwise (=FALSE) vertice order reserved for inner ring polygons""" clockwise = False if (sum(x0*y1 - x1*y0 for ((x0, y0), (x1, y1)) in zip(poly, poly[1:] + [poly[0]]))) < 0: ...
5e9f8fba6cd11e33dfe60a89e62eeac2ac24c805
708,086
def format_stats(stats): """Format statistics for printing to a table""" result = '' for key, value in stats.items(): result += f'{key} - {value}\n' return result[:-1]
2d01b6c48b83f8e8810f4609183b39fad871f942
708,087
def timestamp2str(ts): """ Converts Timestamp object to str containing date and time """ date = ts.date().strftime("%Y-%m-%d") time = ts.time().strftime("%H:%M:%S") return ' '.join([date, time])
0e847a8af0cbbacf18df911e3070ac7c70e504b7
708,088
import os def compute_file_path(data_path, path, command): """Return the computed file path for mocked data Keyword arguments: data_path -- the path of the folder that contains the subbed data path -- the URL path command -- the HTTP verb """ return os.path.realpath( os.path.join...
8260a67edb5fca16e4b9004e8596cc080c98ff19
708,089
import time def getToday(format=3): """返回今天的日期字串""" t = time.time() date_ary = time.localtime(t) if format == 1: x = time.strftime("%Y%m%d", date_ary) elif format == 2: x = time.strftime("%H:%M", date_ary) elif format == 3: x = time.strftime("%Y/%m/%d", date_ary) el...
900c0a0d42dc2220c5e5030eeebd858e3e6a41bf
708,091
def parse_test_config(doc): """ Get the configuration element. """ test_config = doc.documentElement if test_config.tagName != 'configuration': raise RuntimeError('expected configuration tag at root') return test_config
c61c2f4e43c5501c461bb92b63609162b2918860
708,093
import textwrap def _get_control_vars(control_vars): """ Create the section of control variables Parameters ---------- control_vars: str Functions to define control variables. Returns ------- text: str Control variables section and header of model variables section. ...
614a6ca5bc8ac7354f63bfceabaff4eb4b93208a
708,094
def get_paybc_transaction_request(): """Return a stub payment transaction request.""" return { 'clientSystemUrl': 'http://localhost:8080/abcd', 'payReturnUrl': 'http://localhost:8081/xyz' }
b913438562d4f2b0883e340b48843f9954faa8a4
708,095
def have_same_items(list1, list2): """ Проверяет состоят ли массивы list1 и list2 из одинакового числа одних и тех же элементов Parameters ---------- list1 : list[int] отсортированный по возрастанию массив уникальных элементов list2 : list[int] массив...
2973a1961e25686fcbd2003dd366429cbd4c67eb
708,097
def rgb2hex(rgb): """Converts an RGB 3-tuple to a hexadeximal color string. EXAMPLE ------- >>> rgb2hex((0,0,255)) '#0000FF' """ return ('#%02x%02x%02x' % tuple(rgb)).upper()
4c3323e34fcd2c1b4402ebe5f433c5fd9320cce9
708,098
def create_table(p, table_name, schema): """Create a new Prism table. Parameters ---------- p : Prism Instantiated Prism class from prism.Prism() table_name : str The name of the table to obtain details about. If the default value of None is specified, details regarding fir...
43c8c789d4e212d2d98d68f4f22e3f0fb0a97552
708,100
def valid_chapter_name(chapter_name): """ 判断目录名称是否合理 Args: chapter_name ([type]): [description] """ for each in ["目录"]: if each in chapter_name: return False return True
9ec71837503f969808a6a666a3bf999ee3290f03
708,101
def subfield(string, delim, occurrence): """ function to extract specified occurence of subfield from string using specified field delimiter eg select subfield('abc/123/xyz','/',0) returns 'abc' eg select subfield('abc/123/xyz','/',1) returns '123' eg select subfield('abc/123/xyz','/',2) retu...
ef022d0ca05e969e8ad69e4644cd24d1b7f47cb8
708,102
def extract_info(spec): """Extract information from the instance SPEC.""" info = {} info['name'] = spec.get('InstanceTypeId') info['cpu'] = spec.get('CpuCoreCount') info['memory'] = spec.get('MemorySize') info['nic_count'] = spec.get('EniQuantity') info['disk_quantity'] = spec.get('DiskQuan...
7f93dcad1a8d99743a30d441dad64c2b9af08037
708,103
def parse_title(title): """Parse strings from lineageos json :param title: format should be `code - brand phone` """ split_datum = title.split(' - ') split_name = split_datum[1].split(' ') device = split_datum[0] brand = split_name[0] name = ' '.join(split_name[1:]) return [brand,...
c3783ab36f4f7e021bdd5f0f781bb289ab2d458f
708,104
def config_data() -> dict: """Dummy config data.""" return { "rabbit_connection": { "user": "guest", "passwd": "guest", "host": "localhost", "port": 5672, "vhost": "/", }, "queues": {"my_queue": {"settings": {"durable": True}, "...
cbbed3baf79b5928be47d3d00c747ac6be625ae5
708,105
def copy_linear(net, net_old_dict): """ Copy linear layers stored within net_old_dict to net. """ net.linear.weight.data = net_old_dict["linears.0.weight"].data net.linear.bias.data = net_old_dict["linears.0.bias"].data return net
8ba7f40e72b65ebef9948025b3404cbc5a660960
708,106
import sys import logging import os def to_relative(path, root, relative): """Converts any absolute path to a relative path, only if under root.""" if sys.platform == 'win32': path = path.lower() root = root.lower() relative = relative.lower() if path.startswith(root): logging.info('%s starts wi...
50911c6cec942e9be0d694f95213053e23d2707a
708,107
def bdev_nvme_add_error_injection(client, name, opc, cmd_type, do_not_submit, timeout_in_us, err_count, sct, sc): """Add error injection Args: name: Name of the operating NVMe controller opc: Opcode of the NVMe command cmd_type: Type of NVMe command. Va...
3833256e71f47a49eef2643bf8c244308795a0b1
708,108
def prune_deg_one_nodes(sampled_graph): """ prune out degree one nodes from graph """ deg_one_nodes = [] for v in sampled_graph.nodes(): if sampled_graph.degree(v) == 1: deg_one_nodes.append(v) for v in deg_one_nodes: sampled_graph.remove_node(v) return sampled_graph
c4df72a66c6fb57d5d42a1b877a846338f32f42a
708,110
def run_sgd(model, epochs): """ Runs SGD for a predefined number of epochs and saves the resulting model. """ print("Training full network") weights_rand_init = model.optimize(epochs=epochs) # weights_rand_init = model.optimize(epochs=epochs, batch_size=55000, learning_rate=0.1) print("M...
14c6fd1ffa8aab3a783b5738093d69771d036411
708,111
def drift_var(): """ Concept drift: 1. n_drifts 2. concept_sigmoid_spacing (None for sudden) 3. incremental [True] or gradual [False] 4. recurring [True] or non-recurring [False] """ return [(10, None, False, False), (10, 5, False, False), (10, 5, True, False)]
34f2c55f928a16cca8c52307853ab32f56ecd954
708,112
def processed_transcript(df): """ Cleans the Transcript table by splitting value fileds and replacing nan values, drop extra columns PARAMETERS: transcript dataframe RETURNS: Cleaned transcript dataframe """ #expand the dictionary to coulmns (reward, amount, offre...
452668d6d9616ca382f7968e0ac4dd52658be9f6
708,113
def clean_data(list_in): """ Inputs: list_in - filtered list of ticket orders Outputs: Return list of tuples, each tuple contains (last name, first name, note,[tickets]) """ notes_list = [] data_out = [] for row in list_in: trimmed_row = row[row.index('Purcha...
f2cdf17895d1661e40b64f3fcc9ff92558f53bdd
708,114
import json def embed_terms(args, classes, dest, use_cache=True, path_to_json='ebd_cache.json'): """ Embeds class strings into word representations. :param args :param classes: (list of str) topic classes :param dest: (str) path to destination file :param path_to_json: (str) path to json file...
8521b4828907c0083492b0d03848aeeb452d17e6
708,115
def matrixmult (A, B): """Matrix multiplication function This function returns the product of a matrix multiplication given two matrices. Let the dimension of the matrix A be: m by n, let the dimension of the matrix B be: p by q, multiplication will only possible if n = p, thus creating a matr...
98065981c8047d927bacb07877dbf173ba379159
708,116
def next_code(value: int, mul: int = 252533, div: int = 33554393) -> int: """ Returns the value of the next code given the value of the current code The first code is `20151125`. After that, each code is generated by taking the previous one, multiplying it by `252533`, and then keeping the remainder...
a9e5183e405574cc56a138a244f14de08ea68d00
708,117