content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def SetTriggerMode(mode): """ This function will set the trigger mode that the camera will operate in. Valid values: 0. Internal 1. External 6. External Start 7. External Exposure (Bulb) 9. Externa...
9fcb6f3524de7eed5cdda02ce56a5077a97c2d75
57,800
def bit2number(val: np.array, bits: int = 64) -> str: """ Convert binary to array of number Args: val: string of bits bits: number of bits Returns: array of number """ return bitstring.BitArray(bin=val, length=bits).float
e99e7f42f40362e1c1e2ed6a4b94130477746900
57,801
def L(n, ri, c): """Calcula las matrices Li. ri: a[i][c] / a[c][c] c : columna c-esima """ #Matriz identidad L = [[float(i == j) for j in range(n)] for i in range(n)] for k in range(c+1, n): L[k][c] = -ri[k] return L
d6f7293691842d7175facc540c35cd1c1a43ee09
57,802
import pprint def getUser(user_email): """endpoint returning user information --- """ result = db.getUserByEmail(user_email) del result["_id"] pprint(result) return jsonify(result)
90b5e05067153ac430284452104e77c7c5bc5046
57,803
import os import zipfile def unzip(src_path, dst_path = None): """Extracts a zipfile. Defaults extraction to the same path. Returns filename list.""" dst_pathmod = dst_path if dst_path is None: dst_pathmod = os.path.dirname(src_path) with zipfile.ZipFile(src_path) as zf: nmlist = zf.namelist() zf.extractall...
8947922c1026e669fa494d369f8beaedce49bea5
57,804
def resolve_acc_gyro_db(df): """ combine separate accelerometer and gyrocope rows into one row for data already stored in db """ df_accel = df[df['SENSOR_TYPE'] == 'Accelerometer'].copy() df_accel['ACCEL_X'] = df_accel['X_AXIS'] df_accel['ACCEL_Y'] = df_accel['Y_AXIS'] df_accel['ACCEL_Z...
0360018617f7dce9f5c3d02608107dc5873a7991
57,805
def map_(request, id_): """Renders the big map for given activity. Arguments: id_: id of the activity """ activity = get_object_or_404(Activity, pk=id_, user=request.user) template = { 'activity': activity, } return render(request, 'activities/map.html', template)
2c02943aa3b3cf3f9f19d51b623222d6b1fdb7be
57,806
def create_info_dict_lm(x, y, beta, ml_model, fit_algorithm, pred_cols): """Creates a information dictionary for linear model results. Only basic information will be created in this function. A series of these functions are used in a flow to get all information needed in linear model summary. The flow ...
81f36c7861cead2669a8af2092c12b1d2137856d
57,807
def deleteSnapshot(**kargs): """Delete Snapshot of Volume for the KT Cloud NAS. * Args: - zone(String, Required) : [KR-CA, KR-CB, KR-M, KR-M2] - volumeid(String, Required): volume ID - name(String, Required): volume name * Examples: print(nas.deleteSnapshot(zone='KR-M', volumeid='835...
9efcbd9d0cf81d619a99f7caef839cd2c5e27d22
57,808
def list_pipelines( full=False, page_token="", page_size=10, sort_by="", experiment_id=None, namespace=None, ): """List pipelines""" namespace = namespace or mlconf.namespace client = Client(namespace=namespace) resp = client._run_api.list_runs( page_token=page_token, pag...
836f83d0514209e4b773f80bcdf1ca716dbd4d76
57,809
def assembler_parser(): """ Create a ArgumentParser. """ return create_assembler_parser()
af40f420a0b11e01ce3be24791cce6b171936a58
57,810
def convert_array_to_dict(array: np.ndarray) -> dict: """Convert a numpy array to a dictionary. Args: array (numpy.array): a numpy array Returns: dictionary (dict): the dict containing the data """ dictionary = {} if np.iscomplexobj(array): dictionary["real"] = arr...
3e64b6a8f587c8e446f7161c190aab30052bd1c4
57,811
def get_type(type_f): """ A function used to categorized each formula. """ tmp = '' if 'trad' in type_f: tmp = 'T' elif 'TCONG' in type_f: tmp = 'P' elif 'DRA' in type_f: tmp = 'R' elif 'WDBA' in type_f: tmp = 'W' else: tmp = type_f ret...
438c3c3c7fc22fbd09f97727bd30890519efa918
57,812
def like(column: str, value: OpT) -> str: """Like""" return f"{column} LIKE {enclose_in_single_quote_when_value_is_str(value)}"
8fb74d5179aac1621f363046630a520f7f6db33b
57,813
def load_merged_events(conf, dt_range, area, l_evdef, d_el): """for visualization""" areatest = AreaTest(conf) ci_bin_method = conf.get("dag", "ci_bin_method") ci_bin_size = config.getdur(conf, "dag", "ci_bin_size") ci_bin_diff = config.getdur(conf, "dag", "ci_bin_diff") l_df = [] for idx, ...
a27b939530dda1dafc4beb847de39e35231d7117
57,814
def apply_grid_offset(df, axis, offset): """ Shift eta values according to grid offset. Carried out in place """ df.eta_l -= offset df.eta_r -= offset if np.sign(offset) == 1: eta_r_mask = df.eta_r < 0 eta_l_mask = df.eta_l <= -1 df.loc[eta_r_mask, 'eta_l'] = df.eta_r[e...
d8386679fbd87344f479b424a1e3518b19e3957f
57,815
import math def makeDome(point, radius, frequency): """ """ msg = verbose m_center = point m_radius = radius m_frequency = frequency if msg != 0: print_msg("makeDome(point=" + str(m_center) +\ ", radius=" + str(m_radius) +\ ", frequency=" + str...
773c08f174c118ec4e95248d68298a3f1922a5de
57,816
from pathlib import Path def dump_analysis(analysis_id, run_id=None): """" Serialize analysis and related PredictorEvents to JSON. Queries PredictorEvents to get all events for all runs and predictors. """ # Query for analysis analysis = Analysis.query.filter_by(hash_id=analysis_id).one() # Dump...
9937f00cfbbd1d5bccc3666054f6c8d71bacd072
57,817
def hex_to_int(input: str) -> int: """Given a hex string representing bytes, returns an int.""" return int(input, 16)
844714eaec1a2b2804cb4725e458980555516ce2
57,818
def internal(cls): """ Decorator. This class or package is meant to be used only by code within this project. """ return cls
35784ef8c35993834e033f21817f52bb24bc5cfe
57,819
def convolve(img, fil, args=[]): """ Take a PIL image, apply a convolution and return the resultant image :param img: :param fil: :return: """ if hasattr(fil, '__call__'): knl = fil(*args) else: if len(fil) == 25: wh = (5, 5) elif len(fil) == 9: ...
e927fba4ed9648f16ef32a63deff2d01cbba7b26
57,820
def create_zone_ajax(request): """This view tries to create a new zone and returns an JSON with either 'success' = True or 'success' = False and some errors. By default all records are created and added to the public view. Throughout this function note that objects that are created are recorded, an...
2302eb74a71db1bd468b476b2571a2c21213a61a
57,821
def updateMobility2022(directory, mobility_file): """! Merges rows and columns of Eisenach to Wartburgkreis which has become one single county by July 2021. If mobility matrix dimension is different from 401x401, nothing is done. @param directory Path to folder where data is read and written. @para...
bb971ff74f49424c7cfccba24c06dc0acca4aa75
57,822
def couchbase_factory_fixture(request): """ Couchbase factory fixture """ couchbase = CouchBase() def factory( replicas=3, run_in_bg=False, skip_analyze=True, sc_name=None, num_items=None, num_threads=None, ): """ Factory to start ...
12041413c717bf9be75f8d98d8f59ca936441bf9
57,823
def get_luks_device(ns, fmt): """ Return clear-text device for given LUKS format. The format must be already opened by open_luks(). :type fmt: LMIInstance/LMI_EncryptionFormat or string :param fmt: The LUKS format to inspect. :rtype: LMIInstance/LMI_LUKSStorageExtent :returns: Block device ...
a766f2f9e7f0d771377934f7cb865b81721ef0a3
57,824
from typing import Optional from typing import Collection def get_collection(url: str, port: int, database_name: str, collection_name: str) -> Optional["Collection"]: """ Returns a pymongo handler for the specified collection or `None` if the connec...
87948005ab85043ecf5737d719fe6b801e7b03f8
57,825
def read_feat_of_one_movie(feat_dir, mid, region, data_type): """ region: face or body data_type: cast or tracklet """ cache_file = osp.join(feat_dir, mid, '{}_{}_feat.npy'.format(data_type, region)) if osp.isfile(cache_file): feat_mat = np.load(cache_file) else: raise IOErro...
e838b63cb520f217b11c2342c476845b358540c0
57,826
import pathlib from typing import Tuple from typing import Type def get_relative_model_type(relative_path: pathlib.Path) -> Tuple[Type[OscalBaseModel], str]: """ Given the relative path of a file with respect to 'trestle_root' return the oscal model type. Args: relative_path: Relative path of the...
a0b0b7fea82bdeb4eda480d838781c46adaaf269
57,827
def mass_hpa_wing( span, chord, vehicle_mass, n_ribs, # You should optimize on this, there's a trade between rib weight and LE sheeting weight! n_wing_sections=1, # defaults to a single-section wing (be careful: can you disassemble/transport this?) ultimate_load_factor=...
ca6ad4952964cc610afd7b851d8df91b88d6abbb
57,828
def sigmoid_cross_entropy(outputs, labels): """ computes average binary cross entropy """ loss = tf.nn.sigmoid_cross_entropy_with_logits(logits=outputs, labels=labels) return tf.reduce_mean(loss)
2b67e85779383b3b2d15fd066c0312cfaf00ae90
57,829
def get_members(member: discord.Member, exclude_bot=True) -> list[discord.Member]: """ メンバーが接続しているボイスチャンネルの全メンバーを取得する botは除外できる Parameters ---------- member: discord.Member メンバー exclude_bot: bool ボットを除外するか returns ------ connected_members: list[discord.Member] ...
ec7e6b8e2fb420d1ba27ac52ef5b47c6a0c1107e
57,830
import json def list_images(api): """List all images for a Podman service.""" response = api.get("/images/json") return json.loads(str(response.read(), 'utf-8'))
7c694d5b0b75a905273c47bf82ebf2a4b3f5d893
57,831
def contour_level_colors(cmap, levels, vmin=None, vmax=None, center=True): """get colors corresponding to those produced by contourf Arguments: cmap {string or cmap} -- colormap levels {list or array} -- desired levels Keyword Arguments: vmin {number} -- min value (default: {0}) ...
4ef70fc04b05ebd176c879035c07339925af89ff
57,832
def z_rotation(rad): """ returns a transformation matrix in the z direction """ return matrix(4, 4, ([[cos(rad), -sin(rad), 0, 0], [sin(rad), cos(rad), 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]))
f5158f610aa02066410902786ae3904dcfe1dc76
57,833
def fsc3d(*args, **kwargs): """ Compute the local FSC of the map """ if len(args) > 0 and type(args[0]) == "str" or "input_filename1" in kwargs: func = mapfile_fsc3d else: func = array_fsc3d return func(*args, **kwargs)
d5ce40191499c220c17fe2a394aaf58030c4b6f5
57,834
def checkpoint(step, model, optimizer, scheduler, best_valid_loss, train_loss_history, valid_loss_history, args): """ Creates a checkpoint with the current trainig state Parameters ---------- step : int The current training step model : torch.nn.Module The network model in the c...
bba05567c09a5518af77c8efbb46484c910c23a8
57,835
def gen_center(T, y): """Generate the center of feature statistics of positive training set. Args: T: feature statistics list y: labels Return: C: center, where dim(C) = 18*3 = 54. """ T_pos = [T[i] for i in range(len(y)) if y[i] == 1] C = np.mean(T_pos, 0).reshape(1, -1)...
a2eedf6ef07583d0698ebd6fa29cc419572fd1da
57,836
def getGeneAvg(population, Npop, indGeontype, indGene): """ Reads from our generic gene structure """ genes = np.zeros(Npop) for ii in range(Npop): genes[ii] = population[ii].genotype[indGeontype][indGene] return np.average(genes)
04cd0705f09736ae119e49956f3d52278396ae25
57,837
import math def modifier(constitution: int): """ You find your character's constitution modifier by subtracting 10 from your character's constitution, divide by 2 and round down. :param constitution: :return: """ return int(math.floor((constitution - Character....
1f014b5f0ddf7f3cd4feba9c8ac6942221d7f0b9
57,838
import string def filter_filename(filename): """Utility to filter a string into a valid filename""" valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits) filename = ''.join(c for c in filename if c in valid_chars) return filename
8ab97e9a3d9b806090a4b55f6a47d2f011f99ede
57,839
def csvserverbaseline(): """ Return a csv string of raw server metrics data: memfree, memtotal, cpuused, cpusystem, cpuidle. """ return "memory (total, free) = " + csvservermems(collectservermems()) + "\ncputime (used, sys, idl) = " + csvservercputimes(collectservercputimes())
e12c707715dcdab09cd9805e990a6f041675b572
57,840
def success(parsed_args): """ :param :py:class:`argparse.Namespace` parsed_args: :return: Nowcast system message type :rtype: str """ data_date = parsed_args.data_date forecast = parsed_args.forecast logger.info( f"{data_date} Neah Bay ssh {forecast}Z obs/forecast data collectio...
cb6a1381e458008bf956706fa810abf6084e6be9
57,841
async def async_setup(hass, config): """Activate the Alexa component.""" config = config.get(DOMAIN, {}) flash_briefings_config = config.get(CONF_FLASH_BRIEFINGS) intent.async_setup(hass) if flash_briefings_config: flash_briefings.async_setup(hass, flash_briefings_config) try: ...
0dcdb63db03071efcca69c2984739896d44101d3
57,842
def add_times_to_file(df, periodcol, timecol, time_format): """ Uses specified periodcol, timecol, and time_format col to calculate _Secs, time elapsed in game. :param df: dataframe :param periodcol: str, the column that holds period name/number (1, 2, 3, 4 or OT, etc) :param timecol: str, the colu...
e6de34541b92263fff004d4505a2ac5f6f1f2dda
57,843
def get_info(_path) -> dict: """ listing subdirectories and reading info.json files :param _path: [{..}, {..}, {..}] :return: """ result = {} for d in listing(_path)['directories']: directory = path_join(_path, d) info = __get_info(directory) if info is not None: ...
6a6e47bcbfac20c033c892d98f39daa9e17190b7
57,844
import os import re def get_reads(method): """Returns file names from all Read nodes. Options: file - outputs only file names dir - outputs only directory names long - outputs the entire path""" # create variable for the text finalmsg = "" #go thru all the nodes allnodes = nuke.allNodes(gro...
4e14405c6cec9b81ba1a8f96eaa85dc9378f8c17
57,845
def convert_image_to_int(image: np.ndarray, image_type: np.dtype = np.uint8) -> np.ndarray: """Casts data to integer format specified in image_type. Args: image (np.ndarray): RGB or grayscale image. image_type (np.dtype): Either uint8 or uint16, default: np.uint8. Returns: np.ndarr...
5c85b107003715647b6976d6e81d407e249f3925
57,846
from re import U def ts1(model, pre_obs, obs, act, pop_size, npart, num_nets, num_comp, calibrator=None, inv_cal=None): """Trajectory sampling scheme proposed in github.com/kchua/handful-of-trials/blob/master/dmbrl/controllers/MPC.py#L318 Args: model: Transition Probability pre_obs: Pre-proces...
8b99563ced9b5dbcc993b87fa760263b0ca46a95
57,847
def addUser(request, question_id): """ """ cursor = connection.cursor() user = request.user inp_value = request.POST.get('name') member_id = CustomUser.objects.raw("SELECT * FROM users_customuser WHERE name = %s", [inp_value]) question = Question.objects.raw("SELECT * FROM polls_questi...
1d9a0e45840c7fdb16c912c7905f2be84b6a5554
57,848
def normalized_cube(inner, half_length, scale_factor): """Normalized cube algorithm. A cube is projected to a sphere's surface and so mesh is produced. This algorithm fullfills Jacobian's criteria very nice. Args: inner (array): Cube's coordinates (produced by another function). half_le...
78096249c7f4868e9fc0e1086150995330e221b8
57,849
import torch def perspective_project_torch(points, rotation, translation, cam_K=None, focal_length=None, img_wh=None): """ This function computes the perspective projection of a set of points in torch. Input: points (bs, N, 3): 3D points rotation (bs, 3, 3): C...
ab9e8810515226a0670d7b41fc4cc2ec3226e6b8
57,850
def create_residual_wstack_graph(vis_graph_list, model_graph: delayed, **kwargs) -> delayed: """ Create a graph to calculate residual image using w stacking :param vis_graph_list: :param model_graph: Model used to determine image parameters :param vis_slices: Number of vis slices (w stack or timeslice)...
8f376c70d715bc80b9fcbd863a448684b3fad93c
57,851
def parse_layers_number(): """ Parse all available number of layers and set initial probability """ tmp_probability = 1 layers_number_probability = {value: tmp_probability for value in GENERAL['layers_number']} return layers_number_probability
29188923779ebaed95d4fe318055d094f4708e4c
57,852
def df_add_delta(df, col='delta', src_col=None, window=None, inplace=False): """ Add a column containing the delta of the given other column. :param df: The dataframe to act on. :type df: pandas.DataFrame :param col: The name of the column to add. :type col: str :param src_col: Name of th...
5187094ca0fa79029f2c266170bb89df87c234be
57,853
def setup_database(args): """Create connection and setup database. If database of this name already exists drop it (if possible). Parameters ---------- args : Object returned from ArgumentParser.parse_args() Container with arguments specified in :see create_database_utils.py ...
2ced311310ba312f4640be04737317174fc0ec09
57,854
import tqdm import sys def get_softmax_scores_for_untrimmed_videos(data_loader, model, mode, stack_size, return_logits=False): """ Gets the softmax scores for each frame in each untrimmed video :param data_loader: Pytorch data loader :param model: Pytorch model :param mode: either `rgb` or `flow`...
92867636bea924913e7b2f722b7cf4be245ef3c5
57,855
def context_command_parser(subparsers): """ Add `loqet context` sub-command subparser to top level `loqet` command """ context_parser = subparsers.add_parser("context") sub_subparsers = context_parser.add_subparsers( dest="context_command", help="Context sub-command help" ) ...
984bf8a68d3d8f9f339347ec51cb6ec7f8afbc9c
57,856
def to_rgb(x): """4D tensor to RGB, assumes ycbcr input in [-0.5, 0.5].""" s = tf.shape(x) return tf.reshape(tf.matmul(tf.reshape(x, [-1, s[3]]), _YCBCRI), s) + 128 / 255
91847a528c1495e7bd89e924aab2fdeb6dfa694b
57,857
import logging def logger(): """Access global logger. .. deprecated:: 3.3 To control logging from ixmp, instead use :mod:`logging` to retrieve it: .. code-block:: python import logging ixmp_logger = logging.getLogger("ixmp") # Example: set the level to INFO ...
5ca1961947751ba29175a54f25b9f35d84856916
57,858
def _get_fitness(anion, genes, target, model_ID): """ the fitness function passed to the engine. In this case fitness is determined by a model developed by the salty module. It is important to note that the fitness function can handle multi- output models """ cation = Chem.MolFromSmiles(gene...
94e7ce5ad93ee08c16a5fb36476b830eac6926e6
57,859
import sys import tqdm import subprocess import json def get_path(cfg: dict, target: str, target_type: str = "ipv4") -> dict: """ This function runs the MTR and collects its output in JSON format """ allowed_types = {"ipv4", "ipv6"} if target_type not in allowed_types: sys.exit(f"Unsuppor...
954b6504eaa06f5236b9d00264542e0a4c8add6b
57,860
def get_team_fixture_scores(fixture_teams: DF, teams: DF) -> DF: """ Converts the given fixture team stats (one row per fixture) to a data frame with one row for each fixture and team combination. The resulting data frame has twice as many rows. It then calculates stats for each row form the team's point of...
ba943f9339ad04cf2a539af23f47a9e4f66f7f68
57,861
def take_first_col_and_impute(data_arr): """Take the first column in array and impute nan with 0.5. Used within ColumnTransformer. Args: data_arr: Returns: """ for i in range(data_arr.shape[-1]): lb = LabelBinarizer() cur_data = lb.fit_transform(data_arr[:, i]) ...
7a69b630a178673c47225e6c0ecea156dc82255c
57,862
def dot_product(A, B): """ Computes the dot product of vectors A and B. @type A: vector @type B: vector @rtype: number @return: dot product of A and B """ if len(A) != len(B): raise ValueError("Length of operands do not match") result = 0.0 for i, v in enumerate(A): ...
f63528bda5d3890137a35de5fd639086262b5c93
57,863
from typing import Any from typing import List from typing import Optional from typing import Union from typing import Tuple from typing import Dict def density_plot(data:NDArray[(Any,Any),Number], labels:List[str]=[], colors:List[Any]=[], cmap:Optional[Union[str,Colormap]]=None, bin...
cc11f497b81af066f062b8bbe4b417c56decb55e
57,864
def has_sources(target, extension=None): """Returns True if the target has sources. If an extension is supplied the target is further checked for at least 1 source with the given extension. """ return (target.has_label('sources') and (not extension or (hasattr(target, 'sources') ...
71853d034f6fe8283f2178daf3648ac75457ec2e
57,865
def fibo(n): """Returns nth fibonacci number.""" a, b = 0, 1 for i in range(1, n): a, b = b, a+b return b
b9a8d3960cc01f1745151eda250fea97c0e62b14
57,866
def check_accuracy_single(dat, label): """NOTE: OLD! UNUSED. Use sklearn funcs. Test the accuracy for a list of results, with single answer. Parameters ---------- dat : list of int Predicted labels of a set of test data. label : int The correct label. Returns ------- ...
26fec27fcd03eb637dd2c94559c182a172d693a5
57,867
def fromUnicodeSymbols(s): """ Convert a braille string (with unicode symbols) to the representation used in this program. Used for debugging and as a tool to integrate the Nemeth code. """ s_ = s.split(" ") retObj = [] for wrd in s_: word_repr = [] for ch in wrd: ...
4f16e905e785e0679961b9a3a1cf4bab22b805a2
57,868
import os import shutil def make_archive(release_name: str, version: str, root_dir: os.PathLike, release_dir: os.PathLike) -> os.PathLike: """Create a zip archive. Args: release_name: Name of the release. version: Version of the release. root_dir: Path to the root dir...
0fdf059f505eada5804f66748cb8edad26488360
57,869
def test_start_1(monkeypatch): """Verify that start function return exception when namespace is already created. """ output_result = "Namespace is already created" def mockreturn(command): so = "HOST" return so, "", "" lh = IpNetworkNamespace(LH_CFG, OPTS) monkeypatch.setattr(l...
18bfb4b106dc2555c46f3c1c8bf325a12a153ddf
57,870
def policy_iteration(P, nS, nA, policy, gamma=0.9, tol=1e-8): """Runs policy iteration. You should call the policy_evaluation() and policy_improvement() methods to implement this method. Parameters ---------- P, nS, nA, gamma: defined at beginning of file policy: policy to be updat...
35ca7e50bb7bb20fe9038b7c83e7a9810b2e7ede
57,871
from typing import Dict from typing import List from typing import Iterable def get_comments(pf) -> Dict[str, List[str]]: """Retrieves comments from proto file and creates a dictionary symbol which comment was aimed at""" def _get_inner(): i = 0 for location in pf.source_code_info.location: ...
e2617546f62f05c71a2113d06dc31f89cd6b688c
57,872
import os def verify_settings(arguments: Settings, make_abs_path: bool = True) -> Settings: """ Check parameters integrity. Load arguments from config file, if exist. Return valid argument set or raise exception. """ if not arguments.dest_path is None: abspath = os.path.abspath(arguments.dest...
a2d77cb2a9e582789d66a96615263254ff7439e3
57,873
def calculate_throughput(elapsed_time, messages): """calculates throughput and extracts the number of seconds for the run from the elapsed time :param elapsed_time: run time :param int messages: number of messages to write :return: throughput and seconds :rtype: tuple """ ftr = [3600, 6...
7697bc15c26decafea169be681ae1bbf4e2780fe
57,874
def get_group_model(): """ Returns the study group model MRI scans should be related to. Returns ------- django.db.models.Model Study group model """ study_group_model = getattr( settings, "STUDY_GROUP_MODEL", DEFAULT_STUDY_GROUP_MODEL ) return apps.get_model(study_g...
6cdfa669fd4ebb7a601a87ea6309d8f1175ec2a2
57,875
import numpy import math def quaternion_about_axis(angle, axis): """Return quaternion for rotation about axis. >>> q = quaternion_about_axis(0.123, [1, 0, 0]) >>> numpy.allclose(q, [0.99810947, 0.06146124, 0, 0]) True """ q = numpy.array([0.0, axis[0], axis[1], axis[2]]) qlen = vector_no...
e45932baac07c1d9e086dff5f67111e22996f118
57,876
def check_filter(self): """Check if filter is correctly defined Parameters ---------- self: Data1D a Data1D object Returns ------- keys: list list of filter keys in same order as in values """ keys = [] for i, value in enumerate(self.values): items = value...
ceb887a7cb8fde389ae19e4dc786c71f2fdfe028
57,877
def escape_strings(escapist: str) -> str: """Escapes strings as required for ultisnips snippets Escapes instances of \\, `, {, }, $ Parameters ---------- escapist: str A string to apply string replacement on Returns ------- str The input string with all defined replace...
adc6d2ddec37aecdafb8a91d3027ec7e1b5e36c2
57,878
def or_(*args): """Compute the logic OR between expressions. """ return any(*args)
17b775029490d5ca4ea1574186bd02a77a92782a
57,879
def select_db_row(table: str, id: int, database=DATABASE_PATH): """select_db_row. Selects and prints out a row within a registered sqlite database table. Parameters ---------- table : str Name of table to select record from. id : str Id key for required record within table for ...
ad20adf222d087073b56b605dd3b4472dcaba984
57,880
def task_action_router(request, section_id, task_id): """ Routes task actions which share a common function signature. Parameters: request: The client request. Must use one of the following methods: PUT, DELETE. section_id: The id of the section to which the affected task belongs. ...
a28c66af4661d6e409f747e7fd0b902258902c15
57,881
import torch def get_device(gpu: bool = False) -> torch.device: """Get the torch device, try to get a GPU if gpu is set, raise an error if no GPU and gpu is set""" if gpu: if torch.cuda.is_available(): return torch.device("cuda") else: raise ImageTrainerError( ...
2799c575b5320e4881064181dbeb2297c1712127
57,882
def ldns_nsec_bitmap_set_type(*args): """LDNS buffer.""" return _ldns.ldns_nsec_bitmap_set_type(*args)
d7137b51366984146363d6e51bc8131d5b0526cc
57,883
import torch def dice_loss(logits, true, eps=1e-7): """Computes the Sørensen–Dice loss. Note that PyTorch optimizers minimize a loss. In this case, we would like to maximize the dice loss so we return the negated dice loss. Args: true: a tensor of shape [B, 1, H, W]. logits: a tens...
2ad42db5f4bf6bbae3c91baecda9264f4fe78056
57,884
def decimalHour(time_string): """ Converts time from the 24hrs hh:mm:ss format to HH.hhh format. """ hh, mm, ss = time_string.split(':') hh, mm, ss = map(float, (hh, mm, ss)) result = ((ss/60) + mm)/60 + hh return result
b931ce0bd1c57c0d2b47a5d51331685e6c478b61
57,885
def verif(*stim, f, ref, delays=None, cmp=None, check_timing=False, make_report=False): """Verification environment for comparing DUV results with reference model. The environment instantiates the DUV and reference model and drives the passed stimulus to both. The outpus are passed to the scoreboard which ...
bbc3437a22292eefc58141507de48843b9374051
57,886
from datetime import datetime def add_business_days( date: datetime.date, count: int, cal: AbstractCalendar = WEEKEND_CALENDAR ) -> datetime.date: """Add business days to a date. Args: date (datetime.date): The date. count (int): The number of days to add. cal ...
cb54bfc0c55dcd0ccfabd07d4ad30060a5729afd
57,887
from typing import Optional from typing import Tuple from typing import Dict from typing import Any async def fetch_acc_history( # noqa: WPS210 WPS211 user_id: int, db_con: Connection, page_number: int = 1, page_size: int = 20, order_by_date: Optional[SortKey] = None, order_by_total: Optional...
b9350328044be8bd53192dc33eb09408cca3c387
57,888
def _calculate_M( generator: int, prime: int, identity: str, salt: bytes, A: int, B: int, session_key: bytes, ) -> bytes: """ Calculate evidence message M hash. Args: generator (int): the generator of the prime prime (int): the large safe prime ...
b590ef3ffa7000d56c760e2864fc788d3dd5e183
57,889
def get_student_programs(person_id: str = None): """ Returns the programs, degrees, and specializations for a particular student. :param person_id: The numeric ID of the person you're interested in. :returns: String containing xml or an lxml element. """ return get_anonymous('getStudentProgram...
b24c37c36ee1ab6b946570b530a1206497c21895
57,890
def getFileName(fileRequest): """returns the file name from a file Request""" nameByteLength = int(((fileRequest[3] << 8 ) | (fileRequest[4]))) return fileRequest[5:nameByteLength * 2]
d6f500b4101677ab2655650f33f0b3f206c55e9c
57,891
def action_masks(player_unit, unit_handles): """Mask the head with possible actions.""" if not player_unit.is_alive: # Dead player means it can only do the NoOp. masks = {key: np.zeros((1, 1, val)) for key, val in ACTION_OUTPUT_COUNTS.items()} masks['enum'][0, 0, 0] = 1 return masks masks = {key...
cf1b30d48195166ff0540519ed4bdf6ef1ca33a1
57,892
def make_word_copying_data_provider(data_sources_source, data_sources_target, data_sources_schema=None, reader=tf.TextLineReader, num_samples=None, ...
334576b6bae151e4be8b15f998bb8b7f4f83d68c
57,893
def get_listfield(typ, val, path: str): """Parse a type/value and return a ListField if possible, otherwise return None""" subpath = f"{path}[]" typ = _normalize_list_type(typ) if not _is_list(typ): return subfield: Field = get_field(typ.__args__[0], MISSING, subpath) return ListField(ty...
6835130e2c7d1528a515cbe5cac5c5d3142898d9
57,894
import pickle def load_pickle(filepath): """Load pickled data""" documents_f = open('data/sberquad/pickles'+filepath+'.pickle', 'rb') data = pickle.load(documents_f) documents_f.close() return data
093afe0640a5b53f49ba04bd37685e69dc141ca6
57,895
import re def pic_link(soup, min_score=100): """ Return set of links to pics with scores higher than min_score. """ links = set() # soup = bs(html, "lxml") comment_list = soup.find("ol", class_="commentlist").find_all("li") for comment in comment_list: try: score = pic_...
8c80b4a0ad3bf997fb94b46faa59a7cda9a4ef86
57,896
import base64 import zlib import traceback def extract_real_url_from_embedded_url(embedded_url): """ 将 embed_real_url_to_embedded_url() 编码后的url转换为原来的带有参数的url `cdn_redirect_encode_query_str_into_url`设置依赖于本函数, 详细说明请看配置文件中这个参数的部分 eg: https://cdn.domain.com/a.php_zm24_.cT1zb21ldGhpbmc=._zm24_.css ...
a1b6ce9da2639ccea77a4eb1c00186c66871e48f
57,897
def triangle_vertices(width=1.0, height=1.0, edge_resolution=3): """ Create the vertices of a triangle in the xy-plane with corners in (0, 0), (width, 0) and (0, height). :param width: 'Width' of the triangle. :param height: 'Height' of the triangle. :param edge_resolution: Number of vertices a...
ba699d26a3e1c691b43c18845378ad4f9162a742
57,898
import json def request_loader(request): """Get the user provided in X-GGRC-user if whitelisted Appid provided.""" whitelist = settings.ALLOWED_QUERYAPI_APP_IDS inbound_appid = request.headers.get("X-Appengine-Inbound-Appid") if not inbound_appid: # don't check X-GGRC-user if the request doesn't come fro...
a514d0248c2ece5c45afb89baceae7e2216f94a2
57,899