content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import transformers import torch def prepare_ml_span_inputs(model: transformers.EncoderDecoderModel, tokenizer: transformers.T5TokenizerFast, encoder_input_attention: InputAndAttention, context: Tensor, chunk_size: int, device: int, trim_context: int): """Prep...
6ed0669d588d7b03997201a25ca0b226358233d5
3,635,997
def toolButton(pixmap='', orientation=0, size=None): """ toolbutton function with image :param pixmap: location of the image :type pixmap: string :param orientation: rotation in degrees clockwise :type orientation: int :param size: height and width of image in pixels :type size: int :re...
e07f33a19d67d393e926e2d5d50d91734539df94
3,635,998
def process_hub_timeout(bit): """Return the HUB timeout.""" if bit == '1': return '5 Seconds' return '2 Seconds'
64f11056a341d64d670e2e8c918a796c954854a1
3,635,999
import torch def sen_loss(outputs, all_seq, dim_used, dct_n): """ :param outputs: N * (seq_len*dim_used_len) :param all_seq: N * seq_len * dim_full_len :param input_n: :param dim_used: :return: """ n, seq_len, dim_full_len = all_seq.data.shape dim_used_len = len(dim_used) dim_...
e570a142fc7c709de599e9864ec0a074e28b81ac
3,636,000
def get_net_peer_count(endpoint=_default_endpoint, timeout=_default_timeout) -> str: """ Get peer number in the net Parameters ---------- endpoint: :obj:`str`, optional Endpoint to send request to timeout: :obj:`int`, optional Timeout in seconds Returns ------ s...
cd13962e29c6944d5a0bebaa3c63a756d6caa187
3,636,001
def delete_user(user_id: int): """删除""" user = User.query.filter( User.user_id == user_id ).first() if not user: return dbu.inner_error("该不存在或已被删除") db.session.delete(user) try: db.session.commit() except Exception as e: current_app.logger.warning(e) ...
0d2c391eb79ab30a3d80d7caa2c4618e2663a75f
3,636,003
def _combine_odds(odds): """Combine odds of different targets.""" combined_odds = 1 / (1 / odds).sum(axis=1) return combined_odds
a504990dc2c5b00c1c55fe7598bebf2fdecf95b8
3,636,004
def decrypt(pp, skx, cty, max_innerprod=100): """ Performs the decrypt algorithm for IPE on a secret key skx and ciphertext cty. The output is the inner product <x,y>, so long as it is in the range [0,max_innerprod]. """ (k1, k2) = skx (c1, c2) = cty d1 = pair(k1, c1) d2 = innerpro...
4f3e214300a21490a33c4e143ed8d79e30720fe6
3,636,005
def alpha_blend_colors(colors, additional_alpha=1.0): """ Given a sequence of colors, return the alpha blended color. This assumes the last color is the one in front. """ srcr, srcg, srcb, srca = COLOR_CONVERTER.to_rgba(colors[0]) srca *= additional_alpha for color in colors[1:]: ...
cac568988c5794310a058ac98ff8ca572f18432e
3,636,006
def ruled(nrb1, nrb2): """ Construct a ruled surface/volume between two NURBS curves/surfaces. Parameters ---------- nrb1, nrb2 : NURBS """ assert nrb1.dim == nrb2.dim assert nrb1.dim <= 2 assert nrb2.dim <= 2 nrb1, nrb2 = compat(nrb1, nrb2) Cw = np.zeros(nrb1.shape+(2,...
c74ed6ff2485d115f3e387de96c779017e6ea62b
3,636,007
import time async def db_head_state(): """Status/health check.""" sql = ("SELECT num, created_at, extract(epoch from created_at) ts " "FROM hive_blocks ORDER BY num DESC LIMIT 1") row = DB.query_row(sql) return dict(db_head_block=row['num'], db_head_time=str(row['created_at'...
4ffbf84c2e28f91f9182e9b8a4d214ff953c30fd
3,636,008
def d_d_theta_inv(y, alpha): """ xi'(y) = 1/theta''(xi(y)) > 0 = alpha / (1 - |y|)^2 Nikolova et al 2014, table 1, theta_2 and eq 5. """ assert -1 < y < 1 and alpha > 0 denom = 1 - abs(y) return alpha / (denom*denom)
8ed796a46021f64ca3e24972abcf70bd6f64976d
3,636,009
async def add_item( item: ItemEditableFields, db_session: Session = Depends(get_db_session) ): """This handler adds item to the DB. Args: item: ItemEditableFields. The data of item to be added to the DB. db_session: Session. The database session used to interact with the DB. ...
487d26f4d7858a6f720e3f12cb5a2295e0eb6370
3,636,010
def center_crop(img, crop_height, crop_width): """ Crop the central part of an image. Args: img (ndarray): image to be cropped. crop_height (int): height of the crop. crop_width (int): width of the crop. Return: (ndarray): the cropped image. """ def get_center_crop_...
6e5fafee8c34632b61d047e9eb66e9b08b5d0203
3,636,011
import logging import signal def membOutDet(input_slc, cell_mask=10, outer_mask=30, det_cutoff=0.75): """ Detection of mYFP maxima in the line of interest. Algorithm is going from outside to inside cell and finding first outer maxima of the membrane. "cell_mask" - option for hiding inner cell region ...
24077afc3321612c017475ae4f81a25e375369a4
3,636,012
def qaoa_ansatz(gammas, betas): """ Function that returns a QAOA ansatz program for a list of angles betas and gammas. len(betas) == len(gammas) == P for a QAOA program of order P. :param list(float) gammas: Angles over which to parameterize the cost Hamiltonian. :param list(float) betas: Angles ov...
c1b6d45430b9d2d09fe19ea2f505c7cd806c684a
3,636,014
import psutil from datetime import datetime def print_header(procs_status, num_procs): """Print system-related info, above the process list.""" def get_dashes(perc): dashes = "|" * int((float(perc) / 10 * 4)) empty_dashes = " " * (40 - len(dashes)) return dashes, empty_dashes # c...
8986f5852e6922a5ff5e396d6b133eb560414883
3,636,015
def approximated_atmo_spectrum(energy): """Gives an approximated atmospheric neutrino spectrum. Can be used for comparing expected true energy distribution to recorded energy proxy distributions. It is normalised such that the weight for an energy of 1 is equal to 1. (It is agnostic to energy units) ...
86768b5ba0bd31ef19a89dfe27af6c793492daa7
3,636,016
def to_csv(logbook, filename, output=False): """ Write a logbook to a CSV file. The output file is readable using an ordinary CSV reader, e.g. ``pandas.read_csv``. Alternatively you may read it back into a logbook format using ``gt.ops.from_csv``. """ logs = [] for unique_trip_id in log...
4517d8812c795cf856575b7a93fe3be7a912ec8d
3,636,017
import collections def flatten_dict(d, parent_key="", sep="_"): """ Flatten a dictionnary """ items = [] for k, v in d.items(): new_key = parent_key + sep + k if parent_key else k if v and isinstance(v, collections.MutableMapping): items.extend(flatten_dict(v, new_key, ...
36c63188fc49950ac493c2fa7bf72369b465fe3c
3,636,018
def request_mxnet_inference(ip_address="127.0.0.1", port="80", connection=None, model="squeezenet"): """ Send request to container to test inference on kitten.jpg :param ip_address: :param port: :connection: ec2_connection object to run the commands remotely over ssh :return: <bool> True/False b...
886f86b9456c49df42c636391a5305ca57c7e913
3,636,019
def get_ts_pid(pidfile): """Read a pidfile, return a PID.""" try: with open(pidfile) as f: pid = f.readline() except EnvironmentError: LOG.warning("Unable to read pidfile; process metrics will fail!") pid = None return pid
75cb541af8a4b8958b497ed6407497cef4baa614
3,636,021
def conjg(a): """ Find the complex conjugate values of the input. Parameters ---------- a : af.Array Multi dimensional arrayfire array. Returns -------- out : af.Array array containing copmplex conjugate values from `a`. """ return _arith_unary_func(a, backend....
75fa1293a00c83b90fa40085222f07f755451897
3,636,022
def obj_size_avg_residual(coeffs, avg_size, class_id): """ :param coeffs: object sizes :param size_template: dictionary that saves the mean size of each category :param class_id: nyu class id. :return: size residual ground truth normalized by the average size """ size_residual = (coeffs - av...
8d44d4ebf273baf460195ec7c6ade58c8d057025
3,636,023
import re def search_content(obj): """Get the excerpt in which the searched term matches the content.""" indexable_text = [] if hasattr(obj, 'excerpt'): if obj.excerpt: indexable_text.append(obj.excerpt) if not hasattr(obj, 'content_editor'): return ' '.join(indexable_text...
e6bdc25d0ac15d76fd7ddac805c619957a31e6c4
3,636,024
import requests import json def get_total_num_activities(): """Query the IATI registry and return a faceted list of activity counts and their frequencies. The total number of activities is then calculated as the sum of the product of a count and a frequency. E.g. if "30" is the count and the frequency is...
5752a6d5fe5f2bd6125936b639de2ff5226b51ac
3,636,025
def _get_chromosome_dirs(input_directory): """Collect chromosome directories""" dirs = [] for d in input_directory.iterdir(): if not d.is_dir(): continue # Just in case user re-runs and # does not delete output files elif d.name == 'logs': continue ...
5047c0c158f11794e312643dbf7d307b381ba59f
3,636,026
import warnings def calculateCumTimeDiff(df): """ Calculates the cumulative of the time difference between points for each track of 'dfTrack'. """ warnings.warn("The calculateCumTimeDiff function is deprecated and " "will be removed in version 2.0.0. " "Use the ...
6c4b21f07a0d564e63a7b485a1f5d5e831d51058
3,636,027
def optimalPriceFast(z_list, V_list, U, s_radius, max_iter = 1e4): """ Returns tuple of optimal prices p^* chosen in hindsight, and revenue achieved if we know z_t (list of 1-D arrays) V_t (list of 2-D arrays), and U (2-D array) is Orthogonal! Performs optimization over low-dimensional acti...
15fb22257e19b6abf46545dd05d23a6bc7a31da9
3,636,028
def extract_seqIdList_from_cluster(cluster_name, cluster_dic, extract_id, allSeqDf, idName, match_method="contains"): """ For all sequences in a cluster, find corresponding sequences in the dataframe. The extract_id function is used to extract a id that will be used to find the matching entry in th...
de22b77e897c9ca9d14f250e160d6e06790c9b22
3,636,029
def format_imports(import_statements): """ ----- examples: @need from fastest.constants import TestBodies @end @let import_input = TestBodies.TEST_STACK_IMPORTS_INPUT output = TestBodies.TEST_STACK_IMPORTS_OUTPUT @end 1) format_imports(import_input) -> output ----- :...
91514d19da4a4dab8c832e6fc2d3c6cbe7cca04a
3,636,030
import re def parse_modmap(lines): """Parse a modmap file.""" re_range = re.compile(r'KeyCodes range from (\d+) to') lower_bound = 8 re_line = re.compile(r'^\s+(\d+)\s+0x[\dA-Fa-f]+\s+(.*)') re_remainder = re.compile(r'\((.+?)\)') ret = ModMapper() for line in lines.split('\n'): if...
23bfac476377bd549b15bf77fcc47716d61d6908
3,636,031
def read_evoked(fname, setno=None, baseline=None, kind='average', proj=True): """Read an evoked dataset Parameters ---------- fname : string The file name. setno : int or str | list of int or str | None The index or list of indices of the evoked dataset to read. FIF files ca...
f985a6bb5fdfcec92a567470f78b1ed0b0014356
3,636,032
def construct_lexically_addressed_lambda_tree(lambda_tree, surrounding_scope=None): """ Out of a "bare" LambdaTree constructs a LexicallyAddressedLambdaTree, i.e. a tree of lambdas where the nodes are decorated with a dict like so: {symbol: scopes_up_count} It does this by going down the tree, cal...
a838a15b287940b6a32acd0f15e38e146a1a871c
3,636,033
def get_all_news(num_page, limit): """Get all users""" news = News.objects.paginate(page=num_page, per_page=limit) response_object = { 'status': 'success', 'data': news.items, } return jsonify(response_object), 200
a74e30958aedc8dfbc34174ab7e420a22a68c452
3,636,035
def correlations(X, y=None): """ given a pandas DataFrame returns correlation matrix and figure representing the correlations :param y: [pandas Series] target column :param X: [pandas DataFrame] predictor columns :param size: matplotlib figure size :return: correlation matrix and figure represen...
5a84ce44a99662cb4d5cbc72324170e9535aa633
3,636,036
def consensus(): """ Resolve the blockchain based on consensus algorthim when multiple nodes are conencted """ replaced = blockchain.resolve_conflicts() if replaced: response = { 'message': 'Our chain was replaced', 'new_chain': blockchain.chain } else: ...
1026ffe3da9d0306b55c1807a82576d456825b6f
3,636,037
def sha256_secrethash(secret: Secret) -> SecretHash: """Compute the secret hash using sha256.""" return SecretHash(sha256(secret).digest())
9af5d9507575e5fe474eb5fe73d8060825d91add
3,636,039
import requests def make_http_request(method, url, check_response=None, *args, **kwargs): """ Make an HTTP request with the global session. :return: The response object. :raises: WebserviceException """ session = get_requests_session() response = ClientBase._execute_func(lambda *args, **k...
6f88174e61a75e3452a4cf839bb956aba27411f9
3,636,040
def get_pages_matches_no_prep(title, edition, archive, filename, text, keysentences): """ Get pages within a document that include one or more keywords. For each page that includes a specific keyword, add a tuple of form: (<TITLE>, <EDITION>, <ARCHIVE>, <FILENAME>, <TEXT>, <KEYWORD>) If a ...
9a536f7532a77c39172a7deb32dd99d73f629f02
3,636,041
import mpmath def sf(k, r, p): """ Survival function of the negative binomial distribution. Parameters ---------- r : int Number of failures until the experiment is stopped. p : float Probability of success. """ with mpmath.extradps(5): k = mpmath.mpf(k) ...
d836e2cd762c5fa2be11d83aae31ba5d8589b3f0
3,636,042
def process_menu(menu: Menu, perms: PermWrapper) -> MenuGroup: """Enable a menu item if view permissions exist for the user.""" for group in menu.groups: for item in group.items: # Parse the URL template tag to a permission string. app, scope = item.url.split(":") obj...
748d9e1687c661a9b1a2dee32315eadaf54e4fac
3,636,043
def _grid_in_property(field_name, docstring, read_only=False, closed_only=False): """Create a GridIn property.""" def getter(self): if closed_only and not self._closed: raise AttributeError("can only get %r on a closed file" % field_name...
891e3a828b496467c201ad14e0540abf235d7e64
3,636,044
import logging def Run(benchmark_spec): """Runs memtier against memcached and gathers the results. Args: benchmark_spec: The benchmark specification. Contains all data that is required to run the benchmark. Returns: A list of sample.Sample instances. """ client = benchmark_spec.vm_groups['...
87560ad915fe9626632c1ac24fdbdc461a5dec83
3,636,045
from pb_bss import distribution def get_trainer_class_from_model(parameter): """ >>> from IPython.lib.pretty import pprint >>> from pb_bss.distribution.cacgmm import ( ... ComplexAngularCentralGaussian, ... ) >>> get_trainer_class_from_model(ComplexAngularCentralGaussian).__name__ 'Com...
713e5ea055149b851e8c734ebaabba3491364ccb
3,636,046
def is_fractional_it(input_str, short_scale=False): """ This function takes the given text and checks if it is a fraction. Updated to italian from en version 18.8.9 Args: input_str (str): the string to check if fractional short_scale (bool): use short scale if True, long scale if False ...
c62af11f56f81fe84af7723e181a494d64f07bae
3,636,047
def qchem2molgraph(logfile, return_qobj=False, return_none_on_err=False, **kwargs): """ Convert a Q-Chem logfile to a MolGraph object. Return the QChem object in addition to the MolGraph if return_qobj is True. Catch QChemError if return_none_on_err is True and return None. Options in kwargs are pas...
4cbebcd36ae10e060e0c16fd00501a41e46b425c
3,636,048
def extract_signals(data, fs, segmentation_times): """ Signal that given the set of segmentation times, extract the signal from the raw trace. Args: data : Numpy The input seismic data containing both, start and end times of the seismic data. fs : float The sampling f...
81ff3d0b343dbba218eb5d2d988b8ca20d1a7209
3,636,049
import glob def get_dataset( file_pattern, n_classes, batch_size, volume_shape, plane, n_slices=24, block_shape=None, n_epochs=None, mapping=None, shuffle_buffer_size=None, num_parallel_calls=AUTOTUNE, mode="train", ): """Returns tf.data.Dataset after preprocessing...
da09356f40ab1873efbc7fe03d135f3ed90e951b
3,636,050
import math def cos_d(x:int)->float: """ This function takes in input in radians and returns the computed derivaive of cos which is -sin. """ return -math.sin(x)
e8a0ba95d6a53d8c88bfa867dd423e23eb782911
3,636,051
def rhist(ax, data, **kwargs): """ Create a hist plot with default style parameters to look like ggplot2. kwargs can be passed to changed other parameters. """ defaults = {'facecolor': '0.3', 'edgecolor': '0.36', 'linewidth': 1, 'rwidth': 1} for ...
a0ddefcfd58d42ac6fc2cbaa76a98252debd6e43
3,636,052
def follow(request, username_to_follow): """View that is used to let the login user to follow another user""" try: # If the user is not all ready begin follwed if not request.user.following.filter(username=username_to_follow).exists(): user_to_follow = get_object_or_404(User, usernam...
ad4b60813a35100378a114f67e916e9c8a665a5b
3,636,053
def Neq(left: Expr, right: Expr) -> BinaryExpr: """Difference expression. Checks if left != right. Args: left: A value to check. right: The other value to check. Must evaluate to the same type as left. """ return BinaryExpr(Op.neq, right.type_of(), TealType.uint64, left, right)
b0243c6ea70058bd072b5bf0e4be9e185faea0df
3,636,054
def create_simplex_matrix( dimensions: int, distance: float) -> np.ndarray: """ Create centered normalized N-dimensional simplex structure The structure is described by N+1, N-dimensional points that have the same distance between them :param dimensions: The number of dimensions of t...
c23f8ffc8d5578debc6b7ea92780aa3438a11d86
3,636,055
def asymmetric_lorentz_gauss_sum(x, mu, fwhm_l, fwhm_g, alpha=1.0, beta=1.5): """ asymmetric Lorentzian with Gauss convoluted """ ygaus = np.array(gauss_one(x, fwhm_g, mu)) ylorentz = np.array(asymmetric_lorentz(x, fwhm_l, mu, alpha=alpha, beta=beta)) ydata = ylorentz + ygaus return ydata
163ea45934e199cf06ded309c6d51a0d4cb9ef46
3,636,056
def access(path, mode): """Use the real uid/gid to test for access to path. :type path: bytes | unicode :type mode: int :rtype: bool """ return False
c0baab44d63bf354e4da9e5d0048d8b05c1f8040
3,636,057
import unicodedata def _is_punctuation(char: str) -> bool: """Checks whether `chars` is a punctuation character.""" cp = ord(char) # We treat all non-letter/number ASCII as punctuation. # Characters such as "^", "$", and "`" are not in the Unicode # Punctuation class but we treat them as punctuati...
be6f469f4e53ff911d97edfda3eeb98687db8d59
3,636,058
import ast def get_imports(filename, source=None): """ Returns a list of #ImportInfo tuples for all module imports in the specified Python source file or the *source* string. Note that `from X import Y` imports could also refer to a member of the module X named Y and not the module X.Y. """ def _find_n...
4c866ccef90d047bb1de1d2e2edba97ffcc88636
3,636,059
def follow_card(card, deck_size, shuffles, shuffler): """Follow position of the card in deck of deck_size during shuffles.""" position = card for shuffle, parameter in shuffles: shuffling = shuffler(shuffle) position = shuffling(deck_size, position, parameter) return position
10774bd899afde0d64cbf800bc3dad1d86543022
3,636,060
import tempfile def get_secure_directory(): """get a temporary secure sub directory""" temp_dir = tempfile.mkdtemp(suffix='',prefix='') return temp_dir
08fb9587a2d17778e9a733312b08b504d6aff7bd
3,636,061
def area(shape): """Multimethod dispatch key""" return shape.get('type')
0561d97ad21afdda160bd3063948e884a5c02945
3,636,062
def get_trie_properties(trie, offsets, values): """Obtain the length of every trigger in the trie.""" anchor_length = np.zeros(len(values), dtype=np.int32) start, end = 0, 0 for idx, key in enumerate(trie.iterkeys()): end = offsets[idx] anchor_length[start:end] = len(key) start =...
ade365befbc481efec77a9c7b1d2c2e667c108c9
3,636,063
import torch def besseli(X, order=0, Nk=64): """ Approximates the modified Bessel function of the first kind, of either order zero or one. OBS: Inputing float32 can lead to numerical issues. Args: X (torch.tensor): Input (N, 1). order (int, optional): 0 or 1, defaults to 0. ...
5233398b240244f13af595088077b8e43d2a4b2f
3,636,065
def laplacian_total_variation_kernel(x, y, sigma=1.0, **kwargs): """Geodesic Laplacian kernel based on total variation distance.""" dist = np.abs(x - y).sum() / 2.0 return np.exp(-sigma * dist)
a0d123c28493af4aa1400958bab134230c5735c3
3,636,066
import random def print_mimic(mimic_dict, word): """Given mimic dict and start word, prints 200 random words.""" line, text = '', '' # Iterating 200 time to pick up random keys and values for count in range(0, 200): key = random.choice(list(mimic_dict.keys())) val = mimic_dict.get(key...
61dea92175feff7cb3e3744460ccf692cfc18ca7
3,636,067
from pathlib import Path def get_dataset( dataset_name: str, path: Path = default_dataset_path, regenerate: bool = False, ) -> TrainDatasets: """ Get a repository dataset. The datasets that can be obtained through this function have been used with different processing over time by several...
92f5cf094d1eafb4439dbbd57f0ab7cfab84e4ef
3,636,068
def test_view(regression_id): """ Show a single regression test. :param regression_id: id of the regression test :type regression_id: int :return: Regression test :rtype: dict """ test = RegressionTest.query.filter(RegressionTest.id == regression_id).first() if test is None: ...
5765fcca8ee06e64ecadd346ed228696b2ce9dcb
3,636,069
def data_context_path_computation_context_path_comp_serviceuuid_objective_function_post(uuid, tapi_path_computation_path_objective_function=None): # noqa: E501 """data_context_path_computation_context_path_comp_serviceuuid_objective_function_post creates tapi.path.computation.PathObjectiveFunction # noqa: E50...
88d2e8e9442fd6b71ce0f8bb5a5463101e8ed65a
3,636,070
def tbl_2_nparray(in_tbl, flds): """Form the TableToNumPyArray to account for nulls for various dtypes. This is essentially a shortcut to `arcpy.da.TableToNumPyArray` Requires -------- `in_tbl` : table, or featureclass table name `flds` : list of field names `skip_nulls` = F...
1c18526f9dcd4a388b3df6fa8ba113fc18a9fb0a
3,636,071
import html def _get_paper_page(url: str) -> object: # pragma: no cover """ Get a paper page element from a provided URL Parameters ---------- url : str The paper URL Returns ------- Object A HTML element representing the paper given by the provided URL """ ...
2e112469b5928d3156d7786dc506eb3b2b8c6a74
3,636,072
def check_grid_side(ctx, param, value: int) -> int: """ check the size of the grid :type value: int """ if value < 5: raise ValueError("all sides of grid must be at least 5") return value
9e1403ca90c8f0716e10248b418ca59fe501c0c4
3,636,073
def distributed_transformer_model(input_tensor, attention_mask=None, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, intermediate_act_fn=gelu, hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, initializer_range=0.02, ...
d5210a2969e18766956ff3e052a79f6d9fa86d13
3,636,074
from typing import Counter import math import networkx def sgrank(doc, kp_count, window=1500, idf=None): """ Extracts keyphrases from a text using SGRank algorithm. Args: doc: a spacy.Doc object kp_count: number of keyphrases window: word co-occurrence window length idf: a...
4830e30b85bd3020b7bae8bcd14e3cdac5671648
3,636,075
from typing import List from typing import Tuple def save_quantitative_results(quantitative_results: List[Tuple[int, List[float]]], metric_names: List[str], output_file: str): """ Saves the quantitative results into an output file. The quantitative results are passed as a list of entries, where each entry...
ee83d4c779b9376da84bf649f469ca316c351ceb
3,636,076
def interpret(parsed, source_url, base_href=None, item=None, use_rel_syndication=True, want_json=False, fetch_mf2_func=None): """Interpret a permalink of unknown type. Finds the first interesting h-* element, and delegates to :func:`interpret_entry` if it is an h-entry or :func:`interpret_even...
457b0f90e47ff9e37cda4c9359336ef8d1f24960
3,636,077
from typing import List import re def generate(*drf_globs: DRF_list) -> List[str]: """ Generates a list of valid requests from a DRF glob. :param drf_globs: A list of DRF globs. :return: A list of valid requests. """ results = [] def parse_globs(drf_globs): for drf_glob in drf_gl...
96a8a036b4c659ed72b23c0c16c384b4ea8f7efd
3,636,078
def min_rank(series, ascending=True): """ Equivalent to `series.rank(method='min', ascending=ascending)`. Args: series: column to rank. Kwargs: ascending (bool): whether to rank in ascending order (default is `True`). """ ranks = series.rank(method="min", ascending=ascending) ...
a772618570517a324a202d4803983240cb54396b
3,636,079
def glCurrentViewport(x=None, y=None, width=None, height=None): """ Returns a (x, y, width, height)-tuple with the current viewport bounds. If x, y, width and height are given, set the viewport bounds. """ # Why? To switch between the size of the onscreen canvas and the offscreen buffer. # The c...
e532fbaa710ee203cb75b0951ff560c7536a0b4a
3,636,080
def algorithms(): """Get a list of the names of the available stemming algorithms. The only algorithm currently supported is the "english", or porter2, algorithm. """ return ['english']
d09bef4090fbca1729a25784d7befdb8a436bfa6
3,636,081
import yaml def load_yaml(filepath): """Import YAML config file.""" with open(filepath, "r") as stream: try: return yaml.safe_load(stream) except yaml.YAMLError as exc: print(exc)
e1ec81bf36d293788303e4b3379e45ecdfb38dc0
3,636,082
import json import logging def parse_json(json_path): """ parser JSON Args: json_path: input json file path Returns: json_dict: parser json dict result """ try: with open(json_path) as json_file: json_dict = json.load(json_file) except Exception: l...
4bb9b14d3a751451dd2a75da9b60a355934ffa65
3,636,083
def _get_ex_msg(obj): """ Get exception message """ return obj.value.message if hasattr(obj, 'value') else obj.message
be7be0657afab2fe1daba174c441d18f12e78355
3,636,084
from typing import Any def __getattr__(name: str) -> Any: """Lazily imports modules and items within them. Args: name (str): name of sourdough module or item. Raises: AttributeError: if there is no module or item matching 'name'. Returns: Any: a module or item stored wit...
9ec17f2f2b629e1082402dd7baad8ff8558d8d0b
3,636,085
def _validate_isofactor(isofactor, signed): """ [Docstring] """ if isofactor[0] == 0.0: return (False, "Error: 'isovalue' cannot be zero") if isofactor[1] <= 1.0: return (False, "Error: 'factor' must be greater than one") if not signed and isofactor[0] < 0: return (False,...
7b4a4faf3671fdee364cdae41e178f8e6a0453b8
3,636,087
import itertools def get_response_comments(request, comment_id, page, page_size, requested_fields=None): """ Return the list of comments for the given thread response. Arguments: request: The django request object used for build_absolute_uri and determining the requesting user. ...
2ccc449858329bf9e3b5cbaa4477ca97c3ac50a0
3,636,088
from typing import Optional from typing import cast def GetParentStatementNode( node: AST.Node, ) -> Optional[AST.Node]: """\ Returns the statement that is the logical parent of this node. This code attempts to handle the complexities of embedded phrases (for example, a statement that is made up ...
1ff5ed85b9cc4b67a4a0cc0b2d2df43c8a3560bf
3,636,089
def count_possibilities(dic): """ Counts how many unique names can be created from the combinations of each lists contained in the passed dictionary. """ total = 1 for key, value in dic.items(): total *= len(value) return total
856eee9bac0ddf3dbc7b714bb26fe6d4f003ef95
3,636,090
def user_update(): """ test """ username = request.get_json()['username'] email = request.get_json()['email'] password = request.get_json()['password'] try: id = g.user.id currentuser = User.query.get(id) if password: currentuser.password = password ...
84026d9903d70d19b86746ab73f3e65c67d1168d
3,636,091
from typing import Iterable from typing import Tuple from typing import Set from pathlib import Path import ray import tqdm def feature_matrix_hdf5(smis: Iterable[str], size: int, *, featurizer: Featurizer = Featurizer(), name: str = 'fps', path:...
1318d703d27adbd9df800b7a1b97ecc6a67bf151
3,636,092
def xpath_error(code, message=None, token=None, prefix='err'): """ Returns an XPath error instance related with a code. An XPath/XQuery/XSLT error code (ref: https://www.w3.org/2005/xqt-errors/) is an alphanumeric token starting with four uppercase letters and ending with four digits. :param code: ...
db35731f49fc1a1f51c61f365b0aba7a6bfc099e
3,636,093
def _setPropertyValue(self, name, value, typeString = ''): """Set the typed value of a property by its name, creating a child element to hold the property if needed.""" method = getattr(self.__class__, "_setPropertyValue" + getTypeString(value)) return method(self, name, value, typeString)
915091618fded898ab690b0ce223bdb00aa4308b
3,636,094
def build_toy_input_feature_values(features, use_rank_two=False, has_catset=False): """Create a set of input features values. These examples will fall respectively in the nodes 6, 5, 3, 2 of _build_toy_random_forest. Args: features: Dic...
3c18411f8d1934aed979cc43c7e6d674b88b078e
3,636,095
def light_head_preprocess_for_train(image, labels, bboxes, out_shape, data_format='NHWC', scope='light_head_preprocess_train'): """Preprocesses the given image for training. Note that the actual resizing scale is sampled from [`resize_size_min`,...
a2259af8dd79794b60021bcdab5c11e7ed6317d4
3,636,097
def get_dgs(align_dg_dict): """ Function that creates inverse dictionary of align_dg_dict align_dg_dict: dict. Dictionary of alignments and clustering DG assignments Returns dg_align_dict: dict, k=dg_id, v=[alignids] align_dg_dict comes from get_spectral(graph) or get_cliques(graph) """ dgs_...
85bca47657c83d2b308d38f05d1c88d9a78fa448
3,636,098
def DateTime_GetBeginDST(*args, **kwargs): """DateTime_GetBeginDST(int year=Inv_Year, int country=Country_Default) -> DateTime""" return _misc_.DateTime_GetBeginDST(*args, **kwargs)
efb570d487dc68688572326d94a2bea57608ce46
3,636,099
def apply_voigt1d(fid, pks, snorms, a0, b0, a, b, zp, bw, flo=None, up=True, link_gg=True, link_ll=True, dx_snr=None, dx_snr_mode='outside', f_cutoff=0., ftype='voigt', outfile=''): """ Apply Voigt-1D window function, fit the spectrum, and return the treated SnR & FWHM :argu...
4e869225bf976138ab3631d3d0def5b7e3e0cc06
3,636,100
from typing import Optional def parse_options(dict_in: Optional[dict], defaults: Optional[dict] = None): """ Utility function to be used for e.g. kwargs 1) creates a copy of dict_in, such that it is safe to change its entries 2) converts None to an empty dictionary (this is useful, since empty diction...
d679539ba29f4acab11f5db59c324473a2e24cc6
3,636,101
import copy def build_optimizer(model, optimizer_cfg): """Build optimizer from configs. Args: model (:obj:`nn.Module`): The model with parameters to be optimized. optimizer_cfg (dict): The config dict of the optimizer. Positional fields are: - type: class name of t...
43d211d57972274de337725a38ae7c08ff7b4e8c
3,636,102
def test_normal_sw(data): """Shapiro-Wilk""" norm_data = (data - np.mean(data))/(np.std(data)/np.sqrt(len(data))) return st.shapiro(norm_data)
e0b547e0b585a1cb5bf88ef818c3e6e1caf9c16a
3,636,103
from typing import Dict from typing import Any def dict_to_namespace(cfg_dict: Dict[str, Any]) -> 'Namespace': """Converts a nested dictionary into a nested namespace.""" cfg_dict = deepcopy(cfg_dict) def expand_dict(cfg): for k, v in cfg.items(): if isinstance(v, dict) and all(isinsta...
492e629815f477d3263121fcd19afea7d3ec9f6f
3,636,104