content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def pytest_funcarg__testname(request): """ The testname as string, or ``None``, if no testname is known. This is the parameter added by the test generation hook, or ``None`` if no parameter was set, because test generation didn't add a call for this test. """ return getattr(request, 'param', No...
87444cda36635b21c27d260835f96670d6b2d215
2,000
import pathlib import json import logging def try_log_conf_file(file_path: pathlib.Path) -> bool: """It tries to open a log configuration file. filePath: filePath return: boolean (True is succeed, False otherwise) """ global logger try: with file_path.open() as f: logger_c...
c24d4d15fc43870639acac575562d0e1487bfcf5
2,001
def notes_to_editor_view(notes): """Convert notes object content to more readble view Args: notes (list): list of note object Returns: list: list of note object """ for note in notes: note.content = to_editor(note.content) return notes
44dfa40fb0bf3c5c3c2aafb2731583b6e13d8853
2,002
def normalization(arr, normalize_mode, norm_range = [0,1]): """ Helper function: Normalizes the image based on the specified mode and range Args: arr: numpy array normalize_mode: either "whiten", "normalize_clip", or "normalize" representing the type of normalization to use norm_rang...
8400419db77c2f76ba63999ecae89eb3fbdfae6d
2,003
def draw_mask(img, mask, col, alpha=0.4, show_border=True, border_thick=0): """Visualizes a single binary mask.""" was_pil = isinstance(img, (Image.Image)) img = np.array(img) img = img.astype(np.float32) idx = np.nonzero(mask) img[idx[0], idx[1], :] *= 1.0 - alpha img[idx[0], idx[1], ...
047bfc2f26ed38c28ff31f46746542a5d56182c4
2,004
def build_md_page(page_info: parser.PageInfo) -> str: """Given a PageInfo object, return markdown for the page. Args: page_info: Must be a `parser.FunctionPageInfo`, `parser.ClassPageInfo`, or `parser.ModulePageInfo`. Returns: Markdown for the page Raises: ValueError: if `page_info` is an i...
86ed4f8e1b9b733f45e827c65b067295a9a2ff06
2,005
from typing import Optional def transpose(data: NodeInput, input_order: NodeInput, name: Optional[str] = None) -> Node: """Return a node which transposes the data in the input tensor. @param data: The input tensor to be transposed @param input_order: Permutation of axes to be applied to the input tensor ...
bc84792893352cdd235efd9e33fdc53cadd6521f
2,006
def find_opposite_reader(card_reader_list, find): """Returns the card reader on the opposite side of the door for the card reader in find""" for c in card_reader_list: if c.room_a == find.room_b and c.room_b == find.room_a: return c raise (Exception("No reader on opposite side found"))
8a70b9b35174be62f3ca816f385b4c29a6ebebe8
2,007
def tag_from_clark(name): """Get a human-readable variant of the XML Clark notation tag ``name``. For a given name using the XML Clark notation, return a human-readable variant of the tag name for known namespaces. Otherwise, return the name as is. """ match = CLARK_TAG_REGEX.match(name) i...
948ea17b017926353a37d2ceab031751146e445a
2,008
def build_k_indices(y, k_fold, seed): """ Randomly partitions the indices of the data set into k groups Args: y: labels, used for indexing k_fold: number of groups after the partitioning seed: the random seed value Returns: k_indices: an array of k sub-indices that are ra...
3d5684ef59bc1ac0abeca243c394499258be5b54
2,009
def get_parent(obj, default=_marker): """Returns the container the object was traversed via. Returns None if the object is a containment root. Raises TypeError if the object doesn't have enough context to get the parent. """ if IRoot.providedBy(obj): return None parent = aq_parent(...
a6c53ddd4a8bfb81f211737edf1da12688a3f4e2
2,010
import numpy def MRR(logits, target): """ Compute mean reciprocal rank. :param logits: 2d array [batch_size x rel_docs_per_query] :param target: 2d array [batch_size x rel_docs_per_query] :return: mean reciprocal rank [a float value] """ assert logits.shape == target.shape sorted, ind...
eb9249bf0e3942aeb01b148a0db28c3e5f9dd00a
2,011
def range(starts, limits=None, deltas=1, dtype=None, name=None, row_splits_dtype=dtypes.int64): """Returns a `RaggedTensor` containing the specified sequences of numbers. Each row of the returned `RaggedTensor` contains a single sequence: ```python ragged.rang...
177c956844596b5125c288db8859a38ecf4e8b80
2,012
def ecef2enuv(u, v, w, lat0, lon0, deg=True): """ for VECTOR i.e. between two points input ----- x,y,z [meters] target ECEF location [0,Infinity) """ if deg: lat0 = radians(lat0) lon0 = radians(lon0) t = cos(lon0) * u + sin(lon0) * v ...
b9b6adb9232407043927cdbc0c2cec4f0b9b50a2
2,013
def interpolate_ray_dist(ray_dists, order='spline'): """ interpolate ray distances :param [float] ray_dists: :param str order: degree of interpolation :return [float]: >>> vals = np.sin(np.linspace(0, 2 * np.pi, 20)) * 10 >>> np.round(vals).astype(int).tolist() [0, 3, 6, 8, 10, 10, 9, 7, 5...
f1ef1906fd2871e995355a7dd8818a946eefe1e3
2,014
def distance(left, right, pairwise=pairwise['prod'], distance_function=None): """ Calculate the distance between two *k*-mer profiles. :arg left, right: Profiles to calculate distance between. :return: The distance between `left` and `right`. :rtype: float """ if not distance_functio...
1be9b2777cf58bf52e2e33d6c39ed3655edc2354
2,015
def _rec_get_all_imports_exports(fips_dir, proj_dir, result) : """recursively get all imported projects, their exported and imported modules in a dictionary object: project-1: url: git-url (not valid for first, top-level project) exports: header-dirs: ...
66c0d25d27559e6841bcfced49646f5a711bfeb3
2,016
from typing import Optional from typing import Sequence def get_database_cluster(name: Optional[str] = None, tags: Optional[Sequence[str]] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetDatabaseClusterResult: """ Provides information on a ...
edc9d4e0264e90a1491a809c40e2cf2961699d80
2,017
import sys def caller_name(skip=2): """Get a name of a caller module `skip` specifies how many levels of stack to skip while getting caller name. skip=1 means "who calls me", skip=2 "who calls my caller" etc. An empty string is returned if skipped levels exceed stack height Referen...
8823f3a896d4eefcb3626a571250cbc926431c9c
2,018
import os def get_dataset(): """Summary Returns ------- TYPE Description """ stms = [] for dirpath, dirnames, filenames in os.walk('TEDLIUM_release2'): for f in filenames: if f.endswith('stm'): stms.append(os.path.join(dirpath, f)) data = [...
1ab0e272d5fc9c8be797b418b3f826e58a0b8904
2,019
def tesla_loadhook(h, *args, **kwargs): """ Converts a load hook into an application processor. >>> app = auto_application() >>> def f(*args, **kwargs): "something done before handling request" ... >>> app.add_processor(loadhook(f, *args, **kwargs)) """ def processor(han...
65743cd9220ddef40294cde0f4f6566ae9235772
2,020
def force_unicode(s, encoding='utf-8', strings_only=False, errors='strict'): #pragma: no cover """ Force a string to be unicode. If strings_only is True, don't convert (some) non-string-like objects. Originally copied from the Django source code, further modifications have been made. Origina...
61992707364bfbb3e714bb52005a417387f8d7de
2,021
def extractYoloInfo(yolo_output_format_data): """ Extract box, objectness, class from yolo output format data """ box = yolo_output_format_data[..., :6] conf = yolo_output_format_data[..., 6:7] category = yolo_output_format_data[..., 7:] return box, conf, category
ff28a5ce5490c61722ca06b0e09b9bd85ee7e111
2,022
def bbox_diou(bboxes1, bboxes2): """ Complete IoU @param bboxes1: (a, b, ..., 4) @param bboxes2: (A, B, ..., 4) x:X is 1:n or n:n or n:1 @return (max(a,A), max(b,B), ...) ex) (4,):(3,4) -> (3,) (2,1,4):(2,3,4) -> (2,3) """ bboxes1_area = bboxes1[..., 2] * bboxes1[..., 3] ...
f32e4a289f437494fd738c1128d6e7c7a8e02c7e
2,023
def showp1rev(context, mapping): """Integer. The repository-local revision number of the changeset's first parent, or -1 if the changeset has no parents. (DEPRECATED)""" ctx = context.resource(mapping, b'ctx') return ctx.p1().rev()
2c843d5476a8e5b43fa8ac31351de633c5fa3d6c
2,024
def erp_pretax(t,ma,st,ra,par): """ early retirement pension (efterløn) pretax""" # initialize ERP = np.zeros(1) # pre two year period if par.T_erp <= t < par.T_two_year: if ra == 1: priv = priv_pension(ma,st,par) ERP[:] = np.maximum(0,par.ERP_high - 0.6*0.05*np.max...
d9a3142236aa942f8c86db1c484e57e4fc7ee278
2,025
import os import subprocess def main(gen5tt_algo, fs_file, num_tracts, participant_label, session_label, t1_file, eddy_file, bvec_file, bval_file, template_file, atlas_file, output_dir): """Console script for tractify.""" work_dir = os.path.join(output_dir, "scratch") # Set parameters based on CLI, pass...
2ad0568612559c3811d1e6aba4c16d11d855c54e
2,026
def add_missing_cmd(command_list): """Adds missing cmd tags to the given command list.""" # E.g.: given: # ['a', '0', '0', '0', '0', '0', '0', '0', # '0', '0', '0', '0', '0', '0', '0'] # Converts to: # [['a', '0', '0', '0', '0', '0', '0', '0'], # ['a', '0', '0', '0', '0', '0',...
190884575d0110f06088b9be70008da56c279344
2,027
def replace_umlauts(s: str) -> str: """ Replace special symbols with the letters with umlauts (ä, ö and ü) :param s: string with the special symbols (::) :return: edited string """ out = s.replace('A::', 'Ä').replace('O::', 'Ö').replace('U::', 'Ü').replace('a::', 'ä').replace('o::', 'ö') \ ...
8fad1f1017a3fd860d7e32fd191dd060b75a7bb8
2,028
def bandstructure_flow(workdir, scf_input, nscf_input, dos_inputs=None, manager=None, flow_class=Flow, allocate=True): """ Build a :class:`Flow` for band structure calculations. Args: workdir: Working directory. scf_input: Input for the GS SCF run. nscf_input: Input for the NSCF run...
f3515fdfa8c719c8b91a8f76a04d468e545d6f23
2,029
import os def get_modules(): """Returns the list of module names """ def listdir(dir): def clean(name): name = os.path.basename(name) if name[-4:] == '.zip': name = name[:-4] return name def is_really_module(name): for mname ...
7d61468330704167b6a7a93787533e80dc78d0a0
2,030
def resnet_50(num_classes, data_format='channels_first', pruning_method=None): """Returns the ResNet model for a given size and number of output classes.""" return resnet_50_generator( block_fn=bottleneck_block_, lst_layers=[3, 4, 6, 3], num_classes=num_classes, pruning_method=pruning_method...
4962f9a4cf4aaaf0052941279c8156e29b2cb639
2,031
import json import base64 def read_amuselabs_data(s): """ Read in an amuselabs string, return a dictionary of data """ # Data might be base64'd or not try: data = json.loads(s) except json.JSONDecodeError: s1 = base64.b64decode(s) data = json.loads(s1) ret = {} ...
f9c2fb2807d1003261bec7b58e4ba025aac65a6a
2,032
def calinski_harabasz(dataset_values:DatasetValues): """Calinski, T.; Harabasz, J. (1974). A dendrite method for cluster analysis. Communications in Statistics - Theory and Methods, v.3, n.1, p.1�27. The objective is maximize value [0, +Inf]""" if dataset_values.K == 1: return 0 re...
c8231971350d22d1067056c53838f0536ae03e77
2,033
from re import IGNORECASE def parse_version(version): """ input version string of the form: 'Major.Minor.Patch+CommitHash' like: '0.1.5+95ffef4' ------ or ------ '0.1.0' returns version_info tuple of the form: (major,...
cc9b326e498991092a494458d4f98cce7bbb28f9
2,034
def _location_sensitive_score(W_query, W_fil, W_keys): """Impelements Bahdanau-style (cumulative) scoring function. This attention is described in: J. K. Chorowski, D. Bahdanau, D. Serdyuk, K. Cho, and Y. Ben- gio, “Attention-based models for speech recognition,” in Ad- vances in Neural Info...
f3daa106f6ac819ef5037a221e2cd768d6810642
2,035
def get_streamdecks(): """ Retrieves all connected streamdecks """ streamdecks = DeviceManager().enumerate() return streamdecks
f649fe4404ec6be71cdb4f9cd5805738e1d0b823
2,036
import six def clean_string(text): """ Remove Lucene reserved characters from query string """ if isinstance(text, six.string_types): return text.translate(UNI_SPECIAL_CHARS).strip() return text.translate(None, STR_SPECIAL_CHARS).strip()
5387d76d4dc47997eac751538670cc426d854449
2,037
def convert_single_example(example_index, example, label_size, max_seq_length, tokenizer, max_qa_length): """Loads a data file into a list of `InputBatch`s.""" # RACE is a multiple choice task. To perform this task using AlBERT, # we will use the formatting proposed in "Improving Langu...
385f5f2801a41e0216e8a8c22d089e986bb55588
2,038
def GetAllProperties(layers='core'): """Return all properties in the graph.""" global Utc KEY = "AllProperties:%s" % layers if DataCache.get(KEY,Utc): #logging.debug("DataCache HIT: %s" % KEY) return DataCache.get(KEY,Utc) else: #logging.debug("DataCache MISS: %s" % KEY) ...
f3bf05ce6a4497e036cd12e4a05db603f10ca9e6
2,039
from typing import Tuple from typing import Optional def _single_optimal_block(x: NDArray) -> Tuple[float, float]: """ Compute the optimal window length for a single series Parameters ---------- x : ndarray The data to use in the optimal window estimation Returns ------- stat...
7de0221ddc654d4f9e8ddd56d65f688c096a7784
2,040
def predict(params, X): """ Using the learned parameters, predicts a class for each example in X Arguments: parameters -- python dictionary containing your parameters X -- input data of size (n_x, m) Returns predictions -- vector of predictions of our model (red: 0 / blue: 1) """ ...
c647114ad415b2ae6c75f2fe2e207bf279775131
2,041
def response(request): """ 返回相应对象 :param request: :return: """ json_str = '{"name": "张三", "age": 18}' # 整体是个字符串 response = HttpResponse(json_str, content_type="application/json", status=200) response["dev"] = "aGrass0825" # 向响应头中添加内容 ...
a44b35682ff8f5de168711730a10056653319512
2,042
def nest_to_flat_dict(nest): """Convert a nested structure into a flat dictionary. Args: nest: A nested structure. Returns: flat_dict: A dictionary with strings keys that can be converted back into the original structure via `flat_dict_to_nest`. """ flat_sequence = tf.nest.flatten(nes...
f74308fc4f7c0b97d6524faea65915263a8ced9b
2,043
import sys def _live_tensors(f, attr_name="inputs"): """Returns the indices of the used inputs. Note: This currently only handles direct index accesses e.g. op.inputs[1]. If the function has slicing or list comprehension on attr_name then returns _ALL. This ensure that this is correct even if inefficient. ...
6521965fe10f0c7ca76ea867c4b7478d138b9f41
2,044
import os import sys import configparser def update_site_config(site_name, parameters): """Update the site config to establish the database settings""" site_directory = os.path.join('web', 'sites', site_name) if not os.path.isdir(site_directory): print('site directory {} missing'.format(site_direc...
8dce45257189cb5c4830f18fc1bcad388a193252
2,045
def plot_with_front(gen, front, title, fname): """ plot with front: Print the generation gen and front, highlighting front as the pareto front on the graph. Parameters: gen: The generation to plot. front: The pareto front extracted from generation gen title: Plot Title fname: path t...
6556a22c6484e4c96f79a14a770cca934f50e274
2,046
def find_closest_positive_divisor(a, b): """Return non-trivial integer divisor (bh) of (a) closest to (b) in abs(b-bh) such that a % bh == 0""" assert a>0 and b>0 if a<=b: return a for k in range(0, a-b+1): bh = b + k if bh>1 and a % bh == 0: return bh bh = b ...
1a68e1767680f82db232095806adfe1c27fb956e
2,047
def simplify_stl_names(decl): """Take common STL/Standard Library names and simplify them to help make the stack trace look more readable and less like the graphics in the matrix. """ p = simplify_template_call(decl) if p == []: return decl return p[0] + '<' + ', '.join(p[1:-1]) + ...
53ea9c18e47ce4a7d922db74efdc45646441ea49
2,048
from typing import Sequence from typing import Union from typing import Callable from typing import Optional from typing import Tuple def sample_switching_models( models: Sequence, usage_seq: Sequence, X: Union[None, Sequence, Callable] = None, initial_conditions: Optional[Tuple[Sequence, Sequence]] =...
472e20968fe835b01da57c4a0abab376c006094b
2,049
def eval_per_class(c_dets, c_truths, overlap_thresh=0.5, eval_phrase=False): """ Evaluation for each class. Args: c_dets: A dictionary of all detection results. c_truths: A dictionary of all ground-truth annotations. overlap_thresh: A float of the threshold used in IoU matching. Re...
7884255c6fb45d6cb01b88edd5017d134f0344b0
2,050
def define_components(mod): """ Adds components to a Pyomo abstract model object to describe unit commitment for projects. Unless otherwise stated, all power capacity is specified in units of MW and all sets and parameters are mandatory. -- Commit decision, limits, and headroom -- CommitP...
4ad0aae0df9a3953309138dfbc138f944efba74e
2,051
def adjustwithin(df, pCol, withinCols, method='holm'): """Apply multiplicity adjustment to a "stacked" pd.DataFrame, adjusting within groups defined by combinations of unique values in withinCols Parameters ---------- df : pd.DataFrame Stacked DataFrame with one column of pvalues ...
4040c53def07ce5353c111036887b5df4666684c
2,052
def parse_url_query_params(url, fragment=True): """Parse url query params :param fragment: bool: flag is used for parsing oauth url :param url: str: url string :return: dict """ parsed_url = urlparse(url) if fragment: url_query = parse_qsl(parsed_url.fragment) else: url_...
252d2ccfb2fb15db041e97908c982dae9bf3c1ef
2,053
import torch import math def sample_random_lightdirs(num_rays, num_samples, upper_only=False): """Randomly sample directions in the unit sphere. Args: num_rays: int or tensor shape dimension. Number of rays. num_samples: int or tensor shape dimension. Number of samples per ray. upper_...
7f7657ff66d0cffea6892dffdf49ba6b52b9def9
2,054
def gaussgen(sigma): """ Function to generate Gaussian kernels, in 1D, 2D and 3D. Source code in MATLAB obtained from Qiyuan Tian, Stanford University, September 2015 :param sigma: Sigma for use in generating Gaussian kernel (see defaults in generate_FSL_structure_tensor) :return: Gaussian kernel wi...
7673e3fb8ddbb7bbb646331a24380581a7af9617
2,055
import types from typing import List def metrics_specs_from_keras( model_name: Text, model_loader: types.ModelLoader, ) -> List[config.MetricsSpec]: """Returns metrics specs for metrics and losses associated with the model.""" model = model_loader.construct_fn() if model is None: return [] metric...
fd471d20782507e983abec5610115e83c59ed7e0
2,056
def __main__(recipe, params): """ Main code: should only call recipe and params (defined from main) :param recipe: :param params: :return: """ # ---------------------------------------------------------------------- # Main Code # -----------------------------------------------------...
3e9fc1006457be759e1e0b05f36c00297f0c5f4c
2,057
def AICrss(n, k, rss): """Calculate the Akaike Information Criterion value, using: - n: number of observations - k: number of parameters - rss: residual sum of squares """ return n * log((2 * pi) / n) + n + 2 + n * log(rss) + 2 * k
988345930a8544d2979b99d6400198d3a59fa85c
2,058
import sys import os def CONVERT_OUT(s): """ convert a directory of module into a reponsed output directory if s doesn't beneath the module, raise NotInSelfModuleError Args: s : a relative directory beneathed the module Returns: return the relative path of responsed output director...
d6a618ef5183a93b78d1f260bf130832b2751dd1
2,059
def random_traveling_salesman(points, distmat, avg_edges=None, start=None, max_perm_samples=2e3, end=None, debug=0): """ Finds the shortest route to visit all the cities by bruteforce. Time complexity is O(N!), so never use on long lists. We use a limit of max_perm_samples (default=2k) random s...
3096962cb73a30e782ee110fbf23db7aa82fdcda
2,060
from typing import Optional def get_username_from_access_token(token: str, secret_key: str, algorithm: str) -> Optional[str]: """ Decodes a token and returns the "sub" (= username) of the decoded token :param token: JWT access token :param secret_key: The secret key that should be used for token decod...
461ce205b43961af25c77af4d3902d1342bba32a
2,061
import re from os.path import dirname, join def _inject_getter_attrs( metaself, objname, attrs, configurable_attrs, depc_name=None, depcache_attrs=None, settable_attrs=None, aliased_attrs=None, ): """ Used by the metaclass to inject methods and properties into the class inh...
48511de7639dd6de9e6f42c9e4779466d03315fe
2,062
def date_handler(obj): """make datetime object json serializable. Notes ----- Taken from here: https://tinyurl.com/yd84fqlw """ if hasattr(obj, 'isoformat'): return obj.isoformat() else: raise TypeError
741867e05e1b5f3e9d0e042b3b1576fb61ab0219
2,063
def has_type(typestmt, names): """Return type with name if `type` has name as one of its base types, and name is in the `names` list. otherwise, return None.""" if typestmt.arg in names: return typestmt for t in typestmt.search('type'): # check all union's member types r = has_type(t, n...
d534331df62f76efdcbb93be52eb57ee600a7783
2,064
def generic_ecsv(file_name, column_mapping=None, **kwargs): """ Read a spectrum from an ECSV file, using generic_spectrum_from_table_loader() to try to figure out which column is which. The ECSV columns must have units, as `generic_spectrum_from_table_loader` depends on this to determine the meaning...
0c9ac3a8d31a449e698907e02ad4715868844403
2,065
def parse_valuation_line(s, encoding=None): """ Parse a line in a valuation file. Lines are expected to be of the form:: noosa => n girl => {g1, g2} chase => {(b1, g1), (b2, g1), (g1, d1), (g2, d2)} :param s: input line :type s: str :param encoding: the encoding of the input...
aebd7ca9e4e321069a04536f281230b5cd23cceb
2,066
import requests from bs4 import BeautifulSoup from datetime import datetime def scrape_dailykos(keywords=KEYWORDS): """ Scrapes news article titles from dailykos.com """ dk_request = requests.get('https://www.dailykos.com') dk_homepage = dk_request.content dk_soup = BeautifulSoup(dk_homepage, ...
a6b5cbffce87f75c7561bc8939247f80bb10ae11
2,067
def parse_rows(m: utils.Matrix[str]) -> pd.DataFrame: """Parse rows to DataFrame, expecting specific columns and types.""" if len(m) < 2: logger.error('More than one line expected in {}'.format(str(m))) return pd.DataFrame() # parse data rows and add type casting cols = len(m[0]) df...
46749bccf7af71256e1f1d490e1a2f241ed0c4d9
2,068
import base64 import struct def tiny_id(page_id): """Return *tiny link* ID for the given page ID.""" return base64.b64encode(struct.pack('<L', int(page_id)).rstrip(b'\0'), altchars=b'_-').rstrip(b'=').decode('ascii')
1a37b814ff9845949c3999999b61f79b26dacfdc
2,069
def invert_color(color: str, *, black_or_white: bool = False) -> str: """Return a color with opposite red, green and blue values. Example: ``invert_color('white')`` is ``'#000000'`` (black). This function uses tkinter for converting the color to RGB. That's why a tkinter root window must have been cre...
cf6a84957489cba046aebc01457bfd6453bc90b6
2,070
def pcaImageCube(ref, mask = None, pcNum = None, cube=True, ref3D=True, outputEval = False): """Principal Component Analysis, Input: ref: Cube of references, 3D; if ref3D==False, 2D (Flattened and Normalized, with maksked region excluded.) mask: mask, 2D or 1D; pcNum: how...
96a05ef8fd6a618af91903b9c0fc9fc49cfd8130
2,071
def get_cross_kerr_table(epr, swp_variable, numeric): """ Function to re-organize the cross-Kerr results once the quantum analysis is finished Parameters: ------------------- epr : Object of QuantumAnalysis class swp_variable : the variable swept in data according to w...
8dfa860f73c5453ee970f204d4e03d6cef93d010
2,072
def getSpectra(dataframe, indices): """ Returns the files for training and testing Inputs ----------- dataframe: pd.DataFrame object from which we need to get spectra indices: row values for which we need the spectra Returns ----------- spec_vals: pd.DataFrame object ...
606757ffdde39c0847dd0402342441931d66a081
2,073
def config2(): """Configure for one of the restart tests.""" return Config.load(f""" id: cbc_binary_toolkit version: 0.0.1 database: _provider: tests.component.persistor_fixtures.mock_persistor.MockPersistorFactory engine: _provider: tests.component.engine_fixtures.mock_engine.MockLo...
ded0b43392e7e0308cca0f773d2ed687fd0818de
2,074
import sys import traceback def _on_process(*args, **kwargs): """Process the given function in the current subprocess""" try: func = kwargs['__func__'] del kwargs['__func__'] return func(*args, **kwargs) except KeyboardInterrupt: sys.exit() except Exception as e: ...
cc6b90daa3aba127f7c9ea596b0718bdefc5688b
2,075
def diff_cases(couch_cases, log_cases=False): """Diff cases and return diff data :param couch_cases: dict `{<case_id>: <case_json>, ...}` :returns: `DiffData` """ assert isinstance(couch_cases, dict), repr(couch_cases)[:100] assert "_diff_state" in globals() data = DiffData() dd_count =...
545b35b7e37174f93df9e566bc0e1cd777948563
2,076
def rk4(a, b, x0, y0, nu=0, F=0, xdot = x_dot, ydot = y_dot): """rk(a, b, x0, y0, nu=0, F=0, xdot = x_dot, ydot = y_dot) Args: a (float) : Lower bound, t = a*2*pi b (float) : Upper bound, t = b*2*pi x0 (float) : Initial position of ball y0 (float) : Initial velocity of bal...
acd97edb74bc27d03908962e52431bc3fdb7a571
2,077
from furious.async import Async def decode_callbacks(encoded_callbacks): """Decode the callbacks to an executable form.""" callbacks = {} for event, callback in encoded_callbacks.iteritems(): if isinstance(callback, dict): async_type = Async if '_type' in callback: ...
0ff066a21bb2f0c0e0979898d218add1e46da544
2,078
def create_conv_block( use_depthwise, kernel_size, padding, stride, layer_name, conv_hyperparams, is_training, freeze_batchnorm, depth): """Create Keras layers for depthwise & non-depthwise convolutions. Args: use_depthwise: Whether to use depthwise separable conv instead of regular conv. ker...
08c45a1ca62ff290d5e34e1cb544618dababaad1
2,079
def select_eps_for_division(dtype): """Selects default values for epsilon to make divisions safe based on dtype. This function returns an epsilon slightly greater than the smallest positive floating number that is representable for the given dtype. This is mainly used to prevent division by zero, which produces...
7204b2b694c6df98af4608562616655b3c198178
2,080
import os import json def train_freezed_model(x, y, x_tk, y_tk, freezed_comp='encoder', use_check_point=False): """ train the translation model and save checkpoint :param x: Preprocessed English data :param y: Preprocessed French data :param x_tk: English tokenizer :param y_tk: French tokenize...
84ff59edc6aafa7a3ca3b634ef8a21b6ae1a44f8
2,081
def bpm_to_mspt(bpm, res=480): """ Coverts an integer value of beats per minute to miliseconds per quarter note """ return 60000 / res / bpm
6b962b8253eac29f52c48ca89a6dce0417adb11b
2,082
import pickle import os def Test_frcnn(test_images_list, network_arch, config_filename, preprocessing_function = None, num_rois = None, final_classification_threshold = 0.8): """ Test the object detection network test_i...
678f874ae8c89c9d3899e839bb74cd35233b38e2
2,083
import numpy as np def pseudorandom(n, p, key): """ Pseudorandom array of integer indexes >>> pseudorandom(5, [0.5, 0.5], key=123) array([1, 0, 0, 1, 1], dtype=int8) >>> pseudorandom(10, [0.5, 0.2, 0.2, 0.1], key=5) array([0, 2, 0, 3, 0, 1, 2, 1, 0, 0], dtype=int8) """ p = list(p) cp...
5ec3dc8e66451a00d1f13f1df1df680879a16bc6
2,084
def next_hidden(s, A): """From a given state s, use the transition matrix A to generate the next hidden state. """ return choose_idx(A[s])
cc0b106ebeaa98ac2aeba947bd9ed0f653d233b5
2,085
import torch def create_network_rcnn(cls, opt): """Separate function for rcnn, which always loads weights first, no init.""" net = cls(opt) net.print_network() util.load_network_path(net, opt.fastercnn_loc, strict=True, rcnn_load=True) if len(opt.gpu_ids) > 0: assert(torch.cuda.is_availabl...
d653aa9435435ace4f10b134d28ee474353805bb
2,086
import tkinter def get_board_frame(window, mqtt_sender): """Builds the chessboard GUI.""" frame = ttk.Frame(window, padding=10, borderwidth=5, relief="ridge") frame.grid() frame_label = ttk.Label(frame, text="Board") get_state = ttk.Button(frame, text="Get state") get_state["command"] = lambda...
d6f5a13312989613f8b945c8e73cedb9ee7e3851
2,087
import logging def compute_rest_time(gps_data, radius): """Compute the duration during which the track stays in a given radius of each point. Args: gps_data (:py:class:`~gps_data_analyzer.gps_data.PoiPoints`): The data used for computation. radius (float): The radius in which ...
542e37c53948310e240924d729aea16a87c622b2
2,088
import html def body(): """Get map page body. Returns: html.Div: dash layout """ graph_map = get_graph_map() if graph_map is None: return html.Div( dbc.Alert("Cannot retrieve data! Try again later!", color="danger") ) # Put everything in a dcc container an...
6474602d65f71dadce26e043c62f35ec0c489a0f
2,089
from datetime import datetime def custom_strftime(formatting: str, date: datetime.datetime) -> str: """Custom strftime formatting function, using fancy number suffixes (1st, 2nd, 3rd...)""" return date.strftime(formatting).replace("{S}", str(date.day) + suffix(date.day))
3199f6e0590f4bb01c1792976c75c7a0d4208831
2,090
import os def make_workdir(run_dir, ccp4i2=False, MAX_WORKDIRS=100): """Make a work directory rooted at run_dir and return its path Parameters ---------- run_dir : str The path to a run directory where the job was started ccp4i2 : bool, optional Indicate if we are running under CCP...
3aacba4f0e3158a3c828b96f3f6b2954e947de21
2,091
def setup_twitter(config_file='config.py'): """Setup auth keys and session with Twitter client.""" config = {} execfile(config_file, config) twitter_obj = Twitter(auth=OAuth(config["access_key"], config["access_secret"], config["consumer...
bb811f3b6cabbe5dbf8f77d8e5217078f9a57c22
2,092
from datetime import datetime def create_datediff_test_nulls_df(): """Create DataFrame with nulls only for DateDifferenceTransformer tests.""" df = pd.DataFrame( { "a": [ datetime.datetime(1993, 9, 27, 11, 58, 58), np.NaN, ], "b": [ ...
542fd3fdf6fcd93a208e3f1f9cd2a76a0c34e46b
2,093
def business_days_list(start_date: date, end_date: date) -> list[date]: """ business days """ us_holidays = holidays.UnitedStates() days: list[date] = [] for the_date in get_list_of_days(start_date, end_date): if (the_date.weekday() < 5) and (the_date not in us_holidays): days.app...
daa36fe5fda5fc0857c1b29c75d7e784cafefe93
2,094
def test_3d(): """Test FE in 3D""" def setone(arr): arr[0, :, (arr.shape[0] - 1) // 2] = 1.0 return arr assert pipe( 5, lambda x: np.zeros((1, x, x, x), dtype=int), setone, solve_fe(elastic_modulus=(1.0, 10.0), poissons_ratio=(0.0, 0.0)), lambda x: n...
32f3d5fc18a31f01b2e366a3540ec77dd0e6080f
2,095
from typing import List def get_xray_edges(elements: List[str], wmin: float, wmax: float): """ Using xraydb, return the absorbtion edges Parameters ---------- elements: List[str] A list of the element symbols from which to query absorption edges. wmin: float The smallest wavel...
b78c0b999f4faf9e749b3b8388f0a581a5bff476
2,096
import urllib import json def get_mobility_link(): """Get Apple Mobility data link """ # get link with urllib.request.urlopen(index_url) as url: json_link = json.loads(url.read().decode()) base_path = json_link['basePath'] csv_path = json_link['regions']['en-us']['csvPath'] ...
a097e9c0b787a522283d31a8a13d4d13b824b77b
2,097
from datetime import datetime def active_shift(app, token, gqlClient): """returns the currently active shift if it exists""" with app.test_request_context(): request.headers = {'authorization': token} query = '''mutation CreateShift($Active: Boolean!, $StartTime: String) { createShift(...
345ba7f30421e28b879bc5b14409c437b9038d89
2,098
def get_batch_size(input): """ Infer the mini-batch size according to `input`. Args: input (tf.Tensor): The input placeholder. Returns: int or tf.Tensor: The batch size. """ if input.get_shape() is None: batch_size = tf.shape(input)[0] else: batch_size = int...
66201a3a8223ad442f54ac9551060093ee828f9b
2,099