content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def arglast(arr, convert=True, check=True): """Return the index of the last true element of the given array. """ if convert: arr = np.asarray(arr).astype(bool) if np.ndim(arr) != 1: raise ValueError("`arglast` not yet supported for ND != 1 arrays!") sel = arr.size - 1 sel = sel -...
b4c6424523a5a33a926b7530e6a6510fd813a42a
31,563
def number_formatter(number, pos=None): """Convert a number into a human readable format.""" magnitude = 0 while abs(number) >= 100: magnitude += 1 number /= 100.0 return '%.1f%s' % (number, ['', '', '', '', '', ''][magnitude])
a9cfd3482b3a2187b8d18d6e21268e71b69ae2f2
31,564
from pathlib import Path import shutil def simcore_tree(cookies, tmpdir): """ bakes cookie, moves it into a osparc-simcore tree structure with all the stub in place """ result = cookies.bake( extra_context={"project_slug": PROJECT_SLUG, "github_username": "pcrespov"} ) work...
f9889c1b530145eb94cc7ca3547d90759218b1dc
31,565
def calc_density(temp, pressure, gas_constant): """ Calculate density via gas equation. Parameters ---------- temp : array_like temperatur in K pressure : array_like (partial) pressure in Pa gas_constant: array_like specicif gas constant in m^2/(s^2*K) Returns ...
1e492f9fb512b69585035ce2f784d8cf8fd1edb0
31,566
def address(addr, label=None): """Discover the proper class and return instance for a given Oscillate address. :param addr: the address as a string-like object :param label: a label for the address (defaults to `None`) :rtype: :class:`Address`, :class:`SubAddress` or :class:`IntegratedAddress` """...
13b1e24abc7303395ff9bbe82787bc67a4d377d6
31,569
def retrieve_molecule_number(pdb, resname): """ IDENTIFICATION OF MOLECULE NUMBER BASED ON THE TER'S """ count = 0 with open(pdb, 'r') as x: lines = x.readlines() for i in lines: if i.split()[0] == 'TER': count += 1 if i.split()[3] == resname: ...
8342d1f5164707185eb1995cedd065a4f3824401
31,570
import ctypes import ctypes.wintypes import io def _windows_write_string(s, out, skip_errors=True): """ Returns True if the string was written using special methods, False if it has yet to be written out.""" # Adapted from http://stackoverflow.com/a/3259271/35070 WIN_OUTPUT_IDS = { 1: -11, ...
471fd456769e5306525bdd44d41158d2a3b024de
31,571
def in_relative_frame( pos_abs: np.ndarray, rotation_matrix: np.ndarray, translation: Point3D, ) -> np.ndarray: """ Inverse transform of `in_absolute_frame`. """ pos_relative = pos_abs + translation pos_relative = pos_relative @ rotation_matrix return pos_relative
5f7789d7b5ff27047d6bb2df61ba7c841dc05b95
31,572
def check_url_namespace(app_configs=None, **kwargs): """Check NENS_AUTH_URL_NAMESPACE ends with a semicolon""" namespace = settings.NENS_AUTH_URL_NAMESPACE if not isinstance(namespace, str): return [Error("The setting NENS_AUTH_URL_NAMESPACE should be a string")] if namespace != "" and not names...
e97574a60083cb7a61dbf7a9f9d4c335d68577b5
31,573
def get_exif_data(fn): """Returns a dictionary from the exif data of an PIL Image item. Also converts the GPS Tags""" exif_data = {} i = Image.open(fn) info = i._getexif() if info: for tag, value in info.items(): decoded = TAGS.get(tag, tag) if decoded == "GPSInfo": gps_data = {} for t in value: ...
b6a97ed68753bb3e7ccb19a242c66465258ae602
31,574
def _setup_modules(module_cls, variable_reparameterizing_predicate, module_reparameterizing_predicate, module_init_kwargs): """Return `module_cls` instances for reparameterization and for reference.""" # Module to be tested. module_to_reparameterize = _init_module(module_cls, module_init_kwarg...
367ecae71835044055765ace56f6c0540e9a44ba
31,576
def external_compatible(request, id): """ Increment view counter for a compatible view """ increment_hit_counter_task.delay(id, 'compatible_count') return json_success_response()
c82536cdebb2cf620394008d3ff1df13a87a9715
31,577
def lowpass_xr(da,cutoff,**kw): """ Like lowpass(), but ds is a data array with a time coordinate, and cutoff is a timedelta64. """ data=da.values time_secs=(da.time.values-da.time.values[0])/np.timedelta64(1,'s') cutoff_secs=cutoff/np.timedelta64(1,'s') axis=da.get_axis_num('time') ...
0628d63a94c3614a396791c0b5abd52cb3590e04
31,578
def _calc_zonal_correlation(dat_tau, dat_pr, dat_tas, dat_lats, fig_config): """ Calculate zonal partial correlations for sliding windows. Argument: -------- dat_tau - data of global tau dat_pr - precipitation dat_tas - air temperature dat_lats - latitude of the given mo...
f596536bde5ded45da2ef44e388df19d60da2c75
31,579
def is_unary(string): """ Return true if the string is a defined unary mathematical operator function. """ return string in mathwords.UNARY_FUNCTIONS
914785cb757f155bc13f6e1ddcb4f9b41f2dd1a2
31,580
def GetBucketAndRemotePath(revision, builder_type=PERF_BUILDER, target_arch='ia32', target_platform='chromium', deps_patch_sha=None): """Returns the location where a build archive is expected to be. Args: revision: Revision string, e.g. a git commit hash or...
30ced6c37d42d2b531ae6ecafc4066c59fb8f6e4
31,581
def cutmix_padding(h, w): """Returns image mask for CutMix. Taken from (https://github.com/google/edward2/blob/master/experimental /marginalization_mixup/data_utils.py#L367) Args: h: image height. w: image width. """ r_x = tf.random.uniform([], 0, w, tf.int32) r_y = tf.random.uniform([], 0, h, tf...
adf627452ebe25b929cd78242cca382f6a62116d
31,582
import math def compute_star_verts(n_points, out_radius, in_radius): """Vertices for a star. `n_points` controls the number of points; `out_radius` controls distance from points to centre; `in_radius` controls radius from "depressions" (the things between points) to centre.""" assert n_points >= 3 ...
97919efbb501dd41d5e6ee10e27c942167142b24
31,583
def create_ordering_dict(iterable): """Example: converts ['None', 'ResFiles'] to {'None': 0, 'ResFiles': 1}""" return dict([(a, b) for (b, a) in dict(enumerate(iterable)).iteritems()])
389a0875f1542327e4aa5d038988d45a74b61937
31,584
def sparse2tuple(mx): """Convert sparse matrix to tuple representation. ref: https://github.com/tkipf/gcn/blob/master/gcn/utils.py """ if not sp.isspmatrix_coo(mx): mx = mx.tocoo() coords = np.vstack((mx.row, mx.col)).transpose() values = mx.data shape = mx.shape return coords, values, shape
a20b12c3e0c55c2d4739156f731e8db9e2d66feb
31,585
def correct_predicted(y_true, y_pred): """ Compare the ground truth and predict labels, Parameters ---------- y_true: an array like for the true labels y_pred: an array like for the predicted labels Returns ------- correct_predicted_idx: a list of index of correct predicted correct...
3fae4287cb555b7258adde989ef4ef01cfb949ce
31,586
def coord_image_to_trimesh(coord_img, validity_mask=None, batch_shape=None, image_dims=None, dev_str=None): """Create trimesh, with vertices and triangle indices, from co-ordinate image. Parameters ---------- coord_img Image of co-ordinates *[batch_shape,h,w,3]* validity_mask Boolea...
8719498ddf24e67ed2ea245d73ac796662b5d08e
31,587
def expand_db_html(html, for_editor=False): """ Expand database-representation HTML into proper HTML usable in either templates or the rich text editor """ def replace_a_tag(m): attrs = extract_attrs(m.group(1)) if 'linktype' not in attrs: # return unchanged r...
2e01f4aff7bc939fac11c031cde760351322d564
31,588
def hungarian(matrx): """Runs the Hungarian Algorithm on a given matrix and returns the optimal matching with potentials. Produces intermediate images while executing.""" frames = [] # Step 1: Prep matrix, get size matrx = np.array(matrx) size = matrx.shape[0] # Step 2: Generate trivi...
dc4dffa819ed836a8e4aaffbe23b49b95101bffe
31,589
def open_spreadsheet_from_args(google_client: gspread.Client, args): """ Attempt to open the Google Sheets spreadsheet specified by the given command line arguments. """ if args.spreadsheet_id: logger.info("Opening spreadsheet by ID '{}'".format(args.spreadsheet_id)) return google_cl...
355545a00de77039250269c3c8ddf05b2f72ec48
31,590
def perturb_BB(image_shape, bb, max_pertub_pixel, rng=None, max_aspect_ratio_diff=0.3, max_try=100): """ Perturb a bounding box. :param image_shape: [h, w] :param bb: a `Rect` instance :param max_pertub_pixel: pertubation on each coordinate :param max_aspect_ratio_diff: result ca...
4044291bdcdf1639e9af86857cac158a67db5229
31,591
def neural_network(inputs, weights): """ Takes an input vector and runs it through a 1-layer neural network with a given weight matrix and returns the output. Arg: inputs - 2 x 1 NumPy array weights - 2 x 1 NumPy array Returns (in this order): out - a 1 x 1 NumPy array, rep...
dc2d5cccf0cf0591c030b5dba2cd905f4583821c
31,593
def complex_randn(shape): """ Returns a complex-valued numpy array of random values with shape `shape` Args: shape: (tuple) tuple of ints that will be the shape of the resultant complex numpy array Returns: (:obj:`np.ndarray`): a complex-valued numpy array of random values with shape `shape` ...
6379fb2fb481392dce7fb4eab0e85ea85651b290
31,594
def sin(x: REAL) -> float: """Sine.""" x %= 2 * pi res = 0 k = 0 while True: mem_res = res res += (-1) ** k * x ** (2 * k + 1) / fac(2 * k + 1) if abs(mem_res - res) < _TAYLOR_DIFFERENCE: return res k += 1
0ae009139bc640944ad1a90386e6c66a6b874108
31,596
import tokenize from operator import getitem def _getitem_row_chan(avg, idx, dtype): """ Extract (row,chan,corr) arrays from dask array of tuples """ name = ("row-chan-average-getitem-%d-" % idx) + tokenize(avg, idx) dim = ("row", "chan", "corr") layers = db.blockwise(getitem, name, dim, ...
ff3da6b935cd4c3e909008fefea7a9c91d51d399
31,597
import gzip def make_gzip(tar_file, destination): """ Takes a tar_file and destination. Compressess the tar file and creates a .tar.gzip """ tar_contents = open(tar_file, 'rb') gzipfile = gzip.open(destination + '.tar.gz', 'wb') gzipfile.writelines(tar_contents) gzipfile.close() ta...
38d9e3de38cb204cc3912091099439b7e0825608
31,598
def symmetrize_confusion_matrix(CM, take='all'): """ Sums over population, symmetrizes, then return upper triangular portion :param CM: numpy.ndarray confusion matrix in standard format """ if CM.ndim > 2: CM = CM.sum(2) assert len(CM.shape) == 2, 'This function is meant for single subje...
91964cc4fd08f869330413e7485f765696b92614
31,599
def get_entry_values(): """Get entry values""" entry = {} for key, question in ENTRY_QUESTIONS.items(): input_type = int if key == "time" else str while True: print_title(MAIN_MENU[1].__doc__) print(question) user_input = validate(get_input(), input_type)...
6736ac24bbbe83a0dcbd7a43cd12a1c1b1acbdab
31,600
def _create_snapshot(provider_id, machine_uuid, skip_store, wait_spawning): """Create a snapshot. """ _retrieve_machine(provider_id, machine_uuid, skip_store) manager = _retrieve_manager(provider_id) return manager.create_snapshot(machine_uuid, wait_spawning)
0d35309341dd27cc41e713c4fd950fee735c866d
31,601
def get_masked_lm_output(bert_config, input_tensor, positions, label_ids, label_weights): """Get loss and log probs for the masked LM.""" input_tensor = gather_indexes(input_tensor, positions) with tf.variable_scope("cls/predictions"): # We apply one more non-linear transformation be...
7668ff4c4bd18cb14ff625dc0de593250cedb794
31,602
import torch def binary_classification_loss(logits, targets, reduction='mean'): """ Loss. :param logits: predicted classes :type logits: torch.autograd.Variable :param targets: target classes :type targets: torch.autograd.Variable :param reduction: reduction type :type reduction: str ...
507f3b076f6b59a8629bf02aa69ece05f5063f45
31,603
def transform_with(sample, transformers): """Transform a list of values using a list of functions. :param sample: list of values :param transformers: list of functions """ assert not isinstance(sample, dict) assert isinstance(sample, (tuple, list)) if transformers is None or len(transforme...
9a1d7741070b670e7bf8dbf88e8a23361521265f
31,605
def concat_eval(x, y): """ Helper function to calculate multiple evaluation metrics at once """ return { "recall": recall_score(x, y, average="macro", zero_division=0), "precision": precision_score(x, y, average="macro", zero_division=0), "f1_score": f1_score(x, y, average="macro...
5a0732ac5926173f12e3f0bd6d6e0ace653c7494
31,606
from typing import List def split_into_regions(arr: np.ndarray, mode=0) -> List[np.ndarray]: """ Splits an array into its coherent regions. :param mode: 0 for orthogonal connection, 1 for full connection :param arr: Numpy array with shape [W, H] :return: A list with length #NumberOfRegions of arr...
59e46f5877f3f4fd12a918e9aa26a67a92eb4d5b
31,607
def register_model(model_uri, name): """ Create a new model version in model registry for the model files specified by ``model_uri``. Note that this method assumes the model registry backend URI is the same as that of the tracking backend. :param model_uri: URI referring to the MLmodel directory. Us...
7dcdaa54717e6e0ea45390a5af48b1e350574d12
31,608
def noreplace(f): """Method decorator to indicate that a method definition shall silently be ignored if it already exists in the full class.""" f.__noreplace = True return f
88b6e8fdf7064ed04d9a0c310bcf1717e05e7fa8
31,609
def position_encoding(length, depth, min_timescale=1, max_timescale=1e4): """ Create Tensor of sinusoids of different frequencies. Args: length (int): Length of the Tensor to create, i.e. Number of steps. depth (int): Dimensions of embedding. ...
9d8c9082d82fd41ea6b6655a50b3e802a12f6694
31,610
def perform_exchange(ctx): """ Attempt to exchange attached NEO for tokens :param ctx:GetContext() used to access contract storage :return:bool Whether the exchange was successful """ attachments = get_asset_attachments() # [receiver, sender, neo, gas] address = attachments[1] neo_amo...
6c2f01a27b40a284e89da1e84de696baa1464e1d
31,611
def Pose_2_Staubli_v2(H): """Converts a pose to a Staubli target target""" x = H[0,3] y = H[1,3] z = H[2,3] a = H[0,0] b = H[0,1] c = H[0,2] d = H[1,2] e = H[2,2] if c > (1.0 - 1e-10): ry1 = pi/2 rx1 = 0 rz1 = atan2(H[1,0],H[1,1]) elif c < (-1.0 + 1e-1...
9fae83e10df544b7d2c096c7a59aca60567de538
31,612
def create_gru_model(fingerprint_input, model_settings, model_size_info, is_training): """Builds a model with multi-layer GRUs model_size_info: [number of GRU layers, number of GRU cells per layer] Optionally, the bi-directional GRUs and/or GRU with layer-normalization can be explored...
222581216edaf6225fabe850d977d14955c66c6e
31,613
def convergence_rates(N, solver_function, num_periods=8): """ Returns N-1 empirical estimates of the convergence rate based on N simulations, where the time step is halved for each simulation. solver_function(I, V, F, c, m, dt, T, damping) solves each problem, where T is based on simulation for ...
e66b4395557e0a254636546555d87716e4b0cc50
31,614
import cProfile import io import pstats def profile(fnc): """A decorator that uses cProfile to profile a function""" def inner(*args, **kwargs): pr = cProfile.Profile() pr.enable() retval = fnc(*args, **kwargs) pr.disable() s = io.StringIO() s...
9b5d248e2bd13d792e7c3cce646aa4c0432af8db
31,615
def _decode(y_pred, input_length, greedy=True, beam_width=100, top_paths=1): """Decodes the output of a softmax. Can use either greedy search (also known as best path) or a constrained dictionary search. # Arguments y_pred: tensor `(samples, time_steps, num_categories)` containing th...
7a73aa329245136ae560e92ebe67d997e57557f9
31,616
def rand_xyz_box(image_arrays, label, n, depth, img_size): """Returns n number of randomly chosen box. Args: image_arrays: 3D np array of images. label: label of images. normally is A or V n: number of random boxes generated from this function. depth : number of slices in Z...
3127522a7d08b5694fc92ab058736db1d7471676
31,617
def pageviews_by_document(start_date, end_date, verbose=False): """Return the number of pageviews by document in a given date range. * Only returns en-US documents for now since that's what we did with webtrends. Returns a dict with pageviews for each document: {<document_id>: <pageviews>, ...
c1a2c4ba2711803ca4b5e0cb8959a99b36f928ec
31,618
from re import T def format_time_string(seconds): """ Return a formatted and translated time string """ def unit(single, n): # Seconds and minutes are special due to historical reasons if single == "minute" or (single == "second" and n == 1): single = single[:3] if n == 1:...
27e0a084165605aa4b1a2b42c87840439686c255
31,619
import torch def warp_grid(flow: Tensor) -> Tensor: """Creates a warping grid from a given optical flow map. The warping grid determines the coordinates of the source pixels from which to take the color when inverse warping. Args: flow: optical flow tensor of shape (B, H, W, 2). The flow values ...
21f5765603f8fb42d5fe70668ab6d52b60c16bfe
31,620
def FORMULATEXT(*args) -> Function: """ Returns the formula as a string. Learn more: https//support.google.com/docs/answer/9365792. """ return Function("FORMULATEXT", args)
17cb21ee8b36439395b64fd410006ff03db7fedc
31,621
def num_prim_vertices(prim: hou.Prim) -> int: """Get the number of vertices belonging to the primitive. :param prim: The primitive to get the vertex count of. :return: The vertex count. """ return prim.intrinsicValue("vertexcount")
298a4a67133fc857c129b922f7f5a0f21d6d0b40
31,623
def read_geoparquet(path: str) -> GeoDataFrame: """ Given the path to a parquet file, construct a geopandas GeoDataFrame by: - loading the file as a pyarrow table - reading the geometry column name and CRS from the metadata - deserialising WKB into shapely geometries """ # read parquet file ...
0fddb5452010e5d4546b3b34e7afae93698cd953
31,624
def cmd_run_json_block_file(file): """`file` is a file containing a FullBlock in JSON format""" return run_json_block_file(file)
594e10a7ef4e20b130a5b39c22a834208df846a6
31,625
def collide_mask(left, right): """collision detection between two sprites, using masks. pygame.sprite.collide_mask(SpriteLeft, SpriteRight): bool Tests for collision between two sprites by testing if their bitmasks overlap. If the sprites have a "mask" attribute, that is used as the mask; otherwis...
fcb309e0c5ca7bc59e5b39b8fd67a45a5281d262
31,626
import requests def fetch_production(zone_key='IN-GJ', session=None, target_datetime=None, logger=getLogger('IN-GJ')) -> list: """Requests the last known production mix (in MW) of a given country.""" session = session or requests.session() if target_datetime: raise NotImplemen...
e23e409d24349e998eb9c261805a050de12ed30c
31,627
def xyz_order(coordsys, name2xyz=None): """ Vector of orders for sorting coordsys axes in xyz first order Parameters ---------- coordsys : ``CoordinateSystem`` instance name2xyz : None or mapping Object such that ``name2xyz[ax_name]`` returns 'x', or 'y' or 'z' or raises a KeyError ...
983c7adc5df8f54ecc92423eed0cd744971d4ec3
31,628
def parse_item(year, draft_type, row): """Parses the given row out into a DraftPick item.""" draft_round = parse_int(row, 'th[data-stat="draft_round"]::text', -1) draft_pick = parse_int(row, 'td[data-stat="draft_pick"]::text', -1) franchise = '/'.join( row.css('td[data-stat="team"] a::attr(href...
822a596e0c3e381658a853899920347b95a7ff59
31,629
def buildJointChain(prefix, suffix, startPos, endPos, jointNum, orientJoint="xyz", saoType="yup"): """ Build a straight joint chain defined by start and end position. :param prefix: `string` prefix string in joint name :param suffix: `string` suffix string in joint name :param startPos: `list` [x,y,...
fda63b96d2e5a1316fab9d2f9dc268ae0ff270d2
31,630
import time import torch def predict(model, img_load, resizeNum, is_silent, gpu=0): """ input: model: model img_load: A dict of image, which has two keys: 'img_ori' and 'img_data' the value of the key 'img_ori' means the original numpy array the value of the key 'img_data' is the list of five ...
04da68453aab79f732deb153cdcbed9ea267355c
31,631
def reverse_preorder(root): """ @ input: root of lcrs tree @ output: integer list of id's reverse preorder """ node_list = [] temp_stack = [root] while len(temp_stack) != 0: curr = temp_stack.pop() node_list.append(curr.value) if curr.child is not None: ...
06a53756db0f5c990537d02de4fcaa57cc93169d
31,632
import scipy def calc_binned_percentile(bin_edge,xaxis,data,per=75): """Calculate the percentile value of an array in some bins. per is the percentile at which to extract it. """ percen = np.zeros(np.size(bin_edge)-1) for i in xrange(0,np.size(bin_edge)-1): ind = np.where((xaxis > bin_edge[i])...
798cd1e4f1070b27766f2390442fa81dfad15aaa
31,633
def run_services(container_factory, config, make_cometd_server, waiter): """ Returns services runner """ def _run(service_class, responses): """ Run testing cometd server and example service with tested entrypoints Before run, the testing cometd server is preloaded with passed ...
df7d1c3fdf7e99ebf054cfc6881c8073c2cf4dee
31,634
import requests def cleaned_request(request_type, *args, **kwargs): """ Perform a cleaned requests request """ s = requests.Session() # this removes netrc checking s.trust_env = False return s.request(request_type, *args, **kwargs)
b6c99c85a64e5fd78cf10cc986c9a4b1542f47d3
31,635
from typing import List from typing import Set def construct_speech_to_text_phrases_context(event: EventIngestionModel) -> List[str]: """ Construct a list of phrases to use for Google Speech-to-Text speech adaption. See: https://cloud.google.com/speech-to-text/docs/speech-adaptation Parameters -...
e8834afd4e53d446f2dda1fd79383a0266010e5b
31,636
def data_science_community(articles, authors): """ Input: Articles and authors collections. You may use only one of them Output: 3-tuple reporting on subgraph of authors of data science articles and their co-authors: (number of connected components,size of largest connected component, size of smalle...
3a81fc7674a2d421ff4649759e61797a743b7aae
31,637
def breadth_first_search(G, seed): """Breadth First search of a graph. Parameters ---------- G : csr_matrix, csc_matrix A sparse NxN matrix where each nonzero entry G[i,j] is the distance between nodes i and j. seed : int Index of the seed location Returns ------- ...
047596e378f0496189f2e164e2b7ede4a6212f19
31,638
def main_page(): """ Pass table of latest sensor readings as context for main_page """ LOG.info("Main Page triggered") context = dict( sub_title="Latest readings:", table=recent_readings_as_html() ) return render_template('main_page.html', **context)
6c9ac7c3306eb10d03269ca4e0cbca9c68a19644
31,639
import yaml def load_config_file(filename): """Load configuration from YAML file.""" docs = yaml.load_all(open(filename, 'r'), Loader=yaml.SafeLoader) config_dict = dict() for doc in docs: for k, v in doc.items(): config_dict[k] = v return config_dict
d61bb86e605a1e744ce3f4cc03e866c61137835d
31,640
def CausalConv(x, dilation_rate, filters, kernel_size=2, scope = ""): """Performs causal dilated 1D convolutions. Args: x : Tensor of shape (batch_size, steps, input_dim). dilation_rate: Dilation rate of convolution. filters: Number of convolution filters. kernel_size: Width of convolution kernel. ...
08ffde5e4a9ae9ebdbb6ed83a22ee1987bf02b1e
31,641
import functools def makeTable(grid): """Create a REST table.""" def makeSeparator(num_cols, col_width, header_flag): if header_flag == 1: return num_cols * ("+" + (col_width) * "=") + "+\n" else: return num_cols * ("+" + (col_width) * "-") + "+\n" def normalizeCe...
c889a4cf505b5f0b3ef75656acb38f621c7fff31
31,642
def coords_to_bin( x: npt.NDArray, y: npt.NDArray, x_bin_width: float, y_bin_width: float, ) -> tuple[npt.NDArray[np.int_], npt.NDArray[np.int_]]: """ x: list of positive east-west coordinates of some sort y: list of positive north-south coordinates of some sort x_bin_width: bin width fo...
874950836d6d03e1dc0f39bdb53653789fe64605
31,644
from typing import Callable def _gcs_request(func: Callable): """ Wrapper function for gcs requests in order to create more helpful error messages. """ @wraps(func) def wrapper(url: str, *args, **kwargs): try: return func(url, *args, **kwargs) except NotFound: ...
a57867df668eb9b139ee8e07a405868676c9e0f2
31,645
def nllsqfunc(params: np.ndarray, qm: HessianOutput, qm_hessian: np.ndarray, mol: Molecule, loss: list[float]=None) -> np.ndarray: """Residual function for non-linear least-squares optimization based on the difference of MD and QM hessians. Keyword arguments ----------------- para...
0debdca80de9e7ea136683de04bc838ceb2f42e2
31,646
import time def wait_for_mongod_shutdown(mongod_control, timeout=2 * ONE_HOUR_SECS): """Wait for for mongod to shutdown; return 0 if shutdown occurs within 'timeout', else 1.""" start = time.time() status = mongod_control.status() while status != "stopped": if time.time() - start >= timeout: ...
837271069f8aa672372aec944abedbd44664a3d3
31,647
from typing import List import re def get_installed_antivirus_software() -> List[dict]: """ Not happy with it either. But yet here we are... Thanks Microsoft for not having SecurityCenter2 on WinServers So we need to detect used AV engines by checking what is installed and do "best guesses" This test ...
b122960b48edfb0e193c354293b28bc1ead0a936
31,648
def mi(x,y,k=3,base=2): """ Mutual information of x and y x,y should be a list of vectors, e.g. x = [[1.3],[3.7],[5.1],[2.4]] if x is a one-dimensional scalar and we have four samples """ x = [[entry] for entry in x] y = [[entry] for entry in y] assert len(x)==len(y), "Lists should have ...
960501be5134dcfe99ca29b50622dbfc0b403b78
31,649
def _xls_cc_ir_impl_wrapper(ctx): """The implementation of the 'xls_cc_ir' rule. Wrapper for xls_cc_ir_impl. See: xls_cc_ir_impl. Args: ctx: The current rule's context object. Returns: ConvIRInfo provider DefaultInfo provider """ ir_conv_info, built_files, runfiles = _xls_cc...
c76bddc8b05322b2df4af67415f783aa1f2635bb
31,650
from typing import List from typing import Tuple from typing import DefaultDict def create_dataset(message_sizes: List[int], labels: List[int], window_size: int, num_samples: int, rand: np.random.RandomState) -> Tuple[np.ndarray, np.ndarray]: """ Creates the attack dataset by randomly sampling message sizes o...
081e0c6ddc18988d8e24a08ec4a4e565f318d23a
31,651
def infer_Tmap_from_clonal_info_alone_private( adata_orig, method="naive", clonal_time_points=None, selected_fates=None ): """ Compute transition map using only the lineage information. Here, we compute the transition map between neighboring time points. We simply average transitions across all cl...
9926e2a6faf50bed2d1668de031a600e0f65c1af
31,652
import math def percentile(seq: t.Iterable[float], percent: float) -> float: """ Find the percentile of a list of values. prometheus-client 0.6.0 doesn't support percentiles, so we use this implementation Stolen from https://github.com/heaviss/percentiles that was stolen from http://code.activesta...
640f132366bad8bf0c58aa318b5be60136925ab9
31,653
from typing import Union def select_view_by_cursors(**kwargs): """ Selects the Text View ( visible selection ) for the given cursors Keyword Args: sel (Tuple[XTextRange, XTextRange], XTextRange): selection as tuple of left and right range or as text range. o_doc (GenericTextDocument, opti...
42c42c4b60d802a66e942ac8fa8efe97a8253ea3
31,654
from typing import List from typing import Dict def load_types( directories: List[str], loads: LoadedFiles = DEFAULT_LOADS, ) -> Dict[str, dict]: """Load schema types and optionally register them.""" schema_data: Dict[str, dict] = {} # load raw data for directory in directories: load...
8dc1f3625c03451eb9ac28804715ccf260400536
31,655
def fit_circle(img, show_rect_or_cut='show'): """ fit an ellipse to the contour in the image and find the overlaying square. Either cut the center square or just plot the resulting square Code partly taken from here: https://stackoverflow.com/questions/55621959/opencv-fitting-a-single-circle-to-an-...
fdeb8f9a24159236609eac271016624f95f62504
31,656
from typing import Mapping from typing import Any from typing import MutableMapping def unflatten_dict( d: Mapping[str, Any], separator: str = '.', unflatten_list: bool = False, sort: bool = False ) -> MutableMapping[str, Any]: """ Example: In []: unflatten_dict({'count.chans.HU_SN': 10}) Out[]: {'count': {'...
40662a4884171c444ed40c654497f6a0e17a132d
31,657
def _xinf_1D(xdot,x0,args=(),xddot=None,xtol=1.49012e-8): """Private function for wrapping the solving for x_infinity for a variable x in 1 dimension""" try: if xddot is None: xinf_val = float(fsolve(xdot,x0,args,xtol=xtol)) else: xinf_val = float(newton_meth(xdot,x0,...
e69c08b914395d93a94544d9ba085a440951a03c
31,658
import types from typing import Dict import operator def to_bag_of_words( doclike: types.DocLike, *, by: TokenGroupByType = "lemma_", weighting: WeightingType = "count", **kwargs, ) -> Dict[int, int | float] | Dict[str, int | float]: """ Transform a ``Doc`` or ``Span`` into a bag-of-words:...
0065eba8ff7f74b420efc8c65688ab293dee1dda
31,659
def get_trip_info(origin, destination, date): """ Provides basic template for response, you can change as many things as you like. :param origin: from which airport your trip beings :param destination: where are you flying to :param date: when :return: """ template = { "kind": "q...
d1dfd35f41538e800b5c6f5986faac7fcd30ebf3
31,660
def serialise(data, data_type=None): """ Serialises the specified data. The result is a ``bytes`` object. The ``deserialise`` operation turns it back into a copy of the original object. :param data: The data that must be serialised. :param data_type: The type of data that will be provided. If no data type is pr...
6c4e7b144e3e938d30cceee5503290f8cf31ca27
31,661
def topopebreptool_RegularizeShells(*args): """ * Returns <False> if the shell is valid (the solid is a set of faces connexed by edges with connexity 2). Else, splits faces of the shell; <OldFacesnewFaces> describes (face, splits of face). :param aSolid: :type aSolid: TopoDS_Solid & :param OldSheNewS...
8aa44c5b79f98f06596a5e6d9db8a4cf18f7dad3
31,663
def empty_filter(item, *args, **kwargs): """ Placeholder function to pass along instead of filters """ return True
d72ac5a0f787557b78644bcedd75e71f92c38a0b
31,665
def Get_User_Tags(df, json_response, i, github_user): """ Calculate the tags for a user. """ all_repos_tags = pd.DataFrame(0, columns=df.columns, index=pyjq.all(".[] | .name", json_response)) num_repos = len(pyjq.all(".[] | .name", json_response)) # new_element = pd.DataFrame(0, np.zeros(...
80955e2794e9f9d4f65a3f048bc7dc0d450ebb3d
31,666
import ctypes def ssize(newsize, cell): """ Set the size (maximum cardinality) of a CSPICE cell of any data type. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ssize_c.html :param newsize: Size (maximum cardinality) of the cell. :type newsize: int :param cell: The cell. :type c...
52eb884e7477ddb98dc905ab848c61b83ac16123
31,667
def extend_data(data, length, offset): """Extend data using a length and an offset.""" if length >= offset: new_data = data[-offset:] * (alignValue(length, offset) // offset) return data + new_data[:length] else: return data + data[-offset:-offset+length]
923372c1fde14335331eb38b40e118b426cc9219
31,669
def RAND_egd(path): # real signature unknown; restored from __doc__ """ RAND_egd(path) -> bytes Queries the entropy gather daemon (EGD) on the socket named by 'path'. Returns number of bytes read. Raises SSLError if connection to EGD fails or if it does not provide enough data to seed PRNG. ...
5ef4e3e065c44058996c1793541cd9f2a599b106
31,670
from typing import List from typing import Dict from typing import Any def get_types_map(types_array: List[Dict[str, Any]]) -> Dict[str, Dict[str, Any]]: """Get the type name of a metadata or a functionality.""" return {type_["name"]: type_ for type_ in types_array}
9354eff434b589a19360ee13d8bf7d9ab9e1002d
31,671
def update_flavor(request, **kwargs): """Update a flavor. """ data = request.DATA flavor_id = data['flavor']['id'] conn = _get_sdk_connection(request) flavor = conn.load_balancer.update_flavor( flavor_id, name=data['flavor'].get('name'), description=data['flavor'].get('...
9f165df73f3c557956d466e3fec6d720a1ee76cb
31,672
from typing import List import re async def get_all_product_features_from_cluster() -> List[str]: """ Returns a list of all product.feature in the cluster. """ show_lic_output = await scontrol_show_lic() PRODUCT_FEATURE = r"LicenseName=(?P<product>[a-zA-Z0-9_]+)[_\-.](?P<feature>\w+)" RX_PROD...
9822c952654b3e2516e0ec3b5cf397ced8b3eaaf
31,673