content
stringlengths
22
815k
id
int64
0
4.91M
def string_dumper(dumper, value, _tag=u'tag:yaml.org,2002:str'): """ Ensure that all scalars are dumped as UTF-8 unicode, folded and quoted in the sanest and most readable way. """ if not isinstance(value, basestring): value = repr(value) if isinstance(value, str): value = value...
23,400
def to_hours_from_seconds(value): """From seconds to rounded hours""" return Decimal(math.ceil((value / Decimal(60)) / Decimal(60)))
23,401
def extract_named_geoms(sde_floodplains = None, where_clause = None, clipping_geom_obj = None): """ Clips SDE flood delineations to the boundary of FEMA floodplain changes, and then saves the geometry and DRAINAGE name to a list of dictionaries. :param sde_floodplains: {st...
23,402
def parser_train(): """ Parse input arguments (train.py). """ parser = argparse.ArgumentParser(description='Standard + Adversarial Training.') parser.add_argument('--augment', type=str2bool, default=True, help='Augment training set.') parser.add_argument('--batch-size', type=int, default=128, h...
23,403
def convert_examples_to_features(examples: Sequence[InputExampleTC], labels: List[str], tokenizer: Any, max_length: int = 512, ignore_lbl_id: int = -100 ) ...
23,404
def build_image(local_conda_channel, conda_env_file, container_tool, container_build_args=""): """ Build a container image from the Dockerfile in RUNTIME_IMAGE_PATH. Returns a result code and the name of the new image. """ variant = os.path.splitext(conda_env_file)[0].replace(utils.CONDA_ENV_FILENAM...
23,405
def update_setup_cfg(setupcfg: ConfigUpdater, opts: ScaffoldOpts): """Update `pyscaffold` in setupcfg and ensure some values are there as expected""" if "options" not in setupcfg: template = templates.setup_cfg(opts) new_section = ConfigUpdater().read_string(template)["options"] setupcfg...
23,406
def testable_renderable() -> CXRenderable: """ Provides a generic CXRenderable useful for testin the base class. """ chart: CanvasXpress = CanvasXpress( render_to="canvasId", data=CXDictData( { "y": { "vars": ["Gene1"], ...
23,407
def secondSolution( fixed, c1, c2, c3 ): """ If given four tangent circles, calculate the other one that is tangent to the last three. @param fixed: The fixed circle touches the other three, but not the one to be calculated. @param c1, c2, c3: Three circles to which the other tangent circle ...
23,408
def deploy_control_plane(operator_name, namespaces): """ Create OpenShift Service Mesh Control Plane using API POST calls: """ false = False true = True global REQ_HEADER response = 0 count = 0 try: #get_csv_name is used to update the OPERATOR_CSV_NAME global variable ...
23,409
def collect3d(v1a,ga,v2a,use_nonan=True): """ set desired line properties """ v1a = np.real(v1a) ga = np.real(ga) v2a = np.real(v2a) # remove nans for linewidth stuff later. ga_nonan = ga[~np.isnan(ga)*(~np.isnan(v1a))*(~np.isnan(v2a))] v1a_nonan = v1a[~np.isnan(...
23,410
def _DevNull(): """On Windows, sometimes the inherited stdin handle from the parent process fails. Workaround this by passing null to stdin to the subprocesses commands. This function can be used to create the null file handler. """ return open(os.devnull, 'r')
23,411
def get_job_priorities(rest_url): """This retrieves priorities of all active jobs""" url = urllib.parse.urljoin(rest_url, "/jobs/priorities") resp = requests.get(url) return resp.json()
23,412
def create_vertices_intrinsics(disparity, intrinsics): """3D mesh vertices from a given disparity and intrinsics. Args: disparity: [B, H, W] inverse depth intrinsics: [B, 4] reference intrinsics Returns: [B, L, H*W, 3] vertex coordinates. """ # Focal lengths fx = intrinsics[:, 0] fy = int...
23,413
def _find_smart_path(challbs, preferences, combinations): """Find challenge path with server hints. Can be called if combinations is included. Function uses a simple ranking system to choose the combo with the lowest cost. """ chall_cost = {} max_cost = 1 for i, chall_cls in enumerate(pref...
23,414
def run_generator_and_test(test_case, mlmd_connection, generator_class, pipeline, task_queue, use_task_queue, service_job_manager, ...
23,415
def sort_func(kd1, kd2): """ Compares 2 key descriptions :param kd1: First key description :param kd2: Second key description :return: -1,0,1 depending on whether kd1 le,eq or gt then kd2 """ _c = type_order(kd1, kd2) if _c is not None: return _c return kid_order(kd1, kd2)
23,416
def _update_mf2000_files(srcdir, fc, cc, arch, double): """Update MODFLOW-2000 source files Parameters ---------- srcdir : str path to directory with source files fc : str fortran compiler cc : str c/c++ compiler arch : str architecture double : bool ...
23,417
def write_property(row_list, output_file, decl_id): """ @brief: Write property row to CSV file @param row_list: List of rows which should be written to file @param output_file: Output file handler @param decl_id: Declaration id """ for item in row_list: csv_writer(output_file).writer...
23,418
def sumdigits(a: int): """Sum of the digits of an integer""" return sum(map(int, str(a)))
23,419
def nth_weekday_of_month(y, m, n, w): """ y = 2020; m = 2 assert nth_weekday_of_month(y, m, -1, 'sat') == dt(2020, 2, 29) assert nth_weekday_of_month(y, m, -2, 'sat') == dt(2020, 2, 22) assert nth_weekday_of_month(y, m, 1, 'sat') == dt(2020, 2, 1) assert nth_weekday_of_month(y, m, 1, 'sun') == d...
23,420
def validate_ogrn(ogrn: str, is_ip: Optional[bool] = None) -> None: """ Source: https://ru.wikipedia.org/wiki/%D0%9E%D1%81%D0%BD%D0%BE%D0%B2%D0%BD%D0%BE%D0%B9_%D0%B3%D0%BE%D1%81%D1%83%D0%B4%D0%B0%D1%80%D1%81%D1%82%D0%B2%D0%B5%D0%BD%D0%BD%D1%8B%D0%B9_%D1%80%D0%B5%D0%B3%D0%B8%D1%81%D1%82%D1%80%D0%B0%D1%86%D0%...
23,421
def getBits(val, hiIdx: int, loIdx: int) -> int: """Returns a bit slice of a value. Args: val: Original value. hiIdx: Upper (high) index of slice. loIdx: Lower index of slice. Returns: The bit slice. """ return (~(MASK_32<<(hiIdx-loIdx+1)) & (val>>loIdx))
23,422
def test_fid(get_average_fidelitiy): """ Check that the average fideltiy of an identity is maximal. """ almost_equal(get_average_fidelitiy, 1)
23,423
def test_remove_word_removes_word(trie_3): """If word in trie remove should remove it.""" trie_3.remove('potato') with pytest.raises(ValueError): trie_3.remove('potato')
23,424
def check_validation_and_epoch_counts(lines: List[str], **kwargs: Dict) -> None: """Ensure that validation_period and epoch indices increment by 1 each time.""" counts = {"on_epoch": 0, "on_validation_period": 0} for i, line in enumerate(lines): cb = line.split(":")[0] for prefix in counts: ...
23,425
def test_install_uninstall_local(get_integration, get_application): """ Check a local integration can only be installed once, fails otherwise, but multiple calls on the same target simply overwrite the value and activate it """ local_application = get_application(integration=get_integration(is_local...
23,426
def get(context, option): """ Shows a default option.""" config = context.obj["config"] update_config(config) if option in config: echov(f"The value of '{option}' is set to '{config[option]}'.") else: echow(f"The value of '{option}' is not set!")
23,427
def init(ctx): """ Interactively create a paradrop.yaml file. This will ask the user some questions and then writes a paradrop.yaml file. """ chute = build_chute() with open("paradrop.yaml", "w") as output: yaml.safe_dump(chute, output, default_flow_style=False) # If this is a node...
23,428
def get_hostname(): """Returns the hostname, from /etc/hostname.""" hostname = "" try: with open('/etc/hostname') as f: hostname = f.read().rstrip() if len(hostname) == 0: hostname = "Unknown" except: hostname = "Unknown" return hostname
23,429
def is_valid_body(val): """Body must be a dictionary.""" return isinstance(val, dict)
23,430
def safe_hangup(channel): """Safely hang up the specified channel""" try: channel.hangup() print "Hung up {}".format(channel.json.get('name')) except requests.HTTPError as e: if e.response.status_code != requests.codes.not_found: raise e
23,431
def _vba_to_python_op(op, is_boolean): """ Convert a VBA boolean operator to a Python boolean operator. """ op_map = { "Not" : "not", "And" : "and", "AndAlso" : "and", "Or" : "or", "OrElse" : "or", "Eqv" : "|eq|", "=" : "|eq|", ">" : ">", ...
23,432
def file_diff_format(filename1, filename2): """ Inputs: filename1 - name of first file filename2 - name of second file Output: Returns a four line string showing the location of the first difference between the two files named by the inputs. If the files are identical, the fun...
23,433
def _check_assembly_string(base_asm, instr_type, target, operands): """ :param base_asm: :type base_asm: :param instr_type: :type instr_type: :param target: :type target: :param operands: :type operands: """ LOG.debug("Start checking assembly string: %s", base_asm) ope...
23,434
def get_label_number(window): """This method assigns to each label of a window a number.""" mode_list = ["bike", "car", "walk", "bus", "train"] current_label_number = 0 for mode in enumerate(mode_list): if window[1] == mode[1]: current_label_number = mode[0] return current_labe...
23,435
def test_saw3(): """SAW3""" utcnow = utc(2014, 3, 10, 3, 29) sts = utcnow.replace(hour=3, minute=35) ets = utcnow.replace(hour=9, minute=0) prod = sawparser(get_test_file("SAW/SAW3.txt"), utcnow=utcnow) assert prod.saw == 3 assert abs(prod.geometry.area - 7.73) < 0.01 assert prod.ww_num ...
23,436
def midi_array_to_event(midi_as_array): """ Take converted MIDI array and convert to array of Event objects """ # Sort MIDI array midi = sorted(midi_as_array, key=itemgetter(2)) # Init result result = [] # Accumulators for computing start and end times active_notes = [] curr_time = 0 # For comparing velociti...
23,437
def find_benchmarks(module) -> Dict[str, Type[Benchmark]]: """Enumerate benchmarks in `module`.""" found = {} for name in module.__all__: benchmark_type = getattr(module, name) found[benchmark_type.name] = benchmark_type return found
23,438
def out_folder_android_armv8_clang(ctx, section_name, option_name, value): """ Configure output folder for Android ARMv8 Clang """ if not _is_user_input_allowed(ctx, option_name, value): Logs.info('\nUser Input disabled.\nUsing default value "%s" for option: "%s"' % (value, option_name)) return ...
23,439
def remap_classes(dataset, class_map): """ Replaces classes of dataset based on a dictionary""" class_new_names = list(set(class_map.values())) class_new_names.sort() # NOTE sort() is a NoneType return method, it sorts the list without outputting new vars class_originals = copy.deepcopy(dataset['categor...
23,440
def MCTS(root, verbose = False): """initialization of the chemical trees and grammar trees""" run_time=time.time()+600*2 rootnode = Node(state = root) state = root.Clone() maxnum=0 iteration_num=0 start_time=time.time() """----------------------------------------------------------------...
23,441
def update_internalnodes_MRTKStandard() -> bpy.types.NodeGroup: """定義中のノードグループの内部ノードを更新する Returns: bpy.types.NodeGroup: 作成ノードグループの参照 """ # データ内に既にMRTKStandardのノードグループが定義されているか確認する # (get関数は対象が存在しない場合 None が返る) get_nodegroup = bpy.data.node_groups.get(def_nodegroup_name) # ノードグ...
23,442
def _ensure_consistent_schema( frame: SparkDF, schemas_df: pd.DataFrame, ) -> SparkDF: """Ensure the dataframe is consistent with the schema. If there are column data type mismatches, (more than one data type for a column name in the column schemas) then will try to convert the data type if pos...
23,443
def shave_bd(img, bd): """ Shave border area of spatial views. A common operation in SR. :param img: :param bd: :return: """ return img[bd:-bd, bd:-bd, :]
23,444
def get_raw_dir(args): """ Archived function. Ignore this for now """ root = "C:\\Workspace\\FakeNews" if os.name == "posix": root = '..' path = osp.join(root, "Demo", "data", f"{args.dataset}", "raw") return path
23,445
def test_joboffer_detail_view_render_state_with_active_label(publisher_client): """ Test that the joboffer detail view renders the state with active label class """ client = publisher_client joboffer = JobOfferFactory.create(state=OfferState.ACTIVE) target_url = reverse(VIEW_URL, kwargs={'slug'...
23,446
def process_game_hook(instance, created, **_): """Process a game immediately after game creation.""" if created: instance.process_game()
23,447
def plotly_single(ma, average_type, color, label, plot_type='line'): """A plotly version of plot_single. Returns a list of traces""" summary = list(np.ma.__getattribute__(average_type)(ma, axis=0)) x = list(np.arange(len(summary))) if isinstance(color, str): color = list(matplotlib.colors.to_rgb...
23,448
def remove_pip(packages): """Remove pip modules, from anysnake.toml. If they're installed, remove their installation If they're editable, remove their code/folders as well""" import shutil import tomlkit d, config = get_anysnake() local_config = tomlkit.loads(Path("anysnake.toml").read_text...
23,449
def create_task(className, *args, projectDirectory='.', dryrun=None, force=None, source=False): """Generates task class from the parameters derived from :class:`.Task` Fails if the target file already exists unless ``force=True`` or ``--force`` in the CLI is set. Setting the ``--source`` will generate a d...
23,450
def asciitable(columns, rows): """Formats an ascii table for given columns and rows. Parameters ---------- columns : list The column names rows : list of tuples The rows in the table. Each tuple must be the same length as ``columns``. """ rows = [tuple(str(i) for i i...
23,451
def fix_multipath_1(): """Installs multipath tooling packages""" vprint("Fixing multipath settings") if get_os() == UBUNTU: exe("apt-get install multipath-tools -y") else: exe("yum install device-mapper-multipath -y")
23,452
def __resolve_key(key: Handle) -> PyHKEY: """ Returns the full path to the key >>> # Setup >>> fake_registry = fake_reg_tools.get_minimal_windows_testregistry() >>> load_fake_registry(fake_registry) >>> # Connect registry and get PyHkey Type >>> reg_handle = ConnectRegistry(None, HKEY_CURR...
23,453
def vec3f_unitZ(): """vec3f_unitZ() -> vec3f""" return _libvncxx.vec3f_unitZ()
23,454
def view_recipe(tileset, token=None): """View a tileset's recipe JSON tilesets view-recipe <tileset_id> """ mapbox_api = _get_api() mapbox_token = _get_token(token) url = '{0}/tilesets/v1/{1}/recipe?access_token={2}'.format(mapbox_api, tileset, mapbox_token) r = requests.get(url) if r.s...
23,455
def _BotNames(source_config, full_mode=False): """Returns try bot names to use for the given config file name.""" platform = os.path.basename(source_config).split('.')[0] assert platform in PLATFORM_BOT_MAP bot_names = PLATFORM_BOT_MAP[platform] if full_mode: return bot_names return [bot_names[0]]
23,456
def display_board(board): """ show board in terminal""" logging.debug('display_board()') print(board[0] +" | "+ board[1] + " | " + board[2]+ 5*" " + " 1 | 2 | 3 ") print(board[3] +" | "+ board[4] + " | " + board[5]+ 5*" " + " 4 | 5 | 6 ") print(board[6] +" | "+ board[7] + " | " + board[8]+ 5*" " ...
23,457
def get_public_key(public_key_path=None, private_key_path=None): """get_public_key. Loads public key. If no path is specified, loads signing_key.pem.pub from the current directory. If a private key path is provided, the public key path is ignored and the public key is loaded from the private key. ...
23,458
def InitializeState(binaryString): """ State initializer """ state = np.zeros(shape=(4, 4), dtype=np.uint8) plaintextBytes = SplitByN(binaryString, 8) for col in range(4): for row in range(4): binary = plaintextBytes[col * 4 + row] state[row, col] = int(binary, 2)...
23,459
def _apply_modifier(s: str, modifier: str, d: Dict[Any, str]) -> str: """ This will search for the ^ signs and replace the next digit or (digits when {} is used) with its/their uppercase representation. :param s: Latex string code :param modifier: Modifier command :param d: Dict to look upon ...
23,460
def threaded_polling(data, max_workers): """ Multithreaded polling method to get the data from cryptocompare :param data: dictionary containing the details to be fetched :param max_workers: maximum number of threads to spawn :return list: containing the high low metrics for each pair """ hl_...
23,461
def sub(attrs: Dict[str, Any], in_xlayers: List[XLayer]) -> Dict[str, List[int]]: """Return numpy-style subtraction layer registration information (shape) NOTE: https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html""" assert len(in_xlayers) == 2, "Subtract layer expects two input layers" lX,...
23,462
def test_js102_class_def(class_def_file_path): """Class definition should not trigger JS102.""" style_guide = flake8.get_style_guide( select=['JS102'], ) p = os.path.abspath(class_def_file_path) r = style_guide.check_files([p]) assert 0 == r.total_errors
23,463
def flatten_scan(scan, headers, output_file): """ Flattening the sequence data in a single line-separated value and keying always by path, given a ScanCode `scan` results list. """ mainlist = [] parent_dict = {} keys=[] fg_val=0 i = 0 for scanned_file in scan: f...
23,464
def word_column_filter_df(dataframe, column_to_filter, column_freeze, word_list): # La fonction .where() donne une position qu'il faut transformer en index # Il faut entrer le nom d'une colonne repère (exemple: code produit) pour retrouver l'index, ou construire un colonne de re-indexée. """Filtre les colonnes d'un...
23,465
def unlocked(): """ Context manager which unlocks a Document and dispatches ModelChangedEvents triggered in the context body to all sockets on current sessions. """ curdoc = state.curdoc if curdoc is None or curdoc.session_context is None: yield return connections = curdo...
23,466
def pytest_configure(config): """Configure and init envvars for airflow.""" config.old_env = {} for key, value in TEST_ENV_VARS.items(): config.old_env[key] = os.getenv(key) os.environ[key] = value # define some models to get the tests to pass. db.merge_conn( models.Connectio...
23,467
def test_contactus_invalid(client, jwt, session): """Assert that the endpoint returns the failure status.""" req_data = { 'firstName': 'my', 'lastName': 'self', 'email': '', 'description': '' } rv = client.post(API_URI_PREFIX + 'contactus', data=json.dumps(req_data), cont...
23,468
def adjust_learning_rate(optimizer, iteration, epoch_size, hyp, epoch, epochs): """adjust learning rate, warmup and lr decay :param optimizer: optimizer :param gamma: gamma :param iteration: iteration :param epoch_size: epoch_size :param hyp: hyperparameters :param epoch: epoch :param e...
23,469
def initServer(port): """Método para inicializar o servidor e carrgar dados da database. Parameters ---------- port : int A porta a ser escutada pelo servidor. """ global serversocket # pegar nome da maquina local host = socket.gethostname() ...
23,470
def reading_data(data_file): """ Read in a data file (16 bit) and obtain the entire data set that is multiplexed between ECG and Pulse data. The data is then extracted and appended to separate arrays :param data_file: The binary data file to be loaded into the function :return data: The E...
23,471
def daemon_service(dstate, action, retries=10): """ perform systemctl command with action provided Args: dstate: Daemon state action: action to be performed retries: number of retries """ mark = __mark(dstate) daemon = "{cluster}-{role}".format(cluster=dstate.cluster, rol...
23,472
def terminate_app( app_name, sigterm_timeout=DEFAULT_TIMEOUT_AFTER_SIGTERM, sigkill_timeout=DEFAULT_TIMEOUT_AFTER_SIGKILL, ): """Terminate an application. Kill the container with SIGTERM before deleting its resources. If the container's process is already killed, proceed with deleting its r...
23,473
def two_body_mc_grad(env1: AtomicEnvironment, env2: AtomicEnvironment, d1: int, d2: int, hyps: 'ndarray', cutoffs: 'ndarray', cutoff_func: Callable = cf.quadratic_cutoff) \ -> (float, 'ndarray'): """2-body multi-element kernel between two force components and its ...
23,474
def get_task_name(task): """Gets a tasks *string* name, whether it is a task object/function.""" task_name = "" if isinstance(task, (types.MethodType, types.FunctionType)): # If its a function look for the attributes that should have been # set using the task() decorator provided in the deco...
23,475
def EventAddPublication(builder, publication): """This method is deprecated. Please switch to AddPublication.""" return AddPublication(builder, publication)
23,476
def convModel(input1_shape, layers): """" convolutional model defined by layers. ith entry defines ith layer. If entry is a (x,y) it defines a conv layer with x kernels and y filters. If entry is x it defines a pool layer with size x""" model = Sequential() for (i, layer) in enumerate(layers): ...
23,477
def cached_open_doc(db, doc_id, cache_expire=COUCH_CACHE_TIMEOUT, **params): """ Main wrapping function to open up a doc. Replace db.open_doc(doc_id) """ try: cached_doc = _get_cached_doc_only(doc_id) except ConnectionInterrupted: cached_doc = INTERRUPTED if cached_doc in (None, ...
23,478
def Voices_preload_and_split(subset='room-1', test_subset='room-2', seconds=3, path=None, pad=False, splits=None, trim=True): """Index and split librispeech dataset. Args: subset (string): LibriSpeech subset to parse, load and split. Currently can only handle on...
23,479
def dense2bpseq(sequence: torch.Tensor, label: torch.Tensor) -> str: """converts sequence and label tensors to `.bpseq`-style string""" seq_lab = dense2seqlab(sequence, label) return seqlab2bpseq
23,480
def _base_app(config): """ init a barebone flask app. if it is needed to create multiple flask apps, use this function to create a base app which can be further modified later """ app = Flask(__name__) app.config.from_object(config) config.init_app(app) bootstrap.init_app(app) ...
23,481
def test_cpu_bilateral_k3_rgbd1(rgbd1, loops, benchmark): """ Will benchmark bilateral cpu """ a = Matrix3fRef(rgbd1) b = benchmark(opf.filter.bilateral_K3, a, loops)
23,482
def applyC(input_map,nbar,MAS_mat,pk_map,Y_lms,k_grids,r_grids,v_cell,shot_fac,include_pix=True): """Apply the fiducial covariance to a pixel map x, i.e. C[x] = S[x]+N[x]. We decompose P(k;x) = \sum_l P_l(k) L_l(k.x) where x is the position of the second galaxy and use spherical harmonic decompositions. P_...
23,483
def rx_stop(ctx): """Stop LoraP2P RX.""" lora = Rak811() lora.rx_stop() if ctx.obj['VERBOSE']: click.echo('LoraP2P RX stopped.') lora.close()
23,484
def invert_injective_mapping(dictionary): """ Inverts a dictionary with a one-to-one mapping from key to value, into a new dictionary with a one-to-one mapping from value to key. """ inverted_dict = {} for key, value in iteritems(dictionary): assert value not in inverted_dict, "Mapping i...
23,485
def biosql_dbseqrecord_to_seqrecord(dbseqrecord_, off=False): """Converts a DBSeqRecord object into a SeqRecord object. Motivation of this function was two-fold: first, it makes type testing simpler; and second, DBSeqRecord does not have a functional implementation of the translate method. :param DBSeq...
23,486
def idf(): """Commands related to idf""" pass
23,487
def loadConfig(fileName): """ Attempt to load the specified config file. If successful, clean the variables/data the config file has setup """ if not os.path.isfile(fileName): return False if not os.access(fileName, os.R_OK): warn('Unable to read config file: ' + fileName) retur...
23,488
def update_collections_referencing_this_form(form): """Update all collections that reference the input form in their ``contents`` value. When a form is deleted, it is necessary to update all collections whose ``contents`` value references the deleted form. The update removes the reference, recomputes ...
23,489
def test_calc_ta_fwhm(): """Test the calc_ta_fwhm function.""" tests = [(1133775752, 4.208367616629838e-08), (1164110416, 4.098704979920858e-08), (1194350120, 3.9949300287565104e-08)] for obsid, expect_fwhm in tests: ans = calc_ta_fwhm(obsid) assert_almost_equal(an...
23,490
def validate_gpy_model(models: Any): """Make sure that all elements of the list a GPRegression models""" import GPy # pylint:disable=import-outside-toplevel for model in models: if not isinstance(model, GPy.models.GPRegression): raise ValueError("The models must be an instance of GPy.m...
23,491
def parse_rpsbproc(handle): """Parse a results file generated by rpsblast->rpsbproc. This function takes a handle corresponding to a rpsbproc output file. local.rpsbproc returns a subprocess.CompletedProcess object, which contains the results as byte string in it's stdout attribute. """ # Sanit...
23,492
def _invalidate(obj, depth=0): """ Recursively validate type anotated classes. """ annotations = get_type_hints(type(obj)) for k, v in annotations.items(): item = getattr(obj, k) res = not_type_check(item, v) if res: return f"{k} field of {type(obj)} : {res}" ...
23,493
def to_edgelist(graph: Graph, filename: str): """ Save the given graph object as an edgelist file. :param graph: the graph to be saved. :param filename: the edgelist filename. """ with open(filename, 'w', encoding='utf-8') as fout: # Iterate through every edge in the graph, and add the ...
23,494
def maybe_download(filename, expected_bytes, force=False): """Download a file if not present, and make sure it's the right size.""" if force or not os.path.exists(filename): print('Attempting to download:', filename) filename, _ = urlretrieve(url + filename, filename, reporthook=download_progress_hook) ...
23,495
def convtranspose2d_output_shape(h_w, kernel_size=1, stride=1, pad=0, dilation=1, out_pad=0): """Calculates the output height and width of a feature map for a ConvTranspose2D operation.""" h_w, kernel_size, stride, pad, dilation, out_pad = num2tuple(h_w), num2tuple(kernel_size), num2tuple(stride), num2tuple(pad...
23,496
def set_multizone_read_mode(session, read_mode, return_type=None, **kwargs): """ Modifies where data is read from in multizone environments. :type session: zadarapy.session.Session :param session: A valid zadarapy.session.Session object. Required. :type read_mode: str :param read_mode: For mu...
23,497
def main_fn(): """Run the reinforcement learning loop This tries to create a realistic way to run the reinforcement learning with all default parameters. """ if goparams.DUMMY_MODEL: # monkeypatch the hyperparams so that we get a quickly executing network. dual_net.get_default_hype...
23,498
def save_user(user): """ Function to save new user """ user.save_user()
23,499