content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import OrderedDict def read_populations(flname): """ Read populations from a file. We assume that the file has one population per line. The population name comes first and is followed by a comma. The name of each sample follows, also separated by comma. For example: pop1,s...
9467bf2e882a2de0ebfb1ecfb566baeab16a1500
69,200
import inspect def is_instance_of_django_model(reference): """ Tests if a given reference is a reference to a class that extends django.db.models.Model :param reference: A given Anonymous reference. :rtype: boolean :returns: A boolean value that is true only if the given reference is ...
b54536bded37e4a078c266bdc9b3553cbf48e0f3
69,201
import os import csv def reader(filename, subset=[], skip='#', **kwargs): """Reads in an MAF-like file as a dataframe. Determines the correct handler for reading in a given MAF file. Supports reading in TSV files (.tsv, .txt, .text, .vcf, or .maf), CSV files (.csv), and excel files (.xls, .xlsx, .xlsm, .xlsb, ....
e24c51923211151c5000b8d3b1d4a6901d1faaba
69,202
def extract_peers(units, boxes): """ **Function Provided by UDACITY** Initialize a mapping from box names to a list of peer boxes (i.e., a flat list of boxes that are in a unit together with the key box) Parameters ---------- units(dict) a dictionary with a key for each box (string) who...
7a40e913d4b0c0b059b535d7a2b77481127ebf0b
69,203
async def unset_user(session: CommandSession): """注销绑定""" bot = nonebot.get_bot() message_type = session.ctx['message_type'] # 消息类型 user_id = session.ctx['user_id'] # qq群的qq成员id号 # 判断消息是否为群消息 if message_type == "group": message = session.ctx['message'] message = str(message)[1:...
6422156f25b636324d813f4f5930165f71a28c3e
69,204
def edit(request, carrera_jurisdiccional_id): """ Edición de los datos de un título jurisdiccional. """ carrera_jurisdiccional = CarreraJurisdiccional.objects.get(pk=carrera_jurisdiccional_id) titulo_anterior_id = int(carrera_jurisdiccional.carrera_id) if request.method == 'POST': form = CarreraJurisdiccionalD...
2d156a8315f12ec9af746cf10550af457e186be5
69,205
def parse_expression(expression, doc_dict): """Parse an expression.""" return Parser(doc_dict).parse(expression)
5c01121e102cea1114f34ccf7d2a0f201c47520d
69,206
from datetime import datetime def get_unix(str_ts, date_format): """Get unix timestamp from a string timestamp in date_format. Args: str_ts: string timestamp in `date_format` date_format: datetime time stamp format Returns: int: unix timestamp """ return datetime.strptim...
6d0c591734fa78defed11cd5ed8c66da63ad3b5b
69,207
import io import json def load_json(buffer): """ Returns a structure if file was json :param buffer: :return: JSON created object or None """ fp = io.BytesIO(buffer) try: data = json.load(fp) return data except json.decoder.JSONDecodeError: return None
6893a22009ca0093298060913d27d30e2645a92e
69,208
def compute_raw_transect_depths(shore_point, \ direction_vector, bathymetry, bathymetry_uri, landmass, landmass_uri, \ bathymetry_resolution, max_land_profile_len, max_land_profile_height, \ max_sea_profile_len): """ compute the transect endpoints that will be used to cut transects""" # Maximum tran...
71b8e7e48ecd28e4431a5be40c4e4dd52bb81c20
69,209
import torch def convert_raw_locations_batched_top_down(raw_locations, stacking_program, primitives): """ Args raw_locations (tensor [*shape, num_blocks]) stacking_program (tensor [*shape, num_blocks]) primitives (list [num_primitives]) Returns [*shape, num_blocks, 2] """ ...
cee051c4e3450910328bb1fa377a0f4cd02499e8
69,210
import tokenize def MakeGrammar(f, tok_def=None): """Construct a Grammar object from a file.""" lexer = tokenize.generate_tokens(f.readline) p = ParserGenerator(lexer) dfas, startsymbol = p.parse() first = {} # map from symbol name to set of tokens for name in sorted(dfas): if name not in first: ...
718e67314fac64f9bc0506831ffd1bb9af25a450
69,211
def _preprocess_cameras(example, indices, dataset_info): """Instantiates the ops used to preprocess the cameras data.""" raw_pose_params = example['cameras'] raw_pose_params = tf.reshape( raw_pose_params, [-1, dataset_info.sequence_size, _NUM_RAW_CAMERA_PARAMS]) raw_pose_params = tf.gath...
fc43470ac26d793539f305a9a44117c15861d440
69,212
def lad_msoa_mapping(): """Map between lad and msoa {LAD: [MOAS]} """ msoa_lad_map = { 'E06000047': ['E02004297', 'E02004290', 'E02004298', 'E02004299', 'E02004291', 'E02004300', 'E02004292', 'E02004301', 'E02004302', 'E02004303', 'E02004293', 'E02004304', 'E02004294', 'E02004305', 'E02004295',...
55f97fecca6e11df2141991de9bdb4295ca5e4af
69,213
import random import logging def build_encapsulated_ip_packet( rand_selected_interface, ptfadapter, rand_selected_dut, tunnel_traffic_monitor ): """ Build the encapsulated packet to be sent from T1 to ToR. """ tor = rand_selected_dut _, server_ips = rand_selected_interface s...
f2ac6dd830eeadb60404135206b657b1689a03c2
69,214
from typing import List import argparse def parse_arguments(argv: List[str]) -> argparse.Namespace: """parse command line arguments and return argument object""" parser = argparse.ArgumentParser(description=__doc__) common.setup_argument_parser(parser) subparsers = parser.add_subparsers(help='availab...
27f0075ba70396ce867c4d303c132a5b1c75993e
69,215
def test_rows_filled(): """ cycles through all rows in placement_map and returns a list of all row indecies that are filled """ rows_filled = [] for i in range(len(placement_map)): if 0 not in placement_map[i]: rows_filled.append(i) return rows_filled
8a6d937c089a806992690a96d4bd3cedc684d3fa
69,216
def load_img_info(files): """Load the information of one image. Args: files (tuple): The tuple of (img_file, groundtruth_file) Returns: img_info (dict): The dict of the img and annotation information """ assert isinstance(files, tuple) img_file, gt_file = files assert osp.b...
5f1e3ce6dc410985e082fc7b66315e7d80167aed
69,217
def run_transport(definition, transport) -> bool: """ Runs schedule & watch for a transport :param definition: :param transport: :return: """ with definition.transport(binaries=[]): transport.schedule( command="--mocked--", definition=definition, is_backup=T...
e8a3442f670351ed7642abe4b4a837fd84d36f55
69,218
import os def encode_to_tfrecord(data, output_dir): """Encodes a data item to TFRecord format. Args: data: A dictionary maps to the FFCC data bundle. output_dir: The output folder. The record will be saved as <name>.tfrecord. """ def _int64_feature(value): """Converts a list of int64 into TF Fea...
51461992aabbdf302a3b3c6359e0b166095067c9
69,219
def rivers_by_station_number(stations, N): """Passed a list of station objects and a number N, returns the list of N river objects from with the most monitoring stations on it.""" riverstation = stations_by_river(stations) numstations = sorted_by_key([(i, len(riverstation[i])) for i in riverstation], 1, rev...
d2965c4f68bb8519144308f4eff11e3017b1ba28
69,220
def fake_request(): """A faked APIRequest.""" class FakeApiRequest(APIRequest): def send(self, params=None): return self class FakeApiClient(API): def __init__(self): super().__init__("notempty") self.base_url = "" # Overwrite with empty base @property def request_class(self): return FakeApiR...
c6d1639e8f2b43971ffe1176d3511cd665f15dc1
69,221
from typing import Tuple from typing import Optional from typing import Literal import sys def interactive_prompt( keypair_name: str, ) -> Tuple[Optional[Literal["create", "import"]], Optional[str]]: """Interactive prompt.""" if not sys.stdin.isatty(): return None, None try: while Tru...
7e615db744c793e939cf08e0dfd1e580c8b1f040
69,222
def band_dos_atoms_spin_polarized( band_folder, dos_folder, atoms, output='band_dos_atoms_sp.png', scale_factor=5, color_list=None, legend=True, linewidth=0.75, band_color='black', unprojected_band_color='gray', unprojected_linewidth=0.6, figsize=(8, 6), width_ratios=...
83b684619f68f7262ada90f7673bd655f7cde9f6
69,223
from typing import Dict from typing import Any def load_screens() -> Dict[str, Any]: """ Initialize screen components and screens, and store references to them """ for component_name in SCREEN_COMPONENTS: load_kv(component_name) screens = {} for screen_name, screen_cls in SCREENS.items(): ...
3241880c714dc2a709bcbadd1f9f52b30452c2ef
69,224
def play_game(board, original_total_time, time_left, turn_count, move_count_no_change): """ plays the best move using a portion of remaining time input: board (list), time_left (float), turn_count (int) output: result (tuple) -> e.g. ("E", (5, 2), (4, 3)) """ num_pieces_board_in = board.num_pi...
3bab79e00fc1caeb4b3e06c836f67a9e4186b59d
69,225
import sys def continue_or_exit(msg=None): """Prompt user to exit script (default) or continue Args: N/A Kwargs: msg (optional): Message to display to user Returns: None or exits script """ if msg: LOGGER.critical(msg) LOGGER.debug('Prompting user to con...
116de1b410b408ee3f4f86504f35e8f4a317e33d
69,226
def skgrcnn109(num_classes=1000): """ Args: num_classes (uint): number of classes """ model = GRCNN([3, 3, 22, 3], [128, 256, 512, 1024], SKconv=True, expansion=2, num_classes=num_classes) return model
7ee3b244a0689396423e1a6d9753c74a3135e934
69,227
import re def string_to_arrow(datasets_dtype: str) -> pa.DataType: """ string_to_arrow takes a datasets string dtype and converts it to a pyarrow.DataType. In effect, `dt == string_to_arrow(_arrow_to_datasets_dtype(dt))` This is necessary because the datasets.Value() primitive type is constructed usin...
206d66e4c18fc085852667890e7bd4903703299a
69,228
import os def cloc(files): """ cloc returns the counted lines of code by author and file type given a set of files expect the structure to look like this: { git_email: { filetype: loc, ... }, ... } """ m = {} for dirpath, filename in files: filetype = filename.split(".")[-1] ...
b86d190c4214bd7baea0d2acfa69a61081b7dc42
69,229
from typing import Sequence from typing import Dict from typing import Any from typing import List import os def match_with_dataset( config: Config, predictions: Sequence[Prediction], schema_obj: Dict[Any, Any] ) -> List[ExecutionInstructions]: """ Loads an original dataset and matches with a predictions ...
02114a7c9ada357c2a00dd98420406e0e0fc524d
69,230
def document_list_folders(request, destination, location_id): """ Get the folders that are associated with the destination and location id Method ~~~~~~ 1. Get all the document permissions connected to the destination and location 2. Get the folder information from this :param request: ...
c1c4fe9581128a369cc844e1b29ca601e80a3687
69,231
def datacursor(artists=None, axes=None, **kwargs): """ Create an interactive data cursor for the specified artists or specified axes. The data cursor displays information about a selected artist in a "popup" annotation box. If a specific sequence of artists is given, only the specified artists will...
713dcdf67a465afd055f10ad94d0744b776c8522
69,232
def channel_to_module_output(channel): """Returns a (module, output) pair given a CCD channel number.""" if channel < 1 or channel > 88: raise ValueError("Channel number must be in the range 1-88.") lookup = _get_channel_lookup_array() lookup[:,0] = 0 modout = np.where(lookup == channel) ...
dddf0a38bae7f03fb5de8fbbb71e1c932594c58c
69,233
def score_openpose(e, image, w, h): """Score an image using OpenPose model. Args: e: OpenPose model. image: Image in CV2 format. Returns: Nubmer of people in image. """ resize_out_ratio = 4.0 humans = e.inference( image, resize_to_default=(w > 0 and h > ...
d2969d5af4736497d463482c6b0f532b9e9f908c
69,234
def generate_expired_token(create_user): """ generate expired JWT token """ user = create_user user_data = { "email": user.email, "username": user.username } jwt = JWTAuthentication() # encode token encoded_token = jwt.generate_token(user_data) return encoded_toke...
437745a9a7276f448f4dae60e9d405887fb72cb0
69,235
def int_fn_vt(dm_comp, method, timeArr=time_arr, vArr=v_arr, vsun=v_sun, t1=tvernal, from_scratch=False, what_inter='interp2d'): """ Interpolation of a function method for a DM component, coming from a 2D time [days]-velocity [km/s] table, for fixed vsun and t1. The table is either constructed from scratch, or ...
4294f3a7349bffc3552b78612dd17c5677c81547
69,236
def readable_join(xs, conjunction="and", sep=","): """ Accepts a list of strings and separates them with commas as grammatically appropriate with a conjunction before the final entry. Any input strings containing only whitespace will not be included in the result. >>> readable_join(['foo']) 'fo...
d518007954b79ff1cf8120a9bdea010e9594f02b
69,237
def get_fpn_maskrcnn_batch(roidb): """ return a dictionary that contains raw data. """ num_images = len(roidb) imgs, roidb = get_image(roidb, scale=config.TRAIN.SCALE) #TODO #imgs, roidb = get_image(roidb) im_array = tensor_vstack(imgs) assert config.TRAIN.BATCH_ROIS % config.TRAIN.BATC...
4ca47222387b6c8762b43bdc0a4935cb7afdd04d
69,238
def minimize_sat(u, u_min, u_max, desaturation_vector): """ Minimize the saturation of the actuators by adding or substracting a fraction of desaturation_vector. desaturation_vector is the vector that added to the output u, modifies the thrust or angular acceleration on a specific axis. For ...
79e5e898cad83e32c9eb09b084ce3bd3df0639d1
69,239
import shlex def help(bot, message): """#help """ try: cmd, *args = shlex.split(message.text) except ValueError: return False if not cmd[0] in config['trigger']: return False if not cmd[1:] == 'help': return False msg = ['ケルベロス ver3.0.5'] msg_help = [] ...
f07caa7b3b00b334fc1af153ed1a086ff72282e2
69,240
def _cond_apply(x, y, func, prob): """Conditionally apply func to x and y with probability prob.""" return tf.cond((tf.random.uniform([], 0, 1) >= (1.0 - prob)), lambda: func(x,y), lambda: (x,y))
c8f93e40407fc4e7edf8c72095036f19a49db455
69,241
def replace_underscore_with_space(original_string): """ Another really simple method to remove underscores and replace with spaces for titles of plots. Args: original_string: String with underscores Returns: replaced_string: String with underscores replaced """ return original_...
27bea63c33c2ffe44b1ddc591a7813d8830e9f76
69,242
def residual(parameters_vector, datatube, vartube, xfibre, yfibre, wavelength, model_name, fixed_parameters=None, secondary=False): """Return the residual in each fibre for the given model.""" parameters_dict = parameters_vector_to_dict(parameters_vector, model_name) parameters_dict = insert_fi...
6353f2fa17aa09df6f4b98e6195ebc4be07d19a5
69,243
import numpy def gradient_array(ndarray): """ transform numpy array into python list """ out = ndarray if isinstance(out, numpy.ndarray): out = ndarray.tolist() return out
41d4a37e50db0a319d23d18d95978f0d16e569f8
69,244
def is_submod(mod_obj): """ Find out whether module has a parent or not. :param mod_obj: module object :return: module status """ try: bt = mod_obj.get('belongs-to') if not bt: return False return True except Exception as e: return False
274d985b3b7b07f02e919af20ed7fd4531136ccc
69,245
import torch def get_reward(logits, lbl, args): """ given logits, calculate score for Shapley value or interaction Input: logits: (B', num_class) tensor, B' can be (num_region+1)*bs or B'=1 lbl: (B,) tensor, B=1, label Return: v: (B',) tensor, reward score """ num_class = l...
3a6ff438f1c5711a7767c5cdd655ded14dac599d
69,246
def tunnelFromPhaseGW(phases, start_phase, V, dV, Tmax, Ttol = 1e-3, maxiter = 100, phitol = 1e-8, overlapAngle = 45.0, nuclCriterion = lambda S, T: S/(T+1e-100) - 140, verbose = False, fullTunneling_params={}): """ Extends the function tunnelFromPhase by the calculation of the GW parame...
dc3695f737d387b2b0a4620231878faa68482311
69,247
def to_df(song: Song): """Convert pydantic object to pandas dataframe with 1 row.""" return pd.DataFrame([dict(song)])
46f025e72ac042eb75a7afd6be38351b00c8e90e
69,248
import os def make_dummy_file(path, contents=None): """Makes a plain text file. Returns a hash of the file contents. """ dirname = op.dirname(path) if not op.exists(dirname): os.makedirs(dirname) if contents is None: contents = '{}\n'.format(op.basename(path)) with open(path, 'wt...
68bca4a1fe3e7d160339defab768e32a2c2fb230
69,249
def hash_password(password: str, maxtime: int=1, length: int=64) -> bytes: """ Hash a password string using scrypt Args: password: password string maxtime: maximum timed decryption should take length: length of key to generate Returns: Hashed password """ return ...
c997bc99c50f0cddea697617f692d89f087bc035
69,250
def shout_echo(word1, echo=1): """Concatenate echo copies of word1 and three exclamation marks at the end of the string.""" # Raise an error with raise if echo < 0: raise ValueError('echo must be greater than or equal to 0') # Concatenate echo copies of word1 using *: echo_word echo_wo...
68e2cce4adc68b1c7e345d2d3e11b36e1cbbf84c
69,251
import requests import json def _get_arxiv_metadata(identifier): """Get the DOI identifier (if it exists) from the arXiv API.""" response = requests.get( f'https://api.semanticscholar.org/v1/paper/arXiv:{identifier}' ) _validate_response(response, identifier) parsed_response = json.loads(r...
4139b495275babf9b4d818d797168894e27d5432
69,252
def get_member_names(group): """Get a list of resource names of the resources in the specified group. Failed resources will be ignored. """ inspector = GroupInspector.from_parent_resource(group) return list(inspector.member_names(include_failed=False))
f1e4fc7018a1dd4449342d33c5aa522de4fdf455
69,253
def streaming_post_to_es(client, chunk, index_name: str, job_name=None, delete_before_index=True, delete_key="_id"): """ Pump data into an Elasticsearch index. Args: client: Elasticsearch client chunk (List[dict]): list of dictionary objects holding field_name:value data index_name ...
946d1e021106955db2d0e4df9f324536ff2b05bd
69,254
def create_db(df): """ Create a nybb table in the test_geopandas PostGIS database. Returns a boolean indicating whether the database table was successfully created """ # Try to create the database, skip the db tests if something goes # wrong # If you'd like these tests to run, create a ...
2a138481efc54233462e7cde4ca04ad907858a2e
69,255
import pandas def find_cycle_extrema(series, samples_per_cycle): """Find minima and maxima for each cycle in an oscillatory signal. 'series' is a pandas Series. Does *not* directly find successive minima and maxima; instead, looks for 1 of each per cycle. Returns a boolean Series ("isma...
83dccfa12da619282cd3dba99eff2202094cd677
69,256
def gravity_v1() -> ItemParser: """This method is returns a Gravity ItemParser for Gravity row version 1""" def type_conversions(gravity: Gravity): gravity.acc_x = float(gravity.acc_x) gravity.acc_y = float(gravity.acc_y) gravity.acc_z = float(gravity.acc_z) parser = ItemParser(1, ...
fa31bc429438bf5ec35235b79d8c5d0cda00e2a2
69,257
def error_json_serializer(o): """Return a JSON serializable representation of error properties.""" if isinstance(o, sublime.Region): return (o.a, o.b) return o
2f9c9a461159a32c370e53fc2258cfa5770801d5
69,258
def rescale_pixels(traces, db_data, reference, manual_coordinates=None): """Use OpenCV to find corners in the image and rescale the data""" # # set up the looping flag # valid_corners = False # set the crop flag crop_flag = False if 'miniscope' in db_data['rig'] else True # # loop until proper...
de123d6f0ee4aac615b17cfd92e425c1e5bbf881
69,259
def dec2csd(dec_val, WF=0): """ Convert the argument `dec_val` to a string in CSD Format. Parameters ---------- dec_val : scalar (integer or real) decimal value to be converted to CSD format WF: integer number of fractional places. Default is WF = 0 (integer number) ...
8e095ca1507b57b769142f9d781fcd0d1b5c2875
69,260
def normalize_whitespace(text: str): """ Given ``text`` str, replace one or more spacings with a single space, and one or more linebreaks with a single newline. Also strip leading/trailing whitespace. Args: text (str): ``Urdu`` text Returns: str: Returns a ``str`` object containing ...
8817dd4d4f3b84fd0f3c7bef9389cb2fd78e5dbe
69,261
def get_visitor_chat_id(cpf): """ Get a chat_id of a visitor """ session = Session() visitor = session.query(Visitor).\ filter_by( cpf=cpf).first() session.close() if visitor: return visitor.chat_id else: return None
3d3d59dd87883fbcd7997609aaaf7bd488c97c8c
69,262
import numpy def DerXYZEuler(alpha,beta,gamma): """ derivatives of transformation matrix with respect to Euler angle :param float alpha: euler angle alpha (radians) :param float beta: euler angle beta (radians) :param float gamma: euler angle gamma (radians) :return: - du:lst(3*3*3) derivat...
dd620029cc143bca661c532c9d474e4a759fa2e3
69,263
def betaCost(price, is_etf, is_day_trading=False, volumn=1) -> Decimal: """ 證交稅 = 賣出成交金額 * beta :param price: :param is_etf: :param is_day_trading: 是否為當沖 :param volumn: :return: """ # 證交稅:股票 0.003(當沖為 0.0015) ETF 0.001(當沖沒有折扣) if is_etf: beta = Decimal("0.001") else:...
53b41f30957a64e629b502f88f9463b2716902d1
69,264
import ast def used_in_func(statement: str, filename: str = "<string>", mode: str = "exec"): """Parse a Python statement and analyze the symbols used. The result will be used to determine what variables a step depends upon.""" try: return get_used_in_func(ast.parse(statement, filename, mode)) ...
8d1ee04c492767794d2497053f09066aace91cc9
69,265
def get_trainer_with_mock_updater( stop_trigger=(10, 'iteration'), iter_per_epoch=10): """Returns a :class:`~chainer.training.Trainer` object with mock updater. The returned trainer can be used for testing the trainer itself and the extensions. A mock object is used as its updater. The update funct...
68f1e1b875a141f0e722c792489df42379006d47
69,266
from typing import List from typing import Optional import re def filter_comments( comments: List[AnyComment], filter_regex: Optional[str] = None, reverse: bool = False, author: Optional[str] = None, ) -> List[AnyComment]: """ Filters comments from the given list. Args: comments: ...
05922165c58342fd3f88b50229824216922b8283
69,267
def delete_task(task_id): """deletes a task from a project and removes it from the database""" task_to_delete = Task.query.filter_by(task_id=task_id).first() project_id = task_to_delete.project.project_id project_tracker_db.session.delete(task_to_delete) project_tracker_db.session.commit() retur...
64d4e9b295b1f94a3760384cefd9926fb5f73240
69,268
def filter_log_by_end_activities(end_activities, variants, vc, threshold, activity_key="concept:name"): """ Keep only variants of the log with an end activity which number of occurrences is above the threshold Parameters ---------- end_activities Dictionary of end attributes associated ...
fe587c58c775b1900a9e2b2209432cb479d4bfdd
69,269
from typing import List async def resolve_get_rent_events(_parent, args, _ctx, _info) -> List[RentEvent]: """ Resolves 'getRentEvents' graphql query for the Graphql Engine. Returns: List[RentEvent]: Event instance compatible with RentEvent sylvester Graphql schema. """ return await resol...
ccebf446fd60c5c056e2b3128490d7d21766d91e
69,270
def filter_para(paras): """过滤空值和签名""" for k, v in paras.items(): if not v or k in ['sign', 'sign_type']: paras.pop(k) return paras
c73123b15add26debbb3c60e11ca90b46782b6cc
69,271
def remove_nan(data, mask=None): """ Remove nan values from data. Optionally, it can update a mask (masked data = 1 in the mask, 0 otherwise). :param data: numpy ndarray :param mask: if provided, numpy ndarray of the same shape as the data :return: the filtered data and (optionally) mask "...
6dd69f91ca95a7bac6b799f00182dd338cfddfcf
69,272
def filter_connected(df: pd.DataFrame, dist: int = 2) -> pd.DataFrame: """Remove barcodes that are within hamming dist of eachother leving isolated sequences Inspired by the Abseq analysis in https://www.nature.com/articles/srep44447 """ clusterer = UMIClusterer(cluster_method="cluster") # Encode ea...
163a81c415414cc2f59abc91a2978459c89b3c8e
69,273
def test_unexpected_error(): """The credential should raise ClientAuthenticationError when the endpoint returns an unexpected error""" error_message = "something went wrong" for code in range(401, 600): def send(request, **_): if "resource" not in request.query: # avai...
b4b547e8faac9aa302ec8d304a785698057616eb
69,274
import requests def scraper_setup(site): """ site: string url of site to be scraped returns a page, or exits early if an error occurs """ print("[[ About to search {site} ]]".format(site=site)) page = requests.get(site) if page.status_code != 200: # Inform user of why it may have...
545df7c51075bf4e41942e76930384811da90213
69,275
def irbo(topics, weight=0.9, topk=10): """ compute the inverted rank-biased overlap Parameters ---------- topics: a list of lists of words weight: p (float), default 1.0: Weight of each agreement at depth d:p**(d-1). When set to 1.0, there is no weight, the rbo returns t...
1ade13cd4358c5af759fc9806ebe4721c63163a0
69,276
import logging def get_term_codes(): """ Get a list of term codes and their names from the UW API. Returns a TermInfo object and the ID of the current term """ #Create the url to query the API with url = """https://api.uwaterloo.ca/v2/terms/list.json?key={}\ """.format(app.config['API_KE...
a1c5e34b5bca19a7d48865aa65888700394f36ca
69,277
import torch def test_early_stopping_patience(tmpdir, loss_values, patience, expected_stop_epoch): """Test to ensure that early stopping is not triggered before patience is exhausted.""" class ModelOverrideValidationReturn(EvalModelTemplate): validation_return_values = torch.Tensor(loss_values) ...
77d46a268f214287e055efc7f7d6041682e1efd6
69,278
def make_ip_simple_fixed_color_light( device: hm_device.HmDevice, device_address: str, group_base_channels: list[int] ) -> list[hm_entity.BaseEntity]: """Creates simple fixed color light entities like HmIPW-WRC6.""" return make_custom_entity( device=device, device_address=device_address, ...
8dd87a794e60a4d43803a8502a3862dc62be4c0d
69,279
import pathlib def get_fixture(filename): """Return the data fixture.""" current_root = pathlib.Path('.').resolve() fixture_root = current_root / 'tests' / 'fixtures' / 'tools' fixture_path = fixture_root / filename return fixture_path.read_text()
225d4cdc6d2682b0dac8ddfa54b819bea335b82b
69,280
def SpotLightStart(builder): """This method is deprecated. Please switch to Start.""" return Start(builder)
fdb9a14e06c4856e82599fdacdc862b63aadca76
69,281
def clean_password_changes(old_pword, new_pword, new_pword_conf, user, request): """Cleaner for password changes.""" errors = [] success_list = [] if old_pword != '' or new_pword != '': if not user.check_password(old_pword): errors.append('old_pword') ...
0cee9abf7313c9d96fe09c118a4b93d3fc08a3c4
69,282
def mstest_box_post_process(result, cfg): """ Multi-scale Test Only available for batch_size=1 now. """ post_bbox = {} use_flip = False ms_boxes = [] ms_scores = [] im_shape = result['im_shape'][0] for k in result.keys(): if 'bbox' in k: boxes = result[k][0] ...
4b2fa80a2786f6ce8449ae7b236eccfd12546c7d
69,283
def get_model_meta_info(model_name): """returns a dict with model information""" return model_meta_info[model_name].copy()
573fbd461bbde6850ef4b39d6ef69556d1b7198e
69,284
def logout(): """Clear the current session, including the stored user id.""" session.clear() return redirect(url_for("index"))
4046b49a3a3d7d018ee7d87cd37cdcf5b30de555
69,285
import sys def get_args(): """ Function that retrieves the script's arguments when executed. Parameters: / Returns: A dict containing the various arguments. """ valid_args = { "file_path": "" } args = sys.argv for arg_i in range(len(args))...
41e6b9ac23ab3084a77f2b5d658dad0c8890c8bb
69,286
from typing import Optional def dcfc_act_365_a(start: Date, asof: Date, end: Date, freq: Optional[Decimal] = None) -> Decimal: """ Computes the day count fraction for the "Act/365A" convention. :param start: The start date of the period. :param asof: The date which the day count fraction to be calcul...
c7cbcc5281551016dcb9d24a16014113eda6e0ae
69,287
def get_last_commit_year(file_name): """Get year of last commit to the named file""" cmd_list = [ 'git', 'log', '-1', '--format=%ad', '--date=format-local:%Y', file_name ] data = '' try: data = subprocess.check_output(cmd_list) except subprocess.CalledProcessError as exc: ...
23e0da921fb695ceaff32fff8f6c16342ae00c2b
69,288
def get_bbox_from_points(pts): """ Return bbox from a points array :param pts: the points coordinates :return: y1, x1, y2, x2 """ temp = np.array(pts) x1 = np.amin(temp[:, 0]) x2 = np.amax(temp[:, 0]) y1 = np.amin(temp[:, 1]) y2 = np.amax(temp[:, 1]) return y1, x1, y2, x2
c235506e64ab2a5f9c1070deb2456cc940bacf6d
69,289
def getWnPos(treebank_tag : str): """ return WORDNET POS compliance to WORDNET lemmatization (a,n,r,v) """ if treebank_tag.startswith('J'): return wn.ADJ elif treebank_tag.startswith('V'): return wn.VERB elif treebank_tag.startswith('N'): return wn.NOUN elif treebank_...
ea4b749915d0be50e9f0445c09594da37b63a498
69,290
def list_all(t: ListableAPIResource): """Retrieve all objects of type t from Stripe. Should work for Product, Plan. SKU. """ objects = [] last_id = None has_more = True while has_more: response = t.list(limit=100, starting_after=last_id) has_more = response.has_more ...
6e46517f7405715a436c7e4c210138c065a31104
69,291
import logging def run_detect_triage_featurize(recordings, sess, x_tf, output_tf, neighbors, rot): """Detect spikes using a neural network Parameters ---------- recordings: numpy.ndarray (n_observations, n_channels) Neural recordings x_tf: tf.tensors (n_ob...
1935f2cfd3e1900b6fabe06e218cf2390ece072b
69,292
def gen_fake_msa(seqreclist): """ Fake an MSA by adding dashes to the end of sequences up to maximum length and return it as an MSA """ mlength=max(map(len,seqreclist)) newseqreclist=list() for s in seqreclist: l=mlength-len(s.seq) newseqreclist.append(SeqRecord(id=s.id,name...
62598deebfb54eef91a17dd3cb64a13d8abff2f0
69,293
import pickle def dump_qubo(model, output_path=_default_opath, prefix=_default_prefix, **markers): """ Pickle a QUBO using specific markers. See also :py:meth:`use_markers`. The default filename is `qubo.pickle`. :param model: an implementation of :py:class:`~hepqpr.qallse.QallseBase` :param outp...
2cc477190a9ab1f502258449102fa5255e25da82
69,294
import requests def kmodify(host, server, keyword, value): """Modify the value of a keyword. Reproduces the behaviour of modify -s server keyword Parameters ---------- host : str Instrument host computer server : str Server keyword : str Keyword value : generi...
ad7a33848888efe748376989abc2021f5aea939d
69,295
def get_direction_mask(nusc_map, patch_box, canvas_size): """ Return list of map mask layers of the specified patch. :param patch_box: Patch box defined as [x_center, y_center, height, width]. If None, this plots the entire map. :param patch_angle: Patch orientation in degrees. North-facing corresponds ...
5ac166132a3d6c2d374ac1d87ba327b610a17dec
69,296
def get_unique_points( n, x_range=(0, 10), x_grid_dim=101, y_range=(0, 10), y_grid_dim=101 ): """ Get array of unique points, randomly drawn from a uniform grid """ xs, ys = np.meshgrid( np.linspace(x_range[0], x_range[1], x_grid_dim), np.linspace(y_range[0], y_range[1], y_grid_d...
d433b456842bae8eec123ab22eab16f7190d5011
69,297
def CCW_ps(Pxx, Pyy, Pxy): """Counter clockwise power spectrum.""" QS = Pxy.imag return (Pxx + Pyy + 2*QS)/2.
76710ff31e4fead278afc9eb37691f2178f45def
69,298
def generate_below_the_fold_css(theme): """ Returns a string containing below-the-fold Bootstrap CSS using the given BootstrapTheme """ context = get_scss_template_context(theme) scss_string = render_to_string('bootstrap_customizer/bootstrap_below_the_fold.scss', context) if is_windows_envir...
0e970d6bede0f3a3e5cfad20432d7cba9b07fca7
69,299