content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def list_all_connections(pg_id='root', descendants=True): """ Lists all connections for a given Process Group ID Args: pg_id (str): ID of the Process Group to retrieve Connections from descendants (bool): True to recurse child PGs, False to not Returns: (list): List of Connecti...
6df326ff521f175b3ccfe4b1d2488328fe6e6213
3,649,976
def _GetTombstoneData(device, tombstone_file): """Retrieve the tombstone data from the device Args: device: An instance of DeviceUtils. tombstone_file: the tombstone to retrieve Returns: A list of lines """ return device.old_interface.GetProtectedFileContents( '/data/tombstones/' + tombsto...
99322ea3d67e150f4433c713159eb7bc8069271f
3,649,978
import time def _strTogYear(v): """Test gYear value @param v: the literal string @return v @raise ValueError: invalid value """ try: time.strptime(v+"-01-01", "%Y-%m-%d") return v except: raise ValueError("Invalid gYear %s" % v)
a65e04c2d3790d3d55bbc8788d6802e1aae1b78c
3,649,979
def aca_full_pivoting(A, epsilon): """ACA with full pivoting as in the lecture Takes in a matrix, and returns the CUR decomposition """ # R0 = A Rk = A.copy() I_list = [] J_list = [] while frobenius_norm(Rk) > epsilon*frobenius_norm(A): i, j = np.unravel_index(np.argmax(np.abs(R...
96bcfd4b8cb560904efc4ab6cfac6473d8dafe47
3,649,980
def catch_gpu_memory_error( f ): """ Decorator that calls the function `f` and catches any GPU memory error, during the execution of f. If a memory error occurs, this decorator prints a corresponding message and aborts the simulation (using MPI abort if needed) """ # Redefine the original f...
1201236b7d2217fcfc3fcb95905f8f4e2f89af06
3,649,984
def horizontal_tail_planform_raymer(horizontal_stabilizer, wing, l_ht,c_ht): """Adjusts reference area before calling generic wing planform function to compute wing planform values. Assumptions: None Source: Raymer Inputs: horizontal_stabilizer [SUAVE data structure] ...
860a020e3e2b06943df2689bd54707a051fb30b2
3,649,985
from improved_permissions.roles import ALLOW_MODE def inherit_check(role_s, permission): """ Check if the role class has the following permission in inherit mode. """ role = get_roleclass(role_s) if role.inherit is True: if role.get_inherit_mode() == ALLOW_MODE: return Tru...
5dbaa7afee9802ea1eda4cec869dd44395faf0e5
3,649,986
import random def giveHint(indexValue, myBoard): """Return a random matching card given the index of a card and a game board""" validMatches = [] card = myBoard[indexValue] for c in myBoard: if (card[0] == c[0]) and (myBoard.index(c) != indexValue): validMatches.append(myBoard....
e578f40e7d7e2e17ddac53f9cfdc219e47c861cd
3,649,987
async def make_getmatch_embed(data): """Generate the embed description and other components for a getmatch() command. As with its parent, remember that this currently does not support non team-vs. `data` is expected to be the output of `get_individual_match_data()`. The following `dict` is returned...
c37e0d6ee948259e4ad898d3cafb8e13b6452d80
3,649,988
def allreduceCommunicate_op(node, comm): """Make a new instance of AllReduceCommunicateOp and call the instance. Parameters: ---- node : Node The Node to do allreduce Returns: ---- A new Node instance created by Op. """ return AllReduceCommunicateOp(node, comm)
5096a9014ae349e39c2d59de77845221ffdddb10
3,649,989
def reduce_fn(state, values): """tf.data.Dataset-friendly implementation of mean and variance.""" k, n, ex, ex2 = state # If this is the first iteration, we pick the first value to be 'k', # which helps with precision - we assume that k is close to an average # value and calculate mean and variance with respe...
473bb8cae3e898f3a166250fbdb805ad55aaaea9
3,649,990
def winged_edge( face_features: np.ndarray, edge_features: np.ndarray, coedge_features: np.ndarray, coedge_to_next: np.ndarray, coedge_to_mate: np.ndarray, coedge_to_face: np.ndarray, coedge_to_edge: np.ndarray, ): """Create graph according to the `winged edge` configuration.""" coe...
8f023d4e6133b044c435737e49ae768c83f089ca
3,649,991
def dollar_format(dollars): """ Args: dollars (any): A dollar value (Any value that can be turned into a float can be used - int, Decimal, str, etc.) Returns: str: The formatted string """ decimal_dollars = Decimal(dollars) if decimal_dollars < 0: return "-${:,.2f}".forma...
d9f8a9195a92af39df9754e14bae723060c335b1
3,649,992
from typing import Callable from typing import Any def check_aea_project( f: Callable, check_aea_version: bool = True, check_finger_prints: bool = False ) -> Callable: """ Check the consistency of the project as a decorator. - try to load agent configuration file - iterate over all the agent pack...
31d909116613be819b61be16160bd72227462853
3,649,993
def find_closest_cross(wire1_path, wire2_path): """ Compare the coordinates of two wire paths to find the crossing point closest (Manhattan Distance) to the origin (0,0). Returns a list of crossing points, the closest crossing point and its distance to the start point """ best_result ...
c91c5db3bb09cdfc74c4c71c92bf46274eb8d88c
3,649,994
import re def add_signature_source(service, **_): """ Add a signature source for a given service Variables: service => Service to which we want to add the source to Arguments: None Data Block: { "uri": "http://somesite/file_to_get", # URI to fetch for parsing ...
65526852dee90f077e0c8b52fc53e725043ffc1e
3,649,995
def edit_screen_item(self, request, form): """ Edit a screen. """ layout = ManageScreensLayout(self, request) if form.submitted(request): form.update_model(self) request.message(_('Screen modified.'), 'success') request.app.pages_cache.flush() return redirect(layout.manage...
456837172860c808c2347d556cb8aaa4fcf59fbb
3,649,996
def get_xyz_t(): """ CIELAB to XYZ の逆関数の中の値を XYZ のぞれぞれについて求める。 """ c, l, h = symbols('c, l, h', real=True) xt = (l + 16) / 116 + (c * cos(h)) / 500 yt = (l + 16) / 116 zt = (l + 16) / 116 - (c * sin(h)) / 200 xyz_t = [xt, yt, zt] return xyz_t, c, l, h
e823744ada693fb525d57f5a616c89677c8ed0a5
3,649,997
async def home(): """ Home page, welcome Returns: Rendered template of homepage """ return await render_template('home.html')
a981c121c64a99359adac620dfa0f58d31a63956
3,649,998
import torch def compute_inverse_interpolation_img(weights, indices, img, b, h_i, w_i): """ weights: [b, h*w] indices: [b, h*w] img: [b, h*w, a, b, c, ...] """ w0, w1, w2, w3 = weights ff_idx, cf_idx, fc_idx, cc_idx = indices k = len(img.size()) - len(w0.size()) img_0 = w0[(...,) ...
6b69aa5ca372a9c8f976512191d4626919d71311
3,649,999
def layer_prepostprocess(previous_value, x, sequence, dropout_rate, norm_type, depth, epsilon, default_name, name=None, ...
f983888739fa04d0c086e276997cec3919cf3e24
3,650,000
def build_norm_layer(cfg, num_channels, postfix=''): """ Build normalization layer Args: Returns: layer (fluid.dygrah.Layer): created norm layer """ assert isinstance(cfg, dict) and 'type' in cfg cfg_ = cfg.copy() layer_type = cfg_.pop('type') if layer_type not in norm_cfg: ...
d29437854587f7aeaac3b97c2e98d70b56369402
3,650,001
import torchvision def get_split_cifar100_tasks(num_tasks, batch_size): """ Returns data loaders for all tasks of split CIFAR-100 :param num_tasks: :param batch_size: :return: """ datasets = {} # convention: tasks starts from 1 not 0 ! # task_id = 1 (i.e., first task) => start_class = 0, end_class = 4 cif...
85c06c07682c74554aa11826431e5fdbd7eb84c8
3,650,002
def set_simulation_data( state_energies, T_array, state1_index, state2_index ): """ Create and set SimulationData objects for a pair of specified states """ # Set default UnitData object default_UnitData = UnitData( kb=kB.value_in_unit(unit.kilojoule_per_mole/unit.kelvin), ...
edff2bd66a359da10f64c175aa125f8749a2064d
3,650,006
def park2_euc(x): """ Comutes the park2 function """ max_val = 5.925698 x1 = x[0] x2 = x[1] x3 = x[2] x4 = x[3] ret = (2.0/3.0) * np.exp(x1 + x2) - x4*np.sin(x3) + x3 return min(ret, max_val)
96448c502867d360010238526791144fdc1e7581
3,650,007
def num_compositions_jit(m, n): """ Numba jit version of `num_compositions`. Return `0` if the outcome exceeds the maximum value of `np.intp`. """ return comb_jit(n+m-1, m-1)
40562a1ee1564e7b2015f5b8e5d2298a18644493
3,650,008
def fake_get_vim_object(arg): """Stubs out the VMwareAPISession's get_vim_object method.""" return fake_vmware_api.FakeVim()
ee7c7b0331f344b1428e48da38d185dc01bf11d9
3,650,009
import json def get_old_ids(title): """ Returns all the old ids of a particular site given the title of the Wikipedia page """ raw_data = json.loads( readInDataFromURL("https://en.wikipedia.org/w/api.php?action=query&prop=revisions&format=json&rvlimit=100000&titles=" + title) ) old_ids = dict() # initial...
9e9bc37ac51d7b3a8491fa41db5867943a170e1e
3,650,011
def max_expectation_under_constraint(f: np.ndarray, q: np.ndarray, c: float, eps: float = 1e-2, display: bool = False) -> np.ndarray: """ Solve the following constrained optimisation problem: max_p E_p[f] s.t. KL(q || p) <= c :param f: an array of ...
88a67ae4eece82c08bc683dc015904f2d307c54f
3,650,012
def payload_to_plain(payload=None): """ Converts the myADS results into the plain text message payload :param payload: list of dicts :return: plain text formatted payload """ formatted = u'' for p in payload: formatted += u"{0} ({1}) \n".format(p['name'], p['query_url'].format(p['qty...
53050791335dd8d259bf6b55bd36d3e8bc3f5fb0
3,650,013
import json def get_credentials_from_request(cloud, request): """ Extracts and returns the credentials from the current request for a given cloud. Returns an empty dict if not available. """ if request.META.get('HTTP_CL_CREDENTIALS_ID'): return get_credentials_by_id( cloud, req...
29fa45d17a0473643b2db448dfbe2de7837c4dd7
3,650,014
from functools import reduce def nCr(n, r): """n-choose-r. Thanks for the "compact" solution go to: http://stackoverflow.com/questions/2096573/counting-combinations-and-permutations-efficiently """ return reduce( lambda x, y: x * y[0] / y[1], izip(xrange(n - r + 1, n + 1), ...
06ab7a4e12a35cf49f7ddf3e75780576d3b8972c
3,650,015
from pythia.pyre.inventory import facility from pylith.bc.DirichletTimeDependent import DirichletTimeDependent def bcFactory(name): """Factory for boundary condition items. """ return facility(name, family="boundary_condition", factory=DirichletTimeDependent)
65bb203b901c1648ee504bfd5bfd0956e9f849d4
3,650,016
def decode(value): """Decode utf-8 value to string. Args: value: String to decode Returns: result: decoded value """ # Initialize key variables result = value # Start decode if value is not None: if isinstance(value, bytes) is True: result = value....
9704678f6ff96de3b711758922c28f5ecbd11bc7
3,650,017
def sequence_rec_sqrt(x_init, iter, dtype=int): """ Mathematical sequence: x_n = x_{n-1} * sqrt(n) :param x_init: initial values of the sequence :param iter: iteration until the sequence should be evaluated :param dtype: data type to cast to (either int of float) :return: element at the given i...
a7e695ee605caad5cef7881a2eeafbee8a25bf15
3,650,018
def convert_string_to_type(string_value, schema_type): """ Attempts to convert a string value into a schema type. This method may evaluate code in order to do the conversion and is therefore not safe! """ # assume that the value is a string unless otherwise stated. if schema_type == "fl...
4d99470f7094a36567851bb23c1edd49686149cf
3,650,019
def get_local_coordinate_system(time_dep_orientation: bool, time_dep_coordinates: bool): """ Get a local coordinate system. Parameters ---------- time_dep_orientation : If True, the coordinate system has a time dependent orientation. time_dep_coordinates : If True, the coordinat...
daa8259e92a31884d798915522d4e538f316fc91
3,650,021
def _get_tooltip(tooltip_col, gpd): """Show everything or columns in the list.""" if tooltip_col is not None: tooltip = folium.GeoJsonTooltip(fields=tooltip_col) else: tooltip = tooltip_col return tooltip
8a2dc564ef65aa0eaf8a9e85457876ad0e6989ec
3,650,022
def encryption(message: str, key: int) -> str: """Return the ciphertext by xor the message with a repeating key""" return b"".join( [bytes([message[i] ^ key[i % len(key)]]) for i in range(len(message))] )
674e4a27491a9f6c918f2129276349ba426cd676
3,650,023
def data_fun(times): """Generate time-staggered sinusoids at harmonics of 10Hz""" global n n_samp = len(times) window = np.zeros(n_samp) start, stop = [int(ii * float(n_samp) / (2 * n_dipoles)) for ii in (2 * n, 2 * n + 1)] window[start:stop] = 1. n += 1 data = 1e-7 * ...
edbdf5e059b8f4c3559386497961a1c65133a80b
3,650,024
def var(x, axis=None, ddof=0, keepdims=False): """ Computes the variance along the specified axis. The variance is the average of the squared deviations from the mean, i.e., :math:`var = mean(abs(x - x.mean())**2)`. Returns the variance, which is computed for the flattened array by default, oth...
b39bf29caf4f47882fb3be900c2924a90b25a880
3,650,025
def check_inputs(supplied_inputs): """Check that the inputs are of some correct type and returned as AttributeDict.""" inputs = None if supplied_inputs is None: inputs = AttributeDict() else: if isinstance(supplied_inputs, DataFactory('dict')): inputs = AttributeDict(supplied...
a5369767c23a96b44da2bff2c0ac49456e3452f1
3,650,026
def _parse_none(arg, fn=None): """Parse arguments with support for conversion to None. Args: arg (str): Argument to potentially convert. fn (func): Function to apply to the argument if not converted to None. Returns: Any: Arguments that are "none" or "0" are converted to None; ...
4ebd283eb9e2218e523ba185c4500c9879d5719d
3,650,027
def generate_constraint(category_id, user): """ generate the proper basic data structure to express a constraint based on the category string """ return {'year': category_id}
f55151a5b4b17bbf6eb697e1b1489ee4897f5db0
3,650,028
def get_RIB_IN_capacity(cvg_api, multipath, start_value, step_value, route_type, port_speed,): """ Args: cvg_api (pytest fixture): snappi API temp_tg_port (pytest fixture): Por...
e13c85d9e6ebdbfba84e20a81324da8156e7c934
3,650,029
from typing import List from typing import Set def ladder_length(beginWord: str, endWord: str, wordList: List[str]) -> int: """ 双端交替迫近目标层,根据一层数量最多节点确定为目标层 :param beginWord: :param endWord: :param wordList: :return: >>> ladder_length('hit', 'cog', ["hot","dot","dog","lot","log","cog"]) ...
020f3ffd2e009b682a47ff9aad8d1d6025c29f37
3,650,031
def setup_option(request): """Создаем объект для удобство работы с переменными в тестовых методах """ setup_parameters = {} if request.config.getoption('--site_url'): setup_parameters['site_url'] = request.config.getoption('--site_url') return setup_parameters
49908ee8e1422cc4fd05c6d93a96c00d734cf6d1
3,650,032
import time import torch def train_one_epoch(img_input,model,optimizer,writer,epoch,args): """ Finish 1.train for one epoch 2.print process, total loss, data time in terminal 3.save loss, lr, output img in tensorboard Note 1.you can change the save frequency """ loss_train = 0...
b26e2933dd3575e45c33ba6bf801f5a92fc72ab7
3,650,033
def get_unique_tokens(texts): """ Returns a set of unique tokens. >>> get_unique_tokens(['oeffentl', 'ist', 'oeffentl']) {'oeffentl', 'ist'} """ unique_tokens = set() for text in texts: for token in text: unique_tokens.add(token) return unique_tokens
f9c174b264082b65a328fd9edf9421e7ff7808a2
3,650,034
def _symmetric_difference(provided: dict, chosen: dict) -> dict: """ Returns the fields that are not in common between provided and chosen JSON schema. :param provided: the JSON schema to removed the chosen schema from. :param chosen: the JSON schema to remove from the provided schema. :return: a J...
5900c6de35c0665ab2c0ec10c4df4dc87b75483a
3,650,035
def moved_in(nn_orig, nn_proj, i, k): """Determine points that are neighbours in the projection space, but were not neighbours in the original space. nn_orig neighbourhood matrix for original data nn_proj neighbourhood matrix for projection data i index of the point considered ...
b63a9b0f53554032fc920aeaf6d3d76b93dd8ab3
3,650,037
import re def _get_lines_changed(line_summary): """ Parse the line diff summary into a list of numbers representing line numbers added or changed :param line_summary: the summary from a git diff of lines that have changed (ex: @@ -1,40 +1,23 @@) :return: a list of integers indicating which lines chang...
01d1b51ef480a0d7dcdc916fe68aac08ce81d23f
3,650,038
def tj_agri_sup(): """ Real Name: b'Tj Agri Sup' Original Eqn: b'MIN(Tj Agri Dem *Agri Tajan Dam Coef, (Tj Outflow-Tj Dom Sup-Tj Env Sup-Tj Ind Sup))' Units: b'' Limits: (None, None) Type: component b'' """ return np.minimum(tj_agri_dem() * agri_tajan_dam_coef(), ...
07c6029dc062f20756b3f72289640a29526c41bf
3,650,039
def correlation_coefficient(y_true, y_pred): """The CC, is the Pearson’s correlation coefficient and treats the saliency and ground truth density maps, as random variables measuring the linear relationship between them.Values are first divided by their sum for each image to yield a distribution...
9d0f7825219a5957edfbf464ca9b62182b81bb3c
3,650,040
def init_args(): """Init command line args used for configuration.""" parser = init_main_args() return parser.parse_args()
c2939b8d6fbefa7a6b792d13c98a805a3e53785f
3,650,041
import warnings def _fit_binary(estimator, X, y, classes=None, **kwargs): """Fit a single binary estimator with kwargs.""" unique_y = np.unique(y) if len(unique_y) == 1: if classes is not None: if y[0] == -1: c = 0 else: c = y[0] ...
24e37aa50cada6cce4ab52c1be85cace3ad4c417
3,650,042
import csv def data_index(person, dim): """ Output sequence of eye gaze (x, y) positions from the dataset for a person and a dimension of that person (task, session, etc) Index starts at 0. The vectors are [x, y, flag], flag being if it's null """ session = "S1" if dim % 2 == 0 else "S2" #...
e8b37aaeb2c228f0749aece26609fb04e0d4a226
3,650,043
def getStatic(): """ These are "static" params for a smoother application flow and fine tuning of some params Not all functions are implemented yet Returns the necessary Params to run this application """ VISU_PAR = { # ============================================================================...
f82ed9c4156b8199be924fc1ed62398fcbad9e0c
3,650,044
def current_device(): """Return the index of the current active device. Returns ------- int The index of device. """ return dragon.cuda.GetDevice()
453b81673e198ddd3a5870843d16b9cc395802d4
3,650,045
import time async def access_logger(app, handler): """Simple logging middleware to report info about each request/response. """ async def logging_handler(request): start_time = time.time() request_name = hex(int(start_time * 10000))[-6:] client_ip, _ = request.transport.get_extra_i...
55d4ac318a65d6f4256467f7909b5a6ee2115a6d
3,650,046
from typing import Tuple def main(source: str) -> Tuple[astroid.Module, TypeInferer]: """Parse a string representing source text, and perform a typecheck. Return the astroid Module node (with the type_constraints attribute set on all nodes in the tree) and TypeInferer object. """ module = astroid...
f8e9b9a0ac9ff4334cce9ca7c888d3ff11570661
3,650,047
def to_literal_scalar(a_str): """Helper function to enforce literal scalar block (ruamel.yaml).""" return ruamel.yaml.scalarstring.LiteralScalarString(a_str)
7cdb3d37bad184b7c6e68b374d1b6fd7e4c744c4
3,650,048
from typing import Optional def get_first_free_address(subnet_id: Optional[int] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetFirstFreeAddressResult: """ Use this data source to access information about an existing resource. """ __args__ = dict() __...
ea4a599a7f3ac65e296cce4c8fc3a764202bba26
3,650,049
def pagenav(object_list, base_url, order_by, reverse, cur_month, is_paginated, paginator): """Display page navigation for given list of objects""" return {'object_list': object_list, 'base_url': base_url, 'order_by': order_by, 'reverse': reverse, 'cur_month': cur_...
eb61fb76dd32b8d0b3e264e77ce912766d3e38da
3,650,050
def read_input(path: str): """ Read game board file from path. Return list of str. >>> read_input("skyscrapers1.txt") ['***21**', '412453*', '423145*', '*543215', '*35214*', '*41532*', '*2*1***'] """ with open(path, 'r') as f: game_lst = f.readlines() for idx, line in enumerate(...
a4bf08525ca3fe4b0b1efab1901830b4d7c45f05
3,650,051
def run_tweeter(): """ Captures image and sends tweet """ capture_image_and_tweet() return schedule.CancelJob
2cf3895270e5f5f64ecb2e943548f0a290c35b02
3,650,052
import time from functools import reduce from operator import add def get_retro_results( outdir, recos_basedir, events_basedir, recompute_estimate=False, overwrite=False, ): """Extract all rectro reco results from a reco directory tree, merging with original event information from correspo...
e3753b86ed4efa60057f1e3a0c70c34193447718
3,650,053
import copy def split_surface_v(obj, t, **kwargs): """ Splits the surface at the input parametric coordinate on the v-direction. This method splits the surface into two pieces at the given parametric coordinate on the v-direction, generates two different surface objects and returns them. It does not modi...
6603fb5e4c45fa60817168d776ac005475bd37a5
3,650,054
from typing import OrderedDict def oidc_userprofile_test(request): """ OIDC-style userinfo """ user = request.user profile, g_o_c = UserProfile.objects.get_or_create(user=user) data = OrderedDict() data['sub'] = user.username data['name'] = "%s %s" % (user.first_name, user.last_name) ...
aeae1962615ac9894b1b555814851c33efa85b45
3,650,055
def split_idx( idx,a,b): """ Shuffle and split a list of indexes into training and test data with a fixed random seed for reproducibility run: index of the current split (zero based) nruns: number of splits (> run) idx: list of indices to split """ rs = np.random.RandomState() rs.sh...
e5c9850a0bbcdb187d12dff4cd9df6c9faddfacc
3,650,056
def scale(val, src, dst): """ Scale the given value from the scale of src to the scale of dst. val: float or int src: tuple dst: tuple example: print(scale(99, (0.0, 99.0), (-1.0, +1.0))) """ return (float(val - src[0]) / (src[1] - src[0])) * (dst[1] - dst[0]) + dst[0]
26cfaccaeea861ccecb36697838710c0ab706520
3,650,057
def add(c1, c2): """Add two encrypted counters""" a1, b1 = c1 a2, b2 = c2 return (a1 + a2, b1 + b2)
d3e519524fac558622f692a46ffb8fed9899176f
3,650,058
async def wait_all_tasks_blocked(cushion=0.0): """Block until there are no runnable tasks. This is useful in testing code when you want to give other tasks a chance to "settle down". The calling task is blocked, and doesn't wake up until all other tasks are also blocked for at least ``cushi...
35b144f4a214cb1f02bb1448f78a54ed93ac66aa
3,650,059
def get_chisq_grid(data, type, forecast=False, errors=None): """ Generates 2d meshgrid for chisq values of a given type (i.e. BBN, CMB etc) """ masses = np.unique(data['mass']) omegabs = np.unique(data['OmegaB']) MASS, OMEGAB = np.meshgrid(masses, omegabs) OMEGABDAT = data['OmegaB'].reshape(...
3ea6fcf16d6c506733f5164e8808c5d5dce6c969
3,650,060
import ctypes def spectrl2(units, location, datetime, weather, orientation, atmospheric_conditions, albedo): """ Calculate solar spectrum by calling functions exported by :data:`SPECTRL2DLL`. :param units: set ``units`` = 1 for W/m\ :sup:`2`/micron :type units: int :param locatio...
aa8bd3878bc3f230d89e1d9545621a43e2d2fa6c
3,650,062
def setup_transition_list(): """ Creates and returns a list of Transition() objects to represent state transitions for an unbiased random walk. Parameters ---------- (none) Returns ------- xn_list : list of Transition objects List of objects that encode information about th...
702c7a7083546797578e5463841c7b59548dcca2
3,650,063
def error_message(error, text): """ Gives default or custom text for the error. -------------------- Inputs <datatype>: - error <Error Object>: The error code - text <string>: Custom error text if error has no message Returns <datatype>: - error description <string>: The cust...
466fec2d2abefc9f05a3f0adf569fba1c63ea4c1
3,650,064
def maskguard(maskarray, niter=1, xyonly=False, vonly=False): """ Pad a mask by specified number of pixels in all three dimensions. Parameters ---------- maskarray : `~numpy.ndarray` The 3-D mask array with 1s for valid pixels and 0s otherwise. niter : int, optional Number of i...
098964878e313b08c73f1a3c1a66a2b7f1664090
3,650,065
def validdest(repo, old, new): """Is the new bookmark destination a valid update from the old one""" repo = repo.unfiltered() if old == new: # Old == new -> nothing to update. return False elif not old: # old is nullrev, anything is valid. # (new != nullrev has been exclu...
8206b1ec130582864979ea9fb617c60b6175deff
3,650,066
def no_rbac_suffix_in_test_filename(filename): """Check that RBAC filenames end with "_rbac" suffix. P101 """ if "patrole_tempest_plugin/tests/api" in filename: if filename.endswith('rbac_base.py'): return if not filename.endswith('_rbac.py'): return 0, "RBAC t...
6ebfcede8b6e30f24f5ecc1f9d3f0985bd4c44fa
3,650,067
def import_results(results_file, valid_codes=None, session=None): """Take a iterable which yields result lines and add them to the database. If session is None, the global db.session is used. If valid_codes is non-None, it is a set containing the party codes which are allowed in this database. If None,...
e7faea1b78418b6fdb599612fdc72fe20fe45bc6
3,650,068
def fit_lens_data_with_tracer(lens_data, tracer, padded_tracer=None): """Fit lens data with a model tracer, automatically determining the type of fit based on the \ properties of the galaxies in the tracer. Parameters ----------- lens_data : lens_data.LensData or lens_data.LensDataHyper The...
c94454462e4e9fd770eebf39a9574daa0e6a9025
3,650,069
def sround(a, *ndigits): """Termwise round(a) for an iterable. An optional second argument is supported, and passed through to the built-in ``round`` function. As with the built-in, rounding is correct taking into account the float representation, which is base-2. https://docs.python.org/...
ee75d82fa3bdfb50afb279cce87d6d6ec6120adf
3,650,070
def part_b(lines): """ For each valid line consider the stack of opening characters that didn't get closed. Compute a score for each line per the question, then return the median value of these scores. """ scores = [] for line in lines: is_line_valid, stack = assess_line(line) if is_...
e745a3be40f5a83f0e8ce3de4c647bd5984e7511
3,650,071
def _get_activation( spec): """Get a rematlib Layer corresponding to a given activation function.""" if spec == mobile_search_space_v3.RELU: result = layers.ReLU() elif spec == mobile_search_space_v3.RELU6: result = layers.ReLU6() elif spec == mobile_search_space_v3.SWISH6: result = layers.Swish...
d2e67564eb366128b6dfe9f0c1c919ceb0e949ac
3,650,072
def RT2tq(poses, square=False): """ !!NOT TESETED!! :param poses: N x 3 x 4, (R|T) :return: (N, 7) """ N,_,_ = poses.shape R = poses[:,:,:3] T = poses[:,:,3:] # Nx3x1 q = quaternion.as_float_array(quaternion.from_rotation_matrix(R)) #Nx4 t= T.squeeze(-1) tq = np.concatena...
5241aa7110df8074fe203b1cbe33cb7bf509c2f3
3,650,074
import json def make_callback(subscription_path, project_id): """Return a callback closure""" def callback(message): """Handle Pub/Sub resurrection message. Ignore (and ACK) messages that are not well-formed. Try handle any other message, ACKing it eventually (always). """ logger.info('Handl...
ac16d67ee9e7b89d69b79702e4121b1983df2bb8
3,650,075
def data_to_bytes(data, encoding): """\ Converts the provided data into bytes. If the data is already a byte sequence, it will be left unchanged. This function tries to use the provided `encoding` (if not ``None``) or the default encoding (ISO/IEC 8859-1). It uses UTF-8 as fallback. Returns th...
78d0813075c24d2a85412648fa45d720227ae853
3,650,077
def get_session_store(state: State = Depends(get_app_state)) -> SessionStore: """Get a singleton SessionStore to keep track of created sessions.""" session_store = getattr(state, _SESSION_STORE_KEY, None) if session_store is None: session_store = SessionStore() setattr(state, _SESSION_STORE...
4204371079babbfdc15327bb62b3c1c306e27f39
3,650,078
def extractCurrentlyTLingBuniMi(item): """ """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol or frag) or 'preview' in item['title'].lower(): return None if item['title'].startswith('[BNM]'): return buildReleaseMessageWithType(item, 'Bu ni Mi wo Sasagete Hyaku to ...
9b91a6a2329cb4e2572f181b16ddc6b2f0fb3553
3,650,080
from dif import dif_stats def dif_stats(filename, # [<'my/file.txt',...> => name of scored data file] student_id = 'Student_ID', # [<'Student_ID', ...> => student id column label] group = ['Sex', {'focal':0, 'ref':1}], # [<e.g.'Sex', {'focal':'female', 'ref':'male'}]> => column label...
0ed6b94e63d5eacc40aeaf4f2181012ef8aacc22
3,650,081
def delete_all_devices_for_user(): """ delete all active devices for the given user """ try: username = get_jwt_identity() with session_scope() as session: user = user_service.get_user(username, session) device_count = user.devices.count() if device_...
2ac4c0f40e72dc54ca78a109ead9d09f15481b92
3,650,082
def _GetNormalizationTuple(url): """Parse a URL into a components tuple. Parse a URL into 6 components: <scheme>://<netloc>/<path>;<params>?<query>#<fragment> Args: url:A URL string. Returns: A 6-tuple: (scheme, netloc, path, params, query, fragment). """ url = encoding_util.EncodeToAscii(url) ...
cbc8dad95202a9a17f75dac754b6ec00e3efcdfd
3,650,083
def gCallback(dataset, geneid, colors): """Callback to set initial value of green slider from dict. Positional arguments: dataset -- Currently selected dataset. geneid -- Not needed, only to register input. colors -- Dictionary containing the color values. """ colorsDict = colors try: ...
5a97fd16ea362b3b53f33f52a449c4dccc617e44
3,650,084
def intForcesMoments(sliceZnes,method, direction): """ Loops over the sliceZnes and performs an integration of Forces and moments for each slice (Scalar integrals, variables are depending on the method). Returns a ([dir, dirNormalized,fxNr,fyNr,fzNr,mxNr,myNr,mzNr]*Nslices array) """ #direction...
16e0a3adc3a3b171fd02b07f241ed8623b16c7e3
3,650,085
from typing import List def _other_members(other_members: List[parser.MemberInfo], title: str): """Returns "other_members" rendered to markdown. `other_members` is used for anything that is not a class, function, module, or method. Args: other_members: A list of `MemberInfo` objects. title: Title of...
77c02e8532dd01bab0b9ea0f9d14634dc3523cd2
3,650,086
def full_url(parser, token): """Spits out the full URL""" url_node = url(parser, token) f = url_node.render url_node.render = lambda context: _get_host_from_context(context) + f(context) return url_node
d54e9cf5acee1b6283f3166e9479e8c9e8bb5047
3,650,087
def Chi2CoupleDiffFunc(nzbins, nzcorrs, ntheta, mask, data1, xi_obs_1, xi_theo_1, data2, xi_obs_2, xi_theo_2, inDir_cov12, file_name_cov12): """ Estimate chi^2 for difference between two data vectors Note: this assumes two data vectors ...
c0cd8a683447b0572a93914e633fb8f770c3a6fd
3,650,088
def minimax(just_mapping, mapping): """ Scale the mapping to minimize the maximum error from just intonation. """ least_error = float("inf") best_mapping = mapping for i in range(len(just_mapping)): for j in range(i+1, len(just_mapping)): candidate = mapping / (mapping[i] + m...
b2226de7a916e3075327cd30c64e7412e186027d
3,650,089
from datetime import datetime def app_used_today(): """Check the session and the backend database for a record of app use from the last 24 hours.""" now = UTC.localize(datetime.datetime.utcnow()) last_app_use = get_last_app_use_date() day_length_in_seconds = 60 * 60 * 24 if last_app_use and (last_...
290bb4b87e74f5134effeb37da36cedcca05c4aa
3,650,090