content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def _plot_enn_samples_2d(sample_df: pd.DataFrame, train_df: pd.DataFrame) -> gg.ggplot: """Plot realizations of enn samples.""" p = (gg.ggplot(sample_df) + gg.aes(x='x0', y='x1', fill='y') + gg.geom_tile() + gg.geom_point(data=train_df, size=3, stroke=1.5) + gg.s...
975dd8d3ee0a6ce7f13c351915a15a4d95a2722b
52,751
def square2vec(rdm): """map 2D distance matrix to [n,1] vector of unique distances. Returns distances in same order as scipy.spatial.distance.squareform.""" return rdm[np.triu_indices_from(rdm, k=1)][:, None]
830a91f5890017f035383d1c728be3048deed44a
52,752
from datetime import datetime import pytz def parse_date_string(dt_string, alexa=False): """Parse the date string from the database into a `datetime` object. :param date_string: the raw date string to parse :returns: the `datetime` version of the given date string """ if(alexa): return da...
3deb8558d84cd28e2eca5b575587fe8315f6de0c
52,753
from typing import Union from typing import ContextManager from pathlib import Path def _get_filepath( dataset_name: str, dir_path: Union[None, str], filename: str ) -> Union[str, ContextManager[Path]]: """ Returns the path to a decay dataset file (located either within a sub-package of ``radioactived...
a4e7d480bf0abf209f3fc094452d6e38d4334741
52,754
import json def get_frequent_queries(**kwargs): """ Gets the most frequent queries Kwargs: db: global database instance redis: global redis instance """ db = kwargs["db"] with db.scoped_session() as session: q = sqlalchemy.text( "SELECT query, calls FROM pg...
2b0a58aeb4ef228bcf230030d1d2b5f02e49452e
52,755
def Bellman_exp_inplace_prt(Qsa, S, action, action_list, ff=0.9, N_A=9, N_Symbols=3, disp_flag=False): """Evaluate q(s,a) using ``S`` and ``action``. Returns q(s,a). Parameters ---------- S : numpy.ndarray, shape=(N_A,) State matrix <--> state index, ``S_Idx`` action : int ...
77c371749d5cbc0c7162ecf2a4916d34143ce7fd
52,756
def beh_idx_to_2p_idx(beh_indices, cam_line, frame_counter): """ This functions converts behaviour frame numbers into the corresponding 2p frame numbers. Parameters ---------- beh_indices : numpy array Indices of the behaviour frames to be converted. cam_line : numpy array P...
1521f29eaf0fed628dd8dedd3cc0ce5f8223c7ca
52,757
def num2julian(num): """ Convert a Julian days to a matplotlib date. Parameters ---------- num : numpy.ndarray : int32 Number of days since 0001-01-01 00:00:00 UTC *plus* *one*. Returns ------- jd : numpy.ndarray : int32 Julian days. """ return num + 1721424.5
c3d4815ef316062065109ebb7c52290ca13c01fe
52,758
import logging def get_logger(module_name: str) -> logging.Logger: """ Gets a namespaced logger based on the project name and module name """ if "" == LOGGING_PROJECT_NAME: return get_fqn_logger(module_name) return get_fqn_logger("{}.{}".format( LOGGING_PROJECT_NAME, modul...
4543e7fafb5788607664de0749dff5456dc63c6f
52,759
def crop_and_resize_instance_masks(masks, boxes, mask_size): """Crop and resize each mask according to the given boxes. Args: masks: A [N, H, W] float tensor. boxes: A [N, 4] float tensor of normalized boxes. mask_size: int, the size of the output masks. Returns: masks: A [N, mask_size, mask_siz...
81f06b34499ec8c51c5635e4c79a5943179b3108
52,760
def compute_source_flags(tod=None, P=None, mask=None, wrap=None, center_on=None, res=None): """Process masking instructions and create RangesMatrix that flags samples in the TOD that are within the masked region. This masking makes use of a map with the footprint encoded in P, so ...
857eb7db8bd8490695a8198714d3675c2ea5940d
52,761
def _split(df, keepvars, force_numeric=False): """ Splits a dataframe into a list of arrays based on a key variable. Pass keepvars to keep variables other than the key variable """ # df = df.sort_values('__key_var__') #now done outside of function small_df = df[['__key_var__'] + keepvars] ar...
0a93671b0348a3e8d288485733bba1befa93445a
52,762
import functools def pmg_serialize(method): """ Decorator for methods that add MSON serializations keys to the dictionary. See documentation of MSON for more details """ @functools.wraps(method) def wrapper(*args, **kwargs): self = args[0] d = method(*args, **kwargs) #...
bbe2ed20bf563d97c5cfc920e9ad226e096f5cba
52,763
def normalize_dataframes(grouped_df, year): """ Takes a dataframe which has been grouped by phrase and aggregated, and normalizes the total_occurrences and total_docs columns by dividing them by the total no. of phrases or total no. of docs in the relevant year and multiplying by 100 to create percentages. ...
4a4ca38c13b8a18b0b72f86ae9610882314bac74
52,764
async def setup_file(config_file, cmd_args): """Set up control center from config file and command line args. Parameters ---------- config_file : str The path to the configuration YAML file. cmd_args : dict The dict with the command line arguments. Returns ------- Cente...
912b8c044fdfce07f0d2fdad141feb548ea8c5fb
52,765
def egd_get_user_lang(user=None) -> str: """If user logged use gessed language on session beginning or resumption""" if is_app_for_actual_site(): return frappe.local.lang else: return frappe_get_user_lang(user)
2fe52f7259dc2cb5fa33dd883e475960ef7040a3
52,766
def oldest_youngest(): """Get JSON Data. Compile a dictionary of all billionaires' names and ages. Find the oldest billionaire under 80, and youngest living billionaire.""" data = get_json() age_dict = {} for item in data['billionaires']: if item['age'] >= 80 or item['age'] < 0: ...
25e04edac9fb7ba7f4fa7b399dd28403c1ffffe0
52,767
import pickle def read_narr_mask(pickle_file_name): """Reads NARR mask from Pickle file. :param pickle_file_name: Path to input file. :return: mask_matrix: See doc for `check_narr_mask`. """ pickle_file_handle = open(pickle_file_name, 'rb') mask_matrix = pickle.load(pickle_file_handle) p...
ad78202ef4cf136647ad51d4e558fe3de58ef9d0
52,768
from typing import Dict from typing import Optional def get_imported(context: dict) -> Dict[str, Optional[version_types]]: """Create list of imported modules in given context. Only outputs modules from given context that have conventional version attributes. Context is typically globals() or locals()...
1a1e2a84db5de4490f2adbe677fc08315a99de2f
52,769
from typing import Callable def mpi_reduce(x: np.ndarray, op: Callable) -> np.ndarray: """Apply reduce operation over MPI processes.""" buffer = np.zeros_like(x) MPI.COMM_WORLD.Allreduce(x, buffer, op=op) return buffer
7c048c5f3fdcd19b436e45cdbab17ad02255bdbf
52,770
def get_det_bbox_with_cls_of_img(all_boxes, img_idx): """get_det_bbox_with_cls_of_img :param all_boxes: det result :param img_idx: img idx in imageset.txt :return bboxes: N*6-dim matrix, N is number of bbox, 6 is [x1,y1,x2,y2,score,cls], the cls is the addtion information we get from this function ...
b4c2023c385712675b99b944a179614dbac9e1f5
52,772
def _multiply_calculate(a, b): # pragma: no cover """ a in GF(2^m), can be represented as a degree m-1 polynomial in GF(2)[x] b in GF(2^m), can be represented as a degree m-1 polynomial in GF(2)[x] p(x) in GF(2)[x] with degree m is the primitive polynomial of GF(2^m) a * b = c = (a(x) * ...
7cb631ceed1c635eca26c105f82c43301bc158b0
52,773
def hugoniot_rho(p, rho0, c0, s, min_strain=0.01): """ calculate density in g/cm^3 from a hugoniot curve :param p: pressure in GPa :param rho0: density at 1 bar in g/cm^3 :param c0: velocity at 1 bar in km/s :param s: slope of the velocity change :param min_strain: defining minimum v/v0 val...
c8afd51030c9b7c8c1353bab0ac7199b349aa77d
52,774
def name( path ): """Extracts the resource name.""" return path[1+path.rfind('/'):]
7e8448e5b1c62c30e7ae28c80580731aa9f6f9fb
52,777
def report_dfa(q_0, dfa, g): """ Give a complete description of the DFA as a string """ output = "" output += "----------- DFA ----------- " + "Goal: " + g + " ----------- \n" transitions = [(i,dfa[(i,sigma)],sigma) for i,sigma in dfa] transitions.sort() for i,j,sigma in transitions: output += (f"delta({i},{s...
99d86557b9e1aede93f46e1ef78ecb1fe6cdbf30
52,778
def get_page_response(query, page, per_page, itemskey, return_method=None, replaceobj=None, replaceobj_key_only=False, **kwargs): """ 获取一个多页响应对象 :param query: 查询对象,或者直接返回的对象 :param page: 当前页 :param per_page: 每页项目数 :param itemskey: 对应 items 的键名 :param return_method: 若值不为 Non...
fb15af91981ff057ed75a633a9012ab68d5653e3
52,779
def decrypted(data, password=None, is_user=True): """Decrypt to any Python object :param data: a byte string previously encrypted using :func:`encrypted` :param passowrd: the optional password originally used to encrypt :param is_user: optionally indicate whether user or machine :returns: a Python ...
d3924de10aaa4b0918205373cf2e4f7744a0bc7c
52,780
def on_pad_pressed(pad_n=None, pad_ij=None): """Shortcut for registering handlers for ACTION_PAD_PRESSED events. Optional "pad_n" or "pad_ij" arguments are to link the handler to a specific pad. Functions decorated with this decorator will be called with the following positional arguments: * Pus...
458be38bacca5347370bb9526a7603d0d6455f85
52,781
def score(n): """根据成绩,计算成绩的级别,级别有:A、B、C、D 成绩>=90 ——A 成绩>=80 ——B 成绩>=70 ——C 成绩>=60 ——D 参数: - n-:成绩 返回值:返回‘A’或‘B’或者'C'或者'D' """ if n >= 90: return 'A' if n >= 80: return 'B' if n >= 70: return 'C' if n >= 60: return 'D'
fb854dbdb77e31b75a70eddf6d001814100c44d3
52,782
def get_linked_clusters(): """ Get linked clusters. :returns: list of linked clusters :rtype: [LinkedCluster] """ current_cluster = get_attached_cluster() if not current_cluster: return [] links = get_cluster_links(current_cluster.get_url()).get('links') linked_clusters = ...
524d231676d1db77cf1804d626f7aeb2ff69a228
52,785
from unittest.mock import Mock def cube_mesh(): """ cube mesh """ mesh = Mock() mesh.vertices = cube_vertices() mesh.loop_triangles = [ triangle(0, 2, 1), triangle(0, 3, 2), triangle(2, 3, 4), triangle(2, 4, 5), triangle(1, 2, 5), triangle(1, 5, 6), ...
3a572fd73fe5a2aca2f59517ba19f8b7d6b214f9
52,786
def algo_options(): """ Return the list of default options for supported algorithms. """ return {"grid": "", "hubbard": "", "medial": "-merge -burst -expand", "octree": "", "spawn": ""}
f52c12efe477bd50a49e7053cca97fc9e4072433
52,787
def fill_matrix(X: np.ndarray, mixture: GaussianMixture) -> np.ndarray: """Fills an incomplete matrix according to a mixture model Args: X: (n, d) array of incomplete data (incomplete entries =0) mixture: a mixture of gaussians Returns np.ndarray: a (n, d) array with completed data...
c7001e668a04a3221f9db48038815abfcdbb1575
52,789
def detect(agent, fill_none=False): """ fill_none: if name/version is not detected respective key is still added to the result with value None """ result = dict(platform=dict(name=None, version=None)) _suggested_detectors = [] for info_type in detectorshub: detectors = _suggested_detect...
bef47ccbff4bbf09d0195a6f9e71f8ed675f04ef
52,790
def shutting_down(globals=globals): """ Whether the interpreter is currently shutting down. For use in finalizers, __del__ methods, and similar; it is advised to early bind this function rather than look it up when calling it, since at shutdown module globals may be cleared. """ # At shutdow...
01f601b989611b06a438a3be3e15937eff389038
52,791
def _err(msg=None): """To return a string to signal "error" in output table""" if msg is None: msg = 'error' return '!' + msg
029fae3786df61160867696fb71cc94b2edf0506
52,792
from datetime import datetime import pickle def run_qpe( unitary, precision_qubits, query_qubits, query_circuit, device, items_to_keep=1, shots=1000, save_to_pck=False, ): """ Function to run QPE algorithm end-to-end and return measurement counts. Args: precision_q...
04e6cecd3a28c50f635a0a42f1ee24f6ac8c0b70
52,793
def LNETF(N,loc_rad,taper='GC',infl=1.0,Rs=1.0,rot=False,**kwargs): """ The Nonlinear-Ensemble-Transform-Filter (localized). Ref: Julian Tödter and Bodo Ahrens (2014): "A Second-Order Exact Ensemble Square Root Filter for Nonlinear Data Assimilation" It is (supposedly) a deterministic upgrade of the NLEAF ...
e1f3beb387371d3178598b724cc08c0a0e3f53b8
52,794
def alert_unmanaged_error(request_id, error, sys_exc_info): """Compose error on unmanaged error.""" return UNMANAGED_TEXT_MESSAGE.format( date=get_date(), request_id=request_id, error=error, traceback=format_traceback(sys_exc_info), locals=format_locals(sys_exc_info) ...
53c504a2bef9f7c7593988b63238a95c753fbbde
52,795
def load_transcript(transcript_path): """" Load transcript from *.srt file """ transcript = [] subs = pysrt.open(transcript_path) for sub in subs: transcript.append((sub.text, time2second(tuple(sub.start)[:4]), time2second(tuple(sub.end)[:4]))) return transcript
ff4725e0f2ec68b16bd750b28066a4446280c866
52,796
async def get_attachment_obj(ctx: commands.Context): """Gets the attachment object from a message""" # switch to the replied message if it's there if ctx.message.attachments: msg = ctx.message elif ctx.message.reference: msg = ctx.message.reference.resolved else: return False...
176a7e2c9dcc27dff9586440c23486dc7d273301
52,797
def day_wind_chart(qs_list, unit, plot_func, width, height, colors): """ Returns a URL which produces one line for each queryset. """ data_list = [] # list of value lists for date_qs in qs_list: if date_qs: # only work on this if the queryset is not empty data_list.append(conv...
eda14897fec89f14b340c7dc5234b7a91f4ca59d
52,798
from operator import eq def conso(h, t, l): """ Logical cons -- l[0], l[1:] == h, t """ if isinstance(l, (tuple, list)): if len(l) == 0: return fail else: return (conde, [(eq, h, l[0]), (eq, t, l[1:])]) elif isinstance(t, (tuple, list)): return eq((h, ) + tu...
cb576eeeb8de5a2a71a8843a4d81b3933af6d64a
52,799
def select_text(table, col_names, version): """Generate a select statement for new or old values of this table.""" slt = "SELECT {tuple_str} FROM {table} WHERE rowid={version}.rowid".format( tuple_str=sqlite_list_text([col_pair_text(c, version) for c in col_names]), ...
28f22ad8478cd87d1d56c7a1a6b86d0b81e1d457
52,800
def predict(Theta1, Theta2, X): """ outputs the predicted label of X given the trained weights of a neural network (Theta1, Theta2) """ if X.ndim == 1: X = X.reshape(1, -1) # Useful values m = len(X) # ====================== YOUR CODE HERE ====================== # Instructions:...
ba3df784fdd2a76fc59f0f010a9a4eb4c5be035f
52,801
def aml_token(chain, team_multisig, token_name, token_symbol, initial_supply) -> Contract: """Create the token contract.""" args = [token_name, token_symbol, initial_supply, 0, True] # Owner set tx = { "from": team_multisig } contract, hash = chain.provider.deploy_contract('AMLToken', de...
b114cfc3abeeea9c600dccbc1bed78de60a7576f
52,802
def invr(): """ For taking space seperated integer variable inputs. """ return(list(map(int, input().split())))
9794b5c44a817cbd48709de99f16515c8684712b
52,803
def _path_residuals(X, y, train, test, path, path_params, alphas=None, l1_ratio=1, X_order=None, dtype=None): """Returns the MSE for the models computed by 'path' Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Training data. y : arr...
0bfb35f3de8f5c8ba136a9cf29650667c110a039
52,804
def is_an_exact_imagined_object(predicate, imagined_object): """ Returns whether the imagined object matches exactly what the predicate describes. Inputs: predicate: WordPredicate instance imagined_object: RecognizedObject instance """ target = possible_reco...
06aef2d1fb87d02cf60baceff81d8b153d487967
52,805
def read_field__list(infile, varname, lon, lat): """Read point list and initialize field.""" # Read field ... if infile.endswith(".npz"): # ... from numpy archive with np.load(infile) as fi: pts_lon, pts_lat, pts_fld = fi["lon"], fi["lat"], fi[varname] fld = point_list_t...
1e1baafdab9fac5a43bb95d28fb8d7d0c9d8ba31
52,806
def CircuitHeaderStartConfigurationVector(builder, numElems): """This method is deprecated. Please switch to Start.""" return StartConfigurationVector(builder, numElems)
9ad0c7dd86a9f0cb90f573720802658616f81bff
52,807
def get_processed_masks_and_boundaries(mask_path: str, boundary_path: str) -> tuple[ndarray, ndarray]: """Utility function for loading and applying preprocessing to mask and boundary image array :param paths: :return: tuple[ndarray, ndarray] """ masks = np.array( cv2.imread( mask...
26def41a1e8dfe33d2d35b155164412374dfa30f
52,808
import warnings def nx_to_gdf(net, points=True, lines=True, spatial_weights=False, nodeID="nodeID"): """ Convert ``networkx.Graph`` to LineString GeoDataFrame and Point GeoDataFrame Parameters ---------- net : networkx.Graph ``networkx.Graph`` points : bool export point-based ...
1821d06896eb9b7bfafa81aa748521ff2153bd0f
52,809
def p2pkh(pubkey) -> Script: """Return Pay-To-Pubkey-Hash ScriptPubkey""" return Script(b'\x76\xa9\x14'+hashes.hash160(pubkey.sec())+b'\x88\xac')
2728805a090ddcd070b7454549018d538d71ee73
52,810
def _extract_center_face(image_shape, detected_faces): """Extracts the face that's the closest to the center of a image. ### Parameters image: image with the faces. detected_faces: list of resulting bounding boxes and keypoints from\ MTCNN().detect_faces(). ### Returns (bounding_b...
cbfb3bc4c90a62cb75eaa40854fe8829d76a18eb
52,811
from typing import Optional from typing import Union def get_county_polygons(county_ids: Optional[intseq], state_ids: Union[int, intseq]): """Get a dataframe with the polygons or multipolygons representing county borders The returned dataframe will have the county polygons for each county listed. `county_ids...
ad8a71ab0fc38658c4eff0f86030e3b14ac64a28
52,812
def add_xls_tag(file_name): """ Check the file_name to ensure it has ".xlsx" extension, if not add it """ if file_name[:-5] != ".xlsx": return file_name + ".xlsx" else: return file_name
e053d9f7dad8e638122e93d05e49c5a06de3e664
52,813
def order_queryset_by_z_coord_desc(queryset, geometry_field="location"): """Order an queryset based on point geometry's z coordinate""" return queryset.annotate( z_coord=models.ExpressionWrapper( models.Func(geometry_field, function="ST_Z"), output_field=models.FloatField(), ...
bd9e4d9b09b2676727dc2f83452e93b50eda3716
52,814
def err_number(error) : """ Return a error number """ result = errOk if isinstance(error, int) : result = error elif isinstance(error, Error) : result = error.error_code if result < 0 : result = (result - ErrorBaseNumber) * -1 return result
8c6912a8c8466ecf4ce486a43001748d4237a217
52,815
def value_iteration(env): """ Performs Value Iteration to find the most optimal policy for the Tax-v3 environment Args: env: Taxiv3 Gym environment Returns: policy: the most optimum policy """ V = dict() gamma = 0.9 state_size = env.observation_space.n action_si...
461b65bf8de4cf30f018aad24f8452ed6b7ec247
52,816
def keypoint_3d_pck(pred, gt, mask, alignment='none', threshold=150.): """Calculate the Percentage of Correct Keypoints (3DPCK) w. or w/o rigid alignment. Paper ref: `Monocular 3D Human Pose Estimation In The Wild Using Improved CNN Supervision' 3DV'2017. <https://arxiv.org/pdf/1611.09813>`__ . Note...
704cf2cc4b00ad232689d76e65d2a7241eda8fec
52,817
from bioservices import biomart from io import StringIO def mitochondrial_genes(host, org): """Mitochondrial gene symbols for specific organism through BioMart. Parameters ---------- host : {{'www.ensembl.org', ...}} A valid BioMart host URL. org : {{'hsapiens', 'mmusculus'}} Orga...
affd7ff1d9014f36238b535732a1cbaac43b1308
52,818
def Bold(string): """Returns string wrapped in escape codes representing bold typeface.""" return '\x02%s\x0F' % string
4dd1a0d3aecc93873f9763723a3dad76b45e2725
52,819
from typing import List import decimal import json def from_bbox_array(bbox_array: List[decimal.Decimal]): """returns a geojson geometry object from a bounding box array. Keeping default number of decimal places to 6 for now, can change depending on data precision requirements.""" if bbox_array: ...
3bbaf66d6d5d31f45b93e944474cac5f454df313
52,821
def taiwanLightCompensation(im, theta=0.5, thresh=0.2, B=[10, 30]): """ Perform light compensation http://www.csie.ntu.edu.tw/~fuh/personal/LightCompensation.pdf :param theta: weight of corrected image in final output :return: light compensated image """ def getOptimalB(im, thresh, B): ...
ac7c1fa06bb7cc2f0904b8da1ad360a027d6778f
52,823
def _is_sweep_sequential(radar, sweep_number): """ Test if a specific sweep is sequentially ordered. """ start = radar.sweep_start_ray_index['data'][sweep_number] end = radar.sweep_end_ray_index['data'][sweep_number] if radar.scan_type == 'ppi': angles = radar.azimuth['data'][start:end+1] el...
3bc493b80d245a51295c5e3461f9442baecd15cb
52,824
import random def random_expand(image, boxes): """ Perform a zooming out operation by placing the image. Helps to learn to detect smaller objects. Args: image(numpy.array): image, a array of dimensions (original_h, original_w, 3) boxes(numpy.array): bounding boxes in boundary coordin...
79e958a8acdc622e3e2e9270a2a29ededcc110b3
52,825
def matMULTI(first,second): """ Take in two matrix multiply each element against the other at the same index return a new matrix """ newMAT = [] newCOL = [] for i in range(len(first)): for j in range(len(first[i])): newMAT.append(first[i][j]*second[i][j]) #new...
28b3b5954a483311bca6245c7472a99e8a12395c
52,827
def put_html(html, sanitize=False, scope=Scope.Current, position=OutputPosition.BOTTOM) -> Output: """ Output HTML content :param html: html string :param bool sanitize: Whether to use `DOMPurify <https://github.com/cure53/DOMPurify>`_ to filter the content to prevent XSS attacks. :param int scope,...
60a10c44df3b4ba66f8ac428bfbfeaa60b069ac9
52,828
def convert_list2dict(word_list): """ 把列表写成字典 """ word_dict = defaultdict(int) for w in word_list: word_dict[w] = 1 return word_dict
72bf12e52f8ebd8d9b9ce3626b995d0ababc2ab5
52,830
def GetAuthorizationCodeViaCommandLine(config): """Gets authorization code via command line. This way is useful anywhere without a browser. Args: config: a dictionary of config. Returns: authorization code. """ body = urlencode({ 'scope': config['scope'], 'redirect_uri': config['redir...
67f7603825fcf30a4fbb957414e90525a88ceae5
52,831
def pedestal_ids_file(base_test_dir): """Mock pedestal ids file for testing.""" pedestal_ids_dir = base_test_dir / "auxiliary/PedestalFinder/20200117" pedestal_ids_dir.mkdir(parents=True, exist_ok=True) file = pedestal_ids_dir / "pedestal_ids_Run01808.0000.h5" file.touch() return file
edda4c192e577774e0cc4a38aaa7d838127e7dcd
52,832
def get_fa_icon_class(app_config): """Return Font Awesome icon class to use for app.""" if hasattr(app_config, "fa_icon_class"): return app_config.fa_icon_class else: return 'fa-circle'
3766abb1f80b7ccea9e09a5edf011f1586e9b49e
52,833
def linear_activation_forward(a_prev, w, b, activation): """ activation step for forward propagation with multiple choices of activation function. @param a_prev: previous A from last step of forward propagation, numpy arrays @param w: parameter W in current layer, numpy arrays @param b: parameter b...
58a12f753c42201400747e52213b95d372ae6e89
52,834
import time def create_token(args): """ POST /api/v1/create_token HTTP/1.1 Host: 127.0.0.1:5000 Content-Type: application/json Content-Length: 74 { "name":"1234", "password" :"1234", "email" : "1234", "duration":123 } {"access_token":"ad236cdb-f645-456...
74012f112c5d22a088e1e58032d35de5b1436028
52,836
def getDictionary(id_or_identifier): """ 指定した id または identifier を持つ辞書のメタデータを返します。 id, identifier に一致する辞書が存在しない場合は None を返します。 Parameters ---------- id_or_identifier : str or int str の場合は辞書 identifier で指定。 int の場合は内部辞書 id で指定。 Returns ------- Metadata Metadat...
7d3f19ee4a9952afb336eb00cbc28a07191d02b2
52,837
def is_phone_in_call(log, ad): """Return True if phone in call. Args: log: log object. ad: android device. """ return ad.droid.telecomIsInCall()
bf279c1892077de53f13976179ecf762f45f54b6
52,839
def omicron_model( xs: np.ndarray, ts: np.ndarray, params: dict ) -> np.ndarray: """ SL_2I_4R model with dual immunity :param np.ndarray xs: actual array of states :param np.ndarray ts: time values :param dict params: dictionary of parameters :return np.ndarray ""...
52ce91a0be8f8f5054c12c08993ed8303ffd87f3
52,840
def identity(n): """ Return n """ return n
cc3249a1164e18f47f962e4db56a425876a87b17
52,841
def look_for_general( m_str: str, ref_dict: defaultdict, base_num: t.Pattern[str], full_num: t.Pattern[str], doc_type: str, ) -> defaultdict: """ Reference Extraction by Regular Expression: For general use Args: m_str: text string to search ref_dict: dictionary of refere...
1563e85f9228f9ffb14f14869ecf1f73441ae2e6
52,842
def losses_and_metrics(num_classes): """ Define loss and metrics Loss: Categorical Crossentropy Metrics: (Train, Validation) Accuracy, Precision, Recall, F1 Returns: loss, train loss, train acc, valid loss, valid acc, precision, recall, auc, f1 """ loss_fn = CategoricalCrossentropy...
d8f571c4e2948007d8b6f880afbbd0e2fcfab00d
52,843
import copy def get_skill_from_model(skill_model): """Returns a skill domain object given a skill model loaded from the datastore. Args: skill_model: SkillModel. The skill model loaded from the datastore. Returns: skill. A Skill domain object corresponding to the given ...
c75ea6c7705d316a5d279da36468dd9278ceae44
52,844
def delete_tags_for_manifest(manifest): """ Deletes all tags pointing to the given manifest. Returns the list of tags deleted. """ query = Tag.select().where(Tag.manifest == manifest) query = filter_to_alive_tags(query) query = filter_to_visible_tags(query) tags = list(query) now_ms = get_epoch_ti...
a78b77ea96a3870b736301443005e45d58f76c42
52,846
def eeg_epochs_dataset(subject, trial, config, preload=True): """Get the epoched eeg data excluding unnessary channels from fif file and also filter the signal. Parameter ---------- subject : string of subject ID e.g. 7707 trial : HighFine, HighGross, LowFine, LowGross Returns ------...
58e6a1d63d2cc01416761b48a32a5bc9ebeacef9
52,847
def differences(lis, n=1): """ Returns the `n` successive differences of the elements in `lis`. EXAMPLES:: sage: differences(prime_range(50)) [1, 2, 2, 4, 2, 4, 2, 4, 6, 2, 6, 4, 2, 4] sage: differences([i^2 for i in range(1,11)]) [3, 5, 7, 9, 11, 13, 15, 17, 19] ...
067ee6e5744211f2b41f55f8cd7383431df1e486
52,848
def get_bounded_progress(): """ returns progress as a tensor between 0 and 1 """ assert get_default_counter().expected_count is not None return get_default_counter()._bounded_progress
3279ead5729521280bc0fd9295de861944f02b9a
52,849
import six def _is_start_piece_sp(piece): """Check if the current word piece is the starting piece (sentence piece).""" special_pieces = set(list('!"#$%&\"()*+,-./:;?@[\\]^_`{|}~')) special_pieces.add(u"€".encode("utf-8")) special_pieces.add(u"£".encode("utf-8")) # Note(mingdachen): # For foreign characte...
591373699c5e4c41248c81dac2bae5520123b2e7
52,851
import math def atrpips(data, length): """Average True Range indicator in pips Arguments: data {list} -- List of ohlc data [open, high, low, close] length {int} -- Lookback period for atr indicator Returns: list -- ATR (in pips) of given ohlc data """ atr_pips = [] av...
b73ab18cd0e1f338cc8136c0ccd82fd056d668a9
52,852
def start_day(start): """Return TMIN, TAVG, TMAX.""" start_day = session.query(Measurement.date, func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).filter(Measurement.date >= start).group_by(Measurement.date).all() start_day_list = list(start_day) return jsonify(start_da...
3c24c3c22dc1444e4bc46baeaa3e527a1e2af75b
52,853
def R123(a,b,c, degrees=False): """Returns a rotation matrix based on: Z*Y*X""" if degrees: a *= deg2rad b *= deg2rad c *= deg2rad s3 = np.sin(c); c3 = np.cos(c) s2 = np.sin(b); c2 = np.cos(b) s1 = np.sin(a); c1 = np.cos(a) return np.array( [ [c1*c2,...
8097514d390d73d1121c9462cada98060681619e
52,854
from datetime import datetime from typing import Optional import time from typing import Union import calendar def get_next( base: datetime, interval: Interval, frequency: int, at_time: Optional[time] = None, days: Optional[list[int]] = None, ) -> Union[datetime, date]: """Get the next due dat...
678b5c85615e388e2ae221df7ffba7ee38f97584
52,855
from typing import Union def guess_font_size( size: tuple[int, int], font_name: str ) -> tuple[Union[ImageFont, FreeTypeFont], int]: """Try and figure out the correct font size for a given height and font. Args: ``size``: The dimensions of the image in pixels. ``font_name``: The name of t...
01733050378885184ea5e0dbaba053263cf139bd
52,856
def create_model( time_set=None, time_units=pyo.units.s, nfe=5, tee=False, calc_integ=True, ): """Create a test model and solver Args: time_set (list): The beginning and end point of the time domain time_units (Pyomo Unit object): Units of time domain nfe (int): Numb...
9330c87db97d42de665c8198eaa113045ef92897
52,857
from pathlib import Path def read_table(h5file, path, start=None, stop=None, step=None, condition=None) -> Table: """Read a table from an HDF5 file This reads a table written in the ctapipe format table as an `astropy.table.Table` object, inversing the column transformations units. This uses the sam...
f3ef6b3ff7afc81e1afd9cca594727b8117471bc
52,858
from typing import Any def get_valid_ref(ref: Any) -> str: """Checks flow reference input for validity :param ref: Flow reference to be checked :return: Valid flow reference, either 't' or 's' """ if ref is None: ref = 't' else: if not isinstance(ref, str): raise ...
16c66dc9e0568bcd33e1cc9956ed31b5ae47595e
52,859
def k_argmin(l, k, func): """ Gets the indices and values of the k-smallest function results from func. """ l_map = map(func, l) return k_min(l_map, k)
750f408723ad9e024d45796bcc3250a9fcab296a
52,860
from typing import Optional from typing import Tuple def add_ports_from_markers_square( component: Component, pin_layer: LayerSpec = "DEVREC", port_layer: Optional[LayerSpec] = None, orientation: Optional[int] = 90, min_pin_area_um2: float = 0, max_pin_area_um2: float = 150 * 150, pin_extr...
349893ef57c43dfc634af54086c98720207d2d6c
52,862
def calc_periodicity(peak_info, period_min=5, period_max=15): """ calculate the period :param peak_info: :param period_min: :param period_max: :return: """ num_peaks = peak_info.shape[0] # calculate periodicity peak_info[:num_peaks-1, 2] = np.diff(peak_info[:, 0]) peak_info =...
ac7ca44153019773741e6e6ca15fd9961bb16089
52,863
from typing import Type def create_global_resource(group: str, version: str, kind: str, plural: str, verbs=None) \ -> Type[GenericGlobalResource]: """Create a new class representing a global resource with the provided specifications. **Parameters** * **group** `str` - API group of the resource. ...
c6cb2e05a048456ed7103c6e1b4c81692b34987a
52,864
from typing import Dict from typing import Hashable from typing import Any def outline_to_implementation( name: str, design: str, outline: fiat.Outline) -> Dict[Hashable, Any]: """[summary] Args: name (str): [description] design (str): [description] outline (fiat.Outline)...
871c7fd4f950c291832cbd0fc3dce823831c4257
52,865