content
stringlengths
22
815k
id
int64
0
4.91M
def config_backed(config_path: str): """Second order decorator that sets up a backing config for a GuildState type. """ def deco(gs_type: Type[GuildStateTV]) -> Type[GuildStateTV]: gs_type._cfg_path = config_path return gs_type return deco
5,356,500
def determine_if_is_hmmdb(infp): """Return True if the given file is an HMM database (generated using hmmpress from the HMMer3 software package), and return False otherwise. """ #if open(infp, 'r').read().startswith('HMMER3/f'): if open(infp, 'r').readline().startswith('HMMER3/f'): return Tr...
5,356,501
def train_UCSDped2(): # type: () -> None """ Performs video anomaly detection tests on UCSD Ped2. """ dataset_name = "ucsd_ped2" # # lam_svdd_opt(dataset_name) # window_size_opt(dataset_name) latent_code_size_opt(dataset_name)
5,356,502
def do_compare_training( args: argparse.Namespace, story_file: Text, additional_arguments: Optional[Dict] = None, ) -> None: """Train multiple models for comparison of policies and dumps the result.""" train_comparison_models( story_file=story_file, domain=args.domain, output...
5,356,503
def update_state(current_state, log_event): """ current_state is a LogEvent """
5,356,504
def assignment_path(base_var: str, path: Sequence[daglish.PathElement]) -> str: """Generates the LHS of an assignment, given a traversal path. Example: ["foo", 3, "bar"] -> "foo[3].bar". Args: base_var: Base variable name. path: Attribute path on `base_var` to assign to. Returns: Python code stri...
5,356,505
def template_footer(in_template): """Extracts footer from the notebook template. Args: in_template (str): Input notebook template file path. Returns: list: List of lines. """ footer = [] template_lines = [] footer_start_index = 0 with open(in_template) as f...
5,356,506
def set_config(config): """ Updates the current configuration. """ # pylint: disable=unused-argument pass
5,356,507
def get_public_methods(tree): """ Return a list of methods marked as public. The function walks the given tree and extracts all objects that are functions which are marked public. """ for node in ast.walk(tree): if is_public(node): yield node
5,356,508
def conf_auc(test_predictions, ground_truth, bootstrap=1000, seed=None, confint=0.95): """Takes as input test predictions, ground truth, number of bootstraps, seed, and confidence interval""" #inspired by https://stackoverflow.com/questions/19124239/scikit-learn-roc-curve-with-confidence-intervals by ogrisel ...
5,356,509
def empty_heap(): """Instantiate a heap for testing.""" from binheap import BinHeap min_heap = BinHeap() return min_heap
5,356,510
def get_requires_python(dist): # type: (pkg_resources.Distribution) -> Optional[str] """ Return the "Requires-Python" metadata for a distribution, or None if not present. """ pkg_info_dict = get_metadata(dist) requires_python = pkg_info_dict.get('Requires-Python') if requires_python is ...
5,356,511
def standard_primary_main_prefixes(primary = None): """Return list of standard prefixes that may go with particular primary name. **Note** You may wish to use `StandardPrimaryMainPrefixes()` instead. **Description** The function returns, a list of main prefixes that may go together with ...
5,356,512
def post_step1(records): """Apply whatever extensions we have for GISTEMP step 1, that run after the main step 1. None at present.""" return records
5,356,513
def gen_report_complex_no_files() -> dp.Report: """Generate a complex layout report with simple elements""" select = dp.Select(blocks=[md_block, md_block], type=dp.SelectType.TABS) group = dp.Group(md_block, md_block, columns=2) toggle = dp.Toggle(md_block, md_block) return dp.Report( dp.Pa...
5,356,514
def test_processing_entry_form(test_client,test_imaged_request_nonadmin): """ Test that an admin cannot access the processing entry form for lightserv-test request. This is to avoid a conflict between user and admin submission for the same processing request""" imager = current_app.config['IMAGING_ADMINS'][-1] w...
5,356,515
def suggested_associations(wiki_title, language='de'): """Given a Wikipedia page title, return a list of suggested associations for this entry.""" # The main heuristic to determine relevant associations for a given Wikipedia entry is to first gather all # articles that this entry's summary links to. wi...
5,356,516
def manage_categories(): """ Manage expense categories """ alert_message = "" user = User.query.filter_by(id=session["user_id"]).scalar() if request.method == "GET": with app.app_context(): categories = ( Category.query.options(joinedload("category_type")) ...
5,356,517
def shear_3d(sxy=0., sxz=0., syx=0., syz=0., szx=0., szy=0.): """ Returns transformation matrix for 3d shearing. Args: sxy: xy shearing factor sxz: xz shearing factor syx: yx shearing factor syz: yz shearing factor szx: zx shearing factor szy: zy shearing fact...
5,356,518
def Position(context): """Function: <number> position()""" return context.position
5,356,519
def spatial_shift_crop_list(size, images, spatial_shift_pos, boxes=None): """ Perform left, center, or right crop of the given list of images. Args: size (int): size to crop. image (list): ilist of images to perform short side scale. Dimension is `height` x `width` x `chann...
5,356,520
def get_input_args(): """ Used to parse the command line arguments in order to predict the flower name and the class probability. Options: Return top KK most likely classes: python predict.py input checkpoint --top_k 3 Use a mapping of categories to real names: python predict.py input checkpoint --c...
5,356,521
def testsuite_results(log_filename, msg_testsuite_section_start, msg_testsuite_end_message): """Read the NEST Travis CI build log file, find the 'make-installcheck' section which runs the NEST test suite. Extract the total number of tests and the number of tests failed. Return True if ...
5,356,522
def line_state_to_out(line: StaticStates, out_data: bool): """ Calculate the data and enable values given a initial state Args: line: StaticState that represent the line out_data: If line value is 2 it will be returned as the next value of data Returns: Data and Enable values fo...
5,356,523
def GetProxyConfig(http_proxy_uri=None, https_proxy_uri=None, cafile=None, disable_certificate_validation=None): """Returns an initialized ProxyConfig for use in testing. Args: http_proxy_uri: A str containing the full URI for the http proxy host. If this is not specified, the ProxyCon...
5,356,524
def run_multiple_stage_cases(env, extra_data): """ extra_data can be 2 types of value 1. as dict: Mandantory keys: "name" and "child case num", optional keys: "reset" and others 3. as list of string or dict: [case1, case2, case3, {"name": "restart from PRO CPU", "child case num": 2}, ...]...
5,356,525
def get_possible_paths(path: str) -> List[str]: """ Finds possible paths to resources, considering PACKAGE and USER directories first, then system-wide directories :param path: :return: """ # <sphinx_resources-get_possible_paths> dist_name = env.distribution_name() # RKD_DIST_NAME env var...
5,356,526
def test_parametrized_collected_from_command_line(testdir): """Parametrized test not collected if test named specified in command line issue#649. """ py_file = testdir.makepyfile( """ import pytest @pytest.mark.parametrize("arg", [None, 1.3, "2-3"]) def test_func(arg):...
5,356,527
def inchi_key_to_chembl(inchi_keys): """Return list of chembl ids that positionally map to inchi keys.""" molecule = new_client.molecule chembl_mols = [] ndone = 0 # counter for printing progress to console for inchi_key in inchi_keys: if pd.isnull(inchi_key): chembl_mols.appe...
5,356,528
def do_kube_version_show(cc, args): """Show kubernetes version details""" try: version = cc.kube_version.get(args.version) _print_kube_version_show(version) except exc.HTTPNotFound: raise exc.CommandError('kubernetes version not found: %s' % args.versio...
5,356,529
def StandaloneStyle(cfg): """ Construct a OWS style object that stands alone, independent of a complete OWS configuration environment. :param cfg: A valid OWS Style definition configuration dictionary. Refer to the documentation for the valid syntax: https://datacube-ows.readthedocs.io/en...
5,356,530
def __save_cnf_matrix(dataset_id, round_id, part, y_names, cnf_matrix): """ save confusion matrix :param dataset_id: dataset id :param round_id: round id :param part: 'eval' or 'test' :param y_names: y labels :param cnf_matrix: confusion matrix (actual / predict) :return: None """ ...
5,356,531
def insert_or_test_version_number(): """Should the format name and version number be inserted in text representations (not in tests!)""" return INSERT_AND_CHECK_VERSION_NUMBER
5,356,532
def set_seed(seed): """ Setting random seeds """ np.random.seed(seed) torch.manual_seed(seed) if torch.cuda.is_available(): torch.cuda.manual_seed(seed)
5,356,533
def add_login_routes(app): """ initializes this flask for providing access to /login and /logout :param app: :return: """ manager().add_login_routes(app)
5,356,534
def IsInteractive(output=False, error=False, heuristic=False): """Determines if the current terminal session is interactive. sys.stdin must be a terminal input stream. Args: output: If True then sys.stdout must also be a terminal output stream. error: If True then sys.stderr must also be a terminal outp...
5,356,535
def fulfillment(ctx, action, shop, tracking, provider, order_id, filename, message): """ add/edit shipping tracking (by skus or by file) """ click.echo('{} fulfillment at {}... send mesage \ to customer: {}'.format(action, shop, message)) project = ctx.obj['project'] config = ctx.obj["conf...
5,356,536
def get_ipaserver_host(): """Return the fqdn of the node hosting the IPA_SERVER. """ for node in svars['nodes']: if 'ipaserver' in node['groups']: return fqdn(node['name'])
5,356,537
def reverse_file_read(fp): """ a generator that returns the lines of a file in reverse order """ line = '' fp.seek(0, os.SEEK_END) offset = fp.tell() while offset > 0: offset = max(0, offset - 1) fp.seek(offset) byte = fp.read(1) if byte == '\n': ...
5,356,538
def hsv_to_rgb(image): """ Convert HSV img to RGB img. Args: image (numpy.ndarray): NumPy HSV image array of shape (H, W, C) to be converted. Returns: numpy.ndarray, NumPy HSV image with same shape of image. """ h, s, v = image[:, :, 0], image[:, :, 1], image[:, :, 2] to_rg...
5,356,539
def dom_to_tupletree(node): """Convert a DOM object to a pyRXP-style tuple tree. Each element is a 4-tuple of (NAME, ATTRS, CONTENTS, None). Very nice for processing complex nested trees. """ if node.nodeType == node.DOCUMENT_NODE: # boring; pop down one level return dom_to_tuplet...
5,356,540
def import_bom_rf3(filename, **kwargs): """Import a NetCDF radar rainfall product from the BoM Rainfields3. Parameters ---------- filename : str Name of the file to import. Returns ------- out : tuple A three-element tuple containing the rainfall field in mm/h imported ...
5,356,541
def pipe_collapse(fq, outdir, gzipped=True): """ Collapse, by sequence """ fname = filename(fq) check_path(outdir) fq_out = collapse_fx(fq, outdir, gzipped=True) stat_fq(fq_out) # 1U 10A fq_list = split_fq_1u10a(fq_out) for f in fq_list: stat_fq(f) # wrap stat ...
5,356,542
def render_user_weekly_artists(report, file_path, size=(420, 300)): """ :type report: temperfm.records.UserWeeklyArtistReport :type file_path: str :type size: tuple[int, int] """ margin_size = 60, 35 graph_size = size[0] - margin_size[0], size[1] - margin_size[1] graph_border = 2 fon...
5,356,543
def multi_bw(init, y, X, n, k, family, tol, max_iter, rss_score, gwr_func, bw_func, sel_func, multi_bw_min, multi_bw_max, bws_same_times, verbose=False): """ Multiscale GWR bandwidth search procedure using iterative GAM backfitting """ if init is None: bw = sel_func(bw_...
5,356,544
def _commands_with(name, from_cmake, start=0, end=-1): """ Returns a list of all cmkp._Command objects from a cmakeLists with the given name. """ cmd_list = [] for (index, command) in enumerate(from_cmake[start:end]): if isinstance(command, cmkp._Command) and command.name == name: ...
5,356,545
def _auth_url(url): """Returns the authentication URL based on the URL originally requested. Args: url: String, the original request.url Returns: String, the authentication URL. """ parsed_url = urlparse.urlparse(url) parsed_auth_url = urlparse.ParseResult(parsed_url.scheme, ...
5,356,546
def ismount(path): """ Test whether a path is a mount point. This is code hijacked from C Python 2.6.8, adapted to remove the extra lstat() system call. """ try: s1 = os.lstat(path) except os.error as err: if err.errno == errno.ENOENT: # It doesn't exist -- so no...
5,356,547
def getSupportedPrintTypes(mainControl, guiParent=None): """ Returns dictionary {printTypeName: (printObject, printTypeName, humanReadableName, addOptPanel)} addOptPanel is the additional options GUI panel and is always None if guiParent is None """ return groupOptPanelPlugins(mai...
5,356,548
def main(): """ 使用方法,自行搜索selenium配置教程,其实就是要下载一个chromedriver.exe, 放到chrome 根目录。 这个网站每一页的图片是一个http:*.webp, 跳转到这个链接还会继续跳转到图片真正的url (以'.jpg'结尾) """ # 从这一章开始 lastChapter = 'https://m.duoduomh.com/manhua/zujienvyou/853617.html' #避免后面的get参数比如 *.html?p=1 的影响,p是页书,而本脚本根据章节来保存下载下来的图片 cmp...
5,356,549
def read_image(file_name: str) -> np.array: """ pomocna funkce na nacteni obrazku :param file_name: cesta k souboru :return: numpy array, pripravene na upravy pomoci nasich funkcni """ return np.asarray(Image.open(file_name), dtype=np.int32)
5,356,550
def weighted_img(img, initial_img, α=0.8, β=1.0, γ=0.0): """ `img` is the output of the hough_lines(), An image with lines drawn on it. Should be a blank image (all black) with lines drawn on it. `initial_img` should be the image before any processing. The result image is computed as follows: ...
5,356,551
def test_tri_root_improper(): """ Test tri_root-related functions with arguments that are not triangular numbers. """ t = np.arange(1000) with pytest.raises(ValueError): tri.tri_root_strict(t) # Check the truncated version works as expected n = tri.tri_root_trunc(t) t_trunc = tri.tri_n(n) assert np.all((...
5,356,552
def md5SessionKey(params, password): """ If the "algorithm" directive's value is "MD5-sess", then A1 [the session key] is calculated only once - on the first request by the client following receipt of a WWW-Authenticate challenge from the server. This creates a 'session key' for the authentication ...
5,356,553
def all_state_action(buffer: RolloutBuffer, learner: BaseAlgorithm, state_only: bool = False): """ Equivalent of state_action on the whole RolloutBuffer.""" o_shape = get_obs_shape(learner.observation_space) t = lambda x, shape=[-1]: buffer.to_torch(x).view(buffer.buffer_size*buffer.n_envs, *shape) if i...
5,356,554
def write_results(conn, cursor, mag_dict, position_dict): """ Write star truth results to the truth table Parameters ---------- conn is a sqlite3 connection to the database cursor is a sqlite3.conneciton.cursor() object mag_dict is a dict of mags. It is keyed on the pid of the Proces...
5,356,555
def get_sparameters(sim: td.Simulation) -> np.ndarray: """Adapted from tidy3d examples. Returns full Smatrix for a component https://support.lumerical.com/hc/en-us/articles/360042095873-Metamaterial-S-parameter-extraction """ sim = run_simulation(sim).result() def get_amplitude(monitor): ...
5,356,556
def mapmri_STU_reg_matrices(radial_order): """ Generates the static portions of the Laplacian regularization matrix according to [1]_ eq. (11, 12, 13). Parameters ---------- radial_order : unsigned int, an even integer that represent the order of the basis Returns ------- S, T,...
5,356,557
def _checker(word: dict): """checks if the 'word' dictionary is fine :param word: the node in the list of the text :type word: dict :return: if "f", "ref" and "sig" in word, returns true, else, returns false :rtype: bool """ if "f" in word and "ref" in word and "sig" in word: return...
5,356,558
def test_creates_service(image, swarm, network, make_service): """Test that logging in as a new user creates a new docker service.""" test_logger.info("Start of service testing") make_service(hub_service) client = docker.from_env() # jupyterhub service should be running at this point services_be...
5,356,559
def construc_prob(history, window, note_set, model, datafilename): """ This function constructs the proabilities of seeing each next note Inputs: history, A list of strings, the note history in chronological order window, and integer how far back we are looking note_set, the set of n...
5,356,560
def renderPybullet(envs, config, tensor=True): """Provides as much images as envs""" if type(envs) is list: obs = [ env_.render( mode="rgb_array", image_size=config["image_size"], color=config["color"], fpv=config["fpv"], ...
5,356,561
def wifi(request): """Collect status information for wifi and return HTML response.""" context = { 'refresh': 5, 'item': '- Wifi', 'timestamp': timestamp(), 'wifi': sorted(Wifi().aps), } return render(request, 'ulm.html', context)
5,356,562
def genModel( nChars, nHidden, numLayers = 1, dropout = 0.5, recurrent_dropout = 0.5 ): """Generates the RNN model with nChars characters and numLayers hidden units with dimension nHidden.""" model = Sequential() model.add( LSTM( nHidden, input_shape = (None, nChars), return_sequences = True, ...
5,356,563
def print_diff_trials(diff, skip=None): """Print diff of basic trial information""" skip = skip or set() for key, values in viewitems(diff.trial): if key not in skip: print(" {} changed from {} to {}".format( key.capitalize().replace("_", " "), values[0] ...
5,356,564
def rotate_system(shape_list, angle, center_point = None): """Rotates a set of shapes around a given point If no center point is given, assume the center of mass of the shape Args: shape_list (list): A list of list of (x,y) vertices angle (float): Angle in radians to rotate counterclockwis...
5,356,565
def _large_compatible_negative(tensor_type): """Large negative number as Tensor. This function is necessary because the standard value for epsilon in this module (-1e9) cannot be represented using tf.float16 Args: tensor_type: a dtype to determine the type. Returns: a large negative number. """ ...
5,356,566
def classified_unread_counts(): """ Unread counts return by helper.classify_unread_counts function. """ return { 'all_msg': 12, 'all_pms': 8, 'unread_topics': { (1000, 'Some general unread topic'): 3, (99, 'Some private unread topic'): 1 }, ...
5,356,567
def company_key(company_name=DEFAULT_COMPANY_NAME): """Constructs a Datastore key for a Company entity with company_name.""" return ndb.Key('Company', company_name)
5,356,568
def main(): """Main entry point""" fire.Fire({"build_index": build_index, "tune_index": tune_index, "score_index": score_index})
5,356,569
def cappath_config_writer(cappath=None, homepath=None): """ Write a ConfigParser file to store cap preferences. :param cappath: Method to use. :type cappath: str :param homepath: Folder containing ini file. Default is user directory. :type homepath: str """ cappath = grab_cap() if capp...
5,356,570
def to_n_class(digit_lst, data, labels): """to make a subset of MNIST dataset, which has particular digits Parameters ---------- digit_lst : list for example, [0,1,2] or [1, 5, 8] data : numpy.array, shape (n_samples, n_features) labels : numpy.array or list of str Returns ------...
5,356,571
def acosh(x: T.Tensor) -> T.Tensor: """ Elementwise inverse hyperbolic cosine of a tensor. Args: x (greater than 1): A tensor. Returns: tensor: Elementwise inverse hyperbolic cosine. """ y = numpy.clip(x,1+T.EPSILON, numpy.inf) return ne.evaluate('arccosh(y)')
5,356,572
def main(): """ Load the network and parse the output. :return: None """ # Grab command line args args = build_argparser().parse_args() # Connect to the MQTT server client = connect_mqtt() # Perform inference on the input stream infer_on_stream(args, client) #time_took = tim...
5,356,573
def _output_server(host, port): """ Print info about the current instance of SwampDragon """ print('-------- SwampDragon ------') print('Running SwampDragon on {}:{}'.format(host, port)) print('DRAGON_URL: {}'.format(settings.DRAGON_URL)) print('Version {}'.format('.'.join([str(v) for v ...
5,356,574
def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description='Rock the Casbah', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('replace', metavar='str', help='The string that will...
5,356,575
def run_unit_tests(): """ Run unit tests against installed tools rpms """ # At the time of this writing, no unit tests exist. # A unit tests script will be run so that unit tests can easily be modified print "Running unit tests..." success, output = run_cli_cmd(["/bin/sh", UNIT_TEST_SCRIPT], False) ...
5,356,576
def autodetect_binary(argv, config): """Detects the correct binary to run and sets BINARY_SSH accordingly, if it is not already set.""" # If BINARY_SSH is set by the user, respect that and do nothing. if config.get("BINARY_SSH"): config.print("Will run '{0}' as ssh binary - set by user via BINAR...
5,356,577
def encode_input_descr(prm): """ Encode process description input.""" elem = NIL("Input", *_encode_param_common(prm)) elem.attrib["minOccurs"] = ("1", "0")[bool(prm.is_optional)] elem.attrib["maxOccurs"] = "1" if isinstance(prm, LiteralData): elem.append(_encode_literal(prm, True)) elif ...
5,356,578
def eval_src(encoder, classifier, data_loader): """Evaluate classifier for source domain.""" # set eval state for Dropout and BN layers encoder.eval() #eval验证模式不启用Dropout和BatchNormalization classifier.eval() # init loss and accuracy # loss = 0 # acc = 0 loss_1 = 0 loss_2 ...
5,356,579
def fill_replay_buffer( env, replay_buffer: ReplayBuffer, desired_size: int, agent: Agent ): """Fill replay buffer with transitions until size reaches desired_size.""" assert ( 0 < desired_size and desired_size <= replay_buffer._replay_capacity ), f"It's not true that 0 < {desired_size} <= {repl...
5,356,580
def pytest_runtest_call(item): """Before the test item is called.""" try: request = item._request except AttributeError: # pytest-pep8 plugin passes Pep8Item here during tests. return factoryboy_request = request.getfixturevalue("factoryboy_request") factoryboy_request.evalua...
5,356,581
def poly_quo(f, g, *symbols): """Returns polynomial quotient. """ return poly_div(f, g, *symbols)[0]
5,356,582
def preprocess_data(dataset, encoder, config): """ Function to perform 4 preprocessing steps: 1. Exclude classes below minimum threshold defined in config.threshold 2. Exclude all classes that are not referenced in encoder.classes 3. Encode and normalize data into (path: str, label: int)...
5,356,583
def connect(ip, _initialize=True, wait_ready=None, timeout=30, still_waiting_callback=default_still_waiting_callback, still_waiting_interval=1, status_printer=None, vehicle_class=None, rate=4, baud=115200, ...
5,356,584
def load_test_environment(skill): """Load skill's test environment if present Arguments: skill (str): path to skill root folder Returns: Module if a valid test environment module was found else None """ test_env = None test_env_path = os.path.join(skill, 'test/__init__.py') ...
5,356,585
async def ready(request): """ For Kubernetes readiness probe, """ try: # check redis valid. if app.redis_pool: await app.redis_pool.save('health', 'ok', 1) # check mysql valid. if app.mysql_pool: sql = "SELECT 666" result = await app.m...
5,356,586
def evaluate_partition(graph: Graph, true_b: np.ndarray, alg_partition: BlockState, evaluation: Evaluation): """Evaluate the output partition against the truth partition and report the correctness metrics. Compare the partitions using only the nodes that have known truth block assignment. Parameters...
5,356,587
def surface_area(polygon_mesh): """ Computes the surface area for a polygon mesh. Parameters ---------- polygon_mesh : ``PolygonMesh`` object Returns ------- result : surface area """ if isinstance(polygon_mesh, polygonmesh.FaceVertexMesh): print("A FaceVertex Mesh") ...
5,356,588
def main(): """ main program """ # setup the argument parsing parser = argparse.ArgumentParser( description='Program to optimize receptors for the given parameters. ' 'Note that most parameters can take multiple values, in ' 'which case all parameter c...
5,356,589
def add(value, next): """ Adds specified ``value`` to each item passed to pipeline """ while True: item = yield next.send(item + value)
5,356,590
def gas_zfactor(T_pr, P_pr): """ Calculate Gas Compressibility Factor For range: 0.2 < P_pr < 30; 1 < T_pr < 3 (error 0.486%) (Dranchuk and Aboukassem, 1975) """ # T_pr : calculated pseudoreduced temperature # P_pr : calculated pseudoreduced pressure from scipy.optimize import fsolve # non-linear sol...
5,356,591
def download_huc4(HUC4, filename): """Download HUC4 geodatabase (flowlines and boundaries) from NHD Plus HR data distribution site Parameters ---------- HUC4 : str HUC4 ID code filename : str output filename. Will always overwrite this filename. """ with requests.get(D...
5,356,592
def func_complex(): """ complex(real, imag) return complex number with value real + imag*1j or convert a string or number to complex number. Examples: complex(4), complex(-1, -4), complex("1+3j") """ print '4 = {}'.format(complex(4)) print '"5+3j" = {}'.format(complex('5+3j')) print '-6,...
5,356,593
def format_value_with_percentage(original_value): """ Return a value in percentage format from an input argument, the original value """ percentage_value = "{0:.2%}".format(original_value) return percentage_value
5,356,594
def get_Z_and_extent(topofile): """Get data from an ESRI ASCII file.""" f = open(topofile, "r") ncols = int(f.readline().split()[1]) nrows = int(f.readline().split()[1]) xllcorner = float(f.readline().split()[1]) yllcorner = float(f.readline().split()[1]) cellsize = float(f.readline().spli...
5,356,595
def modified_config( file_config: submanager.models.config.ConfigPaths, request: pytest.FixtureRequest, ) -> submanager.models.config.ConfigPaths: """Modify an existing config file and return the path.""" # Get and check request params request_param = getattr(request, PARAM_ATTR, None) if reques...
5,356,596
def train_discrim(discrim, state_features, actions, optim, demostrations, settings): """demostractions: [state_features|actions] """ criterion = torch.nn.BCELoss() for _ in range(settings.VDB_UPDATE_NUM): learner = discrim(torch.cat([state_features, actions], dim=-1)) ...
5,356,597
def task_install(): """install the packages into the sys.packages""" def install(pip): if pip: name = get_name() assert not doit.tools.CmdAction( f"python -m pip install --find-links=dist --no-index --ignore-installed --no-deps {name}" ).execute(sys....
5,356,598
def filter_column(text, column, start=0, sep=None, **kwargs): """ Filters (like grep) lines of text according to a specified column and operator/value :param text: a string :param column: integer >=0 :param sep: optional separator between words (default is arbitrary number of blanks) :param kwargs:...
5,356,599