content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import dbm def get_sim_data(): """ Create the data needed to initialize a simulation Performs the steps necessary to set up a stratified plume model simulation and passes the input variables to the `Model` object and `Model.simulate()` method. Returns ------- profile : `ambient.Profi...
e253665f451b167a188c997ff36fc406e0f3a587
19,171
import numpy as np def _organize_arch(fils, pth): """Allocate data from each specific type of file (keys from the input dict) to a new dict Arguments: fils {dict} -- Dictionary containing type of files and list of files Returns: [dict] -- [description] """ imgdata ...
c62c9b23bf4735c2062090d77278ce5a8acbd668
19,172
def gather_allele_freqs(record, all_samples, males, females, pop_dict, pops, no_combos = False): """ Wrapper to compute allele frequencies for all sex & population pairings """ #Get allele frequencies calc_allele_freq(record, all_samples) if len(males) > 0: calc_allele_freq(record, male...
0f74616fa64ee5b3582467da27161906abf28463
19,173
def get_selected(n=1): """ Return the first n selected object, or None if nothing is selected. """ if get_selection_len(): selection = bpy.context.selected_objects if n == 1: return selection[0] elif n == -1: return selection[:] else: r...
6049900ef069731b1fbe9f40fff184085940c83e
19,174
def label_src_vertno_sel(label, src): """ Find vertex numbers and indices from label Parameters ---------- label : Label Source space label src : dict Source space Returns ------- vertno : list of length 2 Vertex numbers for lh and rh src_sel : array of int ...
a1858258b6c789557d6bdeff9428cc7aacbe4655
19,175
def get_subjects(creative_work): """ Returns generated html of subjects associated with the Creative Work HTML or 0-length string Parameters: creative_work -- Creative Work """ html_output = '' #! Using LOC Facet as proxy for subjects facets = list( REDIS_DATASTORE.smembers(...
328aeadb21a22972c0843efdba251b2f6c5f937d
19,176
def sort(request): """Boolean sort keyword for concat and DataFrame.append.""" return request.param
83f35eb41bc0cf7eecea932ae4f14646d9e8732f
19,178
def is_comprehension(leaf): """ Return true if the leaf is the beginning of a list/set/dict comprehension. Returns true for generators as well """ if leaf.type != 'operator' or leaf.value not in {'[', '(', '{'}: return False sibling = leaf.get_next_sibling() return (sibling.type in...
11fff76ff8ed19b3d57359b56db886c003603a86
19,179
def get_class(x): """ x: index """ # Example distribution = [0, 2000, 4000, 6000, 8000, 10000] x_class = 0 for i in range(len(distribution)): if x > distribution[i]: x_class += 1 return x_class
1ae95f3d9bc6f342169232ab10cd08a42de0f692
19,180
from re import T def square(x): """Elementwise square of a tensor. """ return T.sqr(x)
c052e31a450b91eb1e6a08843f99afd6e618da9d
19,181
import re def update_email_body(parsed_email, key): """ Finds and updates the "text/html" and "text/plain" email body parts. Parameters ---------- parsed_email: email.message.Message, required EmailMessage representation the downloaded email key: string, required The object key...
d942a4cf47af9d7c1e36a4a2af5d0239b90464d8
19,182
import json def create_collaborators(collaborators, destination_url, destination, credentials): """Post collaborators to GitHub INPUT: collaborators: python list of dicts containing collaborators info to be POSTED to GitHub destination_url: the root url for the GitHub API destination: ...
2d39a2970d9f52af5209b1f4717c0b4d39e1cb5c
19,183
import scipy def complexity_recurrence(signal, delay=1, dimension=3, tolerance="default", show=False): """Recurrence matrix (Python implementation) Fast Python implementation of recurrence matrix (tested against pyRQA). Returns a tuple with the recurrence matrix (made of 0s and 1s) and the distance matri...
cc93a80ff34fffc5774f7b52109fd09d8b0ac69e
19,184
def get_awb_shutter( f ): """ Get AWB and shutter speed from file object This routine extracts the R and B white balance gains and the shutter speed from a jpeg file made using the Raspberry Pi camera. These are stored as text in a custom Makernote. The autoexposure and AWB white balance valu...
cfafdf531809729ae0ec96ab90a60a4961b9437a
19,186
def rgb2lab(rgb_arr): """ Convert colur from RGB to CIE 1976 L*a*b* Parameters ---------- rgb_arr: ndarray Color in RGB Returns ------- lab_arr: ndarray Color in CIE 1976 L*a*b* """ return xyz2lab(rgb2xyz(rgb_arr))
3eba11b8017908393e1e238e6b4ae046dd265520
19,187
def format_rfidcard(rfidcard): """ :type rfidcard: apps.billing.models.RfidCard """ return { 'atqa': rfidcard.atqa if len(rfidcard.atqa) > 0 else None, 'sak': rfidcard.sak if len(rfidcard.sak) > 0 else None, 'uid': rfidcard.uid, 'registered_at': rfidcard.registered_at.is...
120ca8e338b01235b2ba12ae3f874fd317ffebe8
19,188
def make_exposure_shares(exposure_levels, geography="geo_nm", variable="rank"): """Aggregate shares of activity at different levels of exposure Args: exposure_levels (df): employment by lad and sector and exposure ranking geography (str): geography to aggregate over variable (str): varia...
02d990f2b08e3acb2a2b8ac01e44848770bdea71
19,189
def boxscores(sports=["basketball/nba"], output="dict", live_only=True, verbose=False): """ ~ 10 seconds """ links = boxlinks(sports=sports, live_only=live_only, verbose=verbose) boxes = [boxscore(link) for link in links] return boxes
9cdc1bd4ec90d8ab9593d49316669dc6b801cf2e
19,191
def runningMedian(seq, M): """ Purpose: Find the median for the points in a sliding window (odd number in size) as it is moved from left to right by one point at a time. Inputs: seq -- list containing items for which a running median (in a sliding window) is t...
b37af61c9f6f62bd6fbd395bc2c423a770ba2797
19,192
def min_max_normalize(img): """ Center and normalize the given array. Parameters: ---------- img: np.ndarray """ min_img = img.min() max_img = img.max() return (img - min_img) / (max_img - min_img)
faaafbc8e0b36f26f8319b671de326dd6a97e6f9
19,193
def find_common_features(experiment: FCSExperiment, samples: list or None = None): """ Generate a list of common features present in all given samples of an experiment. By 'feature' we mean a variable measured for a particular sample e.g. CD4 or FSC-A (forward scatter) Paramete...
8022a97721eb9ff26efcba347e4f631aff3ede84
19,194
import heapq def generate_blend_weights(positions, new_p, n_neighbors): """ Use inverse distance and K-Nearest-Neighbors Interpolation to estimate weights according to [Johansen 2009] Section 6.2.4 """ distances = [] for n, p in positions.items(): distance = np.linalg.norm(new_p - p) ...
f9db2b47d5847cdb2e7367cebe9b9bf81809b11d
19,195
def check_method(adata): """Check that method output fits expected API.""" assert "connectivities" in adata.obsp assert "distances" in adata.obsp return True
0ad772187c6d2960149723df17f6b0cf3fa703d1
19,196
def load_model(Model, params, checkpoint_path='', device=None): """ loads a model from a checkpoint or from scratch if checkpoint_path='' """ if checkpoint_path == '': model = Model(params['model_params'], **params['data_params']) else: print("model:", Model) print(f...
8f1339b5548024714f731de037ef320535fc3b69
19,197
import inspect def get_widget_type_choices(): """ Generates Django model field choices based on widgets in holodeck.widgets. """ choices = [] for name, member in inspect.getmembers(widgets, inspect.isclass): if member != widgets.Widget: choices.append(( "%s....
143ff91ee3bc4166e5091e344a38fb2bbb72934e
19,198
import array def iau2000a(jd_tt): """Compute Earth nutation based on the IAU 2000A nutation model. `jd_tt` - Terrestrial Time: Julian date float, or NumPy array of floats Returns a tuple ``(delta_psi, delta_epsilon)`` measured in tenths of a micro-arcsecond. Each value is either a float, or a NumPy...
beadd6469a85b475dc22ca1e2a967310555140a9
19,199
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
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 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 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
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