content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
from typing import Callable from typing import Any def slice_second_dim(idx: int, to_long: bool = False) -> Callable[[Any], Any]: """ Utility function to generate slice functions for multi-task losses. """ def slice(x: Any) -> Any: if to_long: return x[:, idx].long() else: ...
167c5ba48919350b20ec62cb4d2b1f8e3950e3e4
677,216
import pickle def predict_rf(a): """ shape of a = (21,1) """ filename = 'rf_model.pkl' # try: loaded_model = pickle.load(open(filename, 'rb')) predict = loaded_model.predict(a) print(predict) print("prediction done :)") return predict
444c11a2ae3df598395e4c5d4e84c2fb3db46310
677,217
def parse_json(request): """ Default content parser for JSON """ return request.json
cc45af02c1ac9b3838fbf8434661321af6337f27
677,218
def multi_3_5(nums): """Find multiples of three or five return sum of non-repeating nums. Given a number, find its multiples of three or five input = natural number output = sum non-repeating natural numbers ex input = 10, ex output = 23, i.e. [3, 5, 6, 9] ex input = 20, ex output = 78, i.e. [3...
b0ef93dd0f9228a3aa89340ae509d695e353247d
677,219
def getUrl(sIpAddress): """Returns the full cgi URL of the target""" return 'http://' + sIpAddress + '/cgi-bin/xml-cgi'
d51499ef9828ead13f7a17a6a7ba0484cc3d3b91
677,220
def _initial_gaussian_params(xm, ym, z, width=5): """ Guesses the initial 2D Gaussian parameters given a spatial filter. Parameters ---------- xm : array_like The x-points for the filter. ym : array_like The y-points for the filter. z : array_like The actual data t...
d36522c30d937672c4bfddcb698b0029ddd6bb18
677,221
def _build_stub_groups(args, sources, default_stub_value): """ :type args: CoverageConfig :type sources: List[tuple[str, int]] :type default_stub_value: Func[int] :rtype: dict """ groups = {} if args.stub: stub_group = [] stub_groups = [stub_group] stub_line_limi...
d241d1ab4e2474fb1fefef4d3ac293e6f2bdea7d
677,222
import re def requires(prefix=''): """Retrieve requirements from requirements.txt """ try: reqs = map(str.strip, open(prefix + 'requirements.txt').readlines()) return [req for req in reqs if not re.match(r'\W', req)] except Exception: pass return []
85c53c21bd8aaccd58ee8e37f7f83cf1b0d5abe3
677,223
import os def get_folder_path_and_name(): """ Use case: get_folder_path_and_name() Note: If you are in ~/cells/PurkinjeCell/some_test.py This function will return: 1. path_to_folder -> ~/cells 2. folder_name -> PurkinjeCell """ path_with_folder = os.path.dirna...
cbdacb960c1e28d160e07050aaada290f8b18b89
677,224
import torch def d_mse_loss(input, target): """ Returns the gradient of loss w.r.t to input """ if not isinstance(target, torch.FloatTensor): target = target.float() return 2*(input-target)
52d5ca90dd8d9873c2addec7d6c95010147cc85a
677,225
def get_ray_num(file_path): """ extract the ray's number from it's file name Parameters: file_path : string: full path to ray file Returns: num :string : the number corresponding to the ray """ filename = file_path.split('/')[-1] num = filename[3:-3] return num
3e7367097ea6f57aae083dc1e1463bcdff9fe32d
677,226
from sys import version_info def hex_to_int(value): """ Convert hex string like "\x0A\xE3" to 2787. """ if version_info.major >= 3: return int.from_bytes(value, "big") return int(value.encode("hex"), 16)
74f6c9ce931f693caf9a9259e1c44b96650f5593
677,227
def stats_file_keys(gene_number): """Return fiels in stats file, ordered, as a list of string""" return [ 'popsize', 'genenumber', 'generationnumber', 'diversity', ] + ['viabilityratio' + str(i) for i in range(gene_number) ] + ['viabilityratioDB'...
05a8b6837cc3b68d3e0f8c0ec4ca5e27cfe4e533
677,228
def knight_amount(board_state, player): """ Returns amount of knights the player has """ board = board_state knight_amt = 0 for row in board: for column in row: if player == 1 and column == "k": knight_amt += 1 elif player == 0 and column == "K": ...
4a2cad597ec0751fb6d4d751a177509576cba87d
677,229
def cut_spans_to_slices(cut_spans, start_time, end_time): """ Utility function for reversing list of time spans to cut from the stream to list of time spans which should be provided to ObsPy stream.slice method. :param cut_spans: time spans to cut from the stream :param start_time: stream start time...
6ce0048fec7c21a6ba99487387853b3dd3eb79b2
677,230
def enum(**named_values): """Creates an enum type.""" return type('Enum', (), named_values)
fa8390972f4ef343b3cbcc05bca064fe853aa876
677,231
def assign_pre_id_to_inner_nodes(phylo_tree): """ Replace the name of the inner nodes of a given phylogenetic tree with its preorder number in the tree. """ idx = 0 for node in phylo_tree.find_clades(terminal=False, order='preorder'): node.name = '%d' % (idx) idx += 1 ...
d114fe5c19b749c499cd8a1167ba6bf957c71c35
677,232
import os def jp_process_id(): """Choose a random unused process ID.""" return os.getpid()
9c5a55295c5f47c5b4fc27ea5addbeb3a00aee22
677,233
def get_column_names(path_to_test, key_to_infer): """ Get a list containing the names of the columns in your table minus the column that you want to infer. =Parameters= path_to_test: Path where your test.csv is saved. key_to_infer: The name of the column that you want to infer. """ with ...
f16a7269c2f9c913ec3c8dd86ed7137bb3ec900b
677,234
def _make_bold_stat_signif(value, sig_level=0.05): """Make bold the lowest or highest value(s).""" val = "{%.1e}" % value val = "\\textbf{%s}" % val if value <= sig_level else val return val
bdd9bef3da3e48aa28fbea68103f56fbf3e0dd62
677,235
def list_of_lists_to_md_table(rows): """Convert a list (rows) of lists (columns) to a Markdown table. The last (right-most) column will not have any trailing whitespace so that it wraps as cleanly as possible. Based on solution provided by antak in http://stackoverflow.com/a/12065663 CC-BY-SA 4.0 ...
12cb19028a05c921c9c57c7af93827a4bdcb53fc
677,237
def load_w(dtype): """ Return the function name to load data. This should be used like this:: code = '%s(ival)' % (load_w(input_type),) """ if dtype == 'float16': return 'ga_half2float' else: return ''
40abeda95da5f844a0aad501a28dca0928697390
677,238
def read_lines(file_path): """ Read lines from the file and return then as a list. """ lines = [] with open(file_path, 'r', encoding='utf8') as asm_file: lines = asm_file.readlines() return lines
a6f97f60edefac2207369624c4421829b8637fbe
677,239
import random def between(min_wait, max_wait): """ Returns a function that will return a random number between min_wait and max_wait. Example:: class MyUser(User): # wait between 3.0 and 10.5 seconds after each task wait_time = between(3.0, 10.5) """ return lambda...
54ca9ec56c8848c6672817d8bbd48357faedda6c
677,240
import os def listdir2(path: str): """ Decorates os.listdir by returning list of filenames and filepath :param path: the folder path to list content :return: list of (filename, filepath) """ path = os.path.normpath(path) return [(f, os.path.join(path, f)) for f in os.listdir(path)]
0edd5a16cd9fcb74373b6fc53e2d42e951e1bd1d
677,241
def _recolumn(tmy3_dataframe): """ Rename the columns of the TMY3 DataFrame. Parameters ---------- tmy3_dataframe : DataFrame inplace : bool passed to DataFrame.rename() Returns ------- Recolumned DataFrame. """ # paste in the header as one long line raw_columns...
facc1a29ff277546d5458d179b51003f0d0674db
677,242
def target_to_source(target_adjacency, embedding): """Copied from https://github.com/dwavesystems/dwave-system/blob/master/dwave/embedding/utils.py to avoid dependency cycle""" # the nodes in the source adjacency are just the keys of the embedding source_adjacency = {v: set() for v in embedding} # ...
888d23ad1c8162f5f3c18ee7bc02d475948646ab
677,243
import math def get_integer(value, decimal_type): """小数がある場あるの処理方法 :param value: :param decimal_type: :return: """ if value: if decimal_type == '0': # 切り捨て return math.floor(value) elif decimal_type == '1': # 四捨五入 return round(va...
bda6183c733507282e84a829fbec1b4954bcc7e5
677,244
import argparse def process_command_line(argv): """Process command line invocation arguments and switches. Args: argv: list of arguments, or `None` from ``sys.argv[1:]``. Returns: argparse.Namespace: named attributes of arguments and switches """ #script_name = argv[0] argv =...
da26cdd2799048198fd5a56df56b779736da34ae
677,245
import os def resolve_possible_paths(path, relative_prefix, possible_extensions=None, leading_underscore=False): """ Attempts to resolve the given absolute or relative ``path``. If it doesn't exist as is, tries to create an absolute path using the ``relative_prefix``. If that fails, tries relative/abs...
57a349eed0d62781e0cc51495e7c4d59d0692929
677,247
def get_insertion_excess(cigar): """Return excess insertions over deletions. Using pysam cigartuples sum all insertions and softclips (operation 1 and 4) minus sum of all deletions (operation 2) """ return sum([l for o, l in cigar if o in [1, 4]]) - sum([l for o, l in cigar if o == 2])
2ed458cfd4a46c163a7e19a18da14941e1ad5a28
677,249
import os def open_cmds_file(cmds_file): """Open txt file with intercepted commands and return file object. Raises: RuntimeError: Specified file does not exist or empty. """ if not os.path.exists(cmds_file): raise RuntimeError("Specified {} file does not exist".format(cmds_file)) ...
c009236568949035811c49dabd9a13521cfa3925
677,250
def _transform_outcome(y, t): """Transform outcome. Transforms outcome using approximate propensity scores. Equation is as follows: y_transformed_i = 2 * y_i * t_i - 2 * y_i * (1 - t_i), where t_i denotes the treatment status of the ith individual. This object is equivalent to the individual treatm...
7edda49f2164faeb70406ebc21c198b2eef09caa
677,251
def merge_pred_gt_boxes(pred_dict, gt_dict=None): """ Merge data from precomputed and ground-truth boxes dictionaries. Args: pred_dict (dict): a dict which maps from `frame_idx` to a list of `boxes` and `labels`. Each `box` is a list of 4 box coordinates. `labels[i]` is a lis...
03b2c9800850a7f6ebe34e3d18c4353b32113930
677,252
def _bop_and(obj1, obj2): """Boolean and.""" return bool(obj1) and bool(obj2)
96b285545f4d8d3b04ff68630c38592b192a815d
677,253
import requests import io import gzip def download_single_result(result): """Downloads HTML for single search result. Args: result: Common Crawl Index search result from the search function. Returns: The provided result, extendey by the corresponding HTML String. """ offset, length...
39fa98e891a5f2e7fbd3ec3fb90826ddab247cbc
677,254
import re def find_match(regex, text, stripchars='^$'): """ Finds a match from given text and return match else None. :param regex: Regular expression :param text: Target text :param stripchars: Characters to be removed from left and right :returns: boolean match object if match found else Fa...
38439c5dab26d5b6f4a04315a21f013d770fe715
677,256
def b2h(num, suffix='B'): """Format file sizes as human readable. https://stackoverflow.com/a/1094933 Parameters ---------- num : int The number of bytes. suffix : str, optional (default: 'B') Returns ------- str The human readable file size string. Ex...
6394c4ecc2bdf06f5f7b8f429e6b308030163c57
677,257
import cmath def tt_subscheck(subs): """Check whether the given list of subscripts are valid. Used for sptensor""" isOk = True; if(subs.size == 0): isOk = True; elif(subs.ndim != 2): isOk = False; else: for i in range(0, (subs.size / subs[0].size)): fo...
0a2397a9863a6c89081c3701f5b2f94e31761511
677,258
def get_directives_used(results): """scan search results for directives and return them if any """ result = set() for locations in results.values(): for line_results in locations: line, text, locs = line_results for loc in locs: try: na...
77e33798923efa44a897c8ea0b789116fbf32f0b
677,259
def indent(string_in: str, tabs: int = 0): """Returns the str intended using spaces""" return str(" " * tabs) + string_in
5311de4ab33e0020f95bc126c4db06fdf452212f
677,260
import random import string def generate_secret_key(): """Generate secret key.""" rng = random.SystemRandom() return ''.join( rng.choice(string.ascii_letters + string.digits) for dummy in range(0, 256) )
029827d4423ba39c50618db16aac3bf796c40805
677,261
def no_error_check(func_name, result, func, args): """Nothing special""" return args
d2e6bf201d648812a0a2b7e1bf316aa851508374
677,262
import math def bank_data(data): """Using the median approach, bank to 45 degrees the data. Returns the aspect ratio (w/h) for banking. """ min_x = min(x for (x,y) in data) min_y = min(y for (x,y) in data) max_x = max(x for (x,y) in data) max_y = max(y for (x,y) in data) slopes = [m...
02978f6aa86881ff2c8f4d715c1b39871b2f71d4
677,263
def stare_palette(): """STARE palette for external use.""" return [[120, 120, 120], [6, 230, 230]]
031783a9ff499cfba7a83910add649f448deeb56
677,264
import re def br_with_n(text): """ Replace br with \n """ return re.sub(r'<br.*?>','\n', text, flags=re.IGNORECASE)
105fdc3b83e40b7d0e6e35e4785e11da59772576
677,265
import pandas def local_t_from_dataframe_index(dataframe, local_tz=None): """ Convert unix timestamps found in dataframe index to local datetimes. Args: local_tz (timezone key): timezone you want it converted to. """ return pandas.to_datetime(dataframe.index, unit='s').tz_lo...
fda44044083ecdf9af000b8ab3cb6a06038e1716
677,266
def gal2ft3(gal): """gal -> ft^3""" return 0.13368056*gal
467a8cf7cf03fbbdd69e8b69e7818a5f5f4ccbae
677,267
def getNumCPUs(): """Returns the number of cpus (independent cores) on this machine. If any error, returns 1""" n = [l.strip() for l in open('/proc/cpuinfo') if l.startswith('processor')] return len(n)
9b581a4ef13a9d430d3b8dc3cd8bba6b04e89b27
677,268
import numpy def findEventCCs(doc_doc_scores, cutoff=0.5): """ See "scipy.sparse.cs_graph_components" for potential speedup https://docs.scipy.org/doc/scipy-0.10.0/reference/generated/scipy.sparse.cs_graph_components.html """ # Find where Score is greater than threshold cutoff hi...
d1dad43ab9e0cef176f4efde1df3fb84f249d40a
677,269
def set_tickers(p, x_range=None, y_range=None, n_x_tickers=None, n_y_tickers=None): """ Set the number of tickers""" def make_range(rng, n_step): return list(range(rng[0], rng[1], (rng[1] - rng[0])//n_step)) if n_x_tickers: p.xaxis.ticker = make_range(x_range, n_x_tickers) if n...
9487825542ab2193b6c015fb79df57092165004d
677,270
def S_M_to_mS_cm(CTM_S_M): """ Seabird eq: ctm [mS/cm] = ctm [S/m] * 10.0 """ ctm_mS_cm = CTM_S_M * 10.0 return ctm_mS_cm
38a679d5c39627aaa3e919f199aac826298f03f9
677,271
import _ast def Dict(keys=(), values=()): """Creates an _ast.Dict node. This represents a dict literal. Args: keys: A list of keys as nodes. Must be the same length as values. values: A list of values as nodes. Must be the same length as values. Raises: ValueError: If len(keys) != len(values). ...
60cd4508f47a0160c97d9030ef2560023a08a20c
677,272
def isBinary(x): """ Determine if the array is made up of just 0's and 1's. """ binary = True for arg in x: if (arg > 0) and (arg < 1): binary = False return (binary)
db88f82484a4b252accc3473536df167b9684d48
677,273
def readme(): """ Returns Readme.rst as loaded RST for documentation """ with open('Readme.rst', 'r') as filename: return filename.read()
5d9e1597ab04bb4fbb7c7f10ce16f2fcfbcc0b17
677,275
def stirling2nd(n: int, k: int) -> int: """Stirling number of second kind. Arguments: n (int): [description] k (int): [description] Returns: int: [description] """ if (k >= n or k <= 1): return 1 return stirling2nd(n - 1, k - 1) + k * stirling2nd(n - 1, k)
2f3e91cd41d4085878494fc8b6bd2ea1fd556b42
677,276
from datetime import datetime def format_iso_date(d): """ If the parameter is datetime format as iso, otherwise returns the same value """ if type(d) is datetime: return d.isoformat() return d
19fceb51f32f92c8ed078da5498c1e46317c8cad
677,277
def local_scheme(version: str) -> str: # pylint: disable=unused-argument """Skip the local version (eg. +xyz) to upload to Test PyPI""" return ""
50448c7ecc8457229ca5a752b2157987b80d104e
677,278
def get_K_evp_h_0(): """Kevph0:蒸発温度を計算する式の係数 (-) (4b) Args: Returns: float: Kevph0:蒸発温度を計算する式の係数 """ return -2.95315205817646
042ec5e46fd83345878e2b886b6cb1348a971185
677,279
def cmp_dicts(dict1, dict2): """ Returns True if dict2 has all the keys and matching values as dict1. List values are converted to tuples before comparing. """ result = True for key, v1 in dict1.items(): result, v2 = key in dict2, dict2.get(key) if result: v1, v2 = (t...
8a0bba46b8257d3d82ee21a99d3472e2ebb09c41
677,280
async def absent( hub, ctx, name, route_table, resource_group, connection_auth=None, **kwargs ): """ .. versionadded:: 1.0.0 Ensure a route table does not exist in the resource group. :param name: Name of the route table. :param route_table: The name of the existing route table containing the...
b3a64596fa361e20e8cc62fcf32cdfa82fd43594
677,281
def breaklines(s, maxcol=80, after='', before='', strip=True): """ Break lines in a string. Parameters ---------- s : str The string. maxcol : int The maximum number of columns per line. It is not enforced when it is not possible to break the line. Default 80. af...
4d35d8da06de1d96b3af3c9de997dc58bf85cbba
677,282
def kingdoms(): """Returns the tripartite division of China from 220–280 AD""" return ['Wei', 'Shu', 'Wu']
d4ef1815da66f80da59346ed588a5107ebe0f04a
677,283
def sum_digits(n): """Recursively calculate the sum of the digits of 'n' >>> sum_digits(7) 7 >>> sum_digits(30) 3 >>> sum_digits(228) 12 """ """BEGIN PROBLEM 2.4""" return n % 10 + (0 if n < 10 else sum_digits(n // 10)) """END PROBLEM 2.4"""
18aaf2714970dadf5c6c7a5d009b2e2c9d210502
677,284
import re def escape(pathname: str) -> str: """Escape all special characters.""" return re.sub(r"([*?[\\])", r"[\1]", pathname)
33a357c49acfe44dd25fa897b629b812e07cfdd0
677,285
import argparse def handle_program_options(): """Parses the given options passed in at the command line.""" parser = argparse.ArgumentParser(description="Create network plots based " "on correlation matrix.") parser.add_argument("biom_file", help="Biom file OTU table."...
21d30852cccc25c8e8490cbe7b2596c4a32d2b73
677,286
import argparse import os def parse_args(): """ Parses arguments using argparse and returns parse_args() :return: :rtype: """ parser = argparse.ArgumentParser( 'AppImage Catalog Generator', description='Generates static HTML files for the Appimage catalog' ) parser.add_...
a9883f53a90af06a5ad50e1bb0e59aeae38d3c58
677,287
def extract_NBO_charges(output, natoms): """ extract NBO Charges parsing the outFile """ # Initialize charges list charges = [] with open(output, mode='r') as outFile: line = 'Foobar line' while line: line = outFile.readline() if 'Summary of Natural P...
85b0fe7f95c0e9ec0fe2915f91377b5473ea563d
677,288
import torch def kronecker_prod(x, y): """A function that returns the tensor / kronecker product of 2 complex tensors, x and y. :param x: A complex matrix. :type x: torch.Tensor :param y: A complex matrix. :type y: torch.Tensor :raises ValueError: If x and y do not have 3 dimensions or t...
5a760102bed2dbf7c9c138f64bebcbbec049fa65
677,289
def weather_code_to_text(code): """转换天气代码为文字""" weather_list = [u'晴', u'多云', u'阴', u'阵雨', u'雷阵雨', u'雷阵雨伴有冰雹', u'雨夹雪', u'小雨', u'中雨', u'大雨', u'暴雨', u'大暴雨', u'特大暴雨', u'阵雪', u'小雪', u'中雪', u'大雪', u'暴雪', u'雾', u'冻雨', u'沙尘暴', u'小到中雨', u'中到大雨', u'大到暴雨', ...
99053734bed67096b52a4b735538c75994c5a6d9
677,290
import requests from bs4 import BeautifulSoup import re def get_apps_ids(play_store_url): """Scrape play store to gather App IDs. Returns a list of App IDs Keyword arguments: play_store_url -- URL from a Play Store Search :rtype: list """ page = requests.get(play_store_url) soup = Bea...
18f8304827bf8f269d63ff1a0b342ac5cee9eb8a
677,291
import argparse def arguments(): """ CMD args """ parser = argparse.ArgumentParser(description='Performs inference using a Mask RCNN Model') parser.add_argument('--dataPattern', type=str, required=True, help="A glob file path pattern in quotations. e.g. '/data/plants/plant?...
a5cf4e4083ac179d55691fbd9298ac025b8ca55d
677,293
from typing import Iterable def remove_single_char_and_spaces( text_docs_bow: Iterable[Iterable[str]], ) -> Iterable[Iterable[str]]: """Removes all words that contain only one character and blank spaces from documents. Args: text_docs_bow: A list of lists of words from a document Returns: ...
34ded0813da2e47edcd0164c9a5243517bca62f6
677,294
import yaml def read_config(path): """ Load the yaml file into a dictionary. """ with open(path) as f: return yaml.load(f, Loader=yaml.FullLoader)
24e9ef759141ce11f7e090c76768e77d29018181
677,295
def state_action(L, Lx, Lu, Lxx, Luu, Lxu, V, Vx, Vxx, phi, B): """ takes in the value function, loss and the gradients and Hessians and evaluates the state action value function """ Q = L + V Qx = Lx + phi.T.dot(Vx) Qu = Lu + B.T.dot(Vx) Qxx = Lxx + phi.T.dot(Vxx).dot(phi) Quu = Luu + B.T....
d1c777aff3f4d9cd002aed9c271e2e82ef838d38
677,296
def append_test_args(p): """Append arguments for model testing Args: p :argparse.ArgumentParser object: Returns parameters :argparse.ArgumentParser object: with appended arguments """ p.add_argument('--from_model', '--from-model', nargs='+', type=str, required=Tr...
7cfd049b507456868dfc5e088d01ab293124e6f7
677,297
def number_from_filename(filename): """ Subtracts the number of an apple pick from its filename :param filename: :return: pick number """ name = str(filename) start = name.index('pick') end = name.index('meta') number = name[start + 4:end - 1] return number
7a0bd858791d243cab37c4a23ea6a8ef2baa190b
677,298
import time def current_time(): """ get the current date & time """ current_time = time.strftime('%y_%m_%d_%H-%M-%S') return current_time
3ecb81817a506c97125d57df8564b9a88bfeb5f3
677,299
def mock_valid_redis_config(): """Mock valid Redis config.""" return {"password": "citrus", "host": "localhost", "port": "5432", "id": "main_redis", }
c1e41757c7841cede5c94c5153a876c1c2f6ba5c
677,301
def findRange(coordinates,mesh): """Calculate the square range of a mesh. Output: [x_min, x_max, y_min, y_max].""" if len(mesh)>1: (xMin1,xMax1,yMin1,yMax1)=findRange(coordinates,mesh[0 : len(mesh)//2]) (xMin2,xMax2,yMin2,yMax2)=findRange(coordinates,mesh[len(mesh)//2 : len(mesh)]) ...
5f1c43596929a176235c5c761a210c04b111a065
677,303
def cost(nums, fun): """ originally used: `return [sum(map(fun(num), nums), start=0) for num in range(max(nums)+1)]` but now we have a slight speed up. """ current = float('inf') for num in range(max(nums)+1): result = sum(map(fun(num), nums), start=0) if result > current: break el...
bcd47070b31f0dc6ca3250df180c00e34bd9adb6
677,304
def get_topic_tree(rs, topic, depth=0): """Given one topic, get the list of all included/inherited topics. :param str topic: The topic to start the search at. :param int depth: The recursion depth counter. :return []str: Array of topics. """ # Break if we're in too deep. if depth > rs._de...
b00ee202186c25b1034b36f368f4691b993af4e5
677,306
def houseProd(v,A): """ Usage: houseProd(v,A) using a householder vector V with a matrix of the proper size return HA Note A is modified in-place; but there are create/destroy penalties with this function Note a convenience reference to A is returned """ beta = 2.0/v.jdot...
1a96495ce898d502bbbd61921a81634a3e30264f
677,307
import argparse def get_input_args(): """ Retrieves and parses the command line arguments provided by the user when they run the program from a terminal window. Command Line Arguments: 1. Image Folder as --dir with default value 'data_dir' 2. Model Architecture as --arch with default val...
c23b71f563009e68ad2a54ca6299d83ac6e91799
677,308
import re def normalizeName(name): """Transforms a name to deal with common misspellings.""" # Only use the first of several names. oneName = name.split(' ', 1)[0].lower() REPLACEMENTS = [ ['y$', 'a'], # Szczęsny = Szczęsna ['i$', 'a'], # Nowicki = Nowicka ['ę', 'e'], ['ą', 'a'], ['ó', '...
cc97be3255ea902f34d63ca459dc3b968c73bf0e
677,309
def join_query_keys(keys): """Helper to join keys to query.""" return ",".join(["\"{}\"".format(key) for key in keys])
aae572da696641c548a26acde8e2d94237ca3c19
677,310
def a_reload_na(ctx): """Provide the message when the reload is not possible.""" ctx.msg = "Reload to the ROM monitor disallowed from a telnet line. " \ "Set the configuration register boot bits to be non-zero." ctx.failed = True return False
c45e14ffd3f84083f238b80434a1222e9e2b3ec2
677,311
def defaultparse(wordstags, rightbranching=False): """A default parse to generate when parsing fails. :param rightbranching: when True, return a right branching tree with NPs, otherwise return all words under a single constituent 'NOPARSE'. >>> print(defaultparse([('like','X'), ('this','X'), ('example', 'NN'),...
4770088bdabc2b2036a60402be243a7e072f23de
677,312
import torch def instance_std(x: torch.Tensor, eps: float = 1e-5): """JIT-d helper to do instance standard deviation.""" var = torch.var(x, dim=(2, 3), keepdim=True).expand_as(x) if torch.isnan(var).any(): var = torch.zeros_like(var) return (var + eps).sqrt_()
b3c0bd0da4cbfe85bc814028cb4d957ebd189dd1
677,313
import random def records_select(dataset, size): """ Take a table $dataset and selects only $size rows from it. """ #Randomly select $size lines from data, if size < len(data). Otherwise, take all the data. counter = 0 selected_dataset = [] if size < len(dataset): counter = 0 ...
6d4b01f500f66d03a109657e0432602bd6e4f0ba
677,314
def child_wins(a, b): """ Always returns the second parameter. :param a: An object. :type a: object :param b: An object. :type b: object :returns: b """ return b
f5c228c332f6b484586be92ff95bd717a38a846e
677,315
def string_to_int(string): """ Problem 7.1 convert a string to an integer, without using `int` """ negative = string[0] == '-' if negative: string = string[1:] idx = 0 output = 0 while idx < len(string): low = ord(string[idx]) - ord('0') output = (output * 1...
583a87eb8aea4347f9d04378308ef6a901ffa6a0
677,316
import os def generate_bat_shim(pkg_root, target_rel): """Writes a shim file side-by-side with target and returns abs path to it.""" target_name = os.path.basename(target_rel) bat_name = os.path.splitext(target_name)[0] + '.bat' base_dir = os.path.dirname(os.path.join(pkg_root, target_rel)) bat_path = os.pa...
11f69127a5680c2d35b562305bea0f10c279eb51
677,317
def evolution_1(x_0, lmbda): """ dz1/dt = lambda_2 * z1^2 - (lambda_2 + lambda_3) * z1 * z2 dz2/dt = lambda_1 * z2^2 - (lambda_1 + lambda_3) * z1 * z2 http://www.math.kit.edu/iag3/~herrlich/seite/wws-11/media/wws-talk-valdez.pdf """ x_1 = x_0[0] y_1 = x_0[1] x_2 = x_0[2] y_2 = x_0[3]...
5da7dd11e1fa309b69216a198330702400b74adc
677,318
def apply_LLD(spectrum, LLD=10): """ Applies a low level discriminator (LLD) to a channel. Parameters: ----------- spectrum : vector The spectrum LLD : int The channel where the low level discriminator is applied Returns: -------- spectrum : vecto...
c3dfe53fdbc22aa6c2b3ac1dc054f2a1a0fc40dd
677,320
def wants_json_resp(request): """ Decide whether the response should be in json format based on the request's accept header. Code taken from: http://flask.pocoo.org/snippets/45/ """ best = request.accept_mimetypes.best_match(['application/json', '...
591b66c1a37012e344642d2130cc8e5b06f69f31
677,321
def teensy_config(choice): """ Receives the input given by the user from set.py """ return { '1': "powershell_down.ino", '2': "wscript.ino", '3': "powershell_reverse.ino", '4': "beef.ino", '5': "java_applet.ino", '6': "gnome_wget.ino" }.get(choice, "ERROR")
4bf64079f5fc082a01ce78419c5beb1d663d6a18
677,322
def route_business_logic(logicFn): """ Decorates a function to indicate the business logic that should be executed after security checks pass. :param logicFn: The business logic function to assign. :return: The decorated function. """ def decorator(fn): fn.route_business_logic = logicFn...
b1c50db9ae54ca86755a43ae4cecef6887061b5b
677,323
def _schema_sql_to_bq_compatibility( schema_dict: dict ) -> dict: """ Convert sql schema to be compatible with the bq ui. Args: schema_dict: column name-sql column type as key-value pairs e.g. {'uid': 'STRING', 'clicks': 'INTEGER'} Returns: schema_dict: column name-sql ...
bf07abe26aad00f9d052fffced0563f4efae5551
677,324
import requests import re def get_tif_urls(baseurl): """Return all the links from a webpage with .tif""" r = requests.get(baseurl) links = re.findall('"([^"]*\.tif)"', r.content.decode()) head = "/".join(r.url.split("/")[:3]) return [head + l for l in links]
0a982c5a58921602d077d90329f54a9523253d5d
677,325