content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def compare_data_identifiers(a, b): """Checks if all the identifiers match, besides those that are not in both lists""" a = {tuple(key): value for key, value in a} b = {tuple(key): value for key, value in b} matching_keys = a.keys() & b.keys() a = {k: v for k, v in a.items() if k in matching_keys} ...
f0f5f08e4cc685b62b2af19e0c724561988ed1b9
16,397
import re def expand_abbr(abbr, doc_type = 'html'): """ Разворачивает аббревиатуру @param abbr: Аббревиатура @type abbr: str @return: str """ tree = parse_into_tree(abbr, doc_type) if tree: result = tree.to_string(True) if result: result = re.sub('\|', insertion_point, result, 1) return re.sub('\|',...
23d0edebd9660303d4c361b468c5cb2f6e0e0f03
16,398
def SaveSettings (event=None, SettingsNotebook=None, filename = "settings.hdf5", title="Open HDF5 file to save settings", OpenDialog=True ) : """ Method for saving setting """ if OpenDialog : # Ask user to select the file openFileDialog = wx.FileDialog(SettingsNotebook, title, "", filename, "HDF5 files (*.hdf5...
7e2a221c78ef78f542877a754034084ed8dd8492
16,399
import torch import colorsys def getAfinityCenter(width, height, point, center, radius=7, img_affinity=None): """ Function to create the affinity maps, e.g., vector maps pointing toward the object center. Args: width: image wight height: image height point: (x,y) ce...
5c25274809820f6318b9756680d2967ba8f08a5d
16,400
def unwrap_phase_iterative_fft(mat, iteration=4, win_for=None, win_back=None, weight_map=None): """ Unwrap a phase image using an iterative FFT-based method as described in Ref. [1]. Parameters ---------- mat : array_like 2D array. Wrapped phase-image in t...
e79bb72441379531f70d32d07c4e6e9299a39062
16,401
def wallunderground(idf, bsdobject, deletebsd=True, setto000=False): """return a wall:underground if bsdobject (buildingsurface:detailed) is an underground wall""" # ('WALL:UNDERGROUND', Wall, s.startswith('Ground')) # test if it is an underground wall if bsdobject.Surface_Type.upper() == 'WALL': #...
739ca431088f049323b64e80649e6b23930d1318
16,402
def canonical_order(match): """ It does not make sense to define a separate bond between atoms 1 and 2, and between atoms 2 and 1. This function will swap the atoms in the bond if the first atom > second atom. """ # match[0][0:2] contains the ID numbers for the 2 atoms in the match atom0 =...
ea268fedaa365e0fad3ea49944cc1d1bb5fa7a51
16,403
def grant_db_access_to_role(role, db): # pylint: disable=invalid-name """Grant the role 'database_name', returns grant permission.""" return grant_obj_permission_to_role(role, db, 'database_access')
5adb5f8f06473b20d6e7f386acb889631e042dde
16,404
import json def execute_compute_job(): """Call the execution of a workflow. --- tags: - services consumes: - application/json parameters: - name: consumerAddress in: query description: The consumer address. required: true type: string - name...
3601cc1f9001d23d07ded604f9fa241fe11cebd3
16,405
from typing import List from pathlib import Path def files_filter_ext(files: List[Path], ext: str) -> List[Path]: """Filter files from a list matching a extension. Args: files: List of files. ext: Extension to filter. Returns: List of files that have the extension. """ re...
0ed134583f9fa4868111d1475b8be4d67ba4feb7
16,406
import six def interp_to_grid(tran,v,expand_x=True,expand_y=True): """ Return dense matrix for X,Y and V (from v, or tran[v] if v is str) expand_x: defaults to 1 more value in the X dimension than in V, suitable for passing to pcolormesh. expand_y: defaults to 1 more value in the Y dimension than ...
324e42329588860d6fd45cfa06988f49e56ca504
16,408
def simulation(G, tau, gamma, rho, max_time, number_infected_before_release, release_number, background_inmate_turnover, stop_inflow_at_intervention, p, death_rate, percent_infected, percent_recovered, social_distance, social_distance_tau, initial_infected_list): """Runs a simulation o...
1f9ab389ce2f301266ce6d796c303cfbb5ab4b44
16,409
def relative(link : str): """Convert relative link to absolute""" return f"#{document.URL.split('#')[1]}/{link}"
5f00da06f5277b4a85512b49e9348d8d22949058
16,410
from typing import Tuple from typing import List def _get_axes_names(ndim: int) -> Tuple[List[str], List[str]]: """Get needed axes names given the number of dimensions. Parameters ---------- ndim : int Number of dimensions. Returns ------- axes : List[str] Axes names. ...
4f9dc40131443520a2f43c287b7d0ab1428a878f
16,411
def multi_replace(text, replace_dict): """Perform multiple replacements in one go using the replace dictionary in format: { 'search' : 'replace' } :param text: Text to replace :type text: `str` :param replace_dict: The replacement strings in a dict :type replace_dict: `dict` :return: `str` ...
dc902c988fa57cd9a3d7f4def6089b78d36664c8
16,412
def function_expr(fn: str, args_expr: str = "") -> str: """ DEPRECATED. Please do not add anything else here. In order to manipulate the query, create a QueryProcessor and register it into your dataset. Generate an expression for a given function name and an already-evaluated args expression. This ...
81fc9dc55c7602722303c2623d20aa88ce12f532
16,413
from typing import Sequence def distribute(tensor: np.ndarray, grid_shape: Sequence[int], pmap: bool = True) -> pxla.ShardedDeviceArray: """ Convert a numpy array into a ShardedDeviceArray (distributed according to `grid_shape`). It is assumed that the dimensions of `tensor` are ...
5e0ca59a23f1cde027769334a938e5855b17bf62
16,415
def predict(w, X): """ Returns a vector of predictions. """ return expit(X.dot(w))
c3bcb56cdd700ddf96124792b3f356644680e356
16,417
def maskrgb_to_class(mask, class_map): """ decode rgb mask to classes using class map""" h, w, channels = mask.shape[0], mask.shape[1], mask.shape[2] mask_out = -1 * np.ones((h, w), dtype=int) for k in class_map: matches = np.zeros((h, w, channels), dtype=bool) for c in range(channels)...
0af4d42fc2dfba4d56bf990df222895b94b3002d
16,419
def translate_error_code(error_code): """ Return the related Cloud error code for a given device error code """ return (CLOUD_ERROR_CODES.get(error_code) if error_code in CLOUD_ERROR_CODES else error_code)
f6cc38b296b330811e932d3e7227d201ed09fe80
16,420
def generate_oi_quads(): """Return a list of quads representing a single OI, OLDInstance. """ old_instance, err = domain.construct_old_instance( slug='oka', name='Okanagan OLD', url='http://127.0.0.1:5679/oka', leader='', state=domain.NOT_SYNCED_STATE, is_auto...
6b3466e81014d14f88f17e855d726a608afda946
16,421
import torch def graph_intersection(pred_graph, truth_graph): """ Use sparse representation to compare the predicted graph and the truth graph so as to label the edges in the predicted graph to be 1 as true and 0 as false. """ array_size = max(pred_graph.max().item(), truth_graph.max().item())...
c63ae9cb52c9a55d54bfb5237c43b1998c51c482
16,422
import requests def get_qid_for_title(title): """ Gets the best Wikidata candidate from the title of the paper. """ api_call = f"https://www.wikidata.org/w/api.php?action=wbsearchentities&search={title}&language=en&format=json" api_result = requests.get(api_call).json() if api_result["success...
663db71c7a1bbf1617941ba81c5fa3b7d359e00b
16,423
def experiment(L, T, dL, dT, dLsystm = 0): """ Performs a g-measurement experiment Args: L: A vector of length measurements of the pendulum T: A vector of period measurements of the pendulum dL: The error in length measurement dT: The error in period measurement ...
cdf7384518fb92295675eb1b15bec883b50a450f
16,424
def find_jobs(schedd=None, attr_list=None, **constraints): """Query the condor queue for jobs matching the constraints Parameters ---------- schedd : `htcondor.Schedd`, optional open scheduler connection attr_list : `list` of `str` list of attributes to return for each job, default...
9a6a32002a945d186ea40c534dbc28805458cec2
16,425
def create_vocab(sequences, min_count, counts): """Generate character-to-idx mapping from list of sequences.""" vocab = {const.SOS: const.SOS_IDX, const.EOS: const.EOS_IDX, const.SEP: const.SEP_IDX} for seq in sequences: for token in seq: for char in token: i...
40ca7b3ed88d4134c2949223ec93ef871a18a8fb
16,426
def get_ind_sphere(mesh, ind_active, origin, radius): """Retreives the indices of a sphere object coordintes in a mesh.""" return ( (mesh.gridCC[ind_active, 0] <= origin[0] + radius) & (mesh.gridCC[ind_active, 0] >= origin[0] - radius) & (mesh.gridCC[ind_active, 1] <= origin...
9e246c3c0d3d7750a668476f0d0d90b28c46fc27
16,427
def find_frame_times(eegFile, signal_idx=-1, min_interval=40, every_n=1): """Find imaging frame times in LFP data using the pockels blanking signal. Due to inconsistencies in the fame signal, we look for local maxima. This avoids an arbitrary threshold that misses small spikes or includes two nearby tim...
7ed6a6a5b3d873132575ed5af1d9132d22e3898b
16,428
def _interpolate_signals(signals, sampling_times, verbose=False): """ Interpolate signals at given sampling times. """ # Reshape all signals to one-dimensional array object (e.g. AnalogSignal) for i, signal in enumerate(signals): if signal.ndim == 2: signals[i] = signal.flatten()...
b72d8b5bbd55fb70107e36c551cb558953baed50
16,429
def mean_standard_error_residuals(A, b): """ Mean squared error of the residuals. The sum of squared residuals divided by the residual degrees of freedom. """ n, k = A.shape ssr = sum_of_squared_residuals(A, b) return ssr / (n - k)
6860ea11b2f2af29c9b519ef692ee990d2aef149
16,430
def cel2gal(ra, dec): """ Convert celestial coordinates (J2000) to Galactic coordinates. (Much faster than astropy for small arrays.) Parameters ---------- ra : `numpy.array` dec : `numpy.array` Celestical Coordinates (in degrees) Returns ------- glon : `numpy.array` ...
b1185ce199c0f929c3395c452e619b93e2ee66a9
16,431
def index(request): """Renders main website with welcome message""" return render(request, 'mapper/welcome.html', {})
37194ef3ccc415c6db39f664bc819d7df1b9665a
16,432
def tidy_output(differences): """Format the output given by other functions properly.""" out = [] if differences: out.append("--ACLS--") out.append("User Path Port Protocol") for item in differences: #if item[2] != None: #En algunos casos salían procesos con puerto None out.append("%s %s %...
2a7007ae16e91b111f556ea95eedc466a8606494
16,433
from typing import Dict from typing import Collection def get_issues_overview_for(db_user: User, app_url: str) -> Dict[str, Collection]: """ Returns dictionary with keywords 'user' and 'others', which got lists with dicts with infos IMPORTANT: URL's are generated for the frontend! :param db_user: Use...
02ab5314a961a7fa398df2d43792fed1321939c6
16,434
def load_file(file): """Returns an AdblockRules object using the rules specified in file.""" with open(file) as f: rules = f.readlines() return AdblockRules(rules)
a9783ec4e8a195af688456af1949e33fd17d3cb7
16,435
def isSV0_QSO(gflux=None, rflux=None, zflux=None, w1flux=None, w2flux=None, gsnr=None, rsnr=None, zsnr=None, w1snr=None, w2snr=None, dchisq=None, maskbits=None, objtype=None, primary=None): """Target Definition of an SV0-like QSO. Returns a boolean array. Parameters ---------- ...
f8be10f2d5d52ed0afd06a23cf7a9f1a98af1f25
16,436
def show_df_nans(df, columns=None, plot_width=10, plot_height=8): """ Input: df (pandas dataframe), collist (list) Output: seaborn heatmap plot Description: Create a data frame for features which may be nan. Set NaN values be 1 and numeric values to 0. Plots a heat map where dark squar...
5f93f78eee905c81c7178a2a6ed7167597d4964c
16,437
def evaluate_accuracy(file1, file2): """ evaluate accuracy """ count = 0 same_count = 0 f1 = open(file1, 'r') f2 = open(file2, 'r') while 1: line1 = f1.readline().strip('\n') line2 = f2.readline().strip('\n') if (not line1) or (not line2): break ...
52fdb8054de07fe53f77dd74317f18ed1dfbbb36
16,439
def add_hp_label(merged_annotations_column, label_type): """Adds prefix to annotation labels that identify the annotation as belonging to the provided label_type (e.g. 'h@' for host proteins). Parameters ---------- merged_annotations_column : array-like (pandas Series)) An array containing ...
648f548931a1fae5d19291d81f2355a0a00877c3
16,441
def _serialize_value( target_expr: str, value_expr: str, a_type: mapry.Type, auto_id: mapry.py.generate.AutoID, py: mapry.Py) -> str: """ Generate the code to serialize a value. The code serializes the ``value_expr`` into the ``target_expr``. :param target_expr: Python expression of th...
6ec6051715ca34771bf32582bb86280d58af27d3
16,443
def return_union_close(): """union of statements, close statement""" return " return __result"
c1a1b6b6b1164a641a7f9e598eec346af13f2aa7
16,444
from typing import Union from typing import List from typing import Tuple def parse_unchanged(value: Union[str, List[str]]) -> Tuple[bool, Union[str, List[str]]]: """Determine if a value is 'unchanged'. Args: value: value supplied by user """ unchanges = [ SETTING_UNCHANGED, s...
b4f1e155064c053fa1df65d242e920ae4ecf2fe5
16,445
def get_val(tup): """Get the value from an index-value pair""" return tup[1]
5966bbbb28006c46eaf11afaef152573aaaa8d2a
16,446
def lnprior_d(d,L=default_L): """ Expotentially declining prior. d, L in kpc (default L=0.5) """ if d < 0: return -np.inf return -np.log(2) - 3*np.log(L) + 2*np.log(d) - d/L
fd7cf591c5095fe8129662794b5c05235eda8941
16,449
def textile(text, **args): """This is Textile. Generates XHTML from a simple markup developed by Dean Allen. This function should be called like this: textile(text, head_offset=0, validate=0, sanitize=0, encoding='latin-1', output='ASCII') """ return Textiler(text).pro...
051f2aa254c2c24e80640b0779712d2154a1b67d
16,450
def binary_info_gain(df, feature, y): """ :param df: input dataframe :param feature: column to investigate :param y: column to predict :return: information gain from binary feature column """ return float(sum(np.logical_and(df[feature], df[y])))/len(df[feature])
8aa4bbb6997b913001074e15fcdefb5f6047cab3
16,451
def get_all_instances(region): """ Returns a list of all the type of instances, and their instances, managed by the scheduler """ ec2 = boto3.resource('ec2', region_name=region) rds = boto3.client('rds', region_name=region) return { 'EC2': [EC2Schedulable(ec2, i) for i in ec2.instan...
daf6c4cc71f19c7b94f625a283eeb59f4fcae10f
16,452
import warnings import asyncio def futures_navigating(urls: list, amap: bool = True) -> dict: """ 异步 基于 drive url list 通过请求高德接口 获得 路径规划结果 :param urls: :param amap: 开关 :return: """ data_collections = [None] * len(urls) pack_data_result = {} all_tasks = [] # 准备 with warnings....
4b65488f2c3ba7ac7ecc46a2da949c15bffbbf9b
16,453
def getdim(s): """If s is a representation of a vector, return the dimension.""" if len(s) > 4 and s[0] == "[" and s[-1] == "]": return len(splitargs(s[1:-1], ["(", "["], [")", "]"])) else: return 0
7ad62245ad2ebf7a262f6442ff209b819b1fa36e
16,454
def numToString(num: int) -> str: """Write a number in base 36 and return it as a string :param num: number to encode :return: number encoded as a base-36 string """ base36 = '' while num: num, i = divmod(num, 36) base36 = BASE36_ALPHABET[i] + base36 return base36 or BASE36...
419759cdbe7b4e0dcf38c3f79f0de6dec4f84131
16,457
def parse_enumeration(enumeration_bytes): """Parse enumeration_bytes into a list of test_ids.""" # If subunit v2 is available, use it. if bytestream_to_streamresult is not None: return _v2(enumeration_bytes) else: return _v1(enumeration_bytes)
ce7104f30eda416a59cb1397736886422af866fd
16,459
import re def register_user(username, passwd, email): # type: (str, str, str) -> Optional[str] """Returns an error message or None on success.""" if passwd == "": return "The password can't be empty!" if email: # validate the email only if it is provided result = validate_email_address(e...
d7960dc9c66ee584787b9a2b25f367fcbc7455e8
16,460
def _train_n_hmm(data: _Array, m_states: int, n_trails: int): """Trains ``n_trails`` HMMs each initialized with a random tpm. Args: data: Possibly unporcessed input data set. m_states: Number of states. n_trails: Number of trails. Returns: Best model regarding to log...
db5864ca45ac6fb939a0d1fd63fcb0b61e0ce6b9
16,461
def get_metric_function(name): """ Get a metric from the supported_sklearn_metric_functions dictionary. Parameters ---------- name : str The name of the metric to get. Returns ------- metric : function The metric function. """ if name in supported_sklearn_metric...
ba490650f55fd5d9a480fc9b9b94c5e71fefe23c
16,462
def ping(enode, count, destination, interval=None, quiet=False, shell=None): """ Perform a ping and parse the result. :param enode: Engine node to communicate with. :type enode: topology.platforms.base.BaseNode :param int count: Number of packets to send. :param str destination: The destination...
e9fce1819ea21ad801468653e534350e863e123b
16,463
def calculate_EHF_severity( T, T_p95_file=None, EHF_p85_file=None, T_p95_period=None, T_p95_dim=None, EHF_p85_period=None, EHF_p85_dim=None, rolling_dim="time", T_name="t_ref", ): """ Calculate the severity of the Excess Heat Factor index, defined as: EHF_severity = ...
e82d54f0bd67c5cd4c938dbdd335aed70fe3c521
16,464
from typing import Dict from typing import List from typing import Tuple def arrange_train_data(keypoints: Dict, beg_end_times: List[Tuple], fps: float, MAX_PERSONS: int) -> Dict: """ Arrange data into frames. Add gestures present or not based on time ranges. Generate each frame and also, add dummy when neces...
ef433809c5e59d2b870a84c9cfce9e31faa4659a
16,466
def length(list): """Return the number of items in the list.""" if list == (): return 0 else: _, tail = list return 1 + length(tail)
35864cd8cdd065463592d3737077a4d06b38aad1
16,467
def buzz(x): """ Takes an input `x` and checks to see if x is a number, and if so, also a multiple of 5. If it is both, return 'Buzz'. Otherwise, return the input. """ return 'Buzz' if isinstance(x, Number) and x % 5 == 0 else x
b24a37816d218a6cc1d960bfd767cb1a2052067d
16,468
from typing import Iterable from typing import Any from typing import Tuple def _tuple_of_big_endian_int(bit_groups: Iterable[Any]) -> Tuple[int, ...]: """Returns the big-endian integers specified by groups of bits. Args: bit_groups: Groups of descending bits, each specifying a big endian ...
78d3b739a8d8a3f724dca2b226e976cde93426dd
16,469
def make_simple_server(service, handler, host="localhost", port=9090): """Return a server of type TSimple Server. Based on thriftpy's make_server(), but return TSimpleServer instead of TThreadedServer. Since TSimpleServer's constructor doesn't accept kwargs...
42fc9f0bdcfbe4a509d5a682821ea3e71386f699
16,470
def morph(clm1, clm2, t, lmax): """Interpolate linearly the two sets of sph harm. coeeficients.""" clm = (1 - t) * clm1 + t * clm2 grid_reco = clm.expand(lmax=lmax) # cut "high frequency" components agrid_reco = grid_reco.to_array() pts = [] for i, longs in enumerate(agrid_reco): ilat =...
a6e6ca0070cc38b54f2bfd41b0fe69e2a5bb21f8
16,471
import re from typing import OrderedDict def read_avg_residuemap(infile): """ Read sequence definition from PSN avg file, returning sequence Map :param infile: File handle pointing to WORDOM avgpsn output file :return: Returns an internal.map.Map object mapping the .pdb residues to WORDOM id...
92c4cbe53edcd3d894a038d7cb9308c653e37146
16,472
def schedule_remove(retval=None): """ schedule(retval=stackless.current) -- switch to the next runnable tasklet. The return value for this call is retval, with the current tasklet as default. schedule_remove(retval=stackless.current) -- ditto, and remove self. """ _scheduler_remove(getcurren...
8ba10819d4de5cc676583e7b05036be49e6958cf
16,474
def check_region(read, pair, region): """ determine whether or not reads map to specific region of scaffold """ if region is False: return True for mapping in read, pair: if mapping is False: continue start, length = int(mapping[3]), len(mapping[9]) r = [s...
c71378d9ee674a117635634e3153f3cb7650fab3
16,475
def millisecond_to_clocktime(value): """Convert a millisecond time to internal GStreamer time.""" return value * Gst.MSECOND
8359b65a015febedba8bb6b68d310d70b1b8e1a6
16,477
def SE2_exp(v): """ SE2 matrix exponential """ theta, x, y = v if np.abs(theta) < 1e-6: A = 1 - theta**2/6 + theta**4/120 B = theta/2 - theta**3/24 + theta**5/720 else: A = np.sin(theta)/theta B = (1 - np.cos(theta))/theta V = np.array([[A, -B], [B, A]]) R...
f94454bf4b134fac7b45d89d4c3798b1d6c201fa
16,478
def skip_on_hw(func): """Test decorator for skipping tests which should not be run on HW.""" def decorator(f): def decorated(self, *args, **kwargs): if has_ci_ipus(): self.skipTest("Skipping test on HW") return f(self, *args, **kwargs) return decorated return decorator(func)
6cbde5ce9b70c9d9f71330470f5f2ae913f56021
16,479
def rxns4tag(tag, rdict=None, ver='1.7', wd=None): """ Get a list of all reactions with a given p/l tag Notes ----- - This function is useful, but update to GEOS-Chem flexchem ( in >v11) will make it redundent and therefore this is not being maintained. """ # --- get reaction dictionar...
32243bcdb66c9320679d580da2b6f9ee086179d2
16,480
def DateTime_GetCurrentYear(*args, **kwargs): """DateTime_GetCurrentYear(int cal=Gregorian) -> int""" return _misc_.DateTime_GetCurrentYear(*args, **kwargs)
5f25e4387e72497673ea49d6f67f06e9894e29af
16,481
def exp_lr_scheduler(optimizer, epoch, init_lr=0.01, lr_decay_epoch=10): """Decay learning rate by a f# model_out_path ="./model/W_epoch_{}.pth".format(epoch) # torch.save(model_W, model_out_path) actor of 0.1 every lr_decay_epoch epochs.""" lr = init_lr * (0.8**(epoch // lr_decay_epoch)) ...
2095eda8493e0e53bca5e6f1b9149b544c34da61
16,482
def wait(duration): """ Waits the duration, in seconds, you specify. Args: duration (:any:`DoubleValue`): time, in seconds, this function waits. You may specify fractions of seconds. Returns: float: actual seconds waited. This wait is non-blocking, so other tasks will run while th...
0a40028bbe88d290cc309dc94ef7be48522ded02
16,483
from datetime import datetime def yesterday_handler(update: Update, context: CallbackContext): """ Diary content upload handler. Uploads incoming messages to db as a note for yesterday. """ # get user timezone user_timezone = Dao.get_user_timezone(update.effective_user) # calculate time at use...
7b37d1157fc40ec01703aac92a5b176d14ab2f27
16,484
def get_lens_pos(sequence): """ Calculate positions of lenses. Returns ------- List of tuples with index and position of OPE in sequence. """ d = 0.0 d_ = [] for idx, ope in enumerate(sequence): if ope.is_lens(): d_.append((idx, d)) else: d +=...
f1f1ebb4212406e78e48613584f67f5e2b6f2265
16,485
def disorientation(orientation_matrix, orientation_matrix1, crystal_structure=None): """Compute the disorientation another crystal orientation. Considering all the possible crystal symmetries, the disorientation is defined as the combination of the minimum misorientation angle and the misorientation ax...
eefca78d7736de073646c97190f736bedb302136
16,486
def convert_examples_to_features(examples, label_list, max_seq_length, tokenizer): """Loads a data file into a list of `InputBatch`s.""" label_map = {label : i for i, label in enumerate(label_list,1)} features = [] for (ex_index, example) in enumerate(examples): # example : InputExample obj t...
5d844b9d88fa7bbd5532547b772fef9c1811e039
16,488
def to_json_compatible_object(obj): """ This function returns a representation of a UAVCAN structure (message, request, or response), or a DSDL entity (array or primitive), or a UAVCAN transfer, as a structure easily able to be transformed into json or json-like serialization Args: obj: ...
131fa3a43abf55fd0f51b1e3160ba2f1486d2e25
16,489
def rot_box_kalman_filter(initial_state, Q_std, R_std): """ Tracks a 2D rectangular object (e.g. a bounding box) whose state includes position, centroid velocity, dimensions, and rotation angle. Parameters ---------- initial_state : sequence of floats [x, vx, y, vy, w, h, phi] Q_std...
ac0bca07b6d7b08c3b27439855fac93bddffcb91
16,490
def validate_schema(path, schema_type): """Validate a single file against its schema""" if schema_type not in _VALID_SCHEMA_TYPES.keys(): raise ValueError(f"No validation schema found for '{schema_type}'") return globals()["validate_" + schema_type](path)
8883226eff948de2b05d442157818ab0b3904e47
16,491
def import_vote_internal(vote, principal, file, mimetype): """ Tries to import the given csv, xls or xlsx file. This is the format used by onegov.ballot.Vote.export(). This function is typically called automatically every few minutes during an election day - we use bulk inserts to speed up the import....
03eacf90418fd68bcf24c0a731f2d1216beb786b
16,492
def get_mail_count(imap, mailbox_list): """ Gets the total number of emails on specified account. Args: imap <imaplib.IMAP4_SSL>: the account to check mailbox_list [<str>]: a list of mailboxes Must be surrounded by double quotes Returns: <int>: total emails """ ...
8c8fd2d6849d58860f3bd6c20335e7a399bee99d
16,493
def get_bdb_path_by_shoulder_model(shoulder_model, root_path=None): """Get the path to a BerkeleyDB minter file in a minter directory hierarchy. The path may or may not exist. The caller may be obtaining the path in which to create a new minter, so the path is not checked. Args: shoulder_model...
c694306d18ed940cf229a46dae6fb72d2207418e
16,494
def getDefuzzificationMethod(name): """Get an instance of a defuzzification method with given name. Normally looks into the fuzzy.defuzzify package for a suitable class. """ m = __import__("fuzzy.defuzzify."+name, fromlist=[name]) c = m.__dict__[name] return c()
c3306ba9fc4ce21eae9adb1bde1b04505dd6b24f
16,495
def celestial(func): """ Transform a point x from cartesian coordinates to celestial coordinates and returns the function evaluated at the probit point y """ def f_transf(ref, x, *args, **kwargs): y = cartesian_to_celestial(x) return func(ref, y, *args) return f_transf
e6980abfbc0833639b9d1eb716633d1c6d6dcda2
16,496
def _rescale_to_width( img: Image, target_width: int): """Helper function to rescale image to `target_width`. Parameters ---------- img : PIL.Image Input image object to be rescaled. target_width : int Target width (in pixels) for rescaling. Returns ------- ...
38efe7bbbd1681abfd2d48bcf4765b817a28fa27
16,497
def compute_exact_R_P(final_patterns, centones_tab): """ Function tha computes Recall and Precision with exact matches """ true = 0 for tab in final_patterns: for centon in centones_tab[tab]: check = False for p in final_patterns[tab]: if centon == p: ...
d82e6fccacdc09bb078d6e954150c143994df1ca
16,498
def build_embedding(embedding_matrix, max_len, name): """ Build embedding by lda :param max_len: :param name: :return: """ # build embedding with initial weights topic_emmd = Embedding(embedding_matrix.shape[0], embedding_matrix.shape[1], wei...
87a89462bfb2eee285099353f78e151394c7c74a
16,499
import re def check_playlist_url(playlist_url): """Check if a playlist URL is well-formated. Parameters ---------- playlist_url : str URL to a YouTube playlist. Returns ------- str If the URL is well-formated, return the playlist ID. Else return `None`. """ match...
b14808e3dc25fcb7f91e9b66ec5f31ae869c6ae5
16,500
import multiprocessing import asyncio def test_PipeJsonRpcSendAsync_2(method, params, result, notification): """ Test of basic functionality. Here we don't test for timeout case (it raises an exception). """ value_nonlocal = None def method_handler1(): nonlocal value_nonlocal valu...
3311c1be5013eae986b5c8e358ef08eafff6420c
16,501
def f(t, T): """ returns -1, 0, or 1 based on relationship between t and T throws IndexError """ if(t > 0 and t < float(T/2)): return 1 elif(t == float(T/2)): return 0 elif(t > float(T/2) and t < T): return -1 raise IndexError("Out of function domain")
f2365094d41d2a151322ad640dcf4b290dd1de79
16,502
import http import json def auth0_token(): """ Token for Auth0 API """ auth = settings["auth0"] conn = http.client.HTTPSConnection(auth['domain']) payload = '{' + f"\"client_id\":\"{auth['client']}\"," \ f"\"client_secret\":\"{auth['client-secret']}\"," \ ...
ba27798d4af79999f1c37d5b356a54cd427a0681
16,503
def get_ami(region, instance_type): """Returns the appropriate AMI to use for a given region + instance type HVM is always used except for instance types which cannot use it. Based on matrix here: http://aws.amazon.com/amazon-linux-ami/instance-type-matrix/ .. note:: :func:`populate_ami_...
7ea60dbda0dabb05d9f7509ddb4c567560d681eb
16,504
def convert_config(cfg): """ Convert some configuration values to different values Args: cfg (dict): dict of sub-dicts, each sub-dict containing configuration keys and values pertinent to a process or algorithm Returns: dict: configuration dict with some items converted to diff...
f84ae8f5b90f364eb378b48071c7ea4a99370076
16,505
def _signals_exist(names): """ Return true if all of the given signals exist in this version of flask. """ return all(getattr(signals, n, False) for n in names)
3f62e5a6309d792843947c3aa6f5ad687b6debf5
16,506
def login(): """Route for logging the user in.""" try: if request.method == 'POST': return do_the_login() if session.get('logged_in'): return redirect(url_for('home')) return render_template('login.html') except Exception as e: abort(500, {'message': s...
1f610bcfd450de5de576eef797ed9d26f726ec72
16,507
from typing import List def __screen_info_to_dict(): """ 筛查 :return: """ screen_dict: {str: List[GitLogObject]} = {} for info in git.get_all_commit_info(): if not authors.__contains__(info.name): continue if not info.check_today_time(): continue ...
6fb5519ab746b8918f18ec0c0a1769b5dca3558c
16,509
from typing import Type from typing import Optional def bind_prop_arr( prop_name: str, elem_type: Type[Variable], doc: Optional[str] = None, doc_add_type=True, ) -> property: """Convenience wrapper around bind_prop for array properties :meta private: """ if doc is None: doc = ...
f8e610011f096013c3976ee22f43eb58472c0513
16,510
from typing import Dict from typing import Any import json def generate_profile_yaml_file(destination_type: DestinationType, test_root_dir: str) -> Dict[str, Any]: """ Each destination requires different settings to connect to. This step generates the adequate profiles.yml as described here: https://docs....
f66b8df469b00d8aa11e6aba7d6efb5c2af4e21f
16,511
def get_foreign_trips(db_connection): """ Gets the time series data for all Foreign visitors from the database Args: db_connection (Psycopg.connection): The database connection Returns: Pandas.DataFrame: The time series data for each unique Foreign visitor. It...
bd5f0d308681286c615d60b0bf2fcb88bfd2a806
16,512
from typing import List def get_diagonal_sums(square: Square) -> List[int]: """ Returns a list of the sum of each diagonal. """ topleft = 0 bottomleft = 0 # Seems like this could be more compact i = 0 for row in square.rows: topleft += row[i] i += 1 i = 0 for col in square.columns: bottoml...
37a5e167b3170feece19b963c21eae1359df14ec
16,513