content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
async def get_token(tkn: Token = Depends(from_authotization_header_nondyn)): """ Returns informations about the token currently being used. Requires a clearance level of 0 or more. """ assert_has_clearance(tkn.owner, "sni.read_own_token") return GetTokenOut.from_record(tkn)
19ea12ad43a4a61f940e9dce4ca3c4a5d6fbbdf2
12,900
def import_as_event_history(path): """ Import file as event history json format. Parameters ---------- path : str Absolute path to file. Returns ------- events : list List of historic events. """ # initialise output list events = [] # import through...
1c4362263d177bf2d2a5561d3ed2048ff23faeb2
12,901
def reduce_dataset(d: pd.DataFrame, reduction_pars: dict): """ Reduces the data contained in a pandas DataFrame :param d: pandas DataFrame. Each column contains lists of numbers :param reduction_pars: dict containing 'type' and 'values'. 'type' describes the type of reduction performed on the lists ...
080bb5486787fab25bbc9347e83ed79d4525abe8
12,902
def update_office(office_id): """Given that i am an admin i should be able to edit a specific political office When i visit to .../api/v2/offices endpoint using PATCH method""" if is_admin() is not True: return is_admin() if not request.get_json(): return make_response(jsonify({'statu...
897ee73b508caf1e3d463f68d55c030259efb6e5
12,903
import os import zipfile import json def load_project_resource(file_path: str): """ Tries to load a resource: 1. directly 2. from the egg zip file 3. from the egg directory This is necessary, because the files are bundled with the project. :return: the file as json """ ...
b9d46e1363fc1ca8b397b1512642b7795a8ea9c9
12,904
def phraser_on_header(row, phraser): """Applies phraser on cleaned header. To be used with methods such as: `apply(func, axis=1)` or `apply_by_multiprocessing(func, axis=1, **kwargs)`. Parameters ---------- row : row of pd.Dataframe phraser : Phraser instance, Returns ------- ...
30b9f11607ce1769b15a1c4fda4a4bc3b0aea94b
12,905
from os.path import exists, isfile, join def check_c_includes(filename, includes): """ Check whether file exist in include dirs """ for directory in includes: path = join(directory, filename) if exists(path) and isfile(path): return path
041feddad25bd41cc0bdd0c4cf05c63996ba73f4
12,906
def hard_nms(box_scores, iou_threshold, top_k=-1, candidate_size=200): """ Args: box_scores (N, 5): boxes in corner-form and probabilities. iou_threshold: intersection over union threshold. top_k: keep top_k results. If k <= 0, keep all the results. candidate_size: only consider...
44a6dbcd0db425196bd91f22907be395d270b3d8
12,907
def sma(data, span=100): """Computes and returns the simple moving average. Note: the moving average is computed on all columns. :Input: :data: pandas.DataFrame with stock prices in columns :span: int (defaul: 100), number of days/values over which the average is computed :Output: ...
8f8abf7f851424c20f6cee2ad4a01b934b7b0182
12,908
def parse_csd(dependencies): """Parse C-State Dependency""" return _CSD_factory(len(csd_data))(csd_data)
54ab24def420fd8350e1130b98be6b4651464fb8
12,909
def field_path_get_type(root: HdlType, field_path: TypePath): """ Get a data type of element using field path """ t = root for p in field_path: if isinstance(p, int): t = t.element_t else: assert isinstance(p, str), p t = t.field_by_name[p].dtype ...
d6c5f0c750149505e6da78f7b3e3ed602b8f30b0
12,910
def reverse(rule): """ Given a rule X, generate its black/white reversal. """ # # https://www.conwaylife.com/wiki/Black/white_reversal # # "The black/white reversal of a pattern is the result of # toggling the state of each cell in the universe: bringing # dead cells to life, and killing live cells....
0451b2a49257540b8a069f4cdb96d6bff4337cb7
12,911
import torch def hsic(k_x: torch.Tensor, k_y: torch.Tensor, centered: bool = False, unbiased: bool = True) -> torch.Tensor: """Compute Hilbert-Schmidt Independence Criteron (HSIC) :param k_x: n by n values of kernel applied to all pairs of x data :param k_y: n by n values of kernel on y data :param c...
7c91aa5991b90f396abbf835111a456208cbc50a
12,912
def task_group_task_ui_to_app(ui_dict): """Converts TaskGroupTask ui dict to App entity.""" return workflow_entity_factory.TaskGroupTaskFactory().create_empty( obj_id=ui_dict.get("obj_id"), title=ui_dict["title"], assignees=emails_to_app_people(ui_dict.get("assignees")), start_date=str_to_da...
64ad5bc96b56c2feb41417890c6f04c0f17e4691
12,913
def int_converter(value): """check for *int* value.""" int(value) return str(value)
ba1b780c7886fccf1203225de249ef129561fd36
12,914
def wraps(fun, namestr="{fun}", docstr="{doc}", **kwargs): """Decorator for a function wrapping another. Used when wrapping a function to ensure its name and docstring get copied over. Args: fun: function to be wrapped namestr: Name string to use for wrapped function. docstr: Docstri...
af05b43ee3ac2cc8595d35148b0156cd441dce3a
12,915
from re import L def test_plot_distributed_loads_fixed_left(): """Test the plotting function for distributed loads and fixed support on the left. Additionally, test plotting of continuity points. """ a = beam(L) a.add_support(0, "fixed") a.add_distributed_load(0, L / 2, "-q * x") a.add_dis...
2c7c2b37e19e69a66a751bf59c3150f0b7aa3d3f
12,916
import requests import json def post_report(coverage): """Post coverage report to coveralls.io.""" response = requests.post(URL, files={'json_file': json.dumps(coverage)}) try: result = response.json() except ValueError: result = {'error': 'Failure to submit data. ' '...
a33affb2791d3dbb7528ce9d4aae6a89f46d03f2
12,917
import tokenize def parse_dialogs_per_response(lines,candid_dic,profile_size=None): """Parse dialogs provided in the personalized dialog tasks format. For each dialog, every line is parsed, and the data for the dialog is made by appending profile, user and bot responses so far, user utterance, bot answer ...
b919a9d970e93da9de6221f29573261f83158e49
12,918
import time def get_dist(): """ Measures the distance of the obstacle from the rover. Uses a time.sleep call to try to prevent issues with pin writing and reading. (See official gopigo library) Returns error strings in the cases of measurements of -1 and 0, as -1 indicates and error, and 0 s...
a615d9938b117821d39b9acdce507f0171583c03
12,919
from typing import Callable def map_filter(filter_function: Callable) -> Callable: """ returns a version of a function that automatically maps itself across all elements of a collection """ def mapped_filter(arrays, *args, **kwargs): return [filter_function(array, *args, **kwargs) for arr...
a5f9f97d1a0d4acdaa39b9fb72a73b95a81553bb
12,920
from typing import Literal def compare_models( champion_model: lightgbm.Booster, challenger_model: lightgbm.Booster, valid_df: pd.DataFrame, comparison_metric: Literal["any", "all", "f1_score", "auc"] = "any" ) -> bool: """ A function to compare the performance of the Champion ...
8f5f522375a4c274c3c80fcbfddad2e8cf450328
12,921
def check_additional_args(parsedArgs, op, continueWithWarning=False): """ Parse additional arguments (rotation, etc.) and validate :param additionalArgs: user input list of additional parameters e.g. [rotation, 60...] :param op: operation object (use software_loader.getOperation('operationname') :re...
ab289271fe4a61ec77ed2b522687dd4df7cbd35c
12,922
import re def clean_text(text, language): """ text: a string returns: modified initial string (deletes/modifies punctuation and symbols.) """ replace_by_blank_symbols = re.compile('\#|\u00bb|\u00a0|\u00d7|\u00a3|\u00eb|\u00fb|\u00fb|\u00f4|\u00c7|\u00ab|\u00a0\ude4c|\udf99|\udfc1|...
eaf22844fcd3528c20b34f16c276042810a672f5
12,923
def parameters(): """ Dictionary of parameters defining geophysical acquisition systems """ return { "AeroTEM (2007)": { "type": "time", "flag": "Zoff", "channel_start_index": 1, "channels": { "[1]": 58.1e-6, "[2]": ...
5ae2626c2c8a5445457169f3f2866bf8233ee7f3
12,924
import binascii def generate_ngrams_and_hashit(tokens, n=3): """The function generates and hashes ngrams which gets from the tokens sequence. @param tokens - list of tokens @param n - count of elements in sequences """ return [binascii.crc32(bytearray(tokens[i:i + n])) for i in r...
eb627add56f51a533c773e0dfea029bfcdb808ee
12,925
from typing import List def generate_fingerprints(args: Namespace, logger: Logger = None) -> List[List[float]]: """ Generate the fingerprints. :param logger: :param args: Arguments. :return: A list of lists of target fingerprints. """ # import pdb; pdb.set_trace() checkpoint_path = ar...
aac2b9f342306be7dc79a029c8433dd5f2147d0e
12,926
def transform_xlogx(mat): """ Args: mat(np.array): A two-dimensional array Returns: np.array: Let UsV^† be the SVD of mat. Returns Uf(s)V^†, where f(x) = -2xlogx """ U, s, Vd = np.linalg.svd(mat, full_matrices=False) return (U * (-2.0*s * np.log(s))) @ Vd
f4cf18a8ae9f7a298ffd6b6400a33a9cad5fabbd
12,927
import SimpleITK as sitk import os from collections import ( OrderedDict, ) # Need OrderedDict internally to ensure consistent ordering def get_label_volumes(labelVolume, RefVolume, labelDictionary): """ Get label volumes using 1. reference volume and 2. labeldictionary :param labelV...
b79c5755804192ef9507be98dde06bf8e2750220
12,928
from datetime import datetime def get_clip_name_from_unix_time(source_guid, current_clip_start_time): """ """ # convert unix time to readable_datetime = datetime.fromtimestamp(int(current_clip_start_time)).strftime('%Y_%m_%d_%H_%M_%S') clipname = source_guid + "_" + readable_datetime return...
0a212a76a69507ae3020c1e05ec354a927ad3dae
12,929
def extract_pc_in_box3d(pc, box3d): """Extract point cloud in box3d. Args: pc (np.ndarray): [N, 3] Point cloud. box3d (np.ndarray): [8,3] 3d box. Returns: np.ndarray: Selected point cloud. np.ndarray: Indices of selected point cloud. """ box3d_roi_inds = in_hull(pc[...
2d9cb9089631e357ed8ec5ee454203d5eaec1c1d
12,930
import typing def get_list_as_str(list_to_convert: typing.List[str]) -> str: """Convert list into comma separated string, with each element enclosed in single quotes""" return ", ".join(["'{}'".format(list_item) for list_item in list_to_convert])
6b565c3d63d9887f05d5369511b8453c406f7b72
12,931
def normalize_sides(sides): """ Description: Squares the sides of the rectangles and averages the points so that they fit together Input: - sides - Six vertex sets representing the sides of a drawing Returns: - norm_sides - Squared and fit sides list """ sides_list = [] # Average side vertices and make...
855fcc45d14db2eede9fd7ec2fa6bf2f6854950d
12,932
def GetFieldInfo(column: Schema.Column, force_nested_types: bool = False, nested_prefix: str = 'Nested_') -> FieldInfo: """Returns the corresponding information for provided column. Args: column: the column for which to generate the dataclass FieldInfo. force_n...
e788ef090bb8fd8150f2effe42d2db4e8c3fdde6
12,933
def get_session(): """ Get the current session. :return: the session :raises OutsideUnitOfWorkError: if this method is called from outside a UOW """ global Session if Session is None or not Session.registry.has(): raise OutsideUnitOfWorkError return Session()
8a1bfb7afff2cc1a843eaa01e59eabea5e083339
12,934
import functools import torch def create_sgd_optimizers_fn(datasets, model, learning_rate, momentum=0.9, weight_decay=0, nesterov=False, scheduler_fn=None, per_step_scheduler_fn=None): """ Create a Stochastic gradient descent optimizer for each of the dataset with optional scheduler Args: ...
6d76d5dfc0f633a324d7ee9fe347f1bc68bf0492
12,935
def equalize(img): """ Equalize the histogram of input PIL image. Args: img (PIL image): Image to be equalized Returns: img (PIL image), Equalized image. """ if not is_pil(img): raise TypeError('img should be PIL image. Got {}'.format(type(img))) return ImageOps....
d31d3590ba7927518475053911bdb4251381815d
12,936
import contextlib import os import subprocess def routemaster_serve_subprocess(unused_tcp_port): """ Fixture to spawn a routemaster server as a subprocess. Yields the process reference, and the port that it can be accessed on. """ @contextlib.contextmanager def _inner(*, wait_for_output=None...
4b0d4020a83acc78342d35e7a2e5657b41b12b88
12,937
def ratingRange(app): """ Get the rating range of an app. """ rating = 'Unknown' r = app['rating'] if r >= 0 and r <= 1: rating = '0-1' elif r > 1 and r <= 2: rating = '1-2' elif r > 2 and r <= 3: rating = '2-3' elif r > 3 and r <= 4: rating = '3-4' elif r > 4 and r <= 5: rating = '4-5' return rating
69056c367a87e331cd3b606423540250b20f6485
12,938
def immediate_sister(graph, node1, node2): """ is node2 an immediate sister of node1? """ return (node2 in sister_nodes(graph, node1) and is_following(graph, node1, node2))
cb1cdc13e8aceb88e72781a547c9ef1eb2079cb0
12,939
def get_topic_link(text: str) -> str: """ Generate a topic link. A markdown link, text split with dash. Args: text {str} The text value to parse Returns: {str} The parsed text """ return f"{text.lower().replace(' ', '-')}"
445afc9358f98323934e0e2788ed52658c7040cb
12,940
def load_data(datapath): """Loads data from CSV data file. Args: datapath: Location of the training file Returns: summary dataframe containing RFM data for btyd models actuals_df containing additional data columns for calculating error """ # Does not used the summary_data_from_transaction_data fr...
d7efe25303fa7839a9842d7b04bcdb1f749a4830
12,941
def rms(a, axis=None): """ Calculates the RMS of an array. Args: a (ndarray). A sequence of numbers to apply the RMS to. axis (int). The axis along which to compute. If not given or None, the RMS for the whole array is computed. Returns: ndarray: The RMS of the arra...
1b4a2989f8dd06956ae87a2991ef75ca0c6037fc
12,942
import sys def alpha_114(code, end_date=None, fq="pre"): """ 公式: ((RANK(DELAY(((HIGH - LOW) / (SUM(CLOSE, 5) / 5)), 2)) * RANK(RANK(VOLUME))) / (((HIGH - LOW) / (SUM(CLOSE, 5) / 5)) / (VWAP - CLOSE))) Inputs: code: 股票池 end_date: 查询日期 Outputs: 因子的值 """ end_date = ...
abe8f19581458feef8373e243b6bcc7bf6d3001d
12,943
def event_message(iden, event): """Return an event message.""" return { 'id': iden, 'type': TYPE_EVENT, 'event': event.as_dict(), }
3b30f3f697d0615a55b3b494f73d01c8df5dcb0e
12,944
def logout(): """Logout.""" logout_user() flash(lazy_gettext("You are logged out."), "info") return redirect(url_for("public.home"))
2e65faed65671e881594a9a3c990bc6151417575
12,945
import json def predicate_to_str(predicate: dict) -> str: """ 谓词转文本 :param predicate: 谓词数据 :return: 文本 """ result = "" if "block" in predicate: result += "检查方块\n\n" block = predicate["block"] if "nbt" in block: result += f"检查nbt:\n``` json\n{try_pretty_j...
799f3fe66fe5ca78635c9d9b3f3a33a11ee63912
12,946
import os import importlib import sys def module_str_to_class(module_str): """Parse module class string to a class Args: module_str(str) Dictionary from parsed configuration file Returns: type: class """ if not validate_module_str(module_str): raise ValueError("Module...
94794c2b19a2db0079adae5ec83598c945cffe01
12,947
from typing import Optional async def get_postcode(postcode_like: PostCodeLike) -> Optional[Postcode]: """ Gets the postcode object for a given postcode string. Acts as a middleware between us and the API, caching results. :param postcode_like: The either a string postcode or PostCode object. :ret...
c0123b52dca8892c2f399892bee8f6ee2d5ada60
12,948
def oauth2callback(): """ The 'flow' has this one place to call back to. We'll enter here more than once as steps in the flow are completed, and need to keep track of how far we've gotten. The first time we'll do the first step, the second time we'll skip the first step and do the second, and so on. """ ...
6479dfeb27d99f82555eb01abd453d5a96590ba6
12,949
def get_ebv(path, specs=range(10)): """Lookup the EBV value for all targets from the CFRAME fibermap. Return the median of all non-zero values. """ ebvs = [] for (CFRAME,), camera, spec in iterspecs(path, 'cframe', specs=specs, cameras='b'): ebvs.append(CFRAME['FIBERMAP'].read(columns=['EBV'...
f27fc781109eed9e4e8102c88396f33a735742e9
12,950
from typing import List import os def get_results_df( job_list: List[str], output_dir: str, input_dir: str = None, ) -> pd.DataFrame: """Get raw results in DataFrame.""" if input_dir is None: input_dir = os.path.join(SLURM_DIR, 'inputs') input_files = [ os.path.join(input_dir...
38722fd255eee1a484242a00f66d49a7da8e8e30
12,951
def create_pipeline(pipeline_name: Text, pipeline_root: Text, data_root: Text, beam_pipeline_args: Text) -> pipeline.Pipeline: """Custom component demo pipeline.""" examples = external_input(data_root) # Brings data into the pipeline or otherwise joins/converts training data. example_gen =...
7804df79d4e1ac969df5ef5a2399d841b52d4683
12,952
def toggleAction(*args, **kwargs): """A decorator which identifies a class method as a toggle action. """ return ActionFactory(ToggleAction, *args, **kwargs)
c9bc47a1f62ccac95ace344a4def7bd81064793e
12,953
def getHistograph(dataset = {}, variable = ""): """ Calculates a histogram-like summary on a variable in a dataset and returns a dictionary. The keys in the dictionary are unique items for the selected variable. The values of each dictionary key, is the number of times the unique item occured i...
e07c0d1b3e9ba8507402189057b186ee0f8dee3c
12,954
def _get_client_by_settings( client_cls, # type: Type[BaseClient] bk_app_code=None, # type: Optional[str] bk_app_secret=None, # type: Optional[str] accept_language=None, # type: Optional[str] **kwargs ): """Returns a client according to the django settings""" client = client_cls(**kwargs...
efbb42d7795f7e0939d33f2427470e202d6580c9
12,955
from controllers import sites import jinja2 def create_and_configure_jinja_environment( dirs, autoescape=True, handler=None, default_locale='en_US'): """Sets up an environment and gets jinja template.""" # Defer to avoid circular import. locale = None app_context = sites.get_course_for_current_r...
88d285cd436b5af0848c2ca1e45caa3e28a8e074
12,956
import numpy def bootstrap_cost(target_values, class_probability_matrix, cost_function, num_replicates): """Bootstraps cost for one set of examples. E = number of examples K = number of classes B = number of bootstrap replicates :param target_values: length-E numpy array of ta...
ba76e9b9614407a4c0d49c16e3b9ab9f0974a820
12,957
def jdeblend_bob(src_fm, bobbed): """ Stronger version of jdeblend() that uses a bobbed clip to deblend. Parameters: clip src_fm: Source after field matching, must have field=3 and low cthresh. clip src: Bobbed source. Example: src = from havsfunc impo...
d5e79710d7346a2376656ccfaf9c43a70fa8bc36
12,958
import optparse def ParseArgs(): """Parse the command line options, returning an options object.""" usage = 'Usage: %prog [options] LIST|GET|LATEST' option_parser = optparse.OptionParser(usage) AddCommandLineOptions(option_parser) log_helper.AddCommandLineOptions(option_parser) options, args = option_pars...
cfef602975011d4b04e7797a9e1426293f0d0b7b
12,959
import io def generate_table_definition(schema_and_table, column_info, primary_key=None, foreign_keys=None, diststyle=None, distkey=None, sortkey=None): """Return a CREATE TABLE statement as a string.""" if not column_info: raise Exception('N...
383cdc8ed13fbaa45adadec26f31ad0f5ac52fbc
12,960
def gradient_descent_update(x, gradx, learning_rate): """ Performs a gradient descent update. """ # Return the new value for x return x - learning_rate * gradx
db5ec512883352f473990eca124c8ad302ec3564
12,961
def nth_permutation(n, size=0): """nth permutation of 0..size-1 where n is from 0 to size! - 1 """ lehmer = int_to_lehmer(n, size) return lehmer_to_permutation(lehmer)
b79bb639cbf23296879562fa718218beee86f378
12,962
def signin(request): """ Method for log in of the user """ if request.user.is_authenticated: return_var = render(request, '/') if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=us...
aadab619cca9d71e3f255f910af7b8d1dd59b8f4
12,963
def compare_features(f1, f2): """Comparison method for feature sorting.""" def get_prefix(feature): if feature.startswith('e1-'): return 'e1' if feature.startswith('e2-'): return 'e2' if feature.startswith('e-'): return 'e' if feature.startswith('t-'): return 't' return '...
2b93e2c6b6a9993d13964d726efe855d57f72448
12,964
def localized_index(lang): """ Example view demonstrating rendering a simple HTML page. """ context = make_context() context['lang'] = lang context['content'] = context['COPY']['content-%s' % lang] context['form'] = context['COPY']['form-%s' % lang] context['share'] = context['COPY']['sh...
7d6878f30270c735a2d97353b813cdf632043b92
12,965
def build_output_unit_vqa(q_encoding, m_last, num_choices, apply_dropout, scope='output_unit', reuse=None): """ Apply a 2-layer fully-connected network to predict answers. Apply dropout if specified. Input: q_encoding: [N, d], tf.float32 m_last: [N, d], tf.floa...
2fc8d0c9246cbb3350af9d20a85964c9f3967618
12,966
def coding_problem_16(length): """ You run a sneaker website and want to record the last N order ids in a log. Implement a data structure to accomplish this, with the following API: record(order_id): adds the order_id to the log get_last(i): gets the ith last element from the log. i is guar...
5c1b3e6be920ce826f7c8e8b0fc8fd27cd398079
12,967
def _check_dimensions(n_grobs, nrow = None, ncol = None): """ Internal function to provide non-Null nrow and ncol numbers given a n_number of images and potentially some information about the desired nrow/ncols. Arguments: ---------- n_grobs: int, number of images to be organized nrow: ...
20531024ecabc4b4b7b5ce1d8a20774cf2b568ac
12,968
import re def year_parse(s: str) -> int: """Parses a year from a string.""" regex = r"((?:19|20)\d{2})(?:$|[-/]\d{2}[-/]\d{2})" try: year = int(re.findall(regex, str(s))[0]) except IndexError: year = None return year
f52449aefcba52106fe8c7c03355c237a94775e1
12,969
import random def sampleDistribution(d): """ Expects d to be a list of tuples The first element should be the probability If the tuples are of length 2 then it returns the second element Otherwise it returns the suffix tuple """ # {{{ z = float(sum(t[0] for t in d)) if z == 0.0: ...
4e47b3dead1e9cc42bf152e6854cbd7cdb255438
12,970
def logout(): """ `/register` endpoint Logs out a user and redirects to the index page. """ logout_user() flash("You are logged out.", "info") return redirect(url_for("main.index"))
7054a11253b02522178c528197071c1ae9c3ae81
12,971
import requests def players_season_totals(season_end_year, playoffs=False, skip_totals=False, output_type=None, output_file_path=None, output_write_option=None, json_options=None): """ scrape the "Totals" stats of all players from a single year Args: season_end_year (int): year in which the...
ea0fa62e9b7ec644404d7968f2b11b14781b4c37
12,972
import random def array_shuffle(x,axis = 0, random_state = 2020): """ 对多维度数组,在任意轴打乱顺序 :param x: ndarray :param axis: 打乱的轴 :return:打乱后的数组 """ new_index = list(range(x.shape[axis])) random.seed(random_state) random.shuffle(new_index) x_new = np.transpose(x, ([axis]+[i for i in li...
df6ff3e9fd1d94ff6a6e633451a88815b16f1e83
12,973
import tempfile import os import subprocess def cat(out_media_fp, l_in_media_fp): """ Args: out_media_fp(str): Output Media File Path l_in_media_fp(list): List of Media File Path Returns: return_code(int): """ ref_vcodec = get_video_codec(l_in_media_fp[0]) ref_acodec = ...
e6fec61dd205ec3fdb2340aac543051ebf97e12e
12,974
import time def get_recent_activity_rows(chase_driver): """Return the 25 most recent CC transactions, plus any pending transactions. Returns: A list of lists containing the columns of the Chase transaction list. """ _goto_link(chase_driver, "See activity") time.sleep(10) rows = c...
2ac3d6de1cac0e28d2dd9a9d170cef7f1facf007
12,975
def loglikelihood(x, mean, var, pi): """ 式(9.28) """ lkh = [] for mean_k, var_k, pi_k in zip(mean, var, pi): lkh.append(pi_k * gaussian_pdf(x, mean_k, var_k)) return np.sum(np.log(np.sum(lkh, 0)))
d2355334b305f1bf2084efea3baee78daf06cc35
12,976
def calc_E_ST_GJ(E_star_ST): """基準一次エネルギー消費量(GJ/年)の計算 (2) Args: E_star_ST(float): 基準一次エネルギー消費量(J/年) Returns: float: 基準一次エネルギー消費量(GJ/年) """ # 小数点以下一位未満の端数があるときはこれを切り上げる return ceil(E_star_ST / 100) / 10
06d7ade15d91c205bd9662dd41d218d8b7867a2f
12,977
def next_line(grd_file): """ next_line Function returns the next line in the file that is not a blank line, unless the line is '', which is a typical EOF marker. """ done = False while not done: line = grd_file.readline() if line == '': return line, False elif line.strip(): return line, True
337f188930a03142bae59cdb378b09f1ac5e2ecb
12,978
def look_for(room, position, main, sub=None): """ :type room: rooms.room_mind.RoomMind """ if not room.look_at: raise ValueError("Invalid room argument") if position.pos: position = position.pos if sub: return _.find(room.look_at(LOOK_FLAGS, position), ...
23f521874b7dfbbc2dd00c105ed495a1f9049e00
12,979
def get_proto(proto): """ Returns a protocol number (in the /etc/protocols sense, e.g. 6 for TCP) for the given input value. For the protocols that have PROTO_xxx constants defined, this can be provided textually and case-insensitively, otherwise the provided value gets converted to an integer a...
a3632e0731e4227020eb75d5ea27d211e27e188a
12,980
def f5_update_policy_cookie_command(client: Client, policy_md5: str, cookie_id: str, cookie_name: str, perform_staging: bool, parameter_type: str, enforcement_type: str, attack...
633015c3dc3c478e17975ea540a6e6ab46b710e1
12,981
def ping(): """ Determine if the container is working and healthy. In this sample container, we declare it healthy if we can load the model successfully. :return: """ health = False try: health = model is not None # You can insert a health check here except: pass ...
96cc202cf4cf25dd6fb91ae29cac66667ed13d27
12,982
from .coo import COO def random( shape, density=0.01, random_state=None, data_rvs=None, format='coo' ): """ Generate a random sparse multidimensional array Parameters ---------- shape: Tuple[int] Shape of the array density: float, optional D...
f62ba3afc168bf39734897291d094d43bd1ee7f1
12,983
from pathlib import Path import hashlib def file_md5_is_valid(fasta_file: Path, checksum: str) -> bool: """ Checks if the FASTA file matches the MD5 checksum argument. Returns True if it matches and False otherwise. :param fasta_file: Path object for the FASTA file. :param checksum: MD5 checksum...
ec400afbe29d940d0638a581da7f2ee001b9e985
12,984
def combine_to_int(values): """Combine several byte values to an integer""" multibyte_value = 0 for byte_id, byte in enumerate(values): multibyte_value += 2**(4 * byte_id) * byte return multibyte_value
58ff7cbee356cdcbe5b26e973de16c5b1cc40afc
12,985
import torch def loss_fn(x, results, is_valtest=False, **kwargs): """ Loss weight (MCAE): - sni: snippet reconstruction loss - seg: segment reconstruction loss - cont: smooth regularization - reg: sparsity regularization - con: constrastive loss - cls: auxilliary classification loss <n...
ef5953c3350952a1083aabaa8f656834a32ae17c
12,986
def _as_uint32(x: int) -> QVariant: """Convert the given int to an uint32 for DBus.""" variant = QVariant(x) successful = variant.convert(QVariant.UInt) assert successful return variant
08de1fccf4625485fab82c2569932ffd3e006541
12,987
def svcs_tang_u(Xcp,Ycp,Zcp,gamma_t,R,m,Xcyl,Ycyl,Zcyl,ntheta=180, Ground=False): """ Computes the velocity field for nCyl*nr cylinders, extending along z: nCyl: number of main cylinders nr : number of concentric cylinders within a main cylinder INPUTS: Xcp,Ycp,Zcp: cartesian coo...
f5ee6309a01c493f930086a92db44c93cb33cbba
12,988
def np_to_o3d_images(images): """Convert numpy image list to open3d image list Parameters ---------- images : list[numpy.ndarray] Returns o3d_images : list[open3d.open3d.geometry.Image] ------- """ o3d_images = [] for image in images: image = np_to_o3d_image(image) ...
419f59c47cba9c22595c8d16ca0d35f105ec4882
12,989
def compute_mse(y_true, y_pred): """ignore zero terms prior to comparing the mse""" mask = np.nonzero(y_true) mse = mean_squared_error(y_true[mask], y_pred[mask]) return mse
3c594c4105f99d8088665b4c0a7345807a667e55
12,990
def image2d(math_engine, batch_len, batch_width, height, width, channels, dtype="float32"): """Creates a blob with two-dimensional multi-channel images. :param neoml.MathEngine.MathEngine math_engine: the math engine that works with this blob. :param batch_len: the **BatchLength** dimension of the new blo...
d816388f619ac1e09e2bfc705ddab75a490ec023
12,991
def error_response(error, message): """ returns error response """ data = { "status": "error", "error": error, "message": message } return data
f3e52ea42cb48378f08ecb65f58d2291960e6488
12,992
import tqdm def graph_to_text( graph: MultiDiGraph, quoting: bool = True, verbose: bool = True ) -> str: """Turns a graph into its text representation. Parameters ---------- graph : MultiDiGraph Graph to text. quoting : bool If true, quotes will be added. verbose : b...
a3ccf008f1ebcc62cfe1c8e6620923c665de8768
12,993
def test_has_valid_dir_structure(): """Check if the specified dir structure is valid""" def recurse_contents(contents): if contents is None: return None else: for key, value in contents.items(): assert(isinstance(key, str)) if value is None: return None ...
f2dc8dcb38dc5873dea8500391a1733f9f8a18d1
12,994
def getFBA(fba): """AC factory. reads a fileobject and creates a dictionary for easy insertation into a postgresdatabase. Uses Ohlbergs routines to read the files (ACfile) """ word = fba.getSpectrumHead() while word is not None: stw = fba.stw mech = fba.Type(word) datadic...
e5c5f52fe831938400eec5ae15c043ecbf8cf7d1
12,995
def logtimestamp(): """ returns a formatted datetime object with the curren year, DOY, and UT """ return DT.datetime.utcnow().strftime("%Y-%j-%H:%M:%S")
71b204c473d8e6a4868d966877dd61909252e891
12,996
def get_most_common_non_ascii_char(file_path: str) -> str: """Return first most common non ascii char""" with open(file_path, encoding="raw_unicode_escape") as f: non_ascii = {} for line in f: for char in line: if not char.isascii(): if char in non...
5280b637206964d6b386478ddbaeb6ad69f92c8c
12,997
def compute_noise_from_target_epsilon( target_epsilon, target_delta, epochs, batch_size, dataset_size, alphas=None, approx_ratio=0.01, ): """ Takes a target epsilon (eps) and some hyperparameters. Returns a noise scale that gives an epsilon in [0.99 eps, eps]. The approximati...
60bddeaca8e772fa15582fe87516f4e5c5284b75
12,998
def cart2pol(x, y): """ author : Dr. Schaeffer """ rho = np.sqrt(x**2 + y**2) phi = np.arctan2(y, x) return(rho, phi)
490e839b9a7c7e369643c27df3bbf4a6cd6779ba
12,999