content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def layout_bounding_boxes(canvas_x, canvas_y, canvas_width, line_height, space_widths, y_space, sizes): """Layout token bounding boxes on canvas with greedy wrapping. Args: canvas_x: x coordinate of top left of canvas canvas_y: y coordinate of top left of canvas canvas_width: ...
057eb7976849444efa27d51d2ec1209e0f95eaa8
63,301
def closing(): """HTML boilerplate.""" return """</tr></table>\n<div align='center' style='margin-top: 10px'> <button type="button" id="btn" class="btn btn-primary" onclick='create_playlist()'">Create Playlist</button> </div>\n</html>"""
51556490c82c04e43182923e3e779f8d3fcc392f
63,302
def compute_trust_values(dsk, do_plot=False): """ Compute trust values following formula 6 k:= number of blendshapes n:= num_features (num_markers*3) :param dsk: delta_sk vector (k, n) :param do_plot: decide if we want to plot the between-correlation matrix :return: trust values vector (k,...
5bd8b66ada3699b8426410aa1a1cfe410f23bdc3
63,303
def make_query(user_id=None, tenant_id=None, resource_id=None, user_ids=None, tenant_ids=None, resource_ids=None): """ Returns query built form given parameters. This query can be then used for querying resources, meters and statistics. :Parameters: - `user_id`: user_id, has a priority o...
43a551a50f19d49a963c5a2f855a9df6e3fbe595
63,304
def get_valid_new_slug(slug_base: str, path: str) -> str: """ Given a slug to act as a base/prefix, returns a slug that will satisfy unique constraints, adding/incrementing a numerical suffix as necessary. """ starter_qset = WebsiteStarter.objects.exclude(path=path) slug_exists = starter_qset.fi...
ff45cff0627af600faaf855585e7797ec28535bc
63,305
from typing import List def fat_cross_perform_df(arr_list: List[ArrivalDistribution], ser_list: List[ConstantRateServer], opt_method: OptMethod, perform_param_list: PerformParamList) -> pd.DataFrame: """Compute delay standard_bound for T i...
76eaf2ee7e8fbed7a09741d48d3c0c08e5939a0a
63,306
def estacionesFromXML(element: xmlElement, text:str) -> list: """ devuelve la lista de estaciones de un elemento xml """ estacionesElements = element.findall(text) estaciones = [estacion.text.strip() for estacion in estacionesElements] if len(estaciones) == 0: raise ValueError('no se han...
c049b9fb9a4d55310156084683ea32873f3eea71
63,307
import copy import uuid def create_record(data): """Create a test record.""" with db.session.begin_nested(): data = copy.deepcopy(data) rec_uuid = uuid.uuid4() pid = record_pid_minter(rec_uuid, data) record = ExampleRecord.create(data, id_=rec_uuid) return pid, record
72204912d6b15e1bfbf0bb0150b6710f8cb4501e
63,308
def ldns_rdf2buffer_wire(*args): """LDNS buffer.""" return _ldns.ldns_rdf2buffer_wire(*args)
9450f7016a56c53003b85898c6009ae6946d22d7
63,309
def calc_E_SH(type, tatekata, region, sol_region, A_A, A_MR, A_OR, ENV, mode_H, mode_C, NV_MR, NV_OR, H_MR, H_OR): """暖房設備の設計一次エネルギー消費量 Args: type(str): description] tatekata(str): 建て方 region(int): 省エネルギー地域区分 sol_region(int): 年間の日射地域区分(1-5) A_A(float): 床面積の合計 (m2) A_MR(float...
cd505866a0fa86e6e2b54165197f8035a9c45690
63,310
def get_rostime(): """Returns current ROS1 time, as rospy.Time.""" return rospy.get_rostime()
aa35257b07b8d33e5f8b268709df344b3008c3f7
63,311
def lnlike2(theta, xi, yi, ei): """ Model with LSS variance modeled by a power law as a function of redshift""" f0, t0, gamma, var_a, var_b = theta if 0 <= f0 < 3 and -10 <= t0 < -2 and 1 <= gamma < 7 and \ 0.001 <= var_a < 1 and 1 <= var_b < 5: model = f0 * np.exp(-np.exp(t0) * (1 + xi...
8a128652c35dde95aeae6ed5e59ce0343e7cd354
63,312
import torch def clone(x): """ Clones all torch tensors and numpy arrays in nested dictionary or list or tuple and returns a new nested structure. Args: x (dict or list or tuple): a possibly nested dictionary or list or tuple Returns: y (dict or list or tuple): new nested dict-li...
85b44aee8be9cb9b199201bee0ad2234cc4063c9
63,313
def route_not_found(e): """ Api/Route not found """ return render_template("error/404.html"), 404
8b9b57d7e9a226f1bd708df8bd0831f8f676afca
63,314
def compute_modularity_density(adj, c, conn_clusters, cluster_labels, total_weight, dict_bool): """Determines modularity density of a set of communities. Parameters ---------- adj : SciPy sparse matrix (csr or csc) The N x N Adjacency matrix of the graph of intere...
810ef02788206662e2f8ec32673c74f2aadde55a
63,316
def chisquare_binning_boundary(input_df, feat_name, label_name, k_part): """Calculate binning threshold list by chisqure binning method. Parameters ---------- input_df : DataFrame Sample set. feat_name : str Feature name. label_name : str Label name. k_part : int ...
7452a08899f555f125149c14404822b53564837c
63,317
def index(): """ The home page has a list of prior translations and a form to ask for a new translation. """ return '<h1> Dedicated server (python) is on. </h1>'
3bab9b4ce6ed30c5a265b88581ce7557c8fa5e8d
63,318
from typing import Tuple from typing import List def process_response(response: dict) -> Tuple[List[dict], dict]: """Process response with entries.""" entries = process_data(response) pagination = response['meta']['pagination'] return entries, pagination
6809aba42ebfae81b7c1b0d75109d1be47ad83e5
63,320
def second_moment_loss(tt: np.array, mu: np.array, sigma: np.array, logp: np.array) -> float: """ Because log-price likelihood is Gaussian, standardizing the test data should give a second moment (i.e. squared expectation plus variance) of 1. Parameters ---------- tt: np.array Array of ...
532338c75eb402261c2fe697877a04ced4bd171e
63,321
def unpack_query_results(columns, results): """ Unpacks the result of a SELECT query into a list of Python dicts. :param columns: The columns that map to the fields in each result record. These must be in the same order as the fields in the result records, and are re...
9415f99dec8875d31d3ee090d163e4688f848cd5
63,322
def integer(bits=None): """ Correspond to an integer. :param bits: The bits for the integer. :return: An instance of Integer. """ global csp check_engine() csp.variables.append(csp.int(size=bits)) return csp.variables[-1]
e49f1e38ed2ce12f5ae03b795595be1c60513bc6
63,323
def ExponentialSearch(arr, item): """ If item is in array, Returns the index of first occurence of the item in the array; Else Returns False. Searches for an item using 'Exponential Search' algorithm; Requires a Sorted Array. Time Complexity :- Best Case : Ω(1) Worst Case : O...
525016aaec7820513f91ecd61802f87dab33cce5
63,325
def build_gdrive_bridge(): """ Похоже можно ужать вызов и удалить ключи из кода https://developers.google.com/api-client-library/python/guide/aaa_client_secrets """ # Copy your credentials from the APIs Console CLIENT_ID = '105447427029.apps.googleusercontent.com' CLIENT_SECRET = 'azmcKEseppjZvu...
d40fe8f581c4ef39a7f0618e6abfe03846e7b92c
63,327
import functools def pass_defaults(func): """Decorator that returns a function named wrapper. When invoked, wrapper invokes func with default kwargs appended. Parameters ---------- func : callable The function to append the default kwargs to """ @functools.wraps(func) def wra...
0a6ef20daea604e056e53df24dae5c76da84a16f
63,328
def data_set_cls( types=(), subtypes=False, checked=None, module=None, factory=None, serialized=True, serializer=None, deserializer=None, represented=True, compared=True, qual_name=None, unique=False, ): """ Make auxiliary interactive set data class. :param ...
91248019bf8becf05ff01d6abc9966d93ea9e09c
63,329
from typing import Tuple from typing import Union from typing import List from typing import Dict from typing import Iterable import requests import json def microservice_api_rest_seldon_message( method: str = "predict", microservice_endpoint: str = "localhost:5000", shape: Tuple = (1, 1), data: objec...
5ed167f0dfc89015f24a090b49a446f27e2b8f3b
63,330
def new_article(): """文章资源post请求处理""" article = Article.from_json(request.json) article.author = g.current_user db.session.add(article) db.session.commit() return jsonify(article.to_json()), 201, \ {'Location': url_for('api.get_article', id=article.id)}
e89a5ca858ca7e43669fc2ff89db37ff01547e29
63,331
def align_iterators(func, *iterables): """ This generator takes a bunch of iterables that are ordered by func It sends out ordered tuples:: (func(row), [rows from all iterators matching func(row)]) It is used by :func:`matplotlib.mlab.recs_join` to join record arrays """ class myiter: ...
ad7d816c43ddfa57a5a3a6c14e4209f44d0b1408
63,332
def x1x2(farm_id): """ >>> x1x2(1), x1x2(2), x1x2(3), x1x2(4), x1x2(5) ('x1x6', 'x2x7', 'x3x8', 'x4x9', 'x5x0') """ i = int(str(farm_id)[-1]) - 1 x1 = str(i - 5 * (i / 5) + 1)[-1] x2 = str(i - 5 * (i / 5) + 6)[-1] return 'x%sx%s' % (x1, x2)
b0da6f8e92551247ca0ef6f017adbe03c429487b
63,333
def make_figure( node_name, grid_T_hr, dev_grid_T_hr, timezone, mesh_mask, dev_mesh_mask, figsize=(8, 10), theme=nowcast.figures.website_theme, ): """Plot the temperature and salinity time series of observations and model results at an ONC VENUS node. :arg str node_name: Oce...
4d1400251ba5d3519396c0fa9f280d00a8722343
63,334
import random def load_data(use_test, model_loc): """ Load the data into a train/val/test set that allows for easy access. @return bag-of-word representation of training, validation, test sets (with labels). """ t_ids = set(list(preprocessor.train_document_ids())) te_ids = set(list(prepr...
15f9b1a5d28cd9e0cf12be9e954dd850329749c4
63,335
def filter_tests(test_kind, selector_config, test_file_explorer=_DEFAULT_TEST_FILE_EXPLORER): """Filter the tests according to a specified configuration. Args: test_kind: the test kind, from _SELECTOR_REGISTRY. selector_config: a dict containing the selector configuration. test_file_exp...
bfc914c6304173831755291fb9acba29a7b03860
63,336
def best(equations=None): """Return the equation with the best score, in sympy format. By default this uses the last equation file. """ if equations is None: equations = get_hof() best_sympy = best_row(equations)['sympy_format'] return best_sympy.simplify()
3b10c37c3f2b751889154e0eff51d1c94023658f
63,337
def batchify(fn, chunk): """ Constructs a version of 'fn' that applies to smaller batches. Function from NeRF: https://github.com/bmild/nerf """ # chunck = batch size if chunk is None: return fn def ret(inputs): return tf.concat([fn(inputs[i:i+chunk]) for i in range(0, input...
badf68a4f7481658a713be49af83b4032807ca72
63,338
def shear_x(image, level): """Equivalent of PIL Shearing in X dimension.""" # Shear parallel to x axis is a projective transform # with a matrix form of: # [1 level # 0 1] image = image_transform.transform( wrap(image), [1., level, 0., 0., 1., 0., 0., 0.]) return unwrap(image)
00d621f87521e25691892180d9892730f47e1884
63,340
from typing import Optional def compute_true_measure(measure: BaseMeasure, true_label_dist: ndarray, labels: Optional[ndarray] = None): """Compute the measure given the (unknown) oracle response Parameters ---------- measure : instance of activeeval.measures.BaseMeasure Evaluation measure...
53bd37d91f6bb1b6979be134fd726e36124fac40
63,341
def func_insert_array_parameter_node( node_id, name, value, unit = None, description = None ): """ Define function call to insert array parameter associated to node into the database. """ if not isinstance( node_id, int ): raise TypeError( 'parameter \'node_id\' must be of type \'int\'' ) i...
419ec57e92e6232d1aa00babcd4178b8a88b29b8
63,342
import random from re import X import math def minimax(board): """ Entrypoint for _minimax recursive function Returns None is board is in terminal state. Otherwise returns the utility of the resulting board and action. """ if terminal(board): return None possible_actions = l...
912f092bf7642f6967e09131e342d62ddff5f32f
63,343
import re def split_verses(verses): """ With a string of multiple verses, split on verses >>> split_verses("[1] Verse1 [2] Verse2") ["Verse1", "Verse2"] """ verses_list = re.split("\[\d+\]", verses) verses_list = [verse.strip() for verse in verses_list if verse.strip()] return ...
f965c8a59db21c2c31e9a017d9226e430043c272
63,344
from datetime import datetime import pytz def read_gpgga(sentence, timestamp, do_print=False): """ Read and parse GPGGA message""" values = sentence.split('*')[0].split(',') result = {} # Linux timestamp try: result['linux_stamp'] = int(timestamp) except: result['linux_stamp']...
2612770ed46030bbd36d313cb06b2ffd340c6bb3
63,345
def energy(prog, method, output_string): """ Retrieves the desired electronic energy. """ assert prog in energy_programs() assert method in energy_program_methods(prog) module = _import_module(prog) energy = module.ENERGY_READERS[method](output_string) return energy
9dc76952dd7a13ab500859b5bb77160a3ff7b876
63,346
def translate_avl_body(suave_body): """ Translates body geometry from the vehicle setup to AVL format Assumptions: None Source: None Inputs: body.tag [-] suave_wing.lengths.total ...
987366bb8f9bb482b869c3bd538b39e757983b6a
63,347
def write_intro_end_slides(conn, command_args, orig_file_id, duration, size_x, size_y): """ Uses an original file (jpeg or png) to add frames to the movie. Scales and pads to fit size_x, size_y. @param orig_file_id: Original File (png or jpeg) ID @param duration: ...
21f16d4b8e6c5373533d547737c5ed66d6045982
63,348
def cape_timing(rolling_window, neutral_wt, freq, static_wts, fac_names, start_date='19260731'): """ Function to implement CAPE Valuation Timing Args: rolling_window (int): lookback in months used for evaluating CAPE levels neutral_wt (float): weight assigned to mar...
e192f49d4dab82dd023659ddbf04d341e38d80a2
63,350
def ServerClass(cls): """Decorate classes with for methods implementing OSC endpoints. This decorator is necessary on your class if you want to use the `address_method` decorator on its methods, see `:meth:OSCThreadServer.address_method`'s documentation. """ cls_init = cls.__init__ def __i...
f28760b2a138f1b95405f95dc122881b6d95d2e0
63,351
def read_dataset(): """ Karateclub library requires nodes to be named with consecutive Integer numbers. After running the library, we take as output the embeddings in ascending order. So in this function, we need to reassign each ASN to its own embedding. :return: A dataframe containing tha AS number an...
cbc33472975e1178c9a1b7348f03b17668570767
63,352
from .simplify import bottom_up def _gamma_as_comb(expr): """ Helper function for combsimp. Rewrites expression in terms of factorials and binomials """ expr = expr.rewrite(factorial) def f(rv): if not rv.is_Mul: return rv rvd = rv.as_powers_dict() nd_fa...
c6175f647fbba2438a956a4fc7cb2e4519a107ce
63,353
from operator import add def make_network(input_shape, kernel_size=11): """Create the neural network model. Parameters: input_shape (tuple of ints): the shape of the input tensor kernel_size (int): size of convolution kernel Returns: Keras model """ first = True input...
987bfe10d7964908f35c7876293cb00cddcaa498
63,355
def select_features_by_keyword(keywordList, features): """ Select feature columns by keywords """ selected_features_list = [] for word in keywordList: selected_features = [col for col in features.columns if word in col] con_list = selected_features_list + selected_features se...
5dc16571fd8d48b78edc2cb204938db42c54bd69
63,357
def find_pointsII(gt_rectangle, w_p, h_p): """Find the rectangles at the top-left most-, bottom-left most, top-right most- and bottom-right most corners that have a JI equal to 1/2 to the ground truth rectangle. ! The rectangle needs to be a top-left Rectangle for this function! This is done wit...
0ce75fd7d1aad536a9477af79475e31dd0040fd2
63,358
def include_tagcanvas(element_id, width, height, url_name='tagcanvas-list', forvar=None, limit=3): """ Args: element_id - str - html id width - int - pixels width height - int - pixels height url_name - if url_name=='' then no links. Default: tagcanvas-list ...
ec861bac56c7031e41915c7102c9474accd9a33b
63,359
def measure_corrs_mean(corrs, params=None): """Measure based on computing the mean of the non-auto correlation values. Parameters ---------- corrs: np.ndarray the correlation matrix. params: optional (default=None) the parameters needed to compute the output measure. Returns ...
3476fd1a0bc70d9fac13f6c094d7f563a58bc620
63,360
from typing import Callable from typing import Tuple from typing import Any from typing import Dict import functools def wrap_for_agg( function: Callable, args: Tuple[Any, ...], kwargs: Dict[str, Any], ) -> Callable: """Wrap a function for use with Pandas `agg`. This includes special logic that w...
7152ae610c2dea177758bf0c3337f4425c8d86c5
63,361
def path_as_list(path: dict): """Get sequence of vertices from path[s, t] = v return as list for each searcher s path[s] = [v0, v1, v2...vh]""" pi = dict() h = get_h_from_tuple(path) m = get_m_from_tuple(path) T = get_set_time_u_0(h) S = get_set_searchers(m)[0] # loop through time...
67c17f907a2509c770d6cdc8fbc7840c523746da
63,362
def bisect(changelog, state): """find the next node (if any) for testing during a bisect search. returns a (nodes, number, good) tuple. 'nodes' is the final result of the bisect if 'number' is 0. Otherwise 'number' indicates the remaining possible candidates for the search and 'nodes' contains the ...
e807709e825fb984314e1954296c9ae6afef6de6
63,363
def _sanitize_bin_name(name): """ Sanitize a package name so we can use it in starlark function names """ return name.replace("-", "_")
37e9a09cf60f83c087734b74ccf0ba7d3c46fea6
63,364
def _line(x, a, b): """ Dummy function used for line fitting :param x: independent variable :param a, b: slope and intercept """ return a*x + b
e883689fb39c51064b1f1e0a34d1ab03cc11efb9
63,365
from functools import reduce def getattrd_last_but_one(obj, name: str, default=NoDefaultProvided): """Same as getattrd(), but leaves out last ".foo" part. e.g. name="branch.apple.color" obj = tree -> tree.branch.apple """ try: return reduce(getattr, name.split(".")[:-1], obj) except (Attr...
b390324da6f5750bdebf974071221f095f47d03f
63,366
import torch def init_vuz(A, D, x, v0=None, inv_A=None, device='cpu', force_numpy=False): """ Initialize v, u and z. """ # cast into tensor x = check_tensor(x, device=device) # get useful dimension n_samples, _ = x.shape n_atoms, _ = A.shape # XXX will break if D is not (n_atoms, n_atoms ...
01e55f3d247e5d3da6e808d79ff708e0514c22a6
63,368
def embed(markdown: str, **kwargs) -> Embed: """渡されたマークダウンの文字列をタイトルと説明とフィールドが設定されている`discord.Embed`に変換します。 見出しは三段階設定することができ、一段でタイトルで二段でフィールドそして三段で`**#** ...`のようになります。 もしフィールドの`inline`を`False`にしたい場合は`## !`のようにしてください。 Parameters ---------- markdown : str 変換するマークダウンです。 kwargs : dic...
0bf6b5514a89f7dc7fae7e1d6b43bd94e190ea90
63,369
def tw_connect(keys): """Connect to Twitter API using Tweepy. Parameters ---------- keys : dict Dictionary object containing keys app_public, app_secret, per_public, and per_secret. Returns ------- api : object Authenticated Tweepy API object. """ auth = tw...
641814c5d16cdcf9ee4330837b98c71ef311af9d
63,371
def and_s(*args): """Simplifying Boolean And operator.""" num, c_bxs = _convert_args(args) return _bx(lib.boolexpr_and_s(num, c_bxs))
1f66aa129964e783b85d3e9cb7b95986b42f6535
63,372
def d_y_diffr_dx(x, y): """ derivative of d(y/r)/dx equivalent to second order derivatives dr_dxy :param x: :param y: :return: """ return -x*y / (x**2 + y**2)**(3/2.)
696a5b4a5ff8e6483b5082cb394b3ac4bca83313
63,373
def get_fitter(n_mcsim, generator, model): """Here is where the parameters (particularly priors) are specified for each fitting model. """ if model == "LN2Stationary": fitter = LN2Stationary( synthetic=generator, n_mcsim=n_mcsim, mu_sd=1.5, mu_mean...
789180cafb4bab1160854d1c3380080e77e8ff08
63,374
from typing import Optional from typing import Union def create_digit_recognition_task( train_client_spec: client_spec.ClientSpec, eval_client_spec: Optional[client_spec.ClientSpec] = None, model_id: Union[str, DigitRecognitionModel] = 'cnn_dropout', only_digits: bool = False, use_synthetic_data: ...
97006f9586912bafaa10a2848e0428053b6d18cb
63,376
def xmlescape(data): """ """ return escape(data, entities={ "'": "&apos;", "\"": "&quot;" })
261f2df33839a975d8878c9231d746ada1d79337
63,377
def direct_ft_maximise(obj, bounds, max_evals, *args, **kwargs): """ A wrapper for maximising a function which calls direct_ft_minimise. See arguments under direct_ft_minimise for more details. """ min_obj = lambda x: -obj(x) min_val, max_pt, history = direct_ft_minimise(min_obj, bounds, max_evals, ...
557ba8347c10933ad67e73654e04d8a54d65091a
63,378
from typing import Tuple def splat_bilateral_grid (input: Tensor, guide: Tensor, grid_size: Tuple[int, int, int]) -> Tensor: """ Splat an image into a homogenous bilateral grid. Parameters: input (Tensor): Input image with shape (N,C,H,W). guide (Tensor): Splatting guide map with shape (N...
e9c61ab0c872df9abe5a74b3c909c7b9d30b29e9
63,379
def yeet(yeetee_width, grid_width, enter_from="right"): """ Work out the array indeces needed to slide a grid across a grid. Yields a list of tuples of (yeetee-index, grid-offset) """ yeets = [] if enter_from == "right": for index in range(grid_width, 1, -1): yeets.append((...
62ca3ee33ed1e06000bc50ef4dd927eda9b886f1
63,380
def add(moment): """Return the moment that is a gigasecond after given moment.""" gigaseconds = timedelta(seconds=1E9) # 1E9 == 1_000_000_000 return moment + gigaseconds
75e036e2c1765fe497277cb10a90cec439c6c636
63,381
import types from typing import Any def invoke(boto3_function: types.FunctionType, **kwargs: Any) -> Boto3Result: """Call a function and return the response as a Boto3Result. Arguments: boto3_function: A callable to be called. Typically this will be a function in the boto3 module. ...
e019ab82ddb192e666565a9ac8e58abeae1a933b
63,383
def get_mass_mdot(tracers, nbins_theta=5, nbins_time=100): """Calculates total mass in wind and Mdot_wind as a function of time and angular bin. """ theta_range,t_range,_,mtots,_ = spacetime_bins(tracers, nbin...
da5c7e5fdb01cce9ce23b0cfa307aaa9dfa12e3d
63,384
def parse_v2_cards(cardstring): """Extract card objects from a v2 url encoded list of cards Args: cardstring: Deckbuilder card string (multiple cards) Returns: List of Card objects Note: Card string is a concatenate (with no delimiter) set of 3-4 characters with the the format: XYZ ...
3d45f5f28f175b032a42ddbcfe20f783c4c0faf6
63,385
def get_discoverable_groups_view(request): # type: (Request) -> HTTPException """ List all discoverable groups (publicly available to join). """ public_groups = ru.get_discoverable_groups(request.db) public_group_names = ax.evaluate_call(lambda: [grp.group_name for grp in public_groups], ...
af39241fe87946bd916c36569c3d6e80ebea3a20
63,386
def filter_rewards(rewards: np.ndarray, dones: np.ndarray) -> np.ndarray: """ Filter rewards based on done flags, all rewards after a done are set to 0. :param rewards: The rewards to filter (num_envs, num_steps) or (num_steps,) :param dones: The done flags (num_envs, num_steps) or (num_steps,) :ret...
dab1bb5366e87755ebb98c2d9c103a173fdf1aa3
63,387
def normalise_line_tail(line): """Replace white-space characters at the end of the line with a newline character""" return line.rstrip() + '\n'
25c22c0c39a73d5b9a449f202433f77bd0e1bb3b
63,388
def le(h): # (int) -> Sequence[int] """ Little-endian, takes a 16b number and returns an array arrange in little endian or [low_byte, high_byte]. """ h &= 0xffff # make sure it is 16 bits return [h & 0xff, h >> 8]
8f4b6e7eaf638e1317a9610da68a2e1ce74151ae
63,389
def fast_minor_method(matrix): """ Тот же метод миноров, но с предварительной триангуляцией (сокращение до 50% работы метода миноров) (метод Гаусса) ТОЧНОСТЬ НИЖЕ, ЧЕМ У МЕТОДА МИНОРОВ Returns: float: определитель матрицы Raises: ArithmeticError: если матрица не является квадратной...
6300003469381fd23adb8dc808a0b3f79f9caff9
63,390
def build_versioned_operator_directory( operators_directory: str, operator_name: str, operator_git_tag: str ) -> str: """Returns a versioned operator directory for the "operators collection" repository. e.g., /kudobuilder-operators/repository/cassandra/3.11 """ match = RELEASE_TAG_PATTERN.match...
6b738bdf5a51c5d82ecf399872fb5160d394148c
63,391
def load_facets(): """This loads the facets stored in the corresponding file""" return file_utils.load_dictionary_from_file(config_params.SHODAN_FACETS_FILE)
1bec48c34f09c554f651ae1e82ea599d3b549013
63,392
def Srinit(Srrat,Rbrat,age): """ Calculate initial 87Sr/86Sr. Paramters: Srrat: Measured 87Sr/86Sr ratio Rbrat: Measured 87Rb/86Sr ratio age: Age of sample in Ma Returns: Sri: initial 87Sr/86Sr ratio """ lambdaRb = 1.39e-11 # Rb-87 decay constant ...
d085413b906e6fed70f4a6fd7fcb3531374a7f14
63,394
def reduce2scalar( mv, vid=None, gw=True, weights=None, season=seasonsyr, region=None ): """averages mv over the full range all axes, to a single scalar. Uses the averager module for greater capabilities Latitude weights may be provided as 'gw'. The averager's default is reasonable, however. If weights...
1ad0f73435210270620d19be062a28f446385f4b
63,395
from typing import Mapping def dict_update(orig, updates): """Recursively merges two objects""" for key, val in updates.items(): if isinstance(val, Mapping): orig[key] = dict_update(orig.get(key, {}), val) else: orig[key] = updates[key] return orig
0322b0742b4cc725d5935c94adbe11da3ef13d62
63,396
def request(method, route, status_code=200, content_type='text/html', data=None, data_content_type=None, follow_redirects=True): """ Create the test_client and check status code and content_type. """ response = method(route, content_type=data_content_type, data=data, f...
dd895f9cc4e655153d5bcb5748a94adddb446c81
63,397
import functools def file_mock(func): """Create pseudo file object.""" @functools.wraps(func) def wrapper(*args, **kwargs): content = '\n'.join(f"{i},{i}" for i in range(6)) with mock.patch('lib.image_data.open', mock.mock_open(read_data=content)) as f_mock: ...
d341d14f728b16029f5e43678861bcb50e3e290e
63,398
async def install_admin_user() -> bool: """Retrieve the admin from AUth0 and assign it to the Author.""" api = AuthAPI() users = api.list_users() for user in users: if user.user_id == ADMIN_ID: await Author.objects.get_or_create( username="8area8", ema...
942e703e22bff537c328f229b7767a21af983265
63,399
def deg2rad(value): """ Convert value in degrees to radians (as required used cairo) """ return value * (pi / 180.0)
29432918834f2ee7c907d9f18b50b41c69516770
63,401
from typing import Dict def build_node_ingestion_query(node_label: str, node_property_map: Dict[str, str]) -> str: """ Generates Neo4j query string to write a list of dicts as nodes to the graph with the given node_label, id_field, and other arbitrary fields as provided by field_list. The resulting qu...
5bf76a2cf7f3e4d633762a8f32a1c56a941e1936
63,403
import codecs def load_vocabulary(vocabulary_path, reverse=False): """Load vocabulary from file. We assume the vocabulary is stored one-item-per-line, so a file: d c will result in a vocabulary {"d": 0, "c": 1}, and this function may also return the reversed-vocabulary [0, 1]. Args: vocabulary_...
0bbe55a64657f53a66df7f55b3e85dcb579593a5
63,407
from typing import Dict def biology_qualifiers(session: Session) -> Dict[str, BiologyQualifier]: """Return a map from biology qualifiers to database instances.""" BiologyQualifier.load(session) return BiologyQualifier.get_map(session)
e46c71d6159ba6959d9107e6a4e7e071ce847f81
63,408
def alignments_to_report(alignments): """Determine which alignments should be reported and used to call variants. In the simplest and best case, there is only a single alignment to consider. If there is more than one alignment, determine which ones are interpretable as a variant, and of these return th...
0a8adfb3146ffee4ac8272e5e515fb75ad2f13b4
63,409
import re def read_urls(filename): """Returns a list of the puzzle urls from the given log file, extracting the hostname from the filename itself. Screens out duplicate urls and returns the urls sorted into increasing order. /edu/languages/google-python-class/images/puzzle/a-babb.jpg into https://develo...
2693ce95260a2f941c7532f5f477c97cd198ec57
63,410
from typing import Union from typing import List from typing import Any from typing import Tuple from typing import Dict def decode( spec: Union[List[Any], Tuple[Any], Dict[str, Any]] ) -> Union[specs.Array, List[Any], Tuple[Any], Dict[str, Any]]: """Parses `spec` into the supported dm_env spec formats.""" if...
ed4627a85e138e28d53dfba9660fe7837cbfb3bd
63,412
import torch def rescale_actions( actions: torch.Tensor, new_min: torch.Tensor, new_max: torch.Tensor, prev_min: torch.Tensor, prev_max: torch.Tensor, ) -> torch.Tensor: """ Scale from [prev_min, prev_max] to [new_min, new_max] """ assert torch.all(prev_min <= actions) and torch.all( ...
1304cee5f4d1f7a50b89842fa1bac6de8ab8bd04
63,413
def find_between(doc: str, first: str, last: str) -> FoundText: """ Finds text in doc """ result = FoundText() try: result.start = doc.index(first) + len(first) result.end = doc.index(last, result.start) result.value = doc[result.start:result.end] result.found = True exc...
bf5022658203b6655986150be2f076a0ce89516a
63,415
def clean_pipeline(sentence): """Apply cleaning functions in sequential order to an input sentence""" clean_utils = (remove_hyperlinks, remove_newline, lower, remove_numbers, remove_punctuation, remove_whitespace) for func in clean_utils: sentence = func(sentence) return sentence
409132ab990ff3ebb659cff675ba63eda2b34b81
63,416
def tag_repr(tag): """String of tag value as (0xgggg, 0xeeee)""" return "(0x{group:04x}, 0x{elem:04x})".format(group=tag.group, elem=tag.element)
058f40824c85b834ce759ae1d01275c718a438c6
63,417
from datetime import datetime def _response_letter_handler(request_id, data): """ Process letter template for a response. :param request_id: FOIL Request ID :param data: data from the frontend AJAX call :return: the HTML of a rendered template of a response letter. """ if not eval_request...
577cff3ccebde5f86f9287f2e3b9fc369caa8950
63,418
def create_map(example): """Returns a string filled by lexem categories' first symbols.""" _map = '' for position, symbol in enumerate(example): _map = _map + lexem_type(symbol) return _map
044b821e7389048b00eed8876681f1964d3128f7
63,419
import json import urllib async def post_notification(request): """ Create a new notification to run a specific plugin :Example: curl -X POST http://localhost:8081/foglamp/notification -d '{"name": "Test Notification", "description":"Test Notification", "rule": "threshold", "channel": "email...
ed1dc8479941db4e1cd21d05011d0a9da3b763aa
63,420