content
stringlengths
22
815k
id
int64
0
4.91M
def _normalize_data(data): """Turn entities in properties into entity ids""" entities = data['layout']['entities'] for obj in entities: schema = model.get(obj.get('schema')) if schema is None: raise InvalidData("Invalid schema %s" % obj.get('schema')) properties = obj.get...
5,295,200
def store_token(app, token): """ Takes a token dictionary returned by the Microsoft OAuth provider and stores it in the database. Using the required 'user.read' scope it fetches some identifying information to store with the token :param app: The Application object :param token: The token dicti...
5,295,201
def conv2D_generative(inputs, filters, kernel_size=(1, 1), padding="same", activation=None, reuse=False, name="conv2D", strides=(1, 1), dilation_rate=(1, 1), use_bias=True, mask=None, bias_init=0. ): """ 2D...
5,295,202
def FlattenList(list): """Flattens a list of lists.""" return [item for sublist in list for item in sublist]
5,295,203
def _build_state_value(django_request, user): """Composes the value for the 'state' parameter. Packs the current request URI and an XSRF token into an opaque string that can be passed to the authentication server via the 'state' parameter. Meant to be similar to oauth2client.appengine._build_state_value. A...
5,295,204
def DiscreteMCOperator(valuelist): """Randomly picks a value from the valuelist.""" assert valuelist != [], "'valuelist' must not be empty!" yield random.choice(valuelist)
5,295,205
def test_setdefault(run_cli_command, mock_profiles): """Test the ``verdi profile setdefault`` command.""" profile_list = mock_profiles() run_cli_command(cmd_profile.profile_setdefault, [profile_list[1]]) result = run_cli_command(cmd_profile.profile_list) assert 'Report: configuration folder:' in re...
5,295,206
def test_run_called_process_error(mock_subprocess_check_output): """ Test running Statick when each plugin has a CalledProcessError. Expected result: issues is None """ mock_subprocess_check_output.side_effect = subprocess.CalledProcessError( 1, "", output="mocked error" ) args = Ar...
5,295,207
def noisify_samples(inputs, outputs, errors, batch_size=500, sample_weight=None): """ inputs: {'main_input': X, 'aux_input': X[:, :, [1]]} outputs: X[:, :, [1]] errors: X_raw[:, :, 2] """ if sample_weight is None: sample_weight = np.ones(errors.shape) X = inputs['main_input'] X_a...
5,295,208
def commit(experiment_name, time): """ Try to commit repo exactly as it is when starting the experiment for reproducibility. """ try: sh.git.commit('-a', m=f'"auto commit tracked ' f'files for new experiment: ' f'{experime...
5,295,209
def angd2vec2d(ang: float) -> numpy.array: """Convert angle in degrees to a 2-d unit vector in the x-y plane.""" return ang2vecd(ang)[:2]
5,295,210
def pair_align(a, b): """ Accurate Registration. :param a: Point cloud for previous frame. :param b: Point cloud for current frame. :return: The matrix. """ x = 0 return x
5,295,211
async def battery(request): """GET /api/battery cf. https://docs.mistyrobotics.com/misty-ii/rest-api/api-reference/#getbatterylevel """ return web.json_response({ 'status': 'Success', 'result': generate_batterylevel(), })
5,295,212
def refresh_auth(action): """ Uses the 'Authorization' block in the request header to return a fresh token for a user. """ # first, drop GETs trying to do a refresh: we don't play that shit if action == 'refresh' and flask.request.method == 'GET': return utils.http_405 setattr(flask.reques...
5,295,213
def apply_noise_to_gates( circuit: Circuit, noise: Iterable[Type[Noise]], target_gates: Union[Iterable[Type[Gate]], np.ndarray], target_qubits: QubitSet, ) -> Circuit: """Apply noise after target gates in target qubits. When `noise.qubit_count` == 1, `noise` is applied to target_qubits after `t...
5,295,214
def load_info(path = defaults._default_info_path, verbose = False): """ :param path: :param verbose: :return: """ if verbose: print(path) i = classes.InfoClass() i.load(path) return i
5,295,215
async def attach_user(db, document: Dict[str, Any]) -> Dict[str, Any]: """ Attach more complete user data to a document with a `user.id` field. :param db: the application database client :param document: a document to attach user data to :return: a document with user data attached """ try:...
5,295,216
def fontsize(ax, fz=14): """Set fontsizes for title, axis labels, and ticklabels. Parameters ---------- ax : axis matplotlib axis fz : int font size """ for item in ( [ax.title, ax.xaxis.label, ax.yaxis.label] + ax.get_xticklabels() + ax.get_yticklabe...
5,295,217
def mlevel(level): """Convert level name/int to log level. Borrowed from celery, with <3""" if level and not isinstance(level, numbers.Integral): return LOG_LEVELS[level.upper()] return level
5,295,218
def get_size_checksum_dict(path: str) -> dict: """Compute the file size and the sha256 checksum of a file""" m = sha256() with open(path, "rb") as f: for chunk in iter(lambda: f.read(1 << 20), b""): m.update(chunk) return {"num_bytes": os.path.getsize(path), "checksum": m.hexdigest()...
5,295,219
def split( mapfile_df, output_dir=None, output_filename="split_train_dev.csv", params_filepath="params.yaml", ): """Accept a Pandas DataFrame with image filenames and labels, split into train, test, and dev sets and save file. Modify the n_split, the random_seed, or shuffle in params.yaml""...
5,295,220
def get_legislation_introduced_since(since_date: datetime) -> Dict[str, Any]: """See: http://wslwebservices.leg.wa.gov/legislationservice.asmx?op=GetLegislationIntroducedSince""" argdict: Dict[str, Any] = dict(sinceDate=since_date) keydict: Dict[str, Any] = { "statefiscalnote": lambda boolstr: (bool...
5,295,221
def generate_core_tsv(): """output a list of the core ili concepts ToDO: sort by frequency""" tsv="""# ili_id\n""" core_ss, core_ili = fetch_core() for ili in core_ili: tsv += "i{}\n".format(ili) return Response(tsv, mimetype='text/tab-separated-values')
5,295,222
def extern(decorated): """ A decorator gadget that generates a Rust extern {} block Usage: properties.name = "my::rust::extern" @extern function(generator, outfile, ...): outfile.write("contents inside generated extern block") Generates: extern { ...
5,295,223
def make_exp_vocab(exp_dic): """ Returns a dictionary that maps words to indices. """ exp_vdict = {'<EOS>': 0} exp_vdict[''] = 1 exp_id = 2 for qid in exp_dic.keys(): exp_strings = exp_dic[qid] for exp_str in exp_strings: exp_list = ActivityDataProvider.seq_to_lis...
5,295,224
def load_frames(folder_name, offset=0, desired_fps=3, max_frames=40): """ :param folder_name: Filename with a gif :param offset: How many frames into the gif we want to start at :param desired_fps: How many fps we'll sample from the image :return: [T, h, w, 3] GIF """ coll = ImageCollection(...
5,295,225
def _verify_data_shape(data, shape, path=None) -> Tuple[bool, Union[str, None]]: """ _verify_data_shape( {'data': []}, {'data': list} ) == (True, None) _verify_data_shape( {'data': ''}, {'data': list} ) == (False, '.data') _verify_data_shape( {'data': '', 'empty':...
5,295,226
def MultipleComparisons(trends, kys, aplha = 0.10, MCmethod="fdr_by"): """ Takes the results of an existing trend detection aproach and modifies them to account for multiple comparisons. args trends: list list of numpy arrays containing results of trend analysis kys: list list of what is in results y...
5,295,227
def plot_heatmap(n, data, plt_file, colorbar=True): """Plot heatmaps (Figure 3 in the paper).""" sns.set_style('whitegrid') sns.set(style='ticks', rc={'lines.linewidth': 4}) cmap_reversed = ListedColormap(sns.color_palette('Greys_r', 6).as_hex()) fig, axes = plt.subplots(nrows=n, ncols=n, figsize=(2 * n - 2, ...
5,295,228
def init_input_node(t1w, recon_all_args, output_dir): """Initialize the pipeline. This function will: - Extract <image_id> (e.g. sub-CLNC01_ses-M00) T1w filename; - Check FOV of T1w; - Create SUBJECTS_DIR for recon-all (otherwise, the command won't run); - Print begin execution ...
5,295,229
def test_difference_lists_same(): """ Check ValueError not raised if lists same """ list_1 = list_2 = [0, 1, 2] util.check_difference_between_two_lists(list_1, list_2)
5,295,230
def view_questions_default_page(): """View all tests, for default test page""" questions = Question.select() return questions
5,295,231
def get_tarinfo(path): """Gets the `TarInfo` object for the file at the specified path. This contains useful information such as the owner and the group. @param path: The path. @type path: str @return: The info for that path @rtype: tarfile.TarInfo """ # The `tarfile` library does not ...
5,295,232
def pack_mcmeta(): """Configures pack.mcmeta""" logger.log('Writing to pack.mcmeta') FOLDER = OUTPUT_FOLDER + 'src/main/resources/' pack_mcmeta = FOLDER + 'pack.mcmeta' pack_mcmeta_temp = pack_mcmeta + '.temp' with open(pack_mcmeta, 'r') as read: with open(pack_mcmeta_temp, 'w') as wr...
5,295,233
def chooseAxes(numBits): """Return Alice and Bob's randomly chosen mstment axes for the specified number of qubits in the E91 protocol: A chooses from (0, pi/4, pi/2) with equal probability, B chooses from (pi/4, pi/2, 3pi/4) with equal probability. """ choicesA = [0, pi/8...
5,295,234
async def test_switches(hass, mock_controller): """Test the update_items function with some clients.""" mock_controller.mock_client_responses.append([CLIENT_1, CLIENT_4]) mock_controller.mock_device_responses.append([DEVICE_1]) mock_controller.mock_client_all_responses.append([BLOCKED, UNBLOCKED, CLIENT...
5,295,235
def test_upload_with_server_side_encryption(): """上传带上加密头部,下载时验证有该头部""" response = client.put_object( Bucket=test_bucket, Key=test_object, Body='123', ServerSideEncryption='AES256' ) assert response['x-cos-server-side-encryption'] == 'AES256' response = client.get_ob...
5,295,236
def run_squad(): """run squad task""" parser = argparse.ArgumentParser(description="run squad") parser.add_argument("--device_target", type=str, default="Ascend", choices=["Ascend", "GPU"], help="Device type, def...
5,295,237
def test_load_ri(file_path): """ Use different ``level_type`` for same parameter. 地表理查森数 边界层理查森数 """ parameter = "RI" level_type = "surface" field_surface = load_field_from_file( file_path, parameter=parameter, level_type=level_type ) assert field_surface...
5,295,238
def newCommentUri(secs=None): """this is essentially a bnode, but a real URI is easier to work with""" if secs is None: secs = time.time() return URIRef("http://bigasterisk.com/comment/%r" % secs)
5,295,239
def DrawRectangle(tran, Info): """ Draw Rectangle: tran : transform of object Info : [color,[width, length]]""" pygame.draw.rect(screen, Info[0], [tran.location[0], tran.location[1], Info[1][0], Info[1][1]])
5,295,240
def test_exclude_image_ranges_for_scaling(): """Test for namesake function.""" refl1 = flex.reflection_table() refl1["xyzobs.px.value"] = flex.vec3_double( [(0, 0, 0.5), (0, 0, 1.5), (0, 0, 5.5), (0, 0, 9.5), (0, 0, 10.5)] ) refl1.set_flags(flex.bool(5, False), refl1.flags.user_excluded_in_s...
5,295,241
def debug(line): """Log debug""" return logging.debug(line)
5,295,242
def non_max_suppression(dets, threshold): """执行non-maximum suppression并返回保留的boxes的索引. dets:(x1、y1、x2、y2,scores) threshold: Float型. 用于过滤IoU的阈值. """ x1 = dets[:, 0] y1 = dets[:, 1] x2 = dets[:, 2] y2 = dets[:, 3] scores = dets[:, 4] # 每一个检测框的面积 areas = (x2 - x1 + 1) * (y2 - y1...
5,295,243
def GetLogDir(): """Gets the path to the currently in use log directory. Returns: str, The logging directory path. """ log_file = _log_manager.current_log_file if not log_file: return None return os.path.dirname(log_file)
5,295,244
def wind_rot_div(u, v, truncation=None, const=None): """Split the wind field into divergent and zonal mean and eddy rotational components.""" from windspharm.xarray import VectorWind vec = VectorWind(u, v, rsphere=const.rplanet_m) div_cmpnt_u, div_cmpnt_v, rot_cmpnt_u, rot_cmpnt_v = vec.helmholtz(trunc...
5,295,245
def blank_image(width=1024, height=1024, background=BG_COLOR): """ It creates a blank image of the given background color """ img = np.full((height, width, MONOCHROME), background, np.uint8) return img
5,295,246
def determineAlpha(mag_ratio): """ Bug: No docstring Bug: Each image should have its own alpha, because the different images have different magnifications (these are in the OM10 "MAG" columns, and need to be applied to each image's sourceX magnitude.) Bug: function name should be "dete...
5,295,247
def pretrained_embedding_layer(word_to_vec_map, word_to_index): """ Creates a Keras Embedding() layer and loads in pre-trained GloVe 50-dimensional vectors. Arguments: word_to_vec_map -- dictionary mapping words to their GloVe vector representation. word_to_index -- dictionary mapping from wo...
5,295,248
def generate_gaussian_rewards(num_bandits, num_actions, m, c, v, n, out_file = ""): """ Generate rewards that are correlated across bandits from a Multivariate Gaussian. For example, the reward of arm 1 in bandit 2 may be correlated with the reward of arm 1 in bandit 1. This is modelled as a MVN dis...
5,295,249
def clear_undo_history(buf): """Clear the undo history for a given buffer.""" undo_history[buf] = [''] undo_history_index[buf] = -1
5,295,250
async def update_request(connection: Connection, old_key: str, new_key: str, json: str) -> int: """ returns amount of entries updated """ return await connection.execute( """ update requests.requests set id = :new_key, body = :json, ...
5,295,251
def ns_xml(root, kc_info): """ Parsing NS-XML report and comparing CVE info in the Kernelcare :param root: root XML element in the report :param kc_info: dict - key is device-id, value is set of CVE :return: Iterator tuple (vulnerability-id, device-id, ip address) """ devices = root.find('...
5,295,252
def test_imp_all_behaves_well(): """test passing something that isn't a string or c or d (charge or discharge)""" try: descriptors.process.imp_all(a,"str",'asdf') #should fail because asdf is not c or d! except (AssertionError): pass else: raise Exception ('Exception not handled by asserts') try: descri...
5,295,253
def _prepare_transactions(response, telegram_id, mcc_codes): """Parse response from monobank API and return formatted transaction.""" transactions = [] costs_converter = 100.0 for transaction in response: transactions.append(( transaction["id"], telegram_id, t...
5,295,254
def test_wf_abs_log(): """Test the wave function.""" wf_abs_log = core_funcs.wf_abs_log v = wf_abs_log(ini_state_data, sampling.cfc_spec) print(v)
5,295,255
def get_gaps(o : Tensor, forward : bool = True, backward : bool = True, nearest : bool = True, normalize : bool = True): """Number of sequence steps from previous, to next and/or to nearest real value along the last dimension of 3D arrays or tensors""" _gaps = [] if forward or nearest: ...
5,295,256
def DoubleCast(value): """Explicitly cast a value to type Double.""" if istype(value, Double): return value return UPlus(value)
5,295,257
def search_dsrs( dsi_uuid: str = None, query_params: dict = None, user: dict = None ): """ search dsr(s) from ES / MongoDB """ ### TO DO ### check user's auth res, status = search_documents( index_name = dsi_uuid, doc_type = DSR_DOC_TYPE, query_params = query_params, user = user ) ...
5,295,258
def required(name, value): """ >>> required('field_name', 'aaa') >>> required('field_name', None) #doctest: +ELLIPSIS Traceback (most recent call last): ... EmptyValidationError: "field_name" ... >>> required('field_name', '') #doctest: +ELLIPSIS Traceback (most recent call last): ...
5,295,259
def _find_datapoints(sheet, row, col): """Return start and stop points for adsorption and desorption.""" rowc = 1 # Check for adsorption branch if sheet.cell(row + rowc, col).value == 'ADS': ads_start_row = row + rowc + 1 ads_final_row = ads_start_row point = sheet.cell(ads_final_r...
5,295,260
def archive_mysql_binlogs(port, dry_run): """ Flush logs and upload all binary logs that don't exist to s3 Arguments: port - Port of the MySQL instance on which to act dry_run - Display output but do not uplad """ rotate_binlogs_if_needed(port, dry_run) zk = MysqlZookeeper() instance = ...
5,295,261
def _read_dvxrel2_flag(data: bytes, n0: int, i0: int, i1: int, size: int, ints: np.ndarray) -> Tuple[List[int], List[str]]: """reads the DVxREL2 flag table""" flag = ints[i0+10] #print(ints[i0+11:]) #print(floats[i0+11:]) assert fl...
5,295,262
def eval_step( *, flax_model: nn.Module, train_state: train_utils.TrainState, batch: Batch, metrics_fn: MetricFn, debug: Optional[bool] = False ) -> Tuple[Batch, jnp.ndarray, Dict[str, Tuple[float, int]], jnp.ndarray]: """Runs a single step of training. Note that in this code, the buffer of...
5,295,263
def patient_list(request): """Accepts a request to return a list of all patients from the backing data store. Used for synching the mobile client. Warning: This can return a significant amount of patient data. Request parameters: username a valid username password ...
5,295,264
def test_build_args(): """Test valid manifests with good build arguments.""" for manifest_file in VALID_MANIFESTS: manifest = HardeningManifest.from_yaml(manifest_file) assert manifest.name in ' '.join(manifest.build_args(context_dir='.')) assert 'docker.io' in ' '.join(manifest.build_ar...
5,295,265
def create_dict_playlists_playlistids(p_list, pid_list): """ Create a dictionary of playlists and playlist ids """ playlists_and_playlist_ids = {} for i in range(len(p_list)): playlists_and_playlist_ids[p_list[i]] = pid_list[i] return playlists_and_playlist_ids
5,295,266
def request_tts_choice(): """ Method for setting default Text to Speech Service :return: None """ try: choice = int(input('Which Text to Speech Service do you wish to use? Press number or enter for default.\n' '1. Google Text to Speech (default)\n' ...
5,295,267
async def console(loop, log): """Connect to receiver and show events as they occur. Pulls the following arguments from the command line (not method arguments): :param host: Hostname or IP Address of the device. :param port: TCP port number of the device. :param verbose: Sho...
5,295,268
def create_bot(market, strategy, resolution, start, end, verbose, percent, automatic, btc): """Will create a new bot instance.""" bot = Cointrader(market=market, strategy=strategy, resolution=resolution, start=start, end=end, automatic=automatic, percent=percent, btc=btc) bot.verbose = ...
5,295,269
def fetch_coords_seitzman_2018(ordered_regions=True, legacy_format=True): """Load the Seitzman et al. 300 ROIs. These ROIs cover cortical, subcortical and cerebellar regions and are assigned to one of 13 networks (Auditory, CinguloOpercular, DefaultMode, DorsalAttention, FrontoParietal, MedialTemporalL...
5,295,270
def money_manager(manager): """ Patches a model manager's get_queryset method so that each QuerySet it returns is able to work on money fields. This allow users of django-money to use other managers while still doing money queries. """ # Need to dynamically subclass to add our behaviour, an...
5,295,271
def get_address():# check_author=True): """Get a address and user by id. Checks that the id exists and optionally that the current user is the author. :param id: id of address to get :return: the address :raise 404: if a address with the given id doesn't exist """ success = True uid...
5,295,272
def round(sdf: np.float, radius: np.float) -> np.float: """ Rounds a shape :param sdf: pre-calculated SDF :param radius: radius :return: SDF """ return sdf - radius
5,295,273
def download_all_sfs(session, target_dir): """ Downloads all files managed by Snapchat FS, writing them to `target_dir` @session An SfsSession object that has been logged in. @target_dir Where to download the files to. """ files = all_downloadable_sfs_files(session) download_from_sfs(ta...
5,295,274
def get_in_system_by_id( system_id, stop_id, return_only_stations=True, earliest_time=None, latest_time=None, minimum_number_of_trips=None, include_all_trips_within=None, exclude_trips_before=None, alerts_detail=None, ): """ Get information about a specific stop. """ ...
5,295,275
def required_input(message, method=input): """ Collect input from user and repeat until they answer. """ result = method(message) while len(result) < 1: result = method(message) return result
5,295,276
def traverse_component_and_dependencies(component): """ Given a component in a dependency graph, traverses the graph in topological order, ie such that all dependencies of a component will be yielded before the component itself. Each component is expected to have a `dependencies` property that retu...
5,295,277
def worker_map(worker: WorkerPool, fn: Callable[..., List[Any]], input_objects: List[Any]) -> List[Any]: """ Maps a list of objects through a worker. :param worker: Worker pool to use for parallelization. :param fn: Function to use when mapping. :param input_objects: List of objects to map. :ret...
5,295,278
def standard_solver_config(model, verbose = True): """ Basic solver settings for ETFL :param model: :param verbose: :return: """ # Solver settings model.solver.configuration.verbosity = int(verbose) model.solver.configuration.tolerances.feasibility = 1e-9 model.solver.configurati...
5,295,279
def _generate_normals(polygons): """Takes a list of polygons and return an array of their normals. Normals point towards the viewer for a face with its vertices in counterclockwise order, following the right hand rule. Uses three points equally spaced around the polygon. This normal of course might...
5,295,280
def initSeedSolutions() : """ This function should do any initialization needed to make generating individual solutions fast. It will get called before any solutions are generated. The value returned will be passed into generateSolution, so this is a good place to read in files or initializ...
5,295,281
def show_viz(i,original, masked, mask, inpainted): """Show Image using matplotlib""" plt.figure(i) plt.subplot(221), plt.imshow(original, 'gray') plt.title('original image') plt.subplot(222), plt.imshow(masked, 'gray') plt.title('source image') plt.subplot(223), plt.imshow(mask, 'gray') ...
5,295,282
def gen_courses(): """ Helper function to populate the course dropdown. Creates a list of every course in every degree necessary for a CIS student. Currently static since this app only supports CIS students. Can be changed later to create a dropdown list for a different type of student in future development. """...
5,295,283
def evaluate_model(sess, model, vocab, global_step, summary_writer): """Computes perplexity-per-word over the evaluation dataset. Summaries and perplexity-per-word are written out to the eval directory. Args: sess: Session object. model: Instance of ShowAndTellModel; the model to evaluate. g...
5,295,284
def post_to_add_batch( client: TestClient, ref: str, sku: str, qty: int, eta: Optional[str] ) -> None: """서비스 엔드포인트 `POST /batches` 를 통해 배치를 추가합니다.""" data = {"ref": ref, "sku": sku, "qty": qty} if eta: data["eta"] = eta r = client.post("/batches", json=data) assert r.status_code == 201
5,295,285
def message( val: ArrayLike, src: int, sgroup: int, dest: int, dgroup: int) -> np.void: """Creates a message used for passing information between objects. Args: val: A numpy structured array. src: A 64-bit int that represents the source of the message. ...
5,295,286
def classify(): """ Make a POST to this endpint and pass in an URL to an image in the body of the request. Swap out the model.pkl with another trained model to classify new objects. """ try: body = request.get_json() print(body) img_url = body["url"] # Get the image and...
5,295,287
def check_filenames_present(i_df): """Used for rule 3005 :param i_df: An investigation DataFrame :return: None """ for s_pos, study_df in enumerate(i_df['studies']): if study_df.iloc[0]['Study File Name'] == '': validator_warnings.append({ "message": "Missing stu...
5,295,288
def list_nmmr_tris_bitfield(fp, child, sfrname, offset): """ Format a single bitfield of NMMR TRIS pseudo register Input: - index in .pic - register node Notes: - Expected to be used with 12Fs only """ if (child.nodeType == Node.ELEMENT_NODE): if (child.nodeName == "edc:AdjustPoin...
5,295,289
def _mogrify_team(cursor, xs, fieldsList): """Shortcut for mogrifying a list as if it were a tuple.""" for valueIndex, [thisValue, thisColumn] in enumerate(zip(xs, fieldsList)): if (thisColumn == "team") | (thisColumn == "pos_team"): xs[valueIndex] = nfldb.standard_team(thisValue) ...
5,295,290
def table_columns(table, session): """ :param string table: Name of table or table schema :param Session session: SQLAlchemy Session :returns: List of column names in the table or empty list """ res = [] if isinstance(table, basestring): table = table_schema(table, session) for ...
5,295,291
def _dpss_wavelet(sfreq, freqs, n_cycles=7, time_bandwidth=4.0, zero_mean=False): """Compute Wavelets for the given frequency range Parameters ---------- sfreq : float Sampling Frequency. freqs : ndarray, shape (n_freqs,) The frequencies in Hz. n_cycles : float...
5,295,292
def exportfile(repo, revs, fp, switch_parent=False, opts=None, match=None): """Export changesets to the given file stream""" _prefetchchangedfiles(repo, revs, match) dest = getattr(fp, 'name', b'<unnamed>') with formatter.formatter(repo.ui, fp, b'export', {}) as fm: _exportfile(repo, revs, fm, ...
5,295,293
def setup_module(module): """ Put any test-wide setup code in here, e.g. creating test files """ if verbose: print("setup_module module:%s" % module.__name__) # Should be taken care of by teardown, in case remnants lying around try: shutil.rmtree(tmpdir) except FileNotF...
5,295,294
def create_model(config: ml_collections.ConfigDict, deterministic: bool) -> nn.Module: """Creates a Flax model, as specified by the config.""" if config.model == "GraphNet": return models.GraphNet( latent_size=config.latent_size, num_mlp_layers=config.num_mlp_lay...
5,295,295
def test_set_all_attributes(mockdbcontext): """ This test name is a bit of a misnomer because it's mirroring the method's name (set_all_attributes). We aren't setting _all_ attributes, but rather testing that this method will set and update multiple attributes at once. Unlike the tests that check t...
5,295,296
def property_from_list(index): """Returns the item at position 'index' from a list. Args: index: The (0-based) item in the list to return. Returns: A function that returns the specified item from a list, or '' if the list contains too few items. """ @empty_if_none def property_from_list_lambd...
5,295,297
def clothes_info(request, id): """Просмотр информации об одежде""" clothes = Clothes.objects.get(pk_clothes=id) return render(request, "clothes_info.html", {"clothes": clothes})
5,295,298
def multiTag(type, tag=None, **kwargs): """ Displays the "multiple tag widget" """ kwargs["tag"] = tag kwargs["type"] = type kwargs["atf"] = AddTagForm({"type":type, "colour":["white"]}) return kwargs
5,295,299