content
stringlengths
22
815k
id
int64
0
4.91M
def drdpgr(body, lon, lat, alt, re, f): """ This routine computes the Jacobian matrix of the transformation from planetographic to rectangular coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/drdpgr_c.html :param body: Body with which coordinate system is associated. :type ...
5,324,600
def data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_cost_characteristiccost_name_get(uuid, node_uuid, node_rule_group_uuid, inter_rule_group_uuid, cost_name): # noqa: E501 """data_context_topology_context_topologyuuid_nodenode_uuid_...
5,324,601
def remember(event): """ Запоминание образов. """ image1 = []; image2 = []; image3 = [] for i in range(len_vector): image1.append(c1[i].get()) image2.append(c2[i].get()) image3.append(c3[i].get()) if image1[i] == 0: image1[i] = -1 if image2[i] == 0: image2[i]...
5,324,602
async def joinUserChannel(cls:"PhaazebotTwitch", Message:twitch_irc.Message, Context:TwitchCommandContext) -> None: """ allowed user and admin to like phaaze to a channel """ alternative_target:str = "" UserPerm:TwitchPermission = TwitchPermission(Message, None) if UserPerm.rank >= TwitchConst.REQUIRE_ADMIN: #...
5,324,603
def download_manager(main_keywords, extra_keywords=None, download_dir=None, total=None, download=True): """Delegator function | Takes care to call download_images for each main_keywords | Args are the same as download_images function""" for n in range(len(main_keywords)): download_images(main_keywor...
5,324,604
def budget_balanced_ascending_auction( market:Market, ps_recipes: list)->TradeWithMultipleRecipes: """ Calculate the trade and prices using generalized-ascending-auction. Allows multiple recipes, but only of the following kind: [ [1,0,0,x], [0,1,0,y], [0,0,1,z] ] (i.e., there are n-1 buyer c...
5,324,605
def test_streamrewriter_in_to_out_no_out_path(temp_file_creator): """Stream Rewriter in place edit with path object.""" rewriter = filesystem.StreamRewriter(get_arb_formatted_iter) path_in = temp_file_creator() path_in.write_text('yyy') with patch_logger( 'pypyr.utils.filesystem', logg...
5,324,606
def copy_inputs(paths, file_list): """.. Create copies to inputs from list of files containing copying instructions. Create copies using instructions contained in files of list ``file_list``. Instructions are `string formatted <https://docs.python.org/3.4/library/string.html#format-string-synt...
5,324,607
def validate_api_key_id(api_key_id): """ >>> validate_api_key_id('3ddaeeb10ca690df3fee5e3bd1c329fa') >>> validate_api_key_id('3ddaeeb10ca690df3f') # doctest: +ELLIPSIS +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... VeracodeCredentialsError: API key ... is 18 characters, wh...
5,324,608
def agaricus_lepiota() -> Tuple[np.ndarray, np.ndarray, np.ndarray, List[ALFeature]]: """ Source: https://archive.ics.uci.edu/ml/datasets/Mushroom The function requires the file 'agaricus-lepiota.data' to be in the current folder. Returns the loaded dataset as a tuple of NumPy arrays, ...
5,324,609
def receiveVoteFromLowLevel(): """ input -> params which is received from lower level in the hierarchy return -> 200, 400 params = { string: int "candidate_id_1": num_votes, "candidate_id_2": num_votes, "candidate_id_3": n...
5,324,610
def test_cli_run_as_entrypoint(): """Test the entrypoint script can be called. Allows verification that CLI tool is correctly installed? (via setup.py) """ # Note - the script tool name is set in the entry_points section of setup.py # TODO add a documentation cross ref here out = subprocess.run...
5,324,611
def patch286() -> PatchDiscriminator: """ Patch Discriminator from pix2pix """ return PatchDiscriminator([64, 128, 256, 512, 512, 512])
5,324,612
def best_exons(fp_in,fp_out,rank_by='log2_fold_change', probeset_col=0,gene_symbol_col=1,log2_fold_change_col=12, p_value_col=13): """Read exon data from file, find 'best' exons & output averaged data This function performs the 'best_exons' procedure: it reads exon data from a...
5,324,613
def prefix(m): """Given a NFA `m`, construct a new NFA that accepts all prefixes of strings accepted by `m`. """ if not m.is_finite(): raise ValueError('m must be a finite automaton') f = set(m.get_accept_states()) size = None while len(f) != size: size = len(f) for t...
5,324,614
def _predict_k_neighbors(estimator, X): """Predict using a k-nearest neighbors estimator.""" X = estimator._validate_data(X, reset=False) neigh_dist, neigh_ind = estimator.kneighbors(X) neigh_Y = estimator._y[neigh_ind] neigh_weights = _get_weights(neigh_Y, neigh_dist, estimator.weights) retu...
5,324,615
def _loop_over(var): """ Checks if a variable is in the form of an iterable (list/tuple) and if not, returns it as a list. Useful for allowing argument inputs to be either lists (e.g. [1, 3, 4]) or single-valued (e.g. 3). Parameters ---------- var : int or float or list Variable to che...
5,324,616
def _get_servings_rest(): """ Makes a REST request to Hopsworks to get a list of all servings in the current project Returns: JSON response parsed as a python dict Raises: :RestAPIError: if there was an error with the REST call to Hopsworks """ method = constants.HTTP_CONFIG.H...
5,324,617
def start(): """ Starts ser2sock """ try: sh.ser2sock('-d', _bg=True) except sh.CommandNotFound, err: raise NotFound('Could not locate ser2sock.')
5,324,618
def transform_database_account_resources( account_id: Any, name: Any, resource_group: Any, resources: List[Dict], ) -> List[Dict]: """ Transform the SQL Database/Cassandra Keyspace/MongoDB Database/Table Resource response for neo4j ingestion. """ for resource in resources: resource['data...
5,324,619
def test_mypy_passes(cookies, context_override): """Generated project should pass mypy.""" sh.make("mypy")
5,324,620
def jacsim(doc1, doc2, docsAsShingleSets,sign_matrix): """ Jaccard Similarity. :param doc1: First doc to be compared :param doc2: Second doc to be comapred :param docsAsShingleSets: Document wise shingles :param sign_matrix: The Signature matrix :return: The jaccard similarity value """ ...
5,324,621
def train(model, loss_function, optimizer, train_loader, val_loader=None, max_epochs=100, verbose=False, debug=False): """ Helper method for training a model. Args: model: PyTorch model. loss_function: Loss function. optimizer: Loss function. train_loader: pytorch DataLoader...
5,324,622
def recent_stream(model_name=None, filter=None): """ return a dict, key the model name of the most recent stream, with stage and date model_name : str | None the full name of the model, e.g. P302_8years/uw8000. If None, use the current folder path """ if model_name is None: model_name='/'.join(...
5,324,623
def batch_tile_redshifts(tileid, exptable, group, spectrographs=None, submit=False, queue='realtime', reservation=None, dependency=None, system_name=None, run_zmtl=False, noafterburners=False): """ Generate batch script for spectra+coadd...
5,324,624
def symplot(b, max_m = 20, max_n = 20, ymin = None, sqrts = False, log = True, B0 = True, helical_detail = False, legend_args = {"loc":"best"}, **kwargs): """ Plot the radial variation of all the Fourier ...
5,324,625
def get_holistic_keypoints( frames, holistic=mp_holistic.Holistic(static_image_mode=False, model_complexity=2) ): """ For videos, it's optimal to create with `static_image_mode=False` for each video. https://google.github.io/mediapipe/solutions/holistic.html#static_image_mode """ keypoints = []...
5,324,626
def get_arp_info(pkt): """ Break the ARP packet into its components. """ if len(pkt) < 8: raise ARPError("ARP header too short") ar_hrd, ar_pro, ar_hln, ar_pln, ar_op = struct.unpack("!HHBBH", pkt[0:8]) pkt_len = 8+(2*ar_hln)+(2*ar_pln) if len(pkt) < pkt_len: raise ARPError("...
5,324,627
def update_ref_point(ref_point, fy): """ Update the reference point by an offspring parameter ---------- ref_point: 1D-Array the position of original reference point fy: 1D-Array the fitness values of the offspring return ---------- 1D-Array the position of the up...
5,324,628
def parse(grm: util.PathLike, datum: str, **kwargs: Any) -> interface.Response: """ Parse sentence *datum* with ACE using grammar *grm*. Args: grm (str): path to a compiled grammar image datum (str): the sentence to parse **kwargs: additional keyword arguments to...
5,324,629
def EVLAPolCal(uv, InsCals, err, InsCalPoln=None, \ doCalib=2, gainUse=0, doBand=1, BPVer=0, flagVer=-1, \ solType=" ", fixPoln=False, avgIF=False, \ solInt=0.0, refAnt=0, ChInc=1, ChWid=1, \ doFitRL=False, doFitOri=True, check=False, debug =...
5,324,630
def harvest(ctx, mode, reset=False, no_promote=False, version=None): """ Starts a harvest tasks on the AWS container cluster or localhost """ command = ["python", "manage.py", "run_harvest"] if reset: command += ["--reset"] if no_promote: command += ["--no-promote"] run_harv...
5,324,631
def check_and_store(codechecker_cfg, test_project_name, test_project_path, clean_project=True): """ Check a test project and store the results into the database. :checkers parameter should be a list of enabled or disabled checkers Example: ['-d', 'deadcode.DeadStores'] """ ...
5,324,632
def ansyArticle(data): """分析错误日志""" ids=[] with open(data,'r') as fp: i=0 for line in fp.readlines(): i+=1 if i%5==1: m=re.search('view_(\d+)\.aspx',line) ids.append(m.group(1)) else: continue return ids
5,324,633
def climb_stairs(n): """ Number of paths to climb n stairs if each move comprises of climbing 1 or 2 steps. Args: n integer Returns: integer Preconditions: n >= 0 """ return fib(n)
5,324,634
def randomInt(bit_length, seed): """Returns a random integer.""" s = randomHexString((bit_length + 3) / 4, seed) return int(s, 16) % (1 << bit_length)
5,324,635
def test_logout(mock_log_out, client, session): """ Test the GET method of the logout endpoint. """ resp = client.get('/logout', follow_redirects=True) mock_log_out.assert_called_once() assert resp.status_code == 200 assert request.endpoint == 'main.home'
5,324,636
def config_init(): """Add configuration options to weechat.""" global KEEP_ALIVE_TIMEOUT config = { "hide_inactive": ("off", "Hide inactive buffers"), "hide_private": ("off", "Hide private buffers"), "unhide_low": ("off", "Unhide a buffer when a low priority message (lik...
5,324,637
def best_fit_distribution(data, bins=200, ax=None): """Find the best fitting distribution to the data""" # Get histogram of original data y, x = np.histogram(data, bins=bins, density=True) x = (x + np.roll(x, -1))[:-1] / 2.0 # Distributions to check DISTRIBUTIONS = [ st.alpha, s...
5,324,638
def display_last_contracts( past_transaction_days: int = 2, num: int = 20, sum_contracts: bool = False, export: str = "", external_axes: Optional[List[plt.Axes]] = None, ): """Last government contracts [Source: quiverquant.com] Parameters ---------- past_transaction_days: int ...
5,324,639
def cumulative_completion_rate(completion_times, inc, top): """ Gets the cumulative completion rate data from an array of completion times. Starting from zero, time is incremented by `inc` until `top` is reached (inclusive) and the number of timestamps in `completion_times` under the current time is...
5,324,640
def _bfs_relational(adj, roots, max_nodes_per_hop=None): """ BFS for graphs with multiple edge types. Returns list of level sets. Each entry in list corresponds to relation specified by adj_list. Modified from dgl.contrib.data.knowledge_graph to node accomodate sampling """ visited = set() c...
5,324,641
def test_get_range_count_positive(loaded_store: DynamoStore, key_type_and_group) -> None: """ Tests that the range get does not include the blocks that lie on the boundary """ key = Key(key_type_and_group[0], 'user1', key_type_and_group[1]) blocks = loaded_store.get_range(key, datetime(2018, 3, 7, 1...
5,324,642
def fitPeak(stack, slices, width, startingfit, **kwargs): """ Method to fit a peak through the stack. The method will track the peak through the stack, assuming that moves are relatively small from one slice to the next Parameters ---------- slices : iterator an iterator which dict...
5,324,643
def sbol_empty_space (ax, type, num, start, end, prev_end, scale, linewidth, opts): """ Built-in empty space renderer. """ # Default options zorder_add = 0.0 x_extent = 12.0 # Reset defaults if provided if opts != None: if 'zorder_add' in list(opts.keys()): zorder_add = o...
5,324,644
def find_max_1(array: list) -> int: """ O(n^2) :param array: list of integers :return: integer """ overallmax = array[0] for i in array: is_greatest = True for j in array: if j > i: is_greatest = False if is_greatest: overallm...
5,324,645
def make_element(builder, tag, content): """Make an element with this tag and text content""" builder.start(tag, {}) builder.data(content) # Must be UTF-8 encoded builder.end(tag)
5,324,646
def test_get_profile_returns_none_with_wrong_profile(db_session, dummy_request, profile): """get_profile will attempt to find the profile to match the given username but return None if no profile exists.""" from pyramid_todo.views.main import get_profile assert get_profile(dummy_request, 'nhuntwalker') is N...
5,324,647
def radec2xy(hdr,ra,dec): """Transforms sky coordinates (RA and Dec) to pixel coordinates (x and y). Input: - hdr: FITS image header - ra <float> : Right ascension value in degrees - dec <float>: Declination value in degrees Output: - (x,y) <tuple>: pixel coordinates """ wcs = wcs.WCS(hdr) skycrd = n...
5,324,648
def getStepsBySerialNoAndProcessID(SerialNo, ProcessID): """ 根据流水号和表单ID获取该表单的所有的步骤 :param SerialNo:流水号 :param ProcessID:表单ID :return:返回{"name":步骤名称,"value":步骤ID,"state":步骤状态} """ raw = Raw_sql() raw.sql = "SELECT a.StepID as value, b.StepName as name, Finished as state FROM RMI_TASK_PROCESS_STEP a WITH(NOLOCK) ...
5,324,649
def async_process_queue_worker(func, q_in, q_out, *args, **kwargs): """This is the worker function for a sub-process""" # make sure that we create a new event loop for the new process loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) # set up the queues to operate correctly on this proces...
5,324,650
def _split_train_dataset(y, tx, jet_num_idx=22): """Split the given training dataset into three distinct datasets. Datasets are split depending on the value of the 'PRI_jet_num' column, since this column dictates the -999 values for all the columns containing the latter (except for the 'DER_mass_MMC' c...
5,324,651
def bear( transitions=None, # Common settings discount_factor=0.99, # Adam optimizer settings lr_q=1e-3, lr_pi=1e-3, lr_enc=1e-3, lr_dec=1e-3, # Training settings minibatch_size=100, polyak_rate=0.005, # BEAR settings ...
5,324,652
def benchmark(setup=None, number=10, repeat=3, warmup=5): """A parametrized decorator to benchmark the test. Setting up the bench can happen in the normal setUp, which is applied to all benches identically, and additionally the setup parameter, which is bench-specific. Parameters ---------- ...
5,324,653
def make_dummy_protein_sequence( n_supporting_variant_reads, n_supporting_variant_sequences, n_supporting_reference_transcripts, n_total_variant_sequences=None, n_total_variant_reads=None, n_total_reference_transcripts=None, gene=["TP53"], amino_acids="MKH...
5,324,654
def parse_file(file): """Parses a YAML file containing the bingo board configuration""" with open(file=file, mode="r", encoding='UTF-8') as stream: try: config = yaml.safe_load(stream) except YAMLError as err: sys.exit("Failed to parse YAML: " + err) return config
5,324,655
def process_dataset(path): """Maps entities and relations to ids and saves corresponding pickle arrays. Args: path: Path to dataset directory. Returns: examples: Dictionary mapping splits to with Numpy array contatining corresponding KG triples. filters: Dictionary containing filters f...
5,324,656
def prepare_data(): """Data processing and data partitioning""" prapare_ner = PrepareNer() # entity samples_statistics samples_statistics = defaultdict(int) dataset = [] for file_ann in Path(Config.annotation_data_dir).rglob("*.ann"): file_txt = str(file_ann.with_suffix('.txt')) ...
5,324,657
def InlineEditor(item: Item, view, pos: Optional[Tuple[int, int]] = None) -> bool: """Show a small editor popup in the diagram. Makes for easy editing without resorting to the Element editor. In case of a mouse press event, the mouse position (relative to the element) are also provided. """ ret...
5,324,658
def getMetrics(trueLabels, predictedLabels): """Takes as input true labels, predictions, and prediction confidence scores and computes all metrics""" MSE = sklearn.metrics.mean_squared_error(trueLabels, predictedLabels, squared = True) MAE = sklearn.metrics.mean_absolute_error(trueLabels, predictedLabels) ...
5,324,659
def test_cartesian_to_zero_one(): """ Test to ensure values are mapped to [0, 1] """ cart = np.random.randn(2, 1000) x, _, _ = legacy.cartesian_to_zero_one(*cart) assert np.logical_and(x >= 0, x <= 1).all()
5,324,660
def create_data(feed_slug): """Post Data Post a data point to a feed --- tags: - "Data Points" parameters: - name: feed_slug in: path type: string required: true - name: value in: body schema: type: object ...
5,324,661
def save_vqc(model, path): """ Saves the qsvm model to a certain path. @model :: qsvm model object. @path :: String of full path to save the model in. """ joblib.dump(model, path) print("Trained model saved in: " + path)
5,324,662
async def get_hitokoto(*, c: Optional[str] = None) -> Result.TextResult: """获取一言""" url = 'https://v1.hitokoto.cn' params = { 'encode': 'json', 'charset': 'utf-8' } if c is not None: params.update({'c': c}) headers = HttpFetcher.DEFAULT_HEADERS.update({'accept': 'applica...
5,324,663
def img_unnormalize(src): """ Unnormalize a RGB image. :param src: Image to unnormalize. Must be RGB order. :return: Unnormalized Image. """ img = src.copy() img *= NORMALIZE_VARIANCE img += NORMALIZE_MEAN return img.astype(np.uint8)
5,324,664
def upilab5_9_6() : """5.9.6. Exercice UpyLaB 5.26 - Parcours bleu rouge Une matrice M = \{m_{ij}\} de taille {n}\times{n} est dite antisymétrique lorsque, pour toute paire d’indices i, j, on a m_{ij} = - m_{ji}. Écrire une fonction booléenne antisymetrique(M) qui teste si la matrice M reçue est antisymétrique....
5,324,665
def update(statement): """ Runs an execute command. It should be an UPDATE statement. Unlike `_insert` and `_query`, this function is public because there is no clean and efficient way to create a general purpose update function. This requires raw SQL to be written outside of `databa...
5,324,666
def test_backspace_cmd(vim_bot, text, cmd_list, cursor_pos): """Test backspace command.""" _, _, editor, vim, qtbot = vim_bot editor.set_text(text) cmd_line = vim.get_focus_widget() for cmd in cmd_list: if isinstance(cmd, str): qtbot.keyClicks(cmd_line, cmd) else: ...
5,324,667
def info(request): """provide readable information for *request*.""" qs = request.get('QUERY_STRING') aia = IAdditionalInfo(request, None) ai = aia and str(aia) return (request.get('PATH_INFO', '') + (qs and '?' + qs or '') + (ai and (' [%s] ' % ai) or '') )
5,324,668
def put(entity_pb, **options): """Store an entity in datastore. The entity can be a new entity to be saved for the first time or an existing entity that has been updated. Args: entity_pb (datastore_v1.types.Entity): The entity to be stored. options (Dict[str, Any]): Options for this re...
5,324,669
def get_country_flag(country): """Returns the corresponding flag of a provided country.""" with nation_flag_info as flag_path_info: # Validate the provided nation string. if country.title().replace('_', ' ') not in flag_path_info.keys() and \ country.title().replace(' ', '_') not in flag_path...
5,324,670
def add_time_columns(df): """ @param df: the dataframe you want to add the columns @return: the same dataframe as input, but with new columns """ df['Month'] = df['YYYYMMDD'].str[4:6].astype(np.float64) df['Day'] = df['YYYYMMDD'].str[6:8].astype(np.float64) df['Hour'] = df['hhmmss...
5,324,671
def create_graph_to_decode_and_normalize_image(): """See file docstring. Returns: input: The placeholder to feed the raw bytes of an encoded image. y: A Tensor (the decoded, normalized image) to be fed to the graph. """ image = tf.placeholder(tf.string, shape=(), name='encoded_image_bytes') with tf.n...
5,324,672
def stackbar(x, y, colors=None, **kwargs): """ Given an array of vectors in y, draw a bar chart for each one stacked on the prior. """ x = np.asarray(x) if colors is None: colors = ["" for i in range(0, y.shape[0])] # Stack positive and negative separately for op in ("__ge__", "_...
5,324,673
def bilinear_upsample(x, scale=2): """Bilinear upsample. Caffe bilinear upsample forked from https://github.com/ppwwyyxx/tensorpack Deterministic bilinearly-upsample the input images. Args: x (tf.Tensor): a NHWC tensor scale (int): the upsample factor Returns: tf.Tenso...
5,324,674
def verbose_print(msg: str): """ Verbose Printer. Print called message if verbose mode is on. """ if CONF.debug.verbose and CONF.debug.verbose_level: verbose_level = CONF.debug.verbose_level else: return if verbose_level > 1: print('> ' + msg, file=sys.stderr) ...
5,324,675
def _generate_simplifiers_and_detailers(): """Generate simplifiers, forced full simplifiers and detailers.""" simplifiers = OrderedDict() forced_full_simplifiers = OrderedDict() detailers = [] def _add_simplifier_and_detailer(curr_type, simplifier, detailer, forced=False): if detailer in de...
5,324,676
def read_machine_def(): """ Reads the machine definition file. """ return read_yaml_file(machine_def_file)
5,324,677
def zoo_start(args = '-net_type=mpi -sync=true'): """Start the Zoo, all the Actors will be registered. """ check_call(LIB.HPPS_ZooStart(c_str(args)))
5,324,678
def read_libsvm_format(file_path: str) -> 'tuple[list[list[int]], sparse.csr_matrix]': """Read multi-label LIBSVM-format data. Args: file_path (str): Path to file. Returns: tuple[list[list[int]], sparse.csr_matrix]: A tuple of labels and features. """ def as_ints(str): retu...
5,324,679
def cristal_load_motor(datafile, root, actuator_name, field_name): """ Try to load the CRISTAL dataset at the defined entry and returns it. Patterns keep changing at CRISTAL. :param datafile: h5py File object of CRISTAL .nxs scan file :param root: string, path of the data up to the last subfolder ...
5,324,680
def trackPlot(mat, fig=None, groups=None, ratios=None, labels=None, cmap=None, norm=None, is2D=False, xticks=False): """ This function takes a matrix and generates a track figure with several panel according to a group structure that groups several rows/cols of the matrix into one panel. This can be done fo...
5,324,681
def concatenate( *, target_list: List[str], is_colored: bool = False, number_x: Optional[int] = None, ): """api to concatenate movie/picture (note: keyword-only argument) Args: target_list (List[str]): list of movies, pictures or directories where pictures are stored. is_colored (bool, ...
5,324,682
def split_at(n, coll): """ Returns a tuple of ``(take(n, coll), drop(n coll))``. """ if n <= 0: return [], coll if coll is None: return [], [] # Unfortunately we must consume all elements for the first case because # unlike Clojure's lazy lists, Python's generators yield th...
5,324,683
def clip(x: ArrayLike, lo: ArrayLike = None, up: ArrayLike = None) -> ShapeletsArray: """ Element-wise, limits the values in an array Parameters ---------- x: ArrayLike Input array expression lo: Optional ArrayLike (defaults: None) Low values up: Optional ArrayLike (defa...
5,324,684
def determineNewest(uid, homeType): """ Construct a query to determine the modification time of the newest object in a given home. @param uid: the UID of the home to scan. @type uid: C{str} @param homeType: The type of home to scan; C{ECALENDARTYPE}, C{ENOTIFICATIONTYPE}, or C{EADDRESS...
5,324,685
def get_data(limit = None, filename = "C:/Users/Marcel/OneDrive/Python Courses/Machine Learning/train.csv"): """ Reads the MNIST dataset and outputs X and Y. One can set a limit to the number of rows (number of samples) by editing the 'limit' """ print("Reading in and transforming data...") data...
5,324,686
def vech(A): # TODO: why not just use A[np.triu_indices(A.shape[0])]? """ Simple vech operator Returns ------- vechvec: vector of all elements on and below diagonal """ length = A.shape[1] vechvec = [] for i in range(length): b = i while b < length: vechv...
5,324,687
def file_size(value, fmt="{value:.1f} {suffix}", si=False): """ Takes a raw number of bytes and returns a humanized filesize. """ if si: base = 1000 suffixes = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB") else: base = 1024 suffixes = ("B", "KiB", "MiB", "GiB"...
5,324,688
def login(): """ This method logs the user into the account. It checks the username and the password in the database. --- Args: None Returns: If log in is successful redirects the user to account page """ if request.method == 'POST': email = request.form.get('email') pas...
5,324,689
def index_select_op_tensor(input, dim, index): """ input.index_select(dim, index) -> Tensor See :func:`oneflow.index_select` """ return index_select_op(input, dim, index)
5,324,690
def cull(dsk, keys): """ Return new dask with only the tasks required to calculate keys. In other words, remove unnecessary tasks from dask. ``keys`` may be a single key or list of keys. Examples -------- >>> d = {'x': 1, 'y': (inc, 'x'), 'out': (add, 'x', 10)} >>> dsk, dependencies = cull...
5,324,691
def validate_coot(config, model, val_loader, epoch, constrastive_loss, cmc_loss, writer, logger, use_cuda=True): """Validate COOT model Args: model: COOT model dataloade...
5,324,692
def iniStressProfile((z,dz),(zMin,zMax),ma): """initial acoustic stress profile \param[in] z z-axis \param[in] dz axial increment \param[in] zMin start of new tissue layer \param[in] zMax end of new tissue layer \param[in] ma absorption coefficient ...
5,324,693
def OpenCredentials(cred_path: str): """ Opens and parses an AWS credentials file. :param cred_path: Path to the file containing the credentials :return: A dict containing the credentials """ with open(cred_path) as file: keys, values = map(lambda s: s.strip().split(','), file) cred...
5,324,694
def content_loop_rate(best, n,file_path,file_id, loop_time=20,height=100): """固定迭代次数 Args: best (dict): 最优良的个体 n (NEST): 打包者 file_path (str): 保存路径 file_id (str): 文件id loop_time (int, optional): 迭代次数. Defaults to 20. height (int, optional): 默认高度. Defaults to 100. ...
5,324,695
def get_follow_users(): """ Get all the users stored in the cookie """ follow_users = [] if "follow" in request.cookies: follow_users = request.cookies["follow"] follow_users = follow_users.split(delim) return follow_users
5,324,696
def generate_user_agent(os=None, navigator=None, device_type=None): """ Generates HTTP User-Agent header :param os: limit list of os for generation, possible values: "win", "linux", "mac", "android", "ios", "all" :type os: string or list/tuple or None :param navigator: limit list of ...
5,324,697
def _make_builders( args: argparse.Namespace, ds_to_build: str, ) -> Iterator[tfds.core.DatasetBuilder]: """Yields builders to generate.""" builder_cls, builder_kwargs = _get_builder_cls(ds_to_build) # Eventually overwrite version if args.experimental_latest_version: if 'version' in builder_kwargs:...
5,324,698
def usage_demo(state_machine_name, resources): """ Creates and runs a Step Functions state machine that calls a Lambda function to retrieve message records from a DynamoDB table and record them as sent. The state machine is then updated to also send messages to an Amazon SQS queue and the state mach...
5,324,699