content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def numpy_ndarray(pa_arr): """Return numpy.ndarray view of a pyarrow.Array """ if pa_arr.null_count == 0: # TODO: would memoryview.cast approach be more efficient? see xnd_xnd. return pa_arr.to_numpy() pa_nul, pa_buf = pa_arr.buffers() raise NotImplementedError('numpy.ndarray view of...
b018bc26983ff638441e1bfca3cb5633022de399
19,200
import select import json async def _async_get_states_and_events_with_filter( hass: HomeAssistant, sqlalchemy_filter: Filters, entity_ids: set[str] ) -> tuple[list[Row], list[Row]]: """Get states from the database based on a filter.""" for entity_id in entity_ids: hass.states.async_set(entity_id, ...
fa0131a87ac9ac517ffd63bb563600e12bed68de
19,201
def decrypt_password(private_key: PrivateKey, encrypted: str) -> str: """Return decrypt the given encrypted password using private_key and the RSA cryptosystem. Your implementation should be very similar to the one from class, except now the public key is a data class rather than a tuple. """ n = p...
607b5e33cff940aa999f56b2e39f56673d94ff7f
19,202
from typing import OrderedDict def load_jed(fn): """ JEDEC file generated by 1410/84 from PALCE20V8H-15 06/28/20 22:42:11* DM AMD* DD PALCE20V8H-15* QF2706* G0* F0* L00000 0000000000000000000000000100000000000000* """ ret = {} d = OrderedDict() with open(fn) as f: ...
6570bcdaabb495c13e9419a532c85b15efdf957a
19,203
def plaintext(text, keeplinebreaks=True): """Extract the text elements from (X)HTML content >>> plaintext('<b>1 &lt; 2</b>') u'1 < 2' >>> plaintext(tag('1 ', tag.b('<'), ' 2')) u'1 < 2' >>> plaintext('''<b>1 ... &lt; ... 2</b>''', keeplinebreaks=False) u'1 < 2' :param text: `...
c4e5e9a9b41fc7e0dc6b50995d7ec9a9bae1296f
19,204
import os def check_out_dir(out_dir, base_dir): """Creates the output folder.""" if out_dir is None: out_dir = pjoin(base_dir, default_out_dir_name) try: os.makedirs(out_dir, exist_ok=True) except: raise IOError('Unable to create the output directory as requested.') retu...
5de68a0e8931a6ae3183eb3a3f5d4173ff697296
19,205
def fetch_rows(product): """ Returns the product and a list of timestamp and price for the given product in the current DATE, ordered by timestamp. """ # We query the data lake by passing a SQL query to maystreet_data.query # Note that when we filter by month/day, they need to be 0-padded strin...
8b6f3df658ca38054bd49255b0842f40f6d4bffa
19,206
def create_learner(sm_writer, model_helper): """Create the learner as specified by FLAGS.learner. Args: * sm_writer: TensorFlow's summary writer * model_helper: model helper with definitions of model & dataset Returns: * learner: the specified learner """ learner = None if FLAGS.l...
76231a6413560ccc1e1d90fb974f90a83b3bb4f4
19,207
def load_decoder(autoencoder): """ Gets the decoders associated with the inputted model """ dim = len(autoencoder.get_config()['input_layers']) mag_phase_flag = False decoders = [] if dim == 2: mag_phase_flag = True decoders.append(autoencoder.get_layer('mag_decoder')) ...
8e39470e48f5a6c147d93567c0bdb33a588c790d
19,208
def translate_boarding_cards(boarding_cards): """Translate list of BoardingCards to readable travel instructions. This function sorts list of random BoardingCard objects connecting starts with ends of every stage of the trip then returns readable instructions that include seat numbers, location names a...
0986ab2669fa4376aebd28804586a1566544610e
19,209
def detect_side(start: dict, point: dict, degrees): """detect to which side robot should rotate""" if start['lat'] < point['lat'] and start['lng'] < point['lng']: return f'{degrees} degrees right' elif start['lat'] < point['lat'] and start['lng'] > point['lng']: return f'{degrees} degrees...
124833bbdcdf36c280cdde8e829f15ae5301e323
19,210
import sys def ScanSlnFile(filename): """Scan a Visual Studio .sln and extract the project dependencies.""" try: sln = open(filename, "r") except IOError: sys.stderr.write("Unable to open " + filename + " for reading.\n") return 1 projects = {} project = None while 1: line = sln.readline()...
b3f1d4b54027d6eb1aa6b0a3358e9afdb3e8248b
19,211
import pathlib import sh def iterate_log_lines(file_path:pathlib.Path, n:int = 0, **kwargs): """Reads the file in line by line dev note: One of the best featuers of this functions is we can use efficient unix style operations. Because we know we are inside of a unix container there should...
54684fcc7a41b623321534202ee250e7c46760d2
19,212
import torch def moving_sum(x, start_idx: int, end_idx: int): """ From MONOTONIC CHUNKWISE ATTENTION https://arxiv.org/pdf/1712.05382.pdf Equation (18) x = [x_1, x_2, ..., x_N] MovingSum(x, start_idx, end_idx)_n = Sigma_{m=n−(start_idx−1)}^{n+end_idx-1} x_m for n in {1, 2, 3, ..., N} ...
fa3cb672e23fccad75965da2ca10955134167c7e
19,213
import json import time def _wait_for_event(event_name, redis_address, extra_buffer=0): """Block until an event has been broadcast. This is used to synchronize drivers for the multi-node tests. Args: event_name: The name of the event to wait for. redis_address: The address of the Redis s...
0aa10f52e1682dd9d1cdc0949d245da26c26bcd4
19,214
def _stack_exists(stack_name): """ Checks if the stack exists. Returns True if it exists and False if not. """ cf = boto3.client('cloudformation') exists = False try: cf.describe_stacks(StackName=stack_name) exists = True except botocore.exceptions.ClientError as ex: ...
5ddc6c17342e3c03317d5da0bf8b4d0a338a8f21
19,215
def make_sequence_output(detections, classes): """ Create the output object for an entire sequence :param detections: A list of lists of detections. Must contain an entry for each image in the sequence :param classes: The list of classes in the order they appear in the label probabilities :return: ...
019d3b74699af20a9f3cbc43b575e8bae5e15946
19,216
def json_to_dataframe(json, subset=0): """Load data from path. The file needs to be a .csv Returns:\n Dataframe """ # This is to make sure it has the right format when passed to pandas if type(json) != list: json = [json] try: df = pd.DataFrame(json, [i for i in range(0, len...
151914e3e11759ff74283c303912a0b6842cd213
19,217
def dms_to_angle(dms): """ Get the angle from a tuple of numbers or strings giving its sexagesimal representation in degrees @param dms: (degrees, minutes, seconds) """ sign = 1 angle_string = dms[0] if angle_string.startswith('-'): sign = -1 angle_string = angle_string[1...
c56c66093a877aae6474d583da6d1db81ccbc7cd
19,218
def fix(text): """Repairs encoding problems.""" # NOTE(Jonas): This seems to be fixed on the PHP side for now. # import ftfy # return ftfy.fix_text(text) return text
7fd97db345a604131f52b272a7dd13ab4f3f9153
19,219
def generate_labeled_regions(shape, n_regions, rand_gen=None, labels=None, affine=np.eye(4), dtype=np.int): """Generate a 3D volume with labeled regions. Parameters ---------- shape: tuple shape of returned array n_regions: int number of regions to gene...
501c9bab430558fdc0cf45491498c8e3bcc7d3c4
19,220
def get_source_item_ids(portal, q=None): """ Get ids of hosted feature services that have an associated scene service. Can pass in portal search function query (q). Returns ids only for valid source items. """ source_item_ids = [] scene_item_ids = get_scene_service_item_ids(portal) ...
448ac2d94fda4dc3c69bd8fe9eb00587a0f0dcb2
19,221
def rasterize_poly(poly_xy, shape): """ Args: poly_xy: [(x1, y1), (x2, y2), ...] Returns a bool array containing True for pixels inside the polygon """ _poly = poly_xy[:-1] # PIL wants *EXACTLY* a list of tuple (NOT a numpy array) _poly = [tuple(p) for p in _poly] img = Image.ne...
d1abf5cef5a1fb57286ff38d575a575a679a4002
19,222
def from_url_representation(url_rep: str) -> str: """Reconvert url representation of path to actual path""" return url_rep.replace("__", "/").replace("-_-", "_")
5cf4e1e8cb284c66449807ea275e4fa6b5a3e3ad
19,223
from unittest.mock import patch async def test_async_start_from_history_and_switch_to_watching_state_changes_multiple( hass, recorder_mock, ): """Test we startup from history and switch to watching state changes.""" hass.config.set_time_zone("UTC") utcnow = dt_util.utcnow() start_time = utcnow...
6fb66dde3fad24fbccffb0f8ce74e666e3551e56
19,224
def runningmean(data, nav): """ Compute the running mean of a 1-dimenional array. Args: data: Input data of shape (N, ) nav: Number of points over which the data will be averaged Returns: Array of shape (N-(nav-1), ) """ return np.convolve(data, np.ones((nav,)) / nav, m...
8ba55de399d8789a43624582ac14f2f4804668ef
19,225
def test_space(gym_space, expected_size, expected_min, expected_max): """Test that an action or observation space is the correct size and bounds. Parameters ---------- gym_space : gym.spaces.Box gym space object to be tested expected_size : int expected size expected_min : float...
e43e2e4d064bec033e6cef6f9c1c905b13541cc7
19,226
from typing import Optional from typing import List def multiindex_strategy( pandera_dtype: Optional[DataType] = None, strategy: Optional[SearchStrategy] = None, *, indexes: Optional[List] = None, size: Optional[int] = None, ): """Strategy to generate a pandas MultiIndex object. :param pa...
580a312790d7ff5d9c5f5309f3100e4ebd490f7e
19,227
def pitch_from_centers(X, Y): """Spot pitch in X and Y direction estimated from spot centers (X, Y). """ assert X.shape == Y.shape assert X.size > 1 nspots_y, nspots_x = X.shape if nspots_x > 1 and nspots_y == 1: pitch_x = pitch_y = np.mean(np.diff(X, axis=1)) elif nspots_y > 1 and n...
c9816d3bee4d658a3b00769f26f22b8c0cd0fd10
19,228
def _create_lists(config, results, current, stack, inside_cartesian=None): """ An ugly recursive method to transform config dict into a tree of AbstractNestedList. """ # Have we done it already? try: return results[current] except KeyError: pass # Check recursion depth an...
ef9a51023a44ae1cdbfbadbc762a0ffcd1959562
19,229
def encode(value): """ Encode strings in UTF-8. :param value: value to be encoded in UTF-8 :return: encoded value """ return str(u''.join(value).encode('utf-8'))
697f99f028d4b978b591d006273b9d5f688711f3
19,230
def get_season(months, str_='{}'): """ Creates a season string. Parameters: - months (list of int) - str_ (str, optional): Formatter string, should contain exactly one {} at the position where the season substring is included. Returns: str """ if months is None: retur...
73b4e8169f08ef286a0b57779d22c3436538fc30
19,231
def data_availability(tags): """ get availability based on the validation tags Args: tags (pandas.DataFrame): errors tagged as true (see function data_validation) Returns: pandas.Series: availability """ return ~tags.any(axis=1)
240bed8f169d23610f11c214d3644f02e5435412
19,232
async def fetch_image_by_id( image_uid: str ): """ API request to return a single image by uid """ image_uid = int(image_uid) image = utils_com.get_com_image_by_uid(image_uid) return image
153d24fd35ce18ae9c94d1c7ecf797154bc32c0f
19,233
from datetime import datetime def get_spring_break(soup_lst, year): """ Purpose: * returns a list of the weekdays during spring break * only relevant for spring semesters """ spring_break_week = set() # search for the "Spring Break begins after last class." text for i in range...
cfd80d12da8a22a26d66f4f64f6f8511ed7238a4
19,234
def GetProQ3Option(query_para):#{{{ """Return the proq3opt in list """ yes_or_no_opt = {} for item in ['isDeepLearning', 'isRepack', 'isKeepFiles']: if query_para[item]: yes_or_no_opt[item] = "yes" else: yes_or_no_opt[item] = "no" proq3opt = [ "-r...
e2fe6ba97aa96d01a19a191aabcc3e793a63c490
19,235
def is_empty_config(host): """ Check if any services should to be configured to run on the given host. """ return host.AS is None
c4ec3861c497ac49ed69ecd1d6da31ab8fe2829c
19,236
def total_value(metric): """Given a time series of values, sum the values""" total = 0 for i in metric: total += i return total
4454bfaeb0797bc03b14819bde48dc8f5accc4d3
19,237
import os import tqdm import json def unpackJSON(target_naming_scheme, chemdf_dict): """ most granular data for each row of the final CSV is the well information. Each well will need all associated information of chemicals, run, etc. Unpack those values first and then copy the generated array to each ...
096f1e6619d44b9d4d19c7b96664561070ca264b
19,238
import re def validate_email_add(email_str): """Validates the email string""" email = extract_email_id(email_str) return re.match("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", email.lower())
0f77f223b208471a960e2829efb12a85f82b1381
19,239
def get_seed_nodes_json(json_node: dict, seed_nodes_control: dict or list) -> dict: """ We need to seed some json sections for extract_fields. This seeds those nodes as needed. """ seed_json_output = {} if isinstance(seed_nodes_control, dict) or isinstance(seed_nodes_control, list): for node...
f3672ee019ff4bb72f25582daf5c83fa7c8f72d0
19,240
def load_object(import_path): """ Loads an object from an 'import_path', like in MIDDLEWARE_CLASSES and the likes. Import paths should be: "mypackage.mymodule.MyObject". It then imports the module up until the last dot and tries to get the attribute after that dot from the imported module. ...
5fd45ee31a440cbdd4c90e875e04f4f8f1856b3a
19,241
def _inufft(kspace, trajectory, sensitivities=None, image_shape=None, tol=1e-5, max_iter=10, return_cg_state=False, multicoil=None, combine_coils=True): """MR image reconstruction using iterative inverse NUFFT. For the ...
892350c74ca0b7163b4aec9278af30dd770b5e1e
19,242
def adjust_cart(request, item_id): """Adjust the quantity of the specified product to the specified amount""" album = get_object_or_404(Album, pk=item_id) # Returns 404 if an invalid quantity is entered try: quantity = int(request.POST.get("quantity")) except Exception as e: return...
ed455747341cf581725d2fae326292155a3b77a8
19,243
def calculate_delta_v(scouseobject, momone, momnine): """ Calculate the difference between the moment one and the velocity of the channel containing the peak flux Parameters ---------- scouseobject : instance of the scousepy class momone : ndarray moment one (intensity-weighted aver...
a894eac64f5b88fd6230eb060583fd15552bc8d8
19,244
def _validate_image(values): """ Validates the incoming data and raises a Invalid exception if anything is out of order. :param values: Mapping of image metadata to check """ status = values.get('status', None) if not status: msg = "Image status is required." raise exceptio...
d0ebb8ecbde452c3128e93e917482cff13e47947
19,245
def revcmp(x, y): """Does the reverse of cmp(): Return negative if y<x, zero if y==x, positive if y>x""" return cmp(y, x)
52e5382211379d09703996b0da89821a9521de73
19,246
def linear_regression(data: pd.DataFrame): """ https://www.statsmodels.org/ :param data: 数据集中要包含收盘价Close :return: 拟合的y,k,b以及k转化的角度 """ y_arr = data.Close.values x_arr = np.arange(0, len(y_arr)) b_arr = sm.add_constant(x_arr) model = regression.linear_model.OLS(y_arr, b_arr).fit() ...
9b30a6d90ed1e0131e12b2f7944eb58a90676ad3
19,247
from datetime import datetime from operator import and_ def get_expiry(): """ Returns the membership IDs of memberships expiring within 'time_frame' amount of MONTHS """ time_frame = request.args.get('time_frame') try: time_frame = int(time_frame) except ValueError as e: print...
4fd13a5e2de1feb4b797c225c349031a903f2673
19,248
def get_functions(input_file): """Alias for load_data bellow.""" return load_data(input_file)
7f286809a3c27db32e0aeb3f08d41989a7b3fad2
19,249
def is_elem_ref(elem_ref): """ Returns true if the elem_ref is an element reference :param elem_ref: :return: """ return ( elem_ref and isinstance(elem_ref, tuple) and len(elem_ref) == 3 and (elem_ref[0] == ElemRefObj or elem_ref[0] == ElemRefArr) )
282a5ba04b2cafedd5a043bf83b4ccbd6196ae44
19,250
from typing import Tuple from typing import List def analyse_subcommand( analyser: Analyser, param: Subcommand ) -> Tuple[str, SubcommandResult]: """ 分析 Subcommand 部分 Args: analyser: 使用的分析器 param: 目标Subcommand """ if param.requires: if analyser.sentences !=...
d3be0a7709ae2ebfab414d30494fe7baeba5de8d
19,251
def fetch_pg_types(columns_info, trans_obj): """ This method is used to fetch the pg types, which is required to map the data type comes as a result of the query. Args: columns_info: """ # get the default connection as current connection attached to trans id # holds the cursor whic...
87bdc81134ee4d83ffbce05a77abec555b55a661
19,252
def open_popup(text) -> bool: """ Opens popup when it's text is updated """ if text is not None: return True return False
8ced6b6e73531f97df8ac7fe38723438077ca6d1
19,253
def se_beta_formatter(value: str) -> str: """ SE Beta formatter. This formats SE beta values. A valid SE beta values is a positive float. @param value: @return: """ try: se_beta = float(value) if se_beta >= 0: result = str(se_beta) else: ...
30dde489e1a8a70c0f1093caa1ce289c759b26d6
19,254
from typing import Optional def replace_missing_data( data: pd.DataFrame, target_col: str, source_col: str, dropna: Optional[bool] = False, inplace: Optional[bool] = False, ) -> Optional[pd.DataFrame]: """Replace missing data in one column by data from another column. Parameters -----...
a94e41cb88bcf502192855276ed1f11f73b1c3a1
19,255
def jsonpath_parse(data, jsonpath, match_all=False): """Parse value in the data for the given ``jsonpath``. Retrieve the nested entry corresponding to ``data[jsonpath]``. For example, a ``jsonpath`` of ".foo.bar.baz" means that the data section should conform to: .. code-block:: yaml --- ...
3b5ab89d8315e36f8412e874f393c414c76b8587
19,256
def extract_urlparam(name, urlparam): """ Attempts to extract a url parameter embedded in another URL parameter. """ if urlparam is None: return None query = name+'=' if query in urlparam: split_args = urlparam[urlparam.index(query):].replace(query, '').split('&') ret...
198771d40eeddc3b7dbf2924d9d49fe7a7f0a51d
19,257
def get_nlb_data(elb_data, region, load_balancer_name, ssl_hc_path): """ Render a dictionary which contains Network Load Balancer attributes """ if debug: logger.debug("Building the Network Load Balancer data structure") # this is used for building the load balancer spec nlb_data = {'Vpc...
3cd162176f7e3580f749bfb8af7e8436c4c2dd18
19,258
from typing import Dict from typing import Any def _get_required_var(key: str, data: Dict[str, Any]) -> str: """Get a value from a dict coerced to str. raise RequiredVariableNotPresentException if it does not exist""" value = data.get(key) if value is None: raise RequiredVariableNotPresentExce...
b94db42048779df532a55c2604c7c1b5d02a4f7f
19,259
def phones(): """Return a list of phones used in the main dict.""" cmu_phones = [] for line in phones_stream(): parts = line.decode("utf-8").strip().split() cmu_phones.append((parts[0], parts[1:])) return cmu_phones
972c4c0739cd3c823f98eb6314d25f07b9f720f6
19,260
def load_specific_forecast(city, provider, date, forecasts): """reads in the city, provider, date and forecast_path and returns the data queried from the forecast path :param city: city for which the weather forecast is for :type string :param provider: provider for which the weather forecast is for ...
95f00fd07d218f1e19eb6d771898453d2495cb1d
19,261
from numpy import array, isnan from mne.channels import Montage def eeg_to_montage(eeg): """Returns an instance of montage from an eeg file""" pos = array([eeg.info['chs'][i]['loc'][:3] for i in range(eeg.info['nchan'])]) if not isnan(pos).all(): selection = [i for i in range(eeg...
9d0823bc9633ead4081b4b068717c8f9385c3e69
19,262
def mul_inv2(x:int, k:int) -> int: """ Computes x*2^{-1} in (Z/3^kZ)*.""" return (inv2(k)*x)%(3**k)
5789b4b9837f5b3bf6093aa586fca8f133ff8c51
19,263
def Be(Subject = P.CA(), Contract=FALSE): """Synonym for Agree("be").""" return Agree("be", Subject, Contract)
e6b1f07d17c34157b9b1ca216f4c0e99c5b25c00
19,264
def line_search_armijo(f, xk, pk, gfk, old_fval, args=(), c1=1e-4, alpha0=0.99): """ Armijo linesearch function that works with matrices find an approximate minimum of f(xk+alpha*pk) that satifies the armijo conditions. Parameters ---------- f : function loss function xk : np.nda...
aefbe34ad1b28317e4fc21b1d80beda430183660
19,265
def lprob2sigma(lprob): """ translates a log_e(probability) to units of Gaussian sigmas """ if (lprob>-36.): sigma = norm.ppf(1.-0.5*exp(1.*lprob)) else: sigma = sqrt( log(2./pi) - 2.*log(8.2) - 2.*lprob ) return float(sigma)
b224e9b50fc2a171cbb849965946ccae804648d7
19,266
def convert_from_fortran_bool(stringbool): """ Converts a string in this case ('T', 'F', or 't', 'f') to True or False :param stringbool: a string ('t', 'f', 'F', 'T') :return: boolean (either True or False) """ true_items = ['True', 't', 'T'] false_items = ['False', 'f', 'F'] if isi...
b9840c41a978003e8dcc5191bd7f859fc5b0ecb7
19,267
def gaussian_device(n_subsystems): """Number of qubits or modes.""" return DummyDevice(wires=n_subsystems)
c2779958009ebe2dd7907a0a5f418535d782f4a0
19,268
def create_playlist(current_user, user_id): """ Creates a playlist. :param user_id: the ID of the user. :return: 200, playlist created successfully. """ x = user_id user = session.query(User).filter_by(id=user_id).one() data = request.get_json() new_playlist = Playlist(name=data['nam...
6116949956bbc077205adb66bf51b160b7a0d812
19,269
def gram_matrix(y): """ Input shape: b,c,h,w Output shape: b,c,c """ (b, ch, h, w) = y.size() features = y.view(b, ch, w * h) features_t = features.transpose(1, 2) gram = features.bmm(features_t) / (ch * h * w) return gram
9ea7595870dccc1375626c374fb9db1436523e40
19,270
import torch def process_pair_v2(data, global_labels): """ :param path: graph pair data. :return data: Dictionary with data, also containing processed DGL graphs. """ # print('Using v2 process_pair') edges_1 = data["graph_1"] #diff from v1 edges_2 = data["graph_2"] #diff from v1 edges...
61e0194f521132cfa4e96db925f566abf6b3b427
19,271
from typing import Tuple def calculate_line_changes(diff: Diff) -> Tuple[int, int]: """Return a two-tuple (additions, deletions) of a diff.""" additions = 0 deletions = 0 raw_diff = "\n".join(diff.raw_unified_diff()) for line in raw_diff.splitlines(): if line.startswith("+ "): ...
437859735c904a3c7754091c6cb97ba528dc7e72
19,272
def get_synonyms(token): """ get synonyms of word using wordnet args: token: string returns: synonyms: list containing synonyms as strings """ synonyms = [] if len(wordnet.synsets(token)) == 0: return None for synset in wordnet.synsets(token): for lemma in syn...
ec26875e694f860c38b709979dfc8328eff17f0f
19,273
def concat_experiments_on_channel(experiments, channel_name): """Combines channel values from experiments into one dataframe. This function helps to compare channel values from a list of experiments by combining them in a dataframe. E.g: Say we want to extract the `log_loss` channel values for a list o...
04c8004ccb1a2b5ec2906bb1183e685b8c8ff763
19,274
def sghmc_naive_mh_noresample_uni(u_hat_func, du_hat_func, epsilon, nt, m, M, V, theta_init, r_init, formula): """ This is a function to realize Naive Stochastic Gradient Hamiltonian Monte Carlo with Metropolis-Hastings correction in unidimensional cases without resampling procedure. """ B = 1...
4f330bf3025506bc2bafca0891025ac8b9a4f280
19,275
def detect_voices(aud, sr=44100): """ Detect the presence and absence of voices in an array of audio Args: Returns: """ pcm_16 = np.round( (np.iinfo(np.int16).max * aud)).astype(np.int16).tobytes() voices = [ VAD.is_speech(pcm_16[2 * ix:2 * (ix + SMOOTHING_WSIZE)], ...
ec987cf5e3384cb20d52d07684f7afb5f38f0e98
19,276
def process_to_binary_otsu_image(img_path, inverse=False, max_threshold=255): """ Purpose: Process an image to binary colours using binary otsu thresholding. Args: img_path - path to the image to process inverse - if true an inverted binary thresholding will be applied (optional). ...
f450d29540679f2fa7736e7cd0257a56b58c8a8d
19,277
import hashlib import random def _fold_in_str(rng, data): """Folds a string into a jax.random.PRNGKey using its SHA-1 hash.""" m = hashlib.sha1() m.update(data.encode('utf-8')) d = m.digest() hash_int = int.from_bytes(d[:4], byteorder='big', signed=True) return random.fold_in(rng, hash_int)
e0b3d135a9573892cf7f4cfdcea1bc29bbc3e8c0
19,278
def create_task_dialog(request): """called when creating tasks """ return data_dialog(request, mode='create', entity_type='Task')
6712048914a8417792b0dc8a1ab60c081886d4fa
19,279
def raw_rearrange(da, pattern, **kwargs): """Crudely wrap `einops.rearrange <https://einops.rocks/api/rearrange/>`_. Wrapper around einops.rearrange with a very similar syntax. Spaces, parenthesis ``()`` and `->` are not allowed in dimension names. Parameters ---------- da : xarray.DataArray ...
a16c8e439882acba930fa143e9d2428d38d1ca70
19,280
from typing import Tuple def get_users() -> Tuple[int, ...]: """Count user ids in db.""" db = get_database_connection() user_searches = db.keys(pattern=f'{DB_SEARCH_PREFIX}*') user_ids = [ int(user_search.decode('utf-8').lstrip(DB_SEARCH_PREFIX)) for user_search in user_searches ] ...
2eaded42444fe4ad5395387ddd45022a9e8736ce
19,281
from typing import Optional async def login( email: str, password: str, session: Optional[ClientSession] = None, *, conf_update_interval: Optional[timedelta] = None, device_set_debounce: Optional[timedelta] = None, ): """Login using email and password.""" if session: response =...
274f0785eb0e2fb3b73cfc4c2810df03df52d7b1
19,282
def rcomp_prediction(system, rcomp, predargs, init_cond): """ Make a prediction with the given system Parameters: system (str): Name of the system to predict rcomp (ResComp): Trained reservoir computer predargs (variable length arguments): Passed directly into rcomp.predict init_...
fb4eb3e710335788333a12abcd494015f4784a78
19,283
def get_best_model(X ,y): """Select best model from RandomForestClassifier and AdaBoostClassifier""" ensembles = [ (RandomForestClassifier, SelectParam({ 'estimator': RandomForestClassifier(warm_start=True, random_state=7), 'param_grid': { 'n_estimators': [10, 15,...
c1ac787d89a0086c263490b12081e0bfe98c6c57
19,284
def compareDates(dateA: list, dateB: list) -> int: """ Compares dateA and dateB\n returns: 1 if dateA > dateB,\n -1 if dateA <dateB, 0 if dateA == dateB \n raise Exception if dates are invalid """ if not checkDateValidity(dateA, dateB): raise invalidDateException('Invalid Dates')...
927af2e0164706e8013badd90638b2561ab74241
19,285
def renderPage(res, topLevelContext=context.WebContext, reqFactory=FakeRequest): """ Render the given resource. Return a Deferred which fires when it has rendered. """ req = reqFactory() ctx = topLevelContext(tag=res) ctx.remember(req, inevow.IRequest) render = appserver...
136a06274c9cbb34951a7d2b8544328b4a1f4b60
19,286
def get_header_value(headers, name, default=None): """ Return header value, doing case-insensitive match """ if not headers: return default if isinstance(headers, dict): headers = headers.items() name = to_bytes(name.lower()) for k, v in headers: if name == to_bytes(k.lower...
9ddb9754061554bd59b429b78e472bd514e4c14d
19,287
def parse_gt_from_anno(img_anno, classes): """parse_gt_from_anno""" print('parse ground truth files...') ground_truth = {} for img_name, annos in img_anno.items(): objs = [] for anno in annos: if anno[1] == 0. and anno[2] == 0. and anno[3] == 0. and anno[4] == 0.: ...
63ba02bb0511cdc02245528041257639e764605f
19,288
def pt_to_tup(pt): """ Convenience method to generate a pair of two ints from a tuple or list. Parameters ---------- pt : list OR tuple Can be a list or a tuple of >=2 elements as floats or ints. Returns ------- pt : tuple of int A pair of two ints. """ return (...
7013b2477959f528b98d364e4cc44ac8700fb366
19,289
def _operation(m1, m2, op, k): """Generalized function for basic""" """matrix operations""" n = len(m1) res = [n*[0] for i in range(n)] if n == len(m2): for i in range(n): for j in range(n): tab = { "+" : m1[i][j]+m2[i][j], "-" : ...
5e00ad1a9fbadb9712631450b106b81e5a3413ed
19,290
def jacobi_d1(x, n, alpha, beta): """Evaluate the first derivative of Jacobi polynomial at x using eq. A.1.8 Args: x: the location where the value will be evaluated n: the order of Jacobi polynomial alpha: the alpha parameter of Jacobi polynomial beta: the beta parameter of Jaco...
4a982827916466fad0ed812d2ec3792ca1605f0a
19,291
def gate_expand_1toN(U, N, target): """ Create a Qobj representing a one-qubit gate that act on a system with N qubits. Parameters ---------- U : Qobj The one-qubit gate N : integer The number of qubits in the target space. target : integer The index of the tar...
efb3d4da51e2f6dc90ba7bcf5e085cb651a4fed0
19,292
from typing import Dict from typing import Any from typing import List def build_component_dependency_graph( pipeline_definition: Dict[str, Any], component_definitions: Dict[str, Any] ) -> DiGraph: """ Builds a dependency graph between components. Dependencies are: - referenced components during compo...
c70655e4d2b2405d991af43d4a1ad67eb1d8c9d3
19,293
def count_distribution_artefacts(distribution_artefacts): """ Count distribution artefacts in nested list. :param distribution_artefacts: Nested list containing distribution artefacts mapped to media packages and tenants :type distribution_artefacts: dict :return: Amount of distribution artefacts ...
b9bc159523e8cbb4745d8b7e8897360f6f9c1960
19,294
def nelson_siegel_yield(tau, theta): """For details, see here. Parameters ---------- tau : array, shape (n_,) theta : array, shape (4,) Returns ------- y : array, shape (n_,) """ y = theta[0] - theta[1] * \ ((1 - np.exp(-theta[3] * tau)) / (theta[...
ba328c7698f088c3e371462b6a92c62517054af5
19,295
import argparse def parsing(lst=None): """ Function for parsing command line >>> parsing(["2020", "80", "90", "dataset"]) (2020, 80.0, 90.0, 'dataset') """ parser = argparse.ArgumentParser(description="""Module, which reads data from a file\ with a films list, determines films, \ ma...
f625f09b31b60b80d91474560ca01b5df92d567c
19,296
def fix_filename(filename): """Replace illegal or problematic characters from a filename.""" return filename.translate(_filename_trans)
dc8c8e1f85a7372db97273ae595ff69520824574
19,297
def QDenseModel(weights_f, load_weights=False): """Construct QDenseModel.""" x = x_in = Input((RESHAPED,), name="input") x = QActivation("quantized_relu(4)", name="act_i")(x) x = QDense(N_HIDDEN, kernel_quantizer=ternary(), bias_quantizer=quantized_bits(4, 0, 1), name="dense0")(x) x = QActivatio...
c84f591866708ea086e8c22ff333d60381e1f865
19,298
import os import json def _load_config(): """Load the StreamAlert Athena configuration files Returns: dict: Configuration settings by file, includes two keys: lambda, All lambda function settings global, StreamAlert global settings Raises: ConfigError: For invalid...
beef540e97e3322071561009a726c4c7c529f6f6
19,299