content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_rating(comment): """ """ return comment.xpath( ".//div[@itemprop=\"reviewRating\"]/meta[@itemprop=\"ratingValue\"]" )[0].attrib.get("content")
c80d7f3443a20facdf5a99c3db42d8aa49e95010
28,400
def creat_netmiko_connection(username, password, host, port) -> object: """Logs into device and returns a connection object to the caller. """ credentials = { 'device_type': 'cisco_ios', 'host': host, 'username': username, 'password': password, 'port': port, 'ses...
94c7463235051f87ad106b0c960ad155101fce56
28,401
from typing import List import argparse import os def parse_arguments(args: List[str] = None): """ Parse arguments with argparse.ArgumentParser Args: args: List of arguments from cmdline Returns: Parsed arguments Raises: Exception: On generic failure """ parser = argpar...
4926c99bb574edffbee575cdabdd3913209c544a
28,402
def get_requirements(): """Read the requirements file.""" requirements = read("requirements.txt") return [r for r in requirements.strip().splitlines()]
a178d5148b137b4a6f46112cd73bbf6d2e9fb211
28,403
def handler(fmt, station, issued): """Handle the request, return dict""" pgconn = get_dbconn("asos") if issued is None: issued = utc() if issued.tzinfo is None: issued = issued.replace(tzinfo=timezone.utc) df = read_sql( f""" WITH forecast as ( select id ...
d75940ab5accc36258473d9794fd0449f707b593
28,404
def index_count(index_file=config.vdb_bin_index): """ Method to return the number of indexed items :param index_file: Index DB file :return: Count of the index """ return len(storage.stream_read(index_file))
2abe3a9a3b1e04f67175cabc9099f490556caabd
28,405
import sys import traceback def strexc(): """Return current exception formatted as a single line suitable for logging. """ try: exc_type, exc_value, tb = sys.exc_info() if exc_type is None: return "" # find last frame in this script lineno, func = 0, "" ...
9b41edf403552647124fc2c4f7937ce648b72b21
28,406
def asc_to_dict(filename: str) -> dict: """ Load an asc file into a dict object. :param filename: The file to load. :return dict: A dict object containing data. """ return list_to_dict(asc_to_list(filename))
3509321bc38e53ae1e86fa8b9cea113bec55700a
28,407
def merge_sort(array): """ Merge Sort Complexity: O(NlogN) """ if len(array) > 1: mid = len(array) // 2 left = array[:mid] right = array[mid:] left = merge_sort(left) right = merge_sort(right) array = [] # This is a queue implementation. We c...
73b3ac5b950f5788cbc3e7c98d2a4d5aac427929
28,408
def semi_major_axis(P, Mtotal): """Semi-major axis Kepler's third law Args: P (float): Orbital period [days] Mtotal (float): Mass [Msun] Returns: float or array: semi-major axis in AU """ # convert inputs to array so they work with units P = np.array(P) Mtotal...
338ce7857544d59dca1d78026f2559ce698faae8
28,409
import re from re import T from pathlib import Path def parse_dependency_string(value: str) -> Dependency: """ Convert *value* to a representation as a #Dependency subclass. * In addition to the [PEP 508][] dependency specification, the function supports a `--hash` option as is also supported by Pi...
524e93937af4c110912e15138f3ad4617a93bcd4
28,410
def _check_df_load(df): """Check if `df` is already loaded in, if not, load from file.""" if isinstance(df, str): if df.lower().endswith('json'): return _check_gdf_load(df) else: return pd.read_csv(df) elif isinstance(df, pd.DataFrame): return df else: ...
7245341c8fa58e2aea20761d6832be09e948b0e3
28,411
import sys def confirm(question, assume_yes=True): """ Ask user a yes/no question and return their response as a boolean. ``question`` should be a simple, grammatically complete question such as "Do you wish to continue?", and will have a string similar to ``" [Y/n] "`` appended automatically. Th...
6ba3e6956f157e2cb1c9c126537b02871d84806f
28,412
def ping(host, timeout=False, return_boolean=False): """ Performs an ICMP ping to a host .. versionchanged:: 2015.8.0 Added support for SunOS CLI Example: .. code-block:: bash salt '*' network.ping archlinux.org .. versionadded:: 2015.5.0 Return a True or False instead ...
f5707427eaef1e436618065bea78faa15a5cce7e
28,413
def comp_wind_sym(wind_mat): """Computes the winding pattern periodicity and symmetries Parameters ---------- wind_mat : numpy.ndarray Matrix of the Winding Returns ------- Nperw: int Number of electrical period of the winding """ assert len(wind_mat.shape) == 4, "...
7984eb6f3b1d7d11694ecac1237ce27b11bbd9fe
28,414
import os def FindRepoDir(path): """Returns the nearest higher-level repo dir from the specified path. Args: path: The path to use. Defaults to cwd. """ return osutils.FindInPathParents( '.repo', path, test_func=os.path.isdir)
bf7f560d32f960a1dd7d3c3cd1f8f5648ef04df7
28,415
def row(data, widths="auto", spacing=3, aligns=None): """Format data as a table row. data (iterable): The individual columns to format. widths (iterable or 'auto'): Column widths in order. If "auto", widths will be calculated automatically based on the largest value. spacing (int): Spacing betw...
3adef2268ba1720e7480a3b4d0f873927d14f0b6
28,416
from datetime import datetime import calendar def _increment_date(date, grain): """ Creates a range of dates where the starting date is the given date and the ending date is the given date incremented for 1 unit of the given grain (year, month or day). :param date: the starting date in string for...
53626ad40cdf5a2352a6129fb15ed91ede60838e
28,417
def ErrorCorrect(val,fEC): """ Calculates the error correction parameter \lambda_{EC}. Typical val is 1.16. Defined in Sec. IV of [1]. Parameters ---------- val : float Error correction factor. fEC : float Error correction efficiency. Returns ------- float ...
83c4483c56c7c3b79060dd070ec68f6dfd5ee749
28,418
def BytesGt(left: Expr, right: Expr) -> BinaryExpr: """Greater than expression with bytes as arguments. Checks if left > right, where left and right are interpreted as big-endian unsigned integers. Arguments must not exceed 64 bytes. Requires TEAL version 4 or higher. Args: left: Must eva...
9c509eab36ef0b174248741b656add275d8654b3
28,419
def balanceOf(account): """ can be invoked at every shard. If invoked at non-root shard, the shard must receive a xshard transfer before. Otherwise the function will throw an exception. :param account: user address :return: the token balance of account """ if len(account) != 20: raise Ex...
36d56a2536f33053dc5ed2020d0124380e9ceb28
28,420
def archive_entry(title): """ """ if not session.get('logged_in'): abort(401) db = get_db() # Archive it stmt = ''' insert into archived_entries select * from entries where pretty_title like ? ''' db.execute(stmt, ('%' + title + '%',)) db.execute('delet...
69384fbfda4090352640890105c02304782e541c
28,421
def build_census_df(projection_admits: pd.DataFrame, parameters) -> pd.DataFrame: """ALOS for each category of COVID-19 case (total guesses)""" n_days = np.shape(projection_admits)[0] hosp_los, icu_los, vent_los = parameters.lengths_of_stay los_dict = { "Hospitalized": hosp_los, "ICU": i...
0b1471f6e522a15027e2797484e573c65971e0d4
28,422
def indented_kv(key: str, value: str, indent=1, separator="=", suffix=""): """Print something as a key-value pair whilst properly indenting. This is useful for implementations of`str` and `repr`. Args: key (str): Key. value (str): Value. indent (int, optional): Number of spaces to i...
b27a7ed7a0db4219332fda1e1131c888216141b2
28,423
def are_in_file(file_path, strs_to_find): """Returns true if every string in the given strs_to_find array is found in at least one line in the given file. In particular, returns true if strs_to_find is empty. Note that the strs_to_find parameter is mutated.""" infile = open(file_path) for line in i...
474234a35bf885c5f659f32a25c23580f2014cc2
28,424
def load_data(filename: str): """ Load house prices dataset and preprocess data. Parameters ---------- filename: str Path to house prices dataset Returns ------- Design matrix and response vector (prices) - either as a single DataFrame or a Tuple[DataFrame, Series] """ ...
a8aed077d63c9e2df0f150b2ef7e3c06c30fcb29
28,425
import keyring import os import configparser def ask_user_for_secrets(credo, source=None): """Ask the user for access_key and secret_key""" typ = "amazon" choices = [] access_key_name = "AWS_ACCESS_KEY_ID" secret_key_name = "AWS_SECRET_ACCESS_KEY" environment = os.environ if access_key_n...
e59f7ed2106c06166e89b88b7cda15fa5938f28e
28,426
import unicodedata import re def slugify(value): """ Unicode version of standart slugify. Converts spaces to hyphens. Removes characters that aren't unicode letters, underscores, or hyphens. Converts to lowercase. Also replaces whitespace with hyphens and strips leading and trailing hyphens. ...
e81020b76f4e29f89e44c420e8e95b89f7eb1363
28,427
import sys def _generate_Wl(step, evt_type, energy, evtnumber): """ Here the settings for the Z ee simulation are added to the process. Energy parameter is not used. """ func_id=mod_id+"["+sys._getframe().f_code.co_name+"]" common.log( func_id+" Entering... ") # Choose betwee...
bf6c82b344cb1afb72719f7a79789dbfda738ad0
28,428
from math import factorial as f def binomial_coefficient(n: int, m: int) -> int: """ Binomial Coefficient Returns n!/(m!(n-m)!). This is used in combinatronics and binomial theorem.""" return f(n)/(f(m)*f(n-m))
e0ad7a4cd3cb85bb4c0a48890209a8f71086a853
28,429
def joint(waypoints): """ Calculate a trajectory by a joint operation. """ # total number of segments numSegments = len(waypoints) - 1 # every segment has its own polynomial of 4th degree for X,Y and Z and a polynomial of 2nd degree for Yaw numCoefficients = numSegments * (3*5+3) # list ...
06b3b2f183c749405ecacd4ce639c3c2d5826e55
28,430
import math def logistic(x: float): """Logistic function.""" return 1 / (1 + math.exp(-x))
98b4f7aebd562609789ed5f53f6a79d63eaf6ea0
28,431
def highlight_deleted(obj): """ Display in red lines when object is deleted. """ obj_str = conditional_escape(text_type(obj)) if not getattr(obj, 'deleted', False): return obj_str else: return '<span class="deleted">{0}</span>'.format(obj_str)
daad6a35bab989a2ca9df63292fecf36b05ff715
28,432
def range_(stop): """:yaql:range Returns an iterator over values from 0 up to stop, not including stop, i.e. [0, stop). :signature: range(stop) :arg stop: right bound for generated list numbers :argType stop: integer :returnType: iterator .. code:: yaql> range(3) [0, ...
28717348bcdcd432388b8a4809c897c70a2fce3f
28,433
import argparse import sys import os def my_argument_parser(epilog=None): """ Create a parser with some common arguments used by detectron2 users. Args: epilog (str): epilog passed to ArgumentParser describing the usage. Returns: argparse.ArgumentParser: """ parser = argparse...
d2f5466d09aa0619b48cd9606db6f8b7fbc892fa
28,434
def post(filename: str, files: dict, output_type: str): """Constructs the http call to the deliver service endpoint and posts the request""" url = f"http://{CONFIG.DELIVER_SERVICE_URL}/deliver/{output_type}" logger.info(f"Calling {url}") try: response = session.post(url, params={"filename": fil...
358b408ace8750d1c48ca6bef0855aac4db625ca
28,435
import fnmatch import os import sys import glob def list_files_recursively(root_dir, basename, suffix='y?ml'): """search for filenames matching the pattern: {root_dir}/**/{basename}.{suffix} """ root_dir = os.path.join(root_dir, "") # make sure root dir ends with "/" # TODO - implement skip if sy...
1c4d94efa31b67643c6394a78fef0f4c5356fa59
28,436
def is_off(*args): """ is_off(F, n) -> bool is offset? @param F (C++: flags_t) @param n (C++: int) """ return _ida_bytes.is_off(*args)
43dc5298bad5daf95f76e8426e819e1feb89f8d4
28,437
def get_libdcgm_path(): """ Returns relative path to libdcgm.so.2 """ return "../../lib/libdcgm.so.2"
a1067449bdc9012e07c5707ece68c3aae2799694
28,438
def method(modelclass, **kwargs): """Decorate a ProtoRPC method for use by the endpoints model passed in. Requires exactly one positional argument and passes the rest of the keyword arguments to the classmethod "method" on the given class. Args: modelclass: An Endpoints model class that can create a metho...
801fad462414b94f6ee72e507c17813afc043f81
28,439
def detect_on(window, index=3, threshold=5): # threshold value is important: power(watts) """input: np array listens for a change in active power that exceeds threshold (can use Active/real(P), Apparent(S), and Reactive (Q)(worst..high SNR)) index = index of feature to detect. Used P_real @ index 3 ...
dfea9b4ea95c22b199a63c47cb5f7f16f10df742
28,440
def calculate_target_as_one_column(df:pd.DataFrame, feature_cols:list, target_cols:list): """create a row for every new porduct and give the product name as target column, this is done for the train set""" x = df[target_cols] x = x[x==1].stack().reset_index().drop(0,1) df = pd.merge(df, x, left_on=df.in...
eee8e27a60999c95e2354877526ae27d9679a3ca
28,441
def find_features_with_dtypes(df, dtypes): """ Find feature names in df with specific dtypes df: DataFrame dtypes: data types (defined in numpy) to look for e.g, categorical features usually have dtypes np.object, np.bool and some of them have np.int (with a limited number of unique items) """ return np.asarray...
a94177dd24cb96915245959c0a22b254bd2a59df
28,442
def DeConv2d(net, n_out_channel = 32, filter_size=(3, 3), out_size = (30, 30), strides = (2, 2), padding = 'SAME', batch_size = None, act = None, W_init = tf.truncated_normal_initializer(stddev=0.02), b_init = tf.constant_initializer(value=0.0), W_init_args = {}, b_init_args = {}, name ='decnn2d...
c99d717bac217878bc569d7fad4462d5445ac709
28,443
from typing import List import re def parse_release(base: str, path: str) -> List[str]: """Extracts built images from the release.yaml at path Args: base: The built images will be expected to start with this string, other images will be ignored path: The path to the file (release....
f4fec0908f2975a9ed9eef3e0a3a62549c9f757c
28,444
def build_config(config_file=get_system_config_directory()): """ Construct the config object from necessary elements. """ config = Config(config_file, allow_no_value=True) application_versions = find_applications_on_system() # Add found versions to config if they don't exist. Versions found ...
148e597f7fd9562f9830c8bd41126dd0efef96f1
28,445
import re def preProcess(column): """ Do a little bit of data cleaning with the help of Unidecode and Regex. Things like casing, extra spaces, quotes and new lines can be ignored. """ column = unidecode(column) column = re.sub('\n', ' ', column) column = re.sub('-', '', column) column...
fda71aab1b2ce2baedbbc5d2195f115c9561e75d
28,446
def size_to_pnts(size) -> np.ndarray: """ 获得图片 size 的四个角点 (4,2) """ width = size[0] height = size[1] return np.array([[0, 0], [width, 0], [width, height], [0, height]])
ca189cea9201646b0ce4cf2e32c2e21ad26929f3
28,447
def create_scenario_mms_datasets(variable_name, scenario_name, num_chunks, data_path, normalized=False): """Create the multi-model statistics dataset for a scenario. Runs the func...
0bef48bc009b2ee72abec511d9f6f886a8ed289c
28,448
def carla_rotation_to_numpy_rotation_matrix(carla_rotation): """ Convert a carla rotation to a Cyber quaternion Considers the conversion from left-handed system (unreal) to right-handed system (Cyber). Considers the conversion from degrees (carla) to radians (Cyber). :param carla_rotation: the...
38aed692b0ad7008fff71dc9b31ce03d552ae2f2
28,449
def _liquid_viscocity(_T, ranged=True): """Pa * s""" OutOfRangeTest(_T, 59.15, 130, ranged) A, B, C, D, E = -2.0077E+01, 2.8515E+02, 1.7840E+00, -6.2382E-22, 10.0 return exp(A + B / _T + C * log(_T) + D * _T**E)
2fd29eea442862e4904d3164783694b151cab6c9
28,450
import subprocess def _interactive(git, name): """ Interactive assistant. This will supercede any command line arguments, meaning that it is pointless to add any other arguments when using the -i argument. """ prompt = ( "\n==================================================================...
26eedcccf0c4835c7f9596803485db44130cd370
28,451
import re, fileinput def readConfig(filename): """Parses a moosicd configuration file and returns the data within. The "filename" argument specifies the name of the file from which to read the configuration. This function returns a list of 2-tuples which associate regular expression objects to the c...
3b641686b8e6cfaebec668367a12e32bc59104a8
28,452
def negative_f1(y_true, y_pred) -: """Implements custom negative F1 loss score for use in multi-isotope classifiers. Args: y_true: a list of ground truth. y_pred: a list of predictions to compare against the ground truth. Returns: Returns the custom loss score. ...
255c3e34a17f4301a6c842c4109d930916cac3d5
28,453
import torch def cal_gauss_log_lik(x, mu, log_var=0.0): """ :param x: batch of inputs (bn X fn) :return: gaussian log likelihood, and the mean squared error """ MSE = torch.pow((mu - x), 2) gauss_log_lik = -0.5*(log_var + np.log(2*np.pi) + (MSE/(1e-8 + torch.exp(log_var)))) MSE = torch.mea...
b2d4f660c4475a632c649844694ff3f67dc93fca
28,454
def translate_fun_parseInt(x): """Converts parseInt(string, radix) to __extrafunc_parseInt(string, radix=10) Args: x (str): JavaScript code to translate. Returns: str: Translated JavaScript code. Examples: >>> from ee_extra import translate_fun_parseInt >>> transla...
9bc63d3e4005fed12209de0169ad2641bcf09f65
28,455
def simple_intensity_based_segmentation(image, gaussian_sigma=1, thresh_method="Otsu", smallest_area_of_object=5,label_img_depth = "8bit"): """Perform intensity based thresholding and detect objects Args: raw_image_path : path to a raw image gaussian_sigma : sigma to use f...
2f270b38e7f5d07ceb4437d7b9b6d26174af56fc
28,456
import torch def mish(x): """mish activation function Args: x (Tensor): input tensor. Returns: (Tensor): output tensor and have same shape with x. Examples: >>> mish(to_tensor([-3.0, -1.0, 0.0, 2.0])) tensor([-1.4228e-01, -2.6894e-01, 0.0000e+00, 1.7616e+00] R...
73447216f12a2e60e9ccc249eca9abe4baa94be8
28,457
def text_box_end_pos(pos, text_box, border=0): """ Calculates end pos for a text box for cv2 images. :param pos: Position of text (same as for cv2 image) :param text_box: Size of text (same as for cv2 image) :param border: Outside padding of textbox :return box_end_pos: End xy coordinates for t...
5bd2b46fe3456ccdef1407b90256edeb310d92bc
28,458
def ticket_competence_add_final(request, structure_slug, ticket_id, new_structure_slug, structure, can_manage, ticket, office_employee=None): """ Adds new ticket competence (second step) :type structure_slug: String :type ticket_id: String...
b3e159494d8f7ecf7603596face065f02e44e00e
28,459
def _find_computecpp_root(repository_ctx): """Find ComputeCpp compiler""" computecpp_path = "" if _COMPUTECPP_TOOLKIT_PATH in repository_ctx.os.environ: computecpp_path = repository_ctx.os.environ[_COMPUTECPP_TOOLKIT_PATH].strip() if computecpp_path.startswith("/"): _check_computecpp_version(repository_...
91bc817036a976565434f1a3c52c5bb7e80ed86d
28,460
def distance(v): """ Estimated distance to the body of the Mandelbuld """ z = v for k in range(MAX_ITERS): l = (z**2).sum() if l > BAILOUT: escape_time = k break z = pow3d(z, ORDER) + v else: return 0 return np.log(np.log(l)) / MU_NORM ...
79a6075da3c022c48c111ffec015835716c12f9a
28,461
def _depol_error_value_two_qubit(error_param, gate_time=0, qubit0_t1=inf, qubit0_t2=inf, qubit1_t1=inf, qubit1_t2=inf): """Return 2-qubit depolarizing ...
ab779de7d0fac3f828f9fffbb0c13e588c3fc54b
28,462
def get_google_order_sheet(): """ Return the google orders spreadsheet """ return get_google_sheet(ANDERSEN_LAB_ORDER_SHEET, 'orders')
69ce8dcf03fd31701700eb0515ae7c3b47c9d127
28,463
def collision_check(direction): """ :param direction: Str : example up :return: """ # really scuffed needs hard rework worked on this in night and its bad # but it dose its job so i guess its ok for now if mapGen.map[p.position][direction] is not None: if mapGen.map[mapGen.map[p.pos...
35b0bd0e6e2811b470bd513ea33c339ed7c7a96b
28,464
def get_freq(freq): """ Return frequency code of given frequency str. If input is not string, return input as it is. Example ------- >>> get_freq('A') 1000 >>> get_freq('3A') 1000 """ if isinstance(freq, compat.string_types): base, mult = get_freq_code(freq) ...
16998470970449a9f94758c87c1d42e392c86dc9
28,465
def OMRSE( directed = False, preprocess = "auto", load_nodes = True, load_node_types = True, load_edge_weights = True, auto_enable_tradeoffs = True, sort_tmp_dir = None, verbose = 2, cache = True, cache_path = None, cache_sys_var = "GRAPH_CACHE_DIR", version = "2021-08-30", **kwargs ) -> Graph: """R...
2de03cc7da02e58279ed5b576db4cbe14c98e0b5
28,466
def produce_new_shapedir(verts, n_betas=20): """Given a matrix of batch of vertices, run PCA through SVD in order to identify a certain number of shape parameters to best describe the vert shape. :param verts: (N x V x 3) array :param n_betas: Number of betas to be fitted to, B :return vtempl...
b12008b0c8b3809d211753dab6b89d3fcbb8bbce
28,467
import logging def get_calibration( df: pd.DataFrame, features:pd.DataFrame, outlier_std: float = 3, calib_n_neighbors: int = 100, calib_mz_range: int = 20, calib_rt_range: float = 0.5, calib_mob_range: float = 0.3, **kwargs) -> (np.ndarray, float): """Wrapper function to get calib...
af53baf47e1999f5ef421ddb1a12e2a41757f62e
28,468
import argparse from typing import List def argunparse(options: dict, parser: argparse.ArgumentParser) -> List[str]: """ Convert a dict of flags back into a list of args. """ args = [] for argument in parser.arguments: single_dash_name = next((arg for arg in argument["args"] if arg.startsw...
e0be2dd6e1e55bfebe5e29872d79bd9a8e2f8600
28,469
from typing import Mapping from typing import Iterable def _decode_bytestrings(o): """Decode all base64-encoded values (not keys) to bytestrings""" if isinstance(o, Mapping): return {key: _decode_bytestrings(value) for key, value in o.items()} elif isinstance(o, Iterable) and not isinstance(o, (st...
6a4fd49b50df91ee9705eda2192d10cb8f64606b
28,470
def extinction(lambda1in,R,unit = 'microns'): """ Calculates A(lambda)/A_V. So, if we know E(B - V), we do A(lambda) = A(lambda)/A_V * E(B - V) * R. R is alternatively R_V, usually 3.1---this parameterizes the extinction law, which you should know if you are using this function. This is the CCM...
d6b7a728de0b861786f6e28d3000f77d90248703
28,471
def to_rtp(F0, phi, h): """ Converts from spherical to Cartesian coordinates (up-south-east) """ # spherical coordinates in "physics convention" r = F0 phi = np.radians(phi) theta = np.arccos(h) x = F0*np.sin(theta)*np.cos(phi) y = F0*np.sin(theta)*np.sin(phi) z = F0*np.cos(theta) ...
dbf89e94d9e66925621969c53b476456a27af93d
28,472
def to_base(num, base, numerals=NUMERALS): """Convert <num> to <base> using the symbols in <numerals>""" int(num) int(base) if not (0 < base < len(numerals)): raise ValueError("<base> must be in the range [1, %i>" % len(numerals)) if num == 0: return '0' if num < 0: si...
aa25cb3f26e855d17c88be25b05251ebec216790
28,473
def identify_algorithm_hyperparameters(model_initializer): # FLAG: Play nice with Keras """Determine keyword-arguments accepted by `model_initializer`, along with their default values Parameters ---------- model_initializer: functools.partial, or class, or class instance The algorithm class be...
5ed499e8b5cf832a75009adf3bb29c7f65d97d35
28,474
from typing import List from typing import Tuple def cnf_rep_to_text(cnf_rep: List[List[Tuple[str, bool]]]) -> str: """ Converts a CNF representation to a text. :param cnf_rep: The CNF representation to convert. :return: The text representation of the CNF. """ lines = [] for sentence in ...
dec3754493cfb0bd9fb5e68d2bab92a40bd0f294
28,475
def reshape_for_linear(images): """Reshape the images for the linear model Our linear model requires that the images be reshaped as a 1D tensor """ n_images, n_rgb, img_height, img_width = images.shape return images.reshape(n_images, n_rgb * img_height * img_width)
dffc5e7d0f96c4494443a7480be081b8fe6b4abd
28,476
def otp(data, password, encodeFlag=True): """ do one time pad encoding on a sequence of chars """ pwLen = len(password) if pwLen < 1: return data out = [] for index, char in enumerate(data): pwPart = ord(password[index % pwLen]) newChar = char + pwPart if encodeFlag else char - pwPart newChar = newChar + 2...
34223c69149b09b1cc3bde8bf1c432f21415362b
28,477
from datetime import datetime def export_actions(path='/tmp', http_response=False): """ A script for exporting Enforcement Actions content to a CSV that can be opened easily in Excel. Run from within consumerfinance.gov with: `python cfgov/manage.py runscript export_enforcement_actions` By d...
f85f095b6c7c3bd5a1a5277125c56e17e9d8cbd9
28,478
def reduce_load_R(): """ Used for reconstructing a copy of the R interpreter from a pickle. EXAMPLES:: sage: from sage.interfaces.r import reduce_load_R sage: reduce_load_R() R Interpreter """ return r
858723306137a0e751f25766cbea5609867255f5
28,479
import urllib def path_to_playlist_uri(relpath): """Convert path relative to playlists_dir to M3U URI.""" if isinstance(relpath, compat.text_type): relpath = relpath.encode('utf-8') return b'm3u:%s' % urllib.quote(relpath)
a69c441411b09ccce387ff76d93d17013b960de4
28,480
from json import load import logging def read_drive_properties(path_name): """ Reads drive properties from json formatted file. Takes (str) path_name as argument. Returns (dict) with (bool) status, (str) msg, (dict) conf """ try: with open(path_name) as json_file: conf = lo...
18b9051801b032f5aa5532da0cfcca8793be8c91
28,481
import math def proj( point: np.ndarray, tol: float = 1e-9, bounds: tuple[float, float] = (0, 1) ) -> tuple[np.ndarray, float]: """Find projection on true ROC. Args: point: A point in [0, 1]^2. tol: Tolerance. bounds: Bounds of projection to help with the calculation. Returns...
c56c1d9beb54f45691d63900e7458ed1ec4218ee
28,482
def _split_on_wildcard(string): """Split the string into two such that first part does not have any wildcard. Args: string (str): The string to be split. Returns: A 2-tuple where first part doesn't have any wildcard, and second part does have a wildcard. If wildcard is not found, the second part is ...
09625186d22d50b737c94d2b22156a48bbf9b5ad
28,483
def esgUSPTOPatentGrantsDF(symbol="", **kwargs): """Patent grants are indications that a company has successfully signaled that it values its IP, that its IP is unique in the eyes of the USPTO, and that its initial patent application was a reasonable one. Patent grants data is issued weekly on Tuesdays. Cur...
22524f06572dca4fd2118a407273b7d23e68453c
28,484
import time import pickle def get_nln_metrics(model, train_images, test_images, test_labels, model_type, args): """ Calculates the NLN metrics for either frNN or KNN Parameters ---------- ...
52157740a2507432b16ef007d541e1cc0b77b42e
28,485
import os import scipy def load_ms_file(msfile, fieldid=None, datacolumn='RESIDUAL', method='physical', ddid=0, chunksize:int=10**7, bin_count_factor=1): """ Load selected data from the measurement set (MS) file and convert to xarray DataArrays. Transform data for analysis. Parameters ---------- ...
875d6113fab4898595e4696af49f71e76dcdbe17
28,486
from typing import Optional from typing import Dict def get_web_optimized_params( src_dst, zoom_level_strategy: str = "auto", aligned_levels: Optional[int] = None, tms: morecantile.TileMatrixSet = morecantile.tms.get("WebMercatorQuad"), ) -> Dict: """Return VRT parameters for a WebOptimized COG.""...
2e108f4619f5bf672981e60114065196f15116d0
28,487
from sage.misc.superseded import deprecation def AlternatingSignMatrices_n(n): """ For old pickles of ``AlternatingSignMatrices_n``. EXAMPLES:: sage: sage.combinat.alternating_sign_matrix.AlternatingSignMatrices_n(3) doctest:...: DeprecationWarning: this class is deprecated. Use sage.com...
3fad083e18ded990b62f2453ba75966fac6df6ed
28,488
def _get_band(feature, name, size): """ Gets a band normalized and correctly scaled from the raw data. Args: feature (obj): the feature as it was read from the files. name (str): the name of the band. size (int): the size of the band. Returns: tf.Tensor: the band parsed...
db13abf7dc1cfa1cff88da864c2aaac043f574b2
28,489
import functools def rgetattr(obj, attr, default=sentinel): """ from https://stackoverflow.com/questions/31174295/getattr-and-setattr-on-nested-objects """ if default is sentinel: _getattr = getattr else: def _getattr(obj, name): return getattr(obj, name, default) r...
6b6b7d98e117647a5609e10a499795ad293f1c6d
28,490
def unpack_dims(data, vlabels): """ Unpacks an interleaved 4th dimension in an imaging data array Parameters ---------- data : np array a numpy array of data. Should have 3 spatial dimensions followed by one nonspatial dimension of interleaved data vlabels : pandas DataFrame ...
1eaf0b00d4dd8be26927845aefa334b84e9264df
28,491
def bash_this(s): """produce a shell fragment that runs the string str inside a fresh bash. This works around potential strange options that are set in the topmost bash like POSIX-compatibility mode, -e or similar.""" return 'bash -c %s' % shell_quote(s)
e06d287ebdf226ab6f83004c65cea7ada94232e1
28,492
import re def filter_markdown(md, **kwargs): """Python markdown requires markdown="1" on HTML block elements that contain markdown. AND there's a bug where if you use markdown.extensions.extra, it replaces code fences in HTML block elements with garbled text.""" def add_markdown_class(m):...
4f55362bf336a0b7f8adba56f31b92a4952b14ae
28,493
def multiply_tensors(tensor1, tensor2): """Multiplies two tensors in a matrix-like multiplication based on the last dimension of the first tensor and first dimension of the second tensor. Inputs: tensor1: A tensor of shape [a, b, c, .., x] tensor2: A tensor of shape [x,...
374547e03fe95b02a77ef1420e7cac2f07248fb3
28,494
def get_cumulative_collection(): """获取设备累积数据表 """ client = MongoClient(connection_string) db = client.get_database(database) collection = db.get_collection('equipment_cumulative') return collection
0de651fe424730b2e486298e8e142190514748bb
28,495
import re def self_closing(xml_str, isSelfClosing): """ 是否自闭合空标签, :param isSelfClosing: :param xml_str: :return: """ if(isSelfClosing=="true"): xml_str = re.sub(r"<(.*)>(</.*>)", r"<\1/>" , xml_str) return xml_str else: return xml_str
b8b68626549da9a27335c5340db3ba65b753af90
28,496
def setup_dense_net( num_predictors, neuron_counts=DEFAULT_NEURON_COUNTS, dropout_rates=DEFAULT_DROPOUT_RATES, inner_activ_function_name=DEFAULT_INNER_ACTIV_FUNCTION_NAME, inner_activ_function_alpha=DEFAULT_INNER_ACTIV_FUNCTION_ALPHA, output_activ_function_name=DEFAULT_OUTPUT_ACT...
3f952d3121253208b62ccbd2e3149e820cd6f72b
28,497
def init_weights_he(nin, nout, nd, ny): """ Sample the weights using variance Var(W) = 2/nin according to He initilization for ReLU nonlinearities from a normal distribution with zero mean. """ sigma = np.sqrt(2/(nin)) weights = np.random.normal(0, sigma,((nd, ny))) # Weight vector (nd x ny) return weights
fdb9fcef6888ea8513b22e84207f67cd71d90a9e
28,498
def get_all_message_template(): """returns all drivers or none""" try: return MessageTemplates.objects.all(), "success" except Exception as e: return None, str(e)
1e63e73776b5b15d1cd7512fec32cea14454d717
28,499