content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def scale_image(image, yx_new, zoom_spline): """Perform an exact scaling of image, to the int-valued (y,x) sizes in yx_new. Note that the aspect ratio is not considered here; it should be (approximately) preserved in calculating yx_new if that is desired.""" yx_curr = (image.shape[0], image.shape[1]) ...
63fc74fa1170fccd07f7b3693256ef2db9b66d92
80,052
def is_copy_to_clipboard_supported(): """ There is no way of copying an image to the clipboard if tkinter has to be used as a fallback. This function test whether or not a system compatible function to copy an image to the clipboard has successfully been imported. :return: bool: Is there a system compa...
54af1d083658d32188de9d5d9d218d1def11f557
80,054
def list_to_bytes(input_list): """将字节串数组拼接成字节串 Args: input_list (list): 字节串列表 Returns: bytes: 拼接后的字节串 """ return b''.join(input_list)
7a2341540c131316ec0eebf06e3ffe447a95c9d6
80,055
def artifact_get_prep_req(user_id, artifact_ids): """Returns all prep info sample ids for the given artifact_ids Parameters ---------- user_id : str user making the request artifact_ids : list of int list of artifact ids Returns ------- dict of objects A diction...
e4bed2c64d610c15b396fb402305e00a923d4f76
80,057
from typing import Dict from typing import Optional def get_task_exhaustation_date( plan_worktime_dict: Dict[str, float], annotation_not_started: int, velocity_per_task: float ) -> Optional[str]: """ タスクの枯渇予定日を求める。 教師付されていないタスク数がすでに0ならば、Noneを返す。 Args: plan_worktime_dict: annotatio...
ae4d61398e856403614b47fa95dd7b90a02b07b5
80,058
def select_random_samples(dataset, n_samples, parse=False): """ Return the randomly picked desired number of samples in the provided dataset. Args: dataset (list): the dataset to consider; n_samples (int): the number of samples to pick from the dataset; parse (bool, False): whet...
ee0696d4c5b792710a4ed552b03bae9c2c749220
80,059
def rb_is_true(value: str) -> bool: """String to bool conversion function for use with args.get(...). """ return value.lower() == "true"
05835733e90e1bd756f8e1b02bb1c5683e628798
80,060
import numbers def check_random_affine(method): """Wrapper method to check the parameters of random affine.""" @wraps(method) def new_method(self, *args, **kwargs): [degrees, translate, scale, shear, resample, fill_value], _ = parse_user_args(method, *args, **kwargs) check_degrees(degrees...
28371f67726d772c17f100aeda486c2f2693ddee
80,061
def _get_variables_to_train(): """Returns a list of variables to train. Returns: A list of variables to train by the optimizer. """ if FLAGS.trainable_scopes is None: return tf.trainable_variables() else: scopes = [scope.strip() for scope in FLAGS.trainable_scopes.split(',')...
7f7ff358ebe70b5941b3eb015f6da7ec5323ebbe
80,064
def rotation_matrix_3d(axis: ArrayFloat, theta: float) -> ArrayFloat: """Return rotation matrix to rotate a vector in three dimensions. Makes use of the Euler-Rodrigues formula. Parameters ---------- axis : ndarray(dtype=float, dim=1) Normal axis around which to rotate. theta : float ...
ad9abe5bddb2826353e346695e8d8e922b5fb76e
80,065
from pathlib import Path import pickle def read_dataset3(paths: list, use_cache=True, cache_home='../data/output/cache'): """reading data set api for stacking model Arguments: paths: a list of string or pathlib.Path use_cache: if True and the cache existing, this api will read the cache i...
7364554403b1a25073c890f4ad6e955c2267fbe3
80,066
def get_Cm_MR(i, MR_installed, MR_power=None, MR_multi=None): """主たる居室の照明区画iに設置された照明設備の多灯分散照明方式による補正係数 Args: i(int): 照明区画 MR_installed(str): 主たる居室の設置 MR_power(str, optional): 主たる居室の照明器具の種類 (Default value = None) MR_multi(str, optional): 主たる居室の多灯分散照明方式の採用 (Default value = None) Retu...
3f608dd09d611019af50cf17545d281f6687bbe9
80,067
def unsupervised_sequence_loss( images, flows_sequence, unsupervised_loss_fn, # pylint:disable=g-bare-generic loss_decay = .8, supervision_weight = 0.05, mode = 'unsup_per_update', full_size_images = None, crop_h = None, crop_w = None, pad_h = None, pad_w = None): """Compu...
ebdf7826fe85b9444e0baf3fc70153303470d7bf
80,068
import graph_tool as gt from scipy.sparse import tril def get_graph_tool_from_adjacency(adjacency, directed=None): """Get graph_tool graph from adjacency matrix.""" adjacency_edge_list = adjacency if not directed: adjacency_edge_list = tril(adjacency) g = gt.Graph(directed=directed) g.add_...
291f990ffe6abab731c609a87d2106ec4ad52794
80,069
from typing import List from typing import Callable from typing import Tuple def _compute_moments_sampling(mf: np.ndarray, vf: np.ndarray, ind_winners: List[int], ind_loosers: List[int], nu2: np.ndarray, N: int=10000, get_logger: Callable=None) -> Tuple[float, np.ndarray, np.ndarray]: ...
0c7163f3f5b183ed2feafb0f1ab78bab47979fb8
80,070
def prune_urls(url_set, start_url, allowed_list, ignored_list): """Prunes URLs that should be ignored.""" result = set() for url in url_set: allowed = False for allow_url in allowed_list: if url.startswith(allow_url): allowed = True break ...
134c1fc3aa8482fc965de384bc588ceaf9323517
80,071
def nrmse(actual, target, **kwargs): """Returns RMSE(actual, target) / RMS(target). This gives the normalized RMSE, such that an output of ``0`` corresponds to ``actual=target`` while an output of ``1`` corresponds to ``actual=np.zeros_like(target)``. This is scale-invariant in the power of the tar...
121ae0f7d4e86b7e6117c18867ce24c020728455
80,072
def mean_face(array, plot_img=False) -> np.ndarray: """mean face of the training set and plot image if flagged""" m_f = array.mean(axis=1) if plot_img: plot_image(rotate_image(np.resize(m_f, pixel)), title='Mean Face') return m_f
fd536c0fa69003207c77e0080c0c391f2781c90b
80,073
def float_parser(val): """Must be between range 0 & 1.""" try: val = float(val) except ValueError: raise ArgumentTypeError(f'{val} must be float') if val < 0.0 or val > 1.0: raise ArgumentTypeError('Test split out of bounds [0,1]') return val
06badb62031638a79a3e68ccba9ec36e3d2f50b3
80,074
def _potential_domain_matches(domain): """ Potential domain matches for a cookie. >>> _potential_domain_matches('www.example.com') ['www.example.com', 'example.com', '.www.example.com', '.example.com'] From scrapy.http.cookies.potential_domain_matches(). """ matches = [domain] try: ...
0491f6175ba44f6c1a6ef07327478fc657d71776
80,075
import json def generate_thumbnail_download_link_vimeo(video_id_from_shortcode): """Thumbnail URL generator for Vimeo videos.""" # Following the Vimeo API at https://developer.vimeo.com/api#video-request, we need to request the video's metadata and get the thumbnail from that. First, then, we'll get the metadata ...
067af501899e68b7368233f700d2b51df4cef5b5
80,076
def _floats_array_feature(value): """Returns a float_list from a numpy array of floats / doubles.""" # https://stackoverflow.com/questions/47861084/how-to-store-numpy-arrays-as-tfrecord return tf.train.Feature(float_list=tf.train.FloatList(value=value.reshape(-1)))
f38609ea3bd711aaf0a2de7ec0dd697c2d6a2cc1
80,077
def latex_format(x, digits=2) -> str: """ Creates a LaTeX string for matplotlib plots. Parameters ---------- x: str The value to be formatted digits: int The number of digits to round up to. Returns ------- str: The math-ready string """ fmt_dgts = '...
3cb9c2d41a3e45f9e5b87493794fc505922df576
80,078
def find_latents(data: pd.DataFrame, min_loadings=2, mx_cor=None, underscript='', mode='spca', spca_alpha=1): """ Retrieve number of latent factors and their simple loadings. Simple loadings here mean the simplest model where none of latent factors have joint indicator. Furthermore, th...
58281b9c129c32e8228932d41bb6fb1cdf054ae0
80,079
def box_lidar_to_camera(data, r_rect, velo2cam): """box lidar to camera""" xyz_lidar = data[..., 0:3] w, l, h = data[..., 3:4], data[..., 4:5], data[..., 5:6] r = data[..., 6:7] xyz = lidar_to_camera(xyz_lidar, r_rect, velo2cam) return ops.Concat(axis=-1)([xyz, l, h, w, r])
8057b6269803d4d6f48d523acbb7c3c86be91093
80,080
from typing import Tuple from typing import Optional from typing import Sequence from typing import Dict from operator import gt def nested_model( adata: AnnData, max_iterations: int = 1000000, epsilon: float = 0, equilibrate: bool = False, wait: int = 1000, nbreaks: int = 2, collect_margi...
39b44a22d8e9077b188d420022711a127a733b49
80,081
import logging def handle(req): """Handle function""" try: # Get configuration config = get_config() # Ensure that the defined space exists check_space(config) # Check if defined folders exists check_folders(config) # Get the file from event file...
f53a9b90a3f57861638bb9eeea521211bbf58374
80,082
import torch def most_confident(scores, thresh=0.3): """ :param scores: (n_way, n_queries) :param thresh: float :return: """ confidence, idx = torch.sort(scores, dim=1, descending=True) d = (confidence.min(dim=0, keepdim=True).values > thresh).sum() idx = idx[:, :d] return idx
953d1699019bc6a325faa5b7f84a1c3de656ebf2
80,084
def is_component(node: nodes.Node, name: str): """Check if a node is a certain design component.""" try: return node.get("design_component") == name except AttributeError: return False
751abd134938e93f2203a62225fc3c589c67553a
80,085
import re def do_nothing_but_keep_debit_line( line, previous_line ): """ Debit lines to keep bc contains amount of next line but don't do nothing with it ( as in don't ask if it contains a vendor ) """ if ( 'str1' in line and line_start_w_date_allow_Oo(previous_line) ...
80c1f77d264f62a7775e5cf39fca9914bed93ae2
80,086
from typing import Tuple from typing import Dict def create_beam_and_attenuator_parameters( ispyb_params: IspybParams, ) -> Tuple[Dict, Dict]: """Create beam and attenuator dictionaries that nexgen can understand. Args: ispyb_params (IspybParams): An IspybParams object holding all required data. ...
6c89baa9f7d63a67c1166cae08bf23102e3e697a
80,087
def query_parcel_features(gis, parcel_list, where, fl_id, url, version): """Get a list of dicts containing the globalid and layer id of desired features by querying a FeatureLayer. Extract the GlobalID value from each feature and build up the correct dict format. This format is used in all ParcelFabri...
bde837ccb9689cbe3e6bc286a02c033621263b21
80,088
def gauss_fit1D(data, n_comp=1, comps=[''], bins=50, n_sample=100, title='', rand_state=42): """ gets intensity points and number of components and plots an approximate gaussian fit of the different components""" gmm = GM(n_components=n_comp, covariance_type='full', tol=0.0001, random_state=rand_state)....
d7c1ba0d98c766b73bd5c0cfeee40d10ee960171
80,089
def EdgeNode(*args, **kwargs): """ Edge between nodes Attrs: cls_node -> ObjectType EdgeNode target_model: StructuredNode Target model in edge relationship target_field: str Field name of <StructuredNode> target model resolver -> function (No...
500b1fe80af1dec9b0bd195fb611716d366bb3b2
80,090
def compareList(a, b): """Compare elements of lists, ignoring order (like sets).""" return len(intersect(a, b)) == len(a) == len(b)
1eda0690fff2027707a8378060560ae8df04702c
80,091
def run_linear_model_workflow(): """ Sample workflow using OneHotEncoder and LinearRegression. """ syncer_obj = Syncer.create_syncer("test1", "test_user", "pandas-linear-regression") data, target = load_pandas_dataset() syncer_obj.add_tag(data, "occupation ...
3b4da7e2b14752955c472705619045a9dae0da50
80,092
def split_train_test(data, labels, dim): """ Method that randomly choose the train and test sets from data and labels. # Arguments: data: Numpy matrix with data for extract the validation data labels: Numpy array with labels dim: Size for validation data # Returns: new_...
3716e5a7948d09b23f6497475fa95ab34cb52841
80,094
def parse_engine(config: Config) -> Engine: """Parses an SQLAlchemy engine from a config object. Parameters ---------- config: Config Configuration object to parse engine from. Returns ------- Engine SQLAlchemy engine. """ config = config.parse(PARSER) return sa...
3c050675b9e226e87ce018ff12646ecd621e3934
80,096
from typing import Optional def get_input_label( port: Port, gc: ComponentReference, gc_index: Optional[int] = None, gc_port_name: str = "o1", layer_label: Layer = gf.LAYER.LABEL, component_name: Optional[str] = None, get_input_label_text_function=get_input_label_text, ) -> Label: """R...
0fc4cb3eb5613fca506d5456f6f4b3edc81d22d6
80,097
from ._statistics_entry import STATISTICS_ENTRY from .._tier0 import push from typing import Union def push_regionprops(props : Union[dict, RegionProperties], first_row_index : int = 0) -> Image: """ See Also -------- STATISTICS_ENTRY Parameters ---------- props Returns ----...
0c61bdd5477227b0c7a088f56576a9323f33d491
80,098
def sum_divisible_by_n(target, n): """ Note that for 5: 5+10+15+...+995 = 5*(1+2+....+199) Also note: 1+2+3+...+p = ½*p*(p+1) """ p = target // n return n * (p * (p + 1)) // 2
3dc42da324d19813242b27ff9794ce85163ab7f0
80,099
import typing def minmax(p: dolfin.Function, *, mode: str = "raw", take_abs: bool = False) -> typing.Union[typing.Tuple[float, float], typing.Tuple[typing.List[float], typing.List[f...
7444cfbc89803a66e2f5ba45b20088167d62f1ea
80,100
def dict_to_obj(our_dict): """ Function that takes in a dict and returns a custom object associated with the dict. This function makes use of the "__module__" and "__class__" metadata in the dictionary to know which object type to create. """ if "__class__" in our_dict: # Pop ensures we ...
a6407e4629ada54d63a0d5b6285320f1ea85b4eb
80,102
import json import yaml def load_object_from_file(filename, f_format=None): """ Implicitly load an object from a file. just a friendly wrapper to load_object() Args: filename (str): the filename to load an object from f_format (str): the serialization format (default is auto-detect ba...
4b5414badffbd891f99ebdd8589a229716344535
80,103
from typing import Tuple def _heappop(priorities, indices, length) -> Tuple: """Pop the smallest item off the heap, maintaining the heap invariant.""" lastelt, length = _arr_pop( priorities, indices, length ) # pylint: disable=unbalanced-tuple-unpacking if length > 0: returnitem = _ge...
1a4095604bb415864515eda1204f4a1ee91415e0
80,104
def GlobalMaxPool(onnx_node, ng_inputs): # type: (NodeWrapper, List[TensorOp]) -> Op """Equivalent to MaxPool with kernel size equal to spatial dimensions of input tensor.""" return cast_to_pos_axes(make_global_pooling_op(onnx_node, ng_inputs))
0c0abbc6b04e17d8f3313113413d39b7766c9beb
80,105
def index(request): """ The view for the index with different subjects to pick from. :param request: A HTTPRequest object for the landing page :return: A HTTPResponse object, the rendering of the index.html page """ return render(request, "NYRP/index.html")
4a39d94c39abe661c17b59403647ccf2ea5bd0a3
80,106
def invalid_ds_vsby(i, v): """Checks if visibility is inconsistent with DS or SS""" if i == '+' and v >= 0.3: return True elif i == '' and not 0.3 < v < 0.6: return True return False
c4ee05f4ce8b19f76dfdc1847dc8f3eaf7e1b11b
80,107
def get_deadline_day_name(cur): """Return the name of the deadline day.""" sql = "SELECT dayname(`deadline`) FROM ec_fluv_round" execute_sql(cur, sql) name = None for (name,) in cur: pass if name is None: raise Exception('couldnt get name of deadline day') return name
10e48b51187e49685736c213f4e25bd0efd05c4d
80,108
def make_writer_from_reader(pdf_reader, editable): """ Creates a PdfFileWriter instance from the content of a PdfFileReader instance. Depending on parameter editable, it will be possible to modify the fields of the file produced by the returned writer. Args: pdf_reader (PdfFileReader): an instance of PdfFileRea...
c27d42d5ea070171dbcaf39d2508e4e52037070d
80,109
def set_room_info(room_id: str, table: str, where: str, value: str) -> bool: """Modify room values.""" data = { "filename": room_id, "folder": "rooms", "table": table, "set_values": value, "where": where } success = utils.call_db( event="update table", ...
5249627833dfc2ecc4d75c46dbb37be1222e9add
80,110
def user_tickets(user, conference, only_complete=False): """ Returns the tickets associated with the user (because s/he bought them or because they've been assigned to him/her) """ qs = _user_ticket(user, conference) if not only_complete: return qs else: # I'm not showing tic...
fba9aca73d485522f85607c30e800c4eaa622ce9
80,111
from datetime import datetime def get_from_to_datetime_last_month(): """Get a period for last month. This will return two dates in ISO 8601:2004 format The first date will be at 00:00 in the first of last month, and the second date will be at 00:00 in the first day in this month. Both dates i...
18f2163b9dccd715f8b9d278bb0228d11d3f7040
80,112
def _truncate_string(text, max_length=MAX_LENGTH): """ Keep string fields to a max width in the admin UI >>> _truncate_string('test@example.com') 'test@example.com' >>> _truncate_string('thirty@charactersistoolong.com') 'thirty@charactersistoolong.com' >>> len(_truncate_string('thirty@chara...
4995f92c2a152d6e952bc5fdf1c01918d6cb69b7
80,115
def test_COGReader_Options(): """Set options in reader.""" with COGReader(COGEO, nodata=1) as cog: meta = cog.metadata() assert meta["statistics"][1]["pc"] == [2720, 6896] with COGReader(COGEO, nodata=1) as cog: _, mask = cog.tile(43, 25, 7) assert not mask.all() with C...
9cf365c39cd847ef68386389936f2ff0494e1442
80,116
def get_current_store(**kwargs): """ gets current database store. note that this method will always get the correct session based on available context. so if you are in an atomic context, it gets you the correct atomic session, but if you are not in an atomic context, it will get you the related ...
4ca51716f565c1d6511ef7ece5882f9fed1d6b0b
80,117
from pathlib import Path def predict_fingerprints(data, path_parameters: Path, path_scales: Path): """Predict data using a previously trained fingerprint model.""" # FullyConnected NN net = FingerprintFullyConnected(hidden_cells=100, num_labels=NUMLABELS) return call_modeller(net, data, data.fingerpri...
85fb1ff9eea2f05f50ec28ff100ac424c15f2e1b
80,118
def averageCoords(coordList): """ http://stackoverflow.com/questions/23020659/fastest-way-to-calculate-the-centroid-of-a-set-of-coordinate-tuples-in-python-wi""" avg = np.zeros(3) for c in coordList: avg += c return avg / len(coordList)
4b3759dc9276f5c67a3d90cd6ab65dfca742a215
80,120
def helloworld(data, name): """Executes the Hello World Process""" try: from greetings import GetGreeting except: from .greetings import GetGreeting pcshell.echo('\n{} {}. Details are below:'.format(GetGreeting(), name)) if IsShell: if data: pcshell.echo('\n\tProvided O...
cde811a9ba57c23b9477bea3c1c6d4083dc68ae0
80,121
def sinc(x, w): """ Sinc function. Inputs: - x [ArrayLike]: Input data - w [float]: Inverse mainlobe width Outputs: - y [ArrayLike]: Output data """ xz = np.abs(x) > 1E-4 pat = np.zeros(x.shape) pat[xz] = np.sin(pi*w*x[xz])/pi/x[xz]/w pat[np.logical_not...
aa978da3b6d776d303bc6f721041190d94aa1028
80,122
def tag_dd_lambda_layer(tags): """ Used by lambda_metric to insert the dd_lambda_layer tag """ dd_lambda_layer_tag = _format_dd_lambda_layer_tag() if tags: return tags + [dd_lambda_layer_tag] else: return [dd_lambda_layer_tag]
3ec201a9ef4c56b5b04292c4f5dcea833d4ebad0
80,123
def get_valid_test_pipeline(): """Return an arbitrary pipeline definition.""" return { 'sg1': [ 'step1', 'step2', {'name': 'step3key1', 'in': {'in3k1_1': 'v3k1', 'in3k1_2': 'v3k2'}}, 'step4' ], 'sg2': False, ...
23611472d2cb0d513c59cec42d45893cb328303f
80,124
import torch def instance_propagate(annots_inst, masks_inst, is_sequence=True): """ propagate the last valid instance to the last position. Args: annots_inst: (inst, [seq,] ..., dim) masks_inst: (inst, [seq,] ...) Returns new_annots, new_masks Notes: inst-first...
f8f231b1e2601df2c634458a8db34407f910cd51
80,125
def _ToCamelCase(name): """Converts name to camel-case and returns it.""" capitalize_next = False result = [] for c in name: if c == '_': if result: capitalize_next = True elif capitalize_next: result.append(c.upper()) capitalize_next = False else: result += c # L...
eeea26eebc3a1c639a415cf4a8ce6ab03c54befc
80,126
def conv2d_op_support(X, bXs, tXs): # Type: (XLayer, List[XLayer], List[XLayer]) -> boolean """ Check whether we can execute the provided Conv2D operator on the ultra96 target """ data_layout = X.attrs['data_layout'] kernel_h, kernel_w = X.attrs['kernel_size'] stride_h, stride_w = X.attrs[...
954076cb22e9459cdc8bedd38100c33e91b946db
80,127
from typing import Dict from typing import Any from typing import Type from typing import Union from typing import List def get_type_name(property_dict: Dict[str, Any]) -> str: """Filter. Return the type of a property taking into account the type of items for array and enum""" def _python_type_to_json_type(p...
268c2387a6f9fc088d7939fedfe8f76b322b32d1
80,128
def tconcatv(*seqs): """ >>> tconcatv([], [1], (2, 3)) (1, 2, 3) """ return tuple(concatv(*seqs))
7a7a30ead36f7b3764b41e3cef48eaef02899e75
80,130
def find_superpixel(Yt, cut_off_point, length_cut, eight_neighbours=True): """ Find superpixels in Yt. For each pixel, calculate its correlation with neighborhood pixels. If it's larger than threshold, we connect them together. In this way, we form a lot of connected components. If its length is large...
673bc3e96833c1f80e3eb994c780511727e1f3a9
80,132
def get_first_layer_props(compound_name, first_layer_props): """ 1. Accepts the compound name as a String and the required first layer props as a List 2. Finds its CID 3. Creates a link to PubChem PUG REST API to get the required properties 4. Returns a dictionary with the...
de046f19e092a2d977914a70487c404b3940c102
80,133
def rectangle(rect: Rect, attributes=()): """ Returns an SVG rectangle element as string. :param rect: `Rect` geometric primitive :param attributes: list of SVG attributes :return: <rect x="" y="" width="" height="" ... /> """ return __rect_template \ .replace('{{x}}', str(rect.orig...
f8dd2b0967d55037e73e22e20bb10d3ca11e5b64
80,134
def common_columns(df_a, df_b=None, exclude_cols=[]): """ Common columns given two dataframes, preserve the order of the second dataframe :param df_a: first dataframe :param df_b: second dataframe :param exclude_cols: column names to exclude :return: a list of column names, preserving the ord...
3fa4e9cca1da70cc4538fa6b0a870814bf69fe20
80,135
import re def parse_args(args, strict=True): """Utility for parsing macro "content" and splitting them into arguments. The content is split along commas, unless they are escaped with a backquote (see example below). :param args: a string containing macros arguments :param strict: if `True`, only...
e2291e31e2ed7b51bf61e95ebde0586f353cbbd2
80,136
def get_client(region_name=DEFAULT_REGION): """ Get a boto3 client for the Amazon Lookout for Equipment service. PARAMS ====== region_name: string AWS region name. (Default: eu-west-1) RETURN ====== lookoutequipment_client A boto3 client to inter...
73d87b96b7f546db6178db2df716c9a1f866b5db
80,137
from nidm.core import Constants from nidm.experiment.Core import getUUID import prov def convert_stats_to_nidm(stats): """Convert a stats record into a NIDM entity Returns the entity and the prov document """ fsl = prov.model.Namespace("fsl", str(Constants.FSL)) niiri = prov.model.Namespace("nii...
6038e134d7436172fb21ab253efda67883b26188
80,138
from typing import Callable from typing import get_type_hints import functools def type_check(func: Callable, check_return_type: bool = True) -> Callable: """Decorator that validates the type of the parameters as well as the return value of a function against its type annotations during runtime. Parameter...
e40213674a7d7b750c00cf4cc131b27971f96191
80,139
def while_loop(cond, func, loop_vars, max_iterations=None, name="while_loop"): """Run a while loop with user-defined computation and loop condition. This operator simulates a while loop which iterately does customized computation as long as the condition is satisfied. `loop_vars` is a list of NDArrays...
48f3339bca96825e15663211c6dba464460399b5
80,140
def humiExecute(ip, token, model): """New model https://python-miio.readthedocs.io/en/latest/api/miio.airhumidifier_miot.html""" if model == miio.airhumidifier_miot.SMARTMI_EVAPORATIVE_HUMIDIFIER_2: # "zhimi.humidifier.ca4" return miio.airhumidifier_miot.AirHumidifierMiot(ip, token) else: r...
f92d52a4fb8327fff60c2c7a5ac17b8caec82e8d
80,141
def user_base_info(): """ 宣言基本资料界面 :return: """ user = g.user if request.method == "GET": data = { "user_info":user.to_dict() } return render_template("news/user_base_info.html",data = data) nick_name = request.json.get("nick_name") signature = reque...
c740fd7088ebc575d3e55e6c60c0e035c844aeef
80,142
def models_validation(X, y, model_paramGrid_list, scale_list=None, test_size=0.2, time_series=False, random_state=123, n_folds=5, regr=True, plot=False, plot_train=False, xvalues=None, xlabel="Models", title="Models validation", figsize=(6,6)): """ Select the best mod...
c27899569ec0ecfd011f10e5cc37dc67ed6eb270
80,143
import random def random_rotate_reflect_90(pic: Image): """Randomly applies one of the following transformations: - `None`: leaves the image as is. - `Image.ROTATE_90`, `Image.ROTATE_180`, `Image.ROTATE_270`: rotates by 90, 180, or 270 degrees respectively. - `Image.FLIP_LEFT_RIGHT`: reflects the imag...
7c84c696553200f94d3af48276143a294fa1da03
80,144
def binary_opening(image, footprint=None, out=None): """Return fast binary morphological opening of an image. This function returns the same result as grayscale opening but performs faster for binary images. The morphological opening on an image is defined as an erosion followed by a dilation. Ope...
c0951b41d50847e76fb7fcd426b3c5d84cc67833
80,146
def get_duration_in_time( duration ): """ Calculate the duration in hh::mm::ss and return it @param duration: timestamp from the system @return: formatted string with readable hours, minutes and seconds """ seconds = int( duration % 60 ) minutes = int( (duration / 60) ...
bcd6413b32183688c8b2aac428c5f9bfd5d34b8e
80,147
def get_hermite_polynomial(n): """ Returns a ``np.poly1d`` object representing the degree-n Hermite polynomial. Adapted from https://scipython.com/blog/the-harmonic-oscillator-wavefunctions/. """ assert isinstance(n, int) and n >= 0, "need positive integer" Hr = [None] * (n + 1) Hr[0] = np...
6affb660a69f2face3d1b4e1c54266a24fba45dd
80,148
def ConvertEmailToMembershipResourceName( version, args, group_arg_name, member_arg_name): """Convert email to membership resource name. Args: version: Release track information args: The argparse namespace group_arg_name: argument/parameter name related to group info member_arg_name: argument/...
ec1ca4688ca1b89ce8f3268b731410e225547bd2
80,149
from typing import List def generate_handler_go(package: str, routes: List[Route]) -> str: """ Generate a file which defines the handler interface. :param package: name of the package :param routes: that a handler will handle :return: Golang code """ text = _HANDLER_GO_TPL.render( ...
017cecdbc349aa5e7c251e37c85a7a3a5d01cb66
80,151
def check_submission_subreddit(submission_to_check): """Check if the passed in submission is in a subreddit that should be skipped""" if args.skip_subreddits is not None: return ( submission_to_check.subreddit.display_name in args.skip_subreddits ) return None
119c7795a604681e79e57b91f2562563741d1b8d
80,152
import torch def smooth_l1_loss(input, target, beta: float, reduction: str = "none"): """ Smooth L1 loss defined in the Fast R-CNN paper as: | 0.5 * x ** 2 / beta if abs(x) < beta smoothl1(x) = | | abs(x) - 0.5 * beta otherwise, where x = input - target. ...
239fcc894415b1cfeac98acef1e4193bd3bec6d0
80,153
from datetime import datetime def _datetime_palantir_format() -> str: """Returns datetime str in format used by palantir data enclave e.g. 2021-03-03T13:24:48.000Z (milliseconds allowed, but not common in observed table)""" return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ")[:-4] + 'Z'
fd2f172f0051cc36fc5a7f0666c3675c76b806f2
80,154
def elimate_leading_whitespace(source, target=None): """ return the count of whitespaces before the first target if it is not the mode: <whitespace>*_target_, return 0 """ if not source: return 0 i, length = 0, len(source) while i < length: if source[i] not in ' \t': ...
474bb0094bb8c7f39dd76aa85b72c26af321eb1a
80,155
def set_(data_type): """ Create an alias for a SetType that contains this data type """ return frozenset([data_type])
3ffbe4e111506c5897793cfe423cbbe55137de53
80,156
def test_caching_string(machine_persistent): """ Проверка работы декоратора """ @machine_persistent.cache_call_using_strings() def func(x, y): return x + y assert func(1, 2) == 3 assert func(2, 3) == 5 assert func(1, 2) == 3 assert machine_persistent.keys() == ['func_1_2',...
26f6d736d5249c4a45771b2e46cfe386374d0da4
80,158
def get_test_metrics( scores, labels, mindcf_p_target=1e-2, mindcf_c_fa=1, mindcf_c_miss=1, prefix=None ): """ Return EER and minDCF metrics """ metrics = { "eer": compute_eer(scores, labels), "mindcf": compute_mindcf( scores, labels, p_target=mind...
d4b8d06e59538ca9038d7a519f9dd270bf9d31f2
80,159
import json def indicator_from_event(request): """ Create an Indicator from an Event description. Should be an AJAX POST. :param request: Django request object (Required) :type request: :class:`django.http.HttpRequest` :returns: :class:`django.http.HttpResponse` """ if request.method == ...
4c02cce4645733541d52f2f3a5fff08ca7f48a15
80,161
import numpy def residueToResFragmentDistance_direct ( res, fragInfo, settings ): """ This function computes the procrustes optimal overlay of all available atoms and then proceeds to obtain the RMSD of these atoms. Parameters ---------- list : res A list containing the positions and ...
3432a210dde97ea014c2d12c88ab279fbdf9c94d
80,162
from dallinger_experiment.experiment import Bot def bot_factory(url): """Import the current Bot class, which must be done at runtime, then return an instance. """ return Bot(url)
464e57c023341f3def7ca08851a64698a8756ce4
80,163
from typing import Union from typing import Iterable from typing import Tuple def n_chars_per_word(doc_or_words: Union[Doc, Iterable[Token]]) -> Tuple[int, ...]: """ Compute the number of characters for each word in a document. Args: doc_or_words: If a spaCy ``Doc``, non-punctuation tokens (words...
d8354b53a0fdbdebba10ca08593e8b9c4cea4433
80,164
def ne_on_aff_funcs(self, y_with_uncert): """ __ne__ operator, assuming that both self and y_with_uncert are AffineScalarFunc objects. """ return not eq_on_aff_funcs(self, y_with_uncert)
6de062af91b64e1e76f336d4d480750128d713c1
80,165
def mobilenetv3_small_wd2(**kwargs): """ MobileNetV3 Small 224/0.5 model from 'Searching for MobileNetV3,' https://arxiv.org/abs/1905.02244. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.chainer/models' ...
161aed5219f652a411e3e847ed8217e8dc4e2d16
80,166
def calculate_psnr(img1, img2, crop_border, input_order='HWC', test_y_channel=False): """Calculate PSNR (Peak Signal-to-Noise Ratio). Ref: https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio Args: img1 (ndarray): Imag...
cda3ec403ef70bb6aefed0f3b21582c6637d84af
80,167
import math def ceil(quantity, units): """Compute the ceiling of a quantity with units. :param quantity: the quantity to take the ceiling of :param units: the units to convert to before taking the ceiling, and of the result :returns: the ceiling of quantity, measured in units """ number = qua...
5aa16db252e4ecbb17876a53615b4d4f796f3946
80,169