content
stringlengths
22
815k
id
int64
0
4.91M
def data_artifacts(X_train): """ Creates and stores data artifacts like a sample of the data, the features and indices. --------------------------------------------------- Parameter X_train: The pandas data frame right before it enters the algorithm in the last but one step the pipeline. """ ...
52,100
def precut(layers, links, all_terms, user_info): """ This function cuts terms in layers if they do not exist inside the accuracy file of model 1. It also cuts all links if one of the terms inside does not exist inside the accuracy file of model 1. Finaly it cuts all terms taht do not exist insid...
52,101
def dele(fpath): """ 删除文件 :param fpath: 文件路径 :return: 无 """ if os.path.exists(fpath): os.remove(fpath)
52,102
def main(args): """ Main entry point """ retish = User.objects.get(username='retish') issue_txt = ( "Some ECMWF variables are not true monthly or daily means and are " "instead calculated from instantaneous values at the frequency they " "are output. Experiments and members a...
52,103
def computeMeanStd_binned_old( inDatas, valCol, binCol, binMin, binMax, binCount ): """Compute binned stats for a set of tables""" sums = np.zeros( binCount ) sumsSq = np.zeros_like( sums ) counts = np.zeros_like( sums ) bins = np.linspace( binMin, binMax, binCount+1 ) binSize = ( binMax - binMin ) / binCo...
52,104
def Compute7(surface, multiple=False): """ Computes an AreaMassProperties for a surface. Args: surface (Surface): Surface to measure. Returns: AreaMassProperties: The AreaMassProperties for the given Surface or None on failure. """ url = "rhino/geometry/areamassproperties/compu...
52,105
def instantiate(config: Optional[Union[str, ClassDescription]], *args, **extra_kwargs): """Instantiates class given by `config.cls` with optional args given by `config.args` """ try: if config is None: return None elif type(config) is str: cls = _locate(config) ...
52,106
async def get_hm_generic_entity( central_unit: CentralUnit, address: str, parameter: str ) -> GenericEntity | None: """Return the hm generic_entity.""" hm_device = get_hm_device(central_unit, address) assert hm_device hm_entity = hm_device.entities.get((address, parameter)) assert hm_entity ...
52,107
def dists2corners_numpy(a): """ :param a: dist ndarray, shape = (*, h, w, 4=(t, r, b, l)) :return a: Box ndarray, shape is (*, h, w, 4=(xmin, ymin, xmax, ymax)) """ assert a.ndim >= 3, 'must be greater than 3d' h, w, _ = a.shape[-3:] # shape = (*, h, w, 4=(xmin, ymin, xmax, ymax)) ret =...
52,108
def test_insert_root(): """Test inserting a root value.""" tree = BST() tree.insert(5) assert tree.root.val == 5
52,109
def cryptowatch_ohlc_data_for_pair(Pair): """gets ohlc data from cryptowatch, and return a dict of dataframes""" exchanges = list(Pair.markets) data = {} for ex in exchanges: data[ex] = cryptowatch_ohlc(Pair.name, ex, Pair.period, Pair.start, Pair.end) return data
52,110
def to_string_stream(x): """ For modules that require a encoding as ``str`` in both Python 2 and Python 3, we can't just encode automatically. """ if PY2 and isinstance(x, text_type): x = x.encode('utf-8') return StringIO(x)
52,111
def install_thread_excepthook(): """ Workaround for sys.excepthook thread bug (https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1230540&group_label=5470). Call once from __main__ before creating any threads. If using psyco, call psycho.cannotcompile(threading.Thread.run) since this r...
52,112
def get_all_scores(pdb_path, reference_pdb_path): """Assigns scores (lrmsd, irmsd, fnat, dockQ, bin_class, capri_class) to a protein graph Args: pdb_path (path): path to the scored pdb structure reference_pdb_path (path): path to the reference structure required to compute the different score ...
52,113
def test_modelparams_obj(): """ Test the behavior of the `ModelParams` object Test the instantiation and attribute data for the `ModelParams object of the `stratified_plume_model` module. """ # Get the ambient CTD data profile = get_profile() # Initialize the ModelParams object p ...
52,114
def run_epoch(model, data, optimizer): """ Run a train and validation epoch and return average bpd for each. """ traindata, valdata = data model.train() train_bpd = epoch_iter(model, traindata, optimizer) model.eval() val_bpd = epoch_iter(model, valdata, optimizer) return train_bpd...
52,115
def special_loss(logits, labels): """ This loss (and the rest of the training procedure) was taken from Philipp Kraehenbuehl's code. """ mask = labels != 255 labels1 = tf.clip_by_value(labels, 0, 1) lz = tf.nn.softplus(-tf.abs(logits)) * mask return tf.reduce_sum(lz + (tf.to_float(logits...
52,116
def tobs(): """Return a list of all tobs for the most active station as a list of JSON""" # Query most active station station_list = session.query(Measurement.station, func.count('*')).group_by(Measurement.station).order_by(func.count(Measurement.station).desc()).all() mostactive=station_list[0][0]...
52,117
def tempdir(): """ Create a temp directory to store the generated files. """ tempdir = tempfile.mkdtemp(prefix='sphinx-refdoc-e2e-tests') yield tempdir shutil.rmtree(tempdir)
52,118
def _get_assignment_data_matches(net, mapping_assignment_dataloader, config, sobel=False, using_IR=False, get_data_fn=None, just_matches=False, verbose=0):...
52,119
def prox_max_entropy(X, step, gamma=1, type="relative"): """Proximal operator for maximum entropy regularization. g(x) = gamma sum_i x_i ln(x_i) has the analytical solution of gamma W(1/gamma exp((X-gamma)/gamma)), where W is the Lambert W function. If type == 'relative', the penalty is expressed...
52,120
def phase_vocode(audio_data: np.ndarray, speed: float) -> np.ndarray: """Applies phase vocoding to a 'np.ndarray' representing WAV data.""" reader = ArrayReader(audio_data.transpose()) writer = ArrayWriter(reader.channels) phasevocoder(reader.channels, speed=speed).run(reader, writer) return writer....
52,121
def fullPathListDir(dir: str) -> list: """ Return full path of files in provided directory """ return [os.path.join(dir, file) for file in os.listdir(dir)]
52,122
def test_filesystem_trigger_serialization(): """ Asserts that the TaskStateTrigger correctly serializes its arguments and classpath. """ trigger = FileTrigger(filepath="/files/dags/example_async_file.py", poll_interval=TEST_POLL_INTERVAL) classpath, kwargs = trigger.serialize() assert classp...
52,123
def test_extract_point_df(): """Test if the shape of dataframe is correct.""" df45 = base.read_shape(shapefile, route_num) shape = base.extract_point_df(df45).shape assert shape == (208,1), " Shape of df(route 45) coordinates should be (208,1)" return
52,124
def partion_data_in_two(dataset, dataset_labels, in_sample_labels, oos_labels): """Partition dataset into in-distribution and OODs by labels. Args: dataset: the text from text_to_rank dataset_labels: dataset labels in_sample_labels: a list of newsgroups which the network will/did train on oos_label...
52,125
def check_and_update_generation_args(args): """ checks all generation commandline arguments. Since these arguments are all lists and shorthand can be used, we expand them to match the expected length for instance, [1.0] becomes [1.0 1.0] if all other generation arguments are of length 2 """ hyperpar...
52,126
def create_django_config_file(site_url, emails, locations, django_config_path, db_path): """Creates a site specific Django configuration file. Settings that are common for all sites reside in the wwwhisper_service module. """ settings = """# Don't share this with anyb...
52,127
def usedir(dir): """ Helper for 'with' statements that changes the current directory to @dir and then changes the directory back to its original once the 'with' ends. Can be thought of like pushd with an auto popd after the 'with' scope ends """ curr = os.getcwd() os.chdir(dir) try: ...
52,128
def category_condition_disable(request, structure_slug, category_slug, condition_id, structure): """ Disables a condition from a category :type structure_slug: String :type category_slug: String :type condition_id: Integer :type structure: OrganizationalStructure ...
52,129
def stitch_image_pair(img_a, img_b, stitch_direc): """Function to stitch image B to image A in the mentioned direction Args: img_a (numpy array): of shape (H, W, C) with opencv representation of image A (i.e C: B,G,R) img_b (numpy array): of shape (H, W, C) with opencv representation of image B...
52,130
def write_plugged_timeouts(screen_dim, screen_off, computer_suspend): """Writes the timeouts (in seconds) for screen dimming, screen off and computer suspend when the computer is on mains to the Chrome OS power manager configuration files.""" write_value(os.path.join(POWERMAN_CONF_DIR, "plugged_dim_ms")...
52,131
def as_composite(identifier: str) -> str: """ Translate the identifier of a mapry composite to a composite name in Python. :param identifier: mapry identifier of a composite :return: translated to a Python identifier of a composite >>> as_composite(identifier='Some_URL_class') 'SomeURLClass' ...
52,132
def find_saturation(freq, saturation_values, attenuation): """ Return a saturation value based on the frequency and amount of attenuation :param int freq: the freq of interest, in Hz :param saturation_values: a dict containing the saturation values (keys are frequencies) :param attenuation: the amo...
52,133
def test_display_addr_refs_no_offset(): """should display n/a for offset when there are no offset bits""" sim = Simulator() refs = sim.get_addr_refs( word_addrs=WORD_ADDRS, num_addr_bits=8, num_tag_bits=4, num_index_bits=4, num_offset_bits=0) apply_cache_statuses_to_refs(['miss'] * 12, r...
52,134
def lstm_temporal(x, h0, Wx, Wh, b): """ Forward pass for an LSTM over an entire sequence of data. We assume an input sequence composed of T vectors, each of dimension D. The LSTM uses a hidden size of H, and we work over a minibatch containing N sequences. After running the LSTM forward, we return ...
52,135
def get_info_hardware(): """Create a dictionary for CPU information.""" def _cpu_freq(): """psutil can return `None` sometimes, esp. in Travis.""" func = "psutil.cpu_freq: " try: hz = psutil.cpu_freq() except IOError: return (func + "IOError",) * 3 # See...
52,136
def read_main_results_file(): """Return a Series where each row is one of the COMSOL Main results""" results_filepath = Path(MAIN_RESULTS_FILENAME) results_series = pd.read_table(results_filepath, sep=" ", squeeze=True, ...
52,137
def commandProjector(cmd): """Send commands to a locally-connected projector""" make = "Optoma" if make == "Optoma": ser = serial.Serial("/dev/ttyUSB0", 9600, timeout=0, parity=serial.PARITY_NONE, stopbits=serial....
52,138
def coveralls_enable(request): """Enable coveralls for an experiment""" experiment = get_experiment_from_request_post(request) travis_instance = experiment.travis if travis_instance.enabled: existing_config = enable_coveralls(travis_instance) github_helper = get_github_helper(request, e...
52,139
def download_book(book_id, title, thumbnail, rating_text): """ Download book id=`book_id` by calling the website's `getPage(.,.,.)` function. """ print('in download_book, book_id =', book_id) with WebDriver("http://3asafeer.com/", delay=LOADING_WAIT_TIME_MS) as driver: if DEBUG_MODE: ...
52,140
def games_per_time_period(df, days_per_period=7): """Return list of describing n matches played each time period in days, from start to end of dataframe""" # define start and end dates to observe start = df['date'].min() # end is specified as 6 days after recorded final date of play, so pd.date_range be...
52,141
def train_agent(output_path: str, lr: float = 0.1, exploration_iterations: int = 2500, exploitation_iterations: int = 1500, exploration_exploitation_iterations: int = 1000) -> None: """ Trains a new agent. Parameters ---------- output_path: str Where to save agent's weights....
52,142
def patch_all(): """ Runs all patches. This function ensures that a second invocation has no effect. """ global _patched if _patched: return _patched = True patch_default_retcodes() patch_worker_run_task() patch_worker_factory() patch_keepalive_run() patch_cmdline_p...
52,143
def get_image_dims(image_data, check_is_rgb=False): """Decodes image and return its height and width. Args: image_data: Bytes data representing encoded image. check_is_rgb: Whether to check encoded image is RGB. Returns: Decoded image size as a tuple of (height, width) Raises: ValueError: If ...
52,144
def open_mic_stream(pa, device_index, device_name): """ Open microphone stream from first best microphone device. """ if not device_index and device_name: device_index = find_input_device(device_name) stream = pa.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, inp...
52,145
def importPostgres( connection, desiredColumns, desiredTable, verbose): """Import data from a postgres database""" # making function more explicit address = connection desiredColumns = desiredColumns desiredTable = desiredTable verbose = verbose # inform ...
52,146
def write_config(config): """Writes config to .popper.yml file.""" config_filename = os.path.join(get_project_root(), '.popper.yml') with open(config_filename, 'w') as f: yaml.safe_dump(config, f, default_flow_style=False)
52,147
def main(): """ Top-level function for health service """ service = MagmaService('health', None) # Optionally pipe errors to Sentry sentry_init(service_name=service.name, sentry_mconfig=service.shared_mconfig.sentry_config) # Service state wrapper obj service_state = ServiceStateWrappe...
52,148
def color_threshold(img): """ RGB color space threshold :param img: Undistorted image :return: Thresholded binary image Ref: Course notes """ yellow = select_yellow(img) white = select_white(img) combined_binary = np.zeros_like(yellow) combined_binary[(yellow >= 1) | (white >= 1)...
52,149
def perturb_box(box, min_iou=0.5, sigma_factor=0.1, rng=None): """ Perturb the input box by adding gaussian noise to the co-ordinates args: box - input box min_iou - minimum IoU overlap between input box and the perturbed box sigma_factor - amount of perturbation, relative to the box s...
52,150
def smootherstep(a, b, x): """Improved S-curve interpolation function. Based on reference implementation of the improved algorithm proposed by Ken Perlin that is available at https://en.wikipedia.org/wiki/Smoothstep """ x = clamp((x - a)/(b - a), 0.0, 1.0) return x*x*x*(x*(x*6 - 15) + 10);
52,151
def _clean_conargs(**conargs): """Clean connection arguments""" conargs['metadata'] = [x.strip() for x in conargs['metadata'].split(',') if x.strip()] return conargs
52,152
def select_customer(): """Select customers from customer_name.""" cursor = mysql.cursor(MySQLdb.cursors.DictCursor) TRN = request.form['TRN'] cursor.execute('''SELECT * FROM Customer WHERE TRN=%s''', (TRN,)) data = cursor.fetchone() if data: re...
52,153
def is_date(string): """ Returns whether the string can be interpreted as a date from using Python's dateutil.parser library. If it can parse, it will return true, and false otherwise. """ try: parse(string, fuzzy=False) return True except ValueError: return False
52,154
def get_adt_table( args: argparse.Namespace, edw: pyodbc.Connection, query_directory: str, ) -> pd.DataFrame: """ Get ADT table through one of the following methods: 1. Provide ADT table i. Filter patients by MRN ii. Filter temporally a. By encounter (CSN) ...
52,155
def rosin_rammler(nbins, d50, md_total, sigma, rho_p, rho): """ This function is deprecated: Use psf.rosin_rammler() instead. Return the volume size distribution from the Rosin Rammler distribution Returns the fluid particle diameters in the selected number of bins on a volume basis from ...
52,156
def _get_layer(layer_idx, nn, for_pres): """ Returns a tuple representing the layer label. """ if nn.layer_labels[layer_idx] in ['ip', 'op']: fill_colour = _IPOP_FILLCOLOR elif nn.layer_labels[layer_idx] in ['softmax', 'linear']: fill_colour = _DECISION_FILLCOLOR else: fill_colour = _FILLCOLOR lab...
52,157
def inc_duration(win_size: int, olap_size: int, fs: float) -> RSTimeDelta: """ Get the increment between window start times If the overlap size = 0, then the time increment between windows is simply the window duration. However, when there is an overlap, the increment between window start times has...
52,158
def get_nearest(kd_node, point, dim, dist_func, return_distances=False, i=0, best=None): """ Find the closest neighbour of a point in a list of points using a KD-Tree. Based on a recipe from code.activestate.com """ if kd_node: dist = dist_func(point, kd_node[2]) dx = kd_node[2][i] -...
52,159
def plot_estimated_vs_simulated_edges( graph, sp_Graph, lrn=None, max_res_nodes=None, lamb=1.0 ): """Function to plot estimated vs simulated edge weights to look for significant deviations """ assert lamb >= 0.0, "lambda must be non-negative" assert type(lamb) == float, "lambda must...
52,160
def test_script_on_form4_collection(test_form4_collection, tmpdir): """ Test script on a random sample of Form 4 documents :param test_form4_collection: :return: """ result = runner.invoke( app, ["process", str(test_form4_collection), "--out_dir", str(tmpdir)], ) assert r...
52,161
def index_shape(geometry: Column, resolution: Column): """ Generate an H3 spatial index for an input GeoJSON geometry column. This function accepts GeoJSON `Point`, `LineString`, `Polygon`, `MultiPoint`, `MultiLineString`, and `MultiPolygon` input features, and returns the set of H3 cells at the specif...
52,162
def test_poker_hand_factory_method_should_accept_valid_hand_strings(): """ GIVEN: A valid poker hand string, of the form 'RS RS RS RS RS', where 'R' denotes the rank of the card, and 'S' denotes the suit of the card. WHEN: We call the factory method passing the poker hand string. ...
52,163
def test_experiments(): """Train 1 epoch with all experiment configs.""" command = ["run.py", "-m", "experiment=glob(*)", "trainer.max_epochs=1"] run_command(command)
52,164
def test_graph_remove_node_1(): """ Expectations: """ g = MultiDiGraph() g.add_node("A") g.add_node("B") g.add_node("C") g.add_edge("A", "B", test_attr="TEST_edge1a") g.add_edge("B", "A", test_attr="TEST_edge1a") g.add_edge("A", "B", test_attr="TEST_edge1b") g.add_edge("B", "...
52,165
def edit_buildspec_file(buildspecs, configuration, editor): """Open buildspec in editor and validate buildspec with parser. This method is invoked by command ``buildtest buildspec edit-file``. Args: buildspec (str): Path to buildspec file to edit configuration (buildtest.config.SiteConfiguratio...
52,166
def check_summary_tag(file_list): """ Check whether the structure: <summary> ... </summary> Is correctly followed, if not generates an error. """ after_summary = False error = False err_message = '' for line_number, line in enumerate(file_list): if b'<summary>' in ...
52,167
def mat_mul( input_tensor, weight_tensor, activation=None, activation_params=None, name="mat_mul"): """Compute a matrix multiplication for `input_tensor` and `weight_tensor`. Args: input_tensor: A 2D `Tensor`. Shaped as `NC`, where `N` is batch size and `C` is number of channels. weight_tenso...
52,168
def give_money(bot, trigger): """Give X amount of your money to another user.""" if trigger.sender == "#casino": giver = trigger.nick try: amount = int(trigger.group(3).replace(",", "").replace("$", "")) target = trigger.group(4) except AttributeError: ...
52,169
def discover(uuids): """Initiate discovery for given node uuids.""" if not uuids: raise utils.DiscoveryFailed("No nodes to discover") ironic = utils.get_client() LOG.debug('Validating nodes %s', uuids) nodes = [] for uuid in uuids: try: node = ironic.node.get(uuid) ...
52,170
def get_events(wrapper, student: str = None, time: str = None) -> dict: """ list events """ start, end = get_dates(time) event_data = wrapper.get_events(start_date=start, end_date=end, login=student) return event_data
52,171
def merge_preclusters_ld(preclusters): """ Bundle together preclusters that satisfy the two criteria at the same time: * 1. gwas_snp of clusterA is within ld_snps of clusterB (in LD) * 2. (p-value of gwas_snp of clusterB * 10-3) <= p-value of gwas_snp of clusterA (<= p-value of gwas_snp of clusterB) Args: * ...
52,172
def store_to_cache(tweets, company, category, cache): """Stores Tweet sentiments to cache. key -> (total_sentiment, count) """ data = json.loads(cache.get("all") or '{}') if company not in data: data[company] = dict() if category not in data: data[category] = dict() ...
52,173
def construct_system(sp, scale=1.0): """Construct systems according to job statepoint. Parameters ---------- sp: dict (from job.sp) Dictionary contains information necessary to construct a system. Stored as state of job. The dictionary should resemble: {"molecule": str, ...
52,174
def QA_SU_save_order(orderlist, client=DATABASE): """存储order_handler的order_status Arguments: orderlist {[dataframe]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) """ if isinstance(orderlist, pd.DataFrame): collection...
52,175
def download_data(): """ Download NASA Archive data and save it to `nasa.csv` """ with request.urlopen(download_link) as response: data = response.read() local_file = os.path.join(get_data_dir(), 'nasa.csv') with open(local_file, 'wb') as f: f.write(data) print(f'Saved NA...
52,176
def extract_mappings(uuid, api, unique, file_string): """ Method to iterate over project metadata as well as the entities in all submissions in a project and save progress to file. :param uuid: project uuid :type uuid: string :param api: string of ingest api to search :type api: string :...
52,177
def test_evaluate(integrated): """ Test if values are computed correctly. """ for struct in [ rosen_for_sensi(2, integrated, [0, 1]), poly_for_sensi(2, True, 0.5), ]: _test_evaluate(struct)
52,178
def _tile_images(imgs, tile_shape, concatenated_image, margin_color=None): """Concatenate images whose sizes are same. @param imgs: image list which should be concatenated @param tile_shape: shape for which images should be concatenated @param concatenated_image: returned image. if it is None, new imag...
52,179
def true_positive_rate(y_true, y_pred): """Returns True Positive Rate. Wrapper function of metrics_K() Args: y_true (Tensorflow Tensor): Array of 'true' 0s and 1s y_pred (Tensorflow Tensor): Array of predicted 0s and 1s Returns: specificity_loss (Tensor): True Positive Rate ([...
52,180
def create_camera_widget(name): """Create a camera control widget""" obj = create_widget(name) if not obj.data.vertices: verts = [(0.275136, 0, -0.275136), (0.359483, 0, -0.148903), (0.389102, 0, 0), (0.359483, 0, 0.148903), (0.275136, 0, 0.275136), (0.148903, 0, 0....
52,181
def query_related(uri, filter=None, limit=20): """ Query for terms that are related to a term, or list of terms, according to the mini version of ConceptNet Numberbatch. """ if uri.startswith('/c/'): query = uri elif uri.startswith('/list/') and uri.count('/') >= 3: try: ...
52,182
def train_nn(sess, epochs, batch_size, get_batches_fn, train_op, cross_entropy_loss, input_image, correct_label, keep_prob, learning_rate): """ Train neural network and print out the loss during training. :param sess: TF Session :param epochs: Number of epochs :param batch_size: Batch s...
52,183
def AtF2_kernel(z, psi, r, out): """ :param z: K x MY x MX :param psi: B x K x MY x MX :param r: K x 2 :param out: B x NY x NX :return: """ n = cuda.blockIdx.x * cuda.blockDim.x + cuda.threadIdx.x B, K, MY, MX = psi.shape N = B * K * MY * MX bb = (n // (MY * MX * K)) ...
52,184
def set_name(value): """ Loads the uploaded set name into the Prep data structure :type value: string :param value: name of the uploaded set """ current.assignsetname(value)
52,185
def chain(pairs): """ Generate chain from location pairs. """ table, chain = [], [] for i in numpy.unique(numpy.array(pairs).flatten()): if chain == []: chain.append(i) value = i continue if i == value + 1: chain.append(i) ...
52,186
def search_import( method: str, modules: List[Union[str, ModuleType]] ) -> Optional[object]: """ Method has to check if any of `modules` contains `callable` object with name `method_name` and return list of such objects args: method - name of object (method) we wanna find modules...
52,187
def retrieve_context_connectivity_service_end_point_capacity_total_size_total_size(uuid, local_id): # noqa: E501 """Retrieve total-size Retrieve operation of resource: total-size # noqa: E501 :param uuid: ID of uuid :type uuid: str :param local_id: ID of local_id :type local_id: str :rty...
52,188
def identity(n): """ Creates a n x n identity matrix. """ I = zeroes(n, n) for i in range(n): I.g[i][i] = 1.0 return I
52,189
def flatten_properties( prop_name: str, prop_details: DictStrAny, prop_required: bool, definitions: DictStrAny, ) -> Generator[Tuple[str, DictStrAny, bool], None, None]: """ extracts all nested model's properties into flat properties (used f.e. in GET params with multiple arguments and model...
52,190
def get_config_from_args(config_dict=None, **kwargs): """ Reads arguments and resolves the string configuration to appropriate class instances. :param config_file: yaml file containing the configurations :type config_file: `str` :return: dictionary of class references :rtype: `dict` """ ...
52,191
def show_camera_image(frame, camera_image, camera_labels, layout, cmap=None): """Show a camera image and the given camera labels.""" ax = plt.subplot(*layout) # Draw the camera labels. for camera_labels in frame.camera_labels: # Ignore camera labels that do not correspond to this camera. if camera_lab...
52,192
def mnist_test_labels_file(): """ Train images of MNSIT. :return: filepath :rtype: str """ return data_file('mnist/test_labels', HDF5_EXT)
52,193
def is_eval_epoch(cur_epoch): """Determines if the model should be evaluated at the current epoch.""" return cfg.TRAIN.EVAL_PERIOD != -1 and ( (cur_epoch + 1) % cfg.TRAIN.EVAL_PERIOD == 0 or (cur_epoch + 1) == cfg.OPTIM.MAX_EPOCH )
52,194
def utc_now_to_file_str(): """ Format UTC now to _YYYYmmdd_HHMMSS :return: """ return datetime.datetime.strftime(datetime.datetime.utcnow(), '_%Y%m%d_%H%M%S')
52,195
def _(): """Placeholder for a function argument in the `f` macro."""
52,196
def nose_hoover_invariant(energy_fn: Callable[..., Array], state: NVTNoseHooverState, kT: float, **kwargs) -> float: """The conserved quantity for the Nose-Hoover thermostat. This function is normally used for debugging the Nose-Hoover t...
52,197
def intersect1d( pda1: groupable, pda2: groupable, assume_unique: bool = False ) -> Union[pdarray, groupable]: """ Find the intersection of two arrays. Return the sorted, unique values that are in both of the input arrays. Parameters ---------- pda1 : pdarray/Sequence[pdarray, Strings, Cat...
52,198
def less_or_equal(left: ValueOrExpression, right: ValueOrExpression) -> Expression: """ Constructs a *less than or equal to* expression. """ return Comparison( operators.ComparisonOperator.LE, ensure_expr(left), ensure_expr(right) )
52,199