content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Set from typing import Tuple from typing import cast from typing import List from typing import Dict from typing import Any def _validate_dialogue_section( protocol_specification: ProtocolSpecification, performatives_set: Set[str] ) -> Tuple[bool, str]: """ Evaluate whether the dialogue...
a9155544cae98723bb629d40ae24275c483c807a
3,629,062
def _hsic_naive(x, y, scale=False, sigma_x=None, sigma_y=None, kernel='gaussian', dof=0): """ Naive (slow) implementation of HSIC (Hilbert-Schmidt Independence Criterion). This function is only used to assert correct results of the faster method ``hsic``. Parameters ---------- ...
03ff899048ce740873cd32fc64ba4ce517e8cd5a
3,629,063
def get_percentage(numerator, denominator, precision = 2): """ Return a percentage value with the specified precision. """ return round(float(numerator) / float(denominator) * 100, precision)
7104f6bf2d88f9081913ec3fbae596254cdcc878
3,629,065
def _calculate_verification_code(hash: bytes) -> int: """ Verification code is a 4-digit number used in mobile authentication and mobile signing linked with the hash value to be signed. See https://github.com/SK-EID/MID#241-verification-code-calculation-algorithm """ return ((0xFC & hash[0]) << 5) |...
173f9653f9914672160fb263a04fff7130ddf687
3,629,066
def add_message(user, text, can_dismiss=True): """Add a message to the user's message queue for a variety of purposes. :param user: the instance of `KlaxerUser` to add a message to :param text: the text of the message :param can_dismiss: (optional) whether or not the message can be dismissed :retur...
f0deff8ed230716b88ed9876a06509f04c1cbfbf
3,629,067
def dataQC(json_data): """ perform quality analysis on data """ bad_data = {} for device in json_data.keys(): for item in json_data[device]: if item[1] <= check_lower * abs_std[0+omit_lower]: if device not in bad_data: bad_data[device] = [] ...
388465f3388f871f7a1bd397c964bff63681fac4
3,629,068
from typing import Union from typing import Tuple from typing import List from typing import Optional def get_interatomic_r(atoms: Union[Tuple[str], List[str]], expand: Optional[float] = None) -> float: """ Calculates bond length between two elements Args: atoms (list or tup...
befa7950d0cd52ba26576c9c5c12589f71604577
3,629,069
def annualized_return_nb(returns, ann_factor): """2-dim version of `annualized_return_1d_nb`.""" result = np.empty(returns.shape[1], dtype=np.float_) for col in range(returns.shape[1]): result[col] = annualized_return_1d_nb(returns[:, col], ann_factor) return result
8e7c3ae47a81b7a700b5714544aabd0d9105f88c
3,629,070
import resource def canon_ref(did: str, ref: str, delimiter: str = None, did_type: str = None): """ Given a reference in a DID document, return it in its canonical form of a URI. Args: did: DID acting as the identifier of the DID document ref: reference to canonicalize, either a DID or a ...
5a0fa42a1a28597ec4863ace221c272ad5114076
3,629,071
def cars_produced_this_year() -> dict: """Get number of cars produced this year.""" return get_metric_of(label='cars_produced_this_year')
96f25b773eaaaaf74bdb9d660830d1ddcff821f5
3,629,072
def merge_authentication_authorities(managed_auth_authority, user_record): """Merge two authentication_authority values, giving precedence to the managed_auth_authority""" existing_auth_authority = get_attribute_for_user( "authentication_authority", user_record) if existing_auth_authority: ...
db5e47be422dbc27d1117040bc3632717112a461
3,629,074
def preprocess_pil_image(pil_img, color_mode='rgb', target_size=None): """Preprocesses the PIL image Arguments img: PIL Image color_mode: One of "grayscale", "rgb", "rgba". Default: "rgb". The desired image format. target_size: Either `None` (default to original size) ...
83cb54157d7bd85299b6bc3149f7f14d9ed52d95
3,629,075
import torch def _handle_coord(c, dtype: torch.dtype, device: torch.device) -> torch.Tensor: """ Helper function for _handle_input. Args: c: Python scalar, torch scalar, or 1D torch tensor Returns: c_vec: 1D torch tensor """ if not torch.is_tensor(c): c = torch.tensor...
129a03900e8047a9c37400568d16316601e25671
3,629,076
import time def current_time_hhmmss(): """ Fetches current time in GMT UTC+0 Returns: (str): Current time in GMT UTC+0 """ return str(time.gmtime().tm_hour) + ":" + str(time.gmtime().tm_min) + ":" + str(time.gmtime().tm_sec)
11a2874237c3fc7d25b93d6f10da167c7d700b33
3,629,077
def equalize_adaptive_clahe(image, ntiles=8, clip_limit=0.01): """Return contrast limited adaptive histogram equalized image. The return value is normalised to the range 0 to 1. :param image: numpy array or :class:`jicimagelib.image.Image` of dtype float :param ntiles: number of tile regions :...
8ecd36bc50e9fd147bee676a92a8ebb1a892c59b
3,629,078
def suggest_parameters_DRE_NMNIST(trial, list_lr, list_bs, list_opt, list_wd, list_multLam, list_order): """ Suggest hyperparameters. Args: trial: A trial object for optuna optimization. list_lr: A list of floats. Candidates of learning rates. list_bs: A list of ints. Candidate...
627855f5fe8fd15d43cc7c8ca3da22b704b5907e
3,629,079
def format_seconds(seconds, hide_seconds=False): """ Returns a human-readable string representation of the given amount of seconds. """ if seconds <= 60: return str(seconds) output = "" for period, period_seconds in ( ('y', 31557600), ('d', 86400), ('h', 3600)...
341ab077b9f83a91e89a4b96cb16410efab90c1c
3,629,080
def _contains_atom(example, atoms, get_atoms_fn): """Returns True if example contains any atom in atoms.""" example_atoms = get_atoms_fn(example) for example_atom in example_atoms: if example_atom in atoms: return True return False
c9e60d956585c185f9fb62cc0d11f169e6b79f88
3,629,081
import torch import math def kllossGn2(o, l: 'xtrue'): """KL loss for Gaussian-mixture output, 2D, precision-matrix parameters.""" dx = o[:,0::6] - l[:,0,np.newaxis] dy = o[:,2::6] - l[:,1,np.newaxis] # precision matrix is positive definite, so has positive diagonal terms Fxx = o[:,1::6]**2 Fyy = o[...
198b6b5189d72171b87e05998d326d006e6d156d
3,629,083
def get_diff_level(files): """Return the lowest hierarchical file parts level at which there are differences among file paths.""" for i, parts in enumerate(zip(*[f.parts for f in files])): if len(set(parts)) > 1: return i
c9c3f774712684c6817c8bb5b3bf9c101e1df8fa
3,629,085
def get_max(list_tuples): """ Returns from a list a tuple which has the highest value as first element. If empty, it returns -2's """ if len(list_tuples) == 0: return (-2, -2, -2, -2) # evaluate the max result found = max(tup[0] for tup in list_tuples) for result in list_tuples:...
91c662d5865de346a1ac73025ced78a996077111
3,629,086
def prepare_observation_lst(observation_lst): """Prepare the observations to satisfy the input fomat of torch [B, S, W, H, C] -> [B, S x C, W, H] batch, stack num, width, height, channel """ # B, S, W, H, C observation_lst = np.array(observation_lst, dtype=np.uint8) observation_lst = np.move...
28a4d190c515b4f6aed882b4a3448e49b93f6b39
3,629,087
def test_problem_builder(name: str, n_of_variables: int = None, n_of_objectives: int = None) -> MOProblem: """Build test problems. Currently supported: ZDT1-4, ZDT6, and DTLZ1-7. Args: name (str): Name of the problem in all caps. For example: "ZDT1", "DTLZ4", etc. n_of_variables (int, optional)...
e6917dd1edcd711ae1dd6370223b9bfbca252592
3,629,088
def get_coord_y(x, y): """ Function returns the y value of the coordinate :param x: x value of coordinate :param y: y value of coordinate :return: y value of coordinate """ coord = Coordinates(x, y) return coord.get_y()
ba844806a430130e20cfd320865b78f0af09cf25
3,629,089
import numpy def calc_som2_flow(som2c_1, cmix, defac): """Calculate the C that flows from surface SOM2 to soil SOM2. Some C flows from surface SOM2 to soil SOM2 via mixing. This flow is controlled by the parameter cmix. Parameters: som2c_1 (numpy.ndarray): state variable, C in surface SOM2 ...
a90089f65fa2ff8ea681d9f2c3375920e8cda52c
3,629,090
def cdlseparatinglines(opn, high, low, close): """Separating Lines: Bullish Separating Lines Pattern: With just two candles – one black (or red) and one white (or green) – the Bullish Separating Lines pattern is easy to learn and spot. To confirm its presence, seek out the following criteria: F...
37d4a8e1721cc52157b944c2bf0a8db9a8439f52
3,629,091
def get_context(file_in): """Get genomic context from bed file""" output_dict = {} handle = open(file_in,'r') header = handle.readline().rstrip('\n').split('\t') for line in handle: split_line = line.rstrip('\n').split('\t') contig,pos,context = split_line[:3] if context == '...
90975b6eb929c546372fdce0eb449f455e9ffc18
3,629,092
def get_rating_users_total(contest_id: ContestID) -> int: """Return the number of unique users that have rated bungalows in this contest. """ return User.query \ .join(Rating) \ .join(Contestant) \ .filter(Contestant.contest_id == contest_id) \ .distinct() \ .coun...
25b649f32273c208ae3ad163ffd3ec1929eb1d1c
3,629,093
def read_from_file(filename): """ Reads the set of known plaintexts from the given file. """ candidates = [] with open(filename) as f: lines = f.readlines() if len(lines) > 5: # from first candidate, # to the end of the file, # counting in incre...
d7adda3d84ac02bf2d8095a42dae20b66ca4d4f0
3,629,094
def galactic_offsets_to_celestial(RA, Dec, glongoff=3, glatoff=0): """ Converts offsets in Galactic coordinates to celestial The defaults were chosen by Pineda for Galactic plane survey @param RA : FK5 right ascension in degrees @type RA : float @param Dec : FK5 declination in degrees @type Dec...
737072bc3d26b91dab93a7cbefafe732eba0b43a
3,629,095
import torch from typing import Tuple from typing import List def compute_regularizer_term(model: LinearNet, criterion: torch.nn.modules.loss.CrossEntropyLoss, train_data: Tuple[torch.Tensor, torch.Tensor], valid_data: Tuple[torch.Tensor, torch.Tensor], ...
9216e938f611d085f3c877bb3d9aeb98aaa6565d
3,629,096
def get_to_and(num_bits: int) -> np.ndarray: """ Overview: Get an np.ndarray with ``num_bits`` elements, each equals to :math:`2^n` (n decreases from num_bits-1 to 0). Used by ``batch_binary_encode`` to make bit-wise `and`. Arguments: - num_bits (:obj:`int`): length of the generating...
0da0d253f8951bf54e9d4c2d9d720813fd99c538
3,629,097
def in_role_list(role_list): """Requires user is associated with any role in the list""" roles = [] for role in role_list: try: role = Role.query.filter_by( name=role).one() roles.append(role) except NoResultFound: raise ValueError("role '{...
82f171601b4e823fdc2ab265bd955272d033936d
3,629,098
def handle_not_start(fsm_ctx): """ :param ctx: FSM Context :return: False """ global plugin_ctx plugin_ctx.error("Could not start this install operation because an install operation is still in progress") return False
dc69de1e2c49ed5cda20fecbf9338081c027ff7b
3,629,099
def make_wc2018_dataset( matches_features: pd.DataFrame, team_features: pd.DataFrame, wc2018_qualified: pd.DataFrame): """ Simulating the Tournament With a trained model at our disposal, we can now run tournament simulations on it. For example, let's take the qualified teams for...
a9c0647bd3a87025cd8413170e3e7208b238822d
3,629,100
from typing import OrderedDict def calcular_indices(arr, clases_posibles): """ Calcula los indices positivos y negativos de un arreglo En la primer posicion de cada elemento se espera la clase real. En la segunda posicion de cada elemento se espera la clase calculada. """ dic = [] for clase in clases_...
3607de8e7fb8b269cc2bf10f7acac50043b68119
3,629,101
def _box_faces(image): """ Add borders to all detected faces """ for face in image.faces: _box_face(image, face) return image
8594856f0b789d280a208e8687858f26dccb4b2b
3,629,103
def get_logger(name, is_task_logger=True): """Return a logger with the given name. The logger will by default be constructed as a task logger. This will ensure it contains additional information on the current task name and task ID, if running in a task. If executed outside of a task, the name name and...
a1a4c079603ac3c9aa288d901ab5271c00b1646a
3,629,104
import warnings def get_stratified_gene_usage_frequency(ts = None, replace = True): """ MODIFIES A TCRsampler instance with esitmates vj_occur_freq_stratified by subject Parameters ---------- ts : tcrsampler.sampler.TCRsampler replace : bool if True, ts.v_occur_freq is set to ts...
002367ea1e97ddbdef8692022cd312de5f27f857
3,629,105
def _calculateSvalues(xarr, yarr, sigma2=1.): """Calculates the intermediate S values required for basic linear regression. See, e.g., Numerical Recipes (Press et al 1992) Section 15.2. """ if len(xarr) != len(yarr): raise ValueError("Input xarr and yarr differ in length!") if len(xarr) <= ...
53a7a1427c232e8cf226b6d80bcd59565803a3e0
3,629,106
import six def remove_nulls_from_dict(d): """ remove_nulls_from_dict function recursively remove empty or null values from dictionary and embedded lists of dictionaries """ if isinstance(d, dict): return {k: remove_nulls_from_dict(v) for k, v in six.iteritems(d) if v} if isinstance(d, ...
dd0da02eae06ceccc1347e6ac87dcb65bdc44126
3,629,108
def frame_processors(configuration, call_types, return_types): """:type configuration: ducktest.config_reader.Configuration""" typer = IdleProcessor() chain( typer, MappingTypeProcessor(typer), ContainerTypeProcessor(typer), PlainTypeProcessor(), ) call_frame_process...
ae56574ca20d91c1e50aaeb46dece0536a650940
3,629,109
def StartAndRunFlow(flow_cls, client_mock=None, client_id=None, check_flow_errors=True, **kwargs): """Builds a test harness (client and worker), starts the flow and runs it. Args: flow_cls: Flow class that will be created and run. ...
fb8aee3f2ede547c7eeea293d950f0383060d925
3,629,112
from typing import Optional def check_dk(base: str, add: Optional[str] = None) -> str: """Check country specific VAT-Id""" weights = (2, 7, 6, 5, 4, 3, 2, 1) s = sum(int(c) * w for (c, w) in zip(base, weights)) r = s % 11 if r == 0: return '' # check ok else: return 'f'
306c5fda13ce30ce0c9ddbd9302347ef0a86d393
3,629,113
import html def generate_sidepanel(spin_system, index): """Generate scrollable side panel listing for spin systems""" # title title = html.B(f"Spin system {index}", className="") # spin system name name = "" if "name" not in spin_system else spin_system["name"] name = html.Div(f"Name: {name}"...
c820638c4e9baf2983b6f20ec7fb71a5e18f417b
3,629,114
def clc_points(points): """ Args: points (np.array|list): OpenCV cv2.boxPoints returns coordinates, order is [right_bottom, left_bottom, left_top, right_top] Returns: list: reorder the coordinates, order is [left_top, right_top, right_bottom, left_bottom] ...
201434fda90698d45126fbc99cd505e5c5096518
3,629,116
def choose_til(*args): """ choose_til() -> bool Choose a type library ( 'ui_choose' , 'chtype_idatil' ). """ return _ida_kernwin.choose_til(*args)
48ffd4ff9b66caf40602e4cf778dfff8240db5cc
3,629,117
def _has_child_providers(context, rp_id): """Returns True if the supplied resource provider has any child providers, False otherwise """ child_sel = sa.select([_RP_TBL.c.id]) child_sel = child_sel.where(_RP_TBL.c.parent_provider_id == rp_id) child_res = context.session.execute(child_sel.limit(1)...
000fad116d01e676577bc51ad3049173eb69987a
3,629,118
import random def is_zero(n, p=.5): """Return the sum of n random (-1, 1) variables divided by n. n: number of numbers to sum p: probability of 1 (probablity of -1 is 1-p) """ # This function should be about zero, but as n increases it gets better numbers = random.choices((-1, 1), weights=(1-...
eae43e784d77cb50e1b0b48f6d32d5085164147d
3,629,119
from typing import Union from typing import Sequence from typing import Tuple from typing import List def reduce_loss( sim_time: Union[float, int], n_steps: int, scene: JaxScene, coordinate_init: Sequence, velocity_init: Sequence, target_coordinate: Sequence, attractor: Sequence, const...
9499b0b2b379ba27c77a8d3c2364aed4f387e10b
3,629,120
def lstm_ortho_initializer(scale=1.0): """LSTM orthogonal initializer.""" def _initializer(shape, dtype=tf.float32, partition_info=None): # pylint: disable=unused-argument size_x = shape[0] size_h = shape[1] // 4 # assumes lstm. t = np.zeros(shape) t[:, :size_h] = orthogonal([si...
3eb9e743c7002878ade487d2d6a9cb0803bfea44
3,629,121
def extract_data(loss_logs, fields, max_x=-1): """Extract numerical logs from loss logs. Arguments: loss_logs: list of text files containing numerical log data generated by autoencoders fields: types of values to plot (each gets its own subplot, e.g. nonzero_mae, loss, p...
ce63d683569bf49447aff32c1bb3aa23f6f164eb
3,629,122
def roc_pr_curves(xaxis, tpr_list, precision_list, model_names, model_colors=None, prc_chance=None, prc_upper_ylim=None, figname=None, legend=True, figax=None, **kwargs): """Make a ROC and PR curve for each model, optionally with a SD. Compute an AUC score for each curve. Parameters -----...
3fa02960e628ab8ed43b8c9c53761e84efea182a
3,629,123
def safe_divide(num, denom): """Divides the two numbers, avoiding ZeroDivisionError. Args: num: numerator denom: demoninator Returns: the quotient, or 0 if the demoninator is 0 """ try: return num / denom except ZeroDivisionError: return 0
144cf6bf8b53ab43f3ab2e16e7dd2c95f5408035
3,629,124
def npSigma11( fitResult, nuisFilter="alpha_" ): """ Returns the block of the covariance matrix that corresponds to the main term. """ cov,pars = npCov( fitResult ) newPars = list( pars ) for i in reversed( range(len(pars)) ): if nuisFilter not in pars[i]: continue cov = np.delete( cov, i, 0 ) cov = np.del...
751a7780b7d4a887a2b86cb9f8d0bfefda86177d
3,629,125
import socket def webpack_dev_url(request): """ If webpack dev server is running, add HMR context processor so template can switch script import to HMR URL """ if not getattr(settings, "WEBPACK_DEV_URL", None): return {} data = {"host": split_domain_port(request._get_raw_host())[0]} ...
9e5146f87d25067b43debc0a75d2f02763502c1e
3,629,126
from typing import Any from typing import AbstractSet import sympy def parameter_symbols(val: Any) -> AbstractSet[sympy.Symbol]: """Returns parameter symbols for this object. Args: val: Object for which to find the parameter symbols. Returns: A set of parameter symbols if the object is p...
d289dc941d93c34f87e6568df83b5d8e7f39f753
3,629,127
import re def datetime(el, default_date=None): """Process dt-* properties Args: el (bs4.element.Tag): Tag containing the dt-value Returns: a tuple (string string): a tuple of two strings, (datetime, date) """ def try_normalize(dtstr, match=None): """Try to normalize a datetim...
38858690a4d77f522eb8d9a6967f75b5d5d7f9cd
3,629,128
def lexicallyRelated(word1, word2): """ Determine whether two words might be lexically related to one another. """ return any(map(lambda stem: stem(word1) == stem(word2), stemmers) ) or word1.startswith(word2) or word2.startswith(word1)
be6df99aee20d0275682e60f8877a3b107dc8579
3,629,129
async def playing_check(ctx: commands.Context): """ Checks whether we are playing audio in VC in this guild. This doubles up as a connection check. """ if await connected_check(ctx) and not ctx.guild.voice_client.is_playing(): raise commands.CheckFailure("The voice client in this guild is ...
480bd5ef0e6b6eef63af3f07307f99805adf73fb
3,629,130
def create_calibrated_rtl(feature_columns, config, quantiles_dir): """Creates a calibrated RTL estimator.""" feature_names = [fc.name for fc in feature_columns] hparams = tfl.CalibratedRtlHParams( feature_names=feature_names, num_keypoints=200, learning_rate=0.02, lattice_l2_laplacian_reg=...
e6a73e66049e47fd8f18272647b5b948b015a004
3,629,131
def route_distance(df, con): """ Given a route's dataframe determine total distance (m) using gid """ dist = 0 cur = con.cursor() for edge in df.edge[0:-1]: query = 'SELECT length_m FROM ways WHERE gid={0}'.format(edge) cur.execute(query) out = cur.fetchone() dis...
ca83cca270a97b60b615f89c83541c0491abddcf
3,629,132
def convert_units(P, In='cm', Out='m'): """ Quickly convert distance units between meters, centimeters and millimeters """ c = {'m':{'mm':1000.,'cm':100.,'m':1.}, 'cm':{'mm':10.,'cm':1.,'m':0.01}, 'mm':{'mm':1.,'cm':0.1,'m':0.001}} return c[In][Out]*P
bc318011ffc71d575c7e7276c2dede467a84dc2c
3,629,133
def _nonmonotone_line_search_cheng(f, x_k, d, f_k, C, Q, eta, gamma=1e-4, tau_min=0.1, tau_max=0.5, nu=0.85): """ Nonmonotone line search from [1] Parameters ---------- f : callable Function returning a tuple ``(f, F)`` w...
a8ccaf00d39848495da9d2cc66014012d57bb146
3,629,134
def course_state_editor(func): """ Decorator for any method that will be used to alter a Course's 'state'. It does a few useful things: 1. Clears any lingering dashboard data for a given course run to ensure that it will be in the right state after the command. 2. Allows the user to specify a...
891cfccd9d4a0da4c80010cd2f7827d040c82e8e
3,629,135
def importDataFromCSV(dataType, filename): """ Import from a `.csv` file into a dataframe or python time/distance matrix dictionary. Parameters ---------- dataType: string, Required The type of data to be imported. Valid options are 'nodes', 'arcs', 'assignments', or 'matrix'. filename: string, Required The...
cc185dd59fbc0a820e6f3fe2262154325e61d915
3,629,136
def main(): """Run the exploit and go interactive.""" args = get_parsed_args() host = args.host port = int(args.port) sock = None t = None try: sock = exploit(host, port) t = Telnet() t.sock = sock print_info('Exploit sent, going interactive!') t.mt_i...
ed9f340f42aadaf25157fee156d16313faf6e553
3,629,137
from typing import Optional def xyz_to_str(xyz_dict: dict, isotope_format: Optional[str] = None, ) -> str: """ Convert an ARC xyz dictionary format, e.g.:: {'symbols': ('C', 'N', 'H', 'H', 'H', 'H'), 'isotopes': (13, 14, 1, 1, 1, 1), 'coords': ((0.66165...
589d1ac44649c9a464c051791a9044830a6aa175
3,629,138
def get_simclr_transform(size, s=1): """Return a set of data augmentation transformations as described in the SimCLR paper.""" color_jitter = transforms.ColorJitter(0.8 * s, 0.8 * s, 0.8 * s, 0.2 * s) normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ...
237de2baa38f4e0e6859c5f66d6364438026b155
3,629,141
import json def dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, indent=None, separators=None, sort_keys=False, core: Core = None, **kw): """ Dumps an object into a Writer with support for HomeControl's data types """ return json.dump(obj, fp, ...
b76016041dfe99b8fa9335974eebacf3ba668dcd
3,629,142
async def get_sender_data(user_id: int) -> dict: """ Sender profile :param user_id: User ID :type user_id: int :return: Sender profile :rtype: dict """ return await get_sender_data_request(user_id)
7ecf5290ed9d19ccd52ba5d31595adcca762eb82
3,629,144
def conditional_input_prediction_2d(x, y_pred, var_1_index, var_2_index, var_1_bins, var_2_bins, dependence_function=np.mean): """ For a given set of 2 input values, calculate a summary statistic based on all of the examples that fall within each binned region of the input data space. The goal is to show ho...
8f34450c9780bba1503d093bef19d808ee4b869e
3,629,145
def fgt_get_pressureUnit(pressure_index, get_error = _get_error): """Get current unit on selected pressure device. Args: pressure_index: Index of pressure channel or unique ID Returns: current unit as a string """ pressure_index = int(pressure_index) low_level_function = low...
dd5b80fbdef7b4644c944c22207b4505082c498d
3,629,147
def _get_rawhide_version(): """ Query Koji to find the rawhide version from the build target. :return: the rawhide version (e.g. "f32") :rtype: str """ koji_session = get_session(conf, login=False) build_target = koji_session.getBuildTarget("rawhide") if build_target: return bui...
c8fbb63f40ca5744563f598b58b998ad4aec2d14
3,629,148
def test_mixed(): """Test positional arguments passed via keyword. """ class TestView(simple.SimpleView): args = ['id'] def __call__(self, foo): return self.request, self.id, foo testview = create_view(TestView) # generally is a possibility... assert testview('reques...
93d9594e91d10a2aa92d7e853057dc84d638efca
3,629,149
def fail_event_on_handler_exception(func): """ Decorator which marks the models.Event associated with handler by BaseHandler.set_context() as FAILED in case the `func` raises an exception. The exception is re-raised by this decorator once its finished. """ @wraps(func) def decorator(han...
07a0b5a24b95470bee29eff545c9676b1438e801
3,629,150
def intensityAdjustment(image, template): """Tune image intensity based on template ---------- images : <numpy.ndarray> image needed to be adjusted template : <numpy.ndarray> Typically we use the middle image from image stack. We want to match the image in...
4e1021c718c80c46d05c276a3c8e4e682a6fa7b5
3,629,151
def Define_core_memesa_model(): """\nOriginal core model + inefficient branch\n""" model_name = 'core_model_1b' Reactions ={'R01' : {'id' : 'R01', 'reversible' : False, 'reagents' : [(-1, 'X0'), (1, 'A')], 'SUBSYSTEM' : ''}, 'R02' : {'id' : 'R02', 'reversible' : True, 'reagents' : ...
7ff51107de0de6ed9ea6a86dc759a54eff4bcfc4
3,629,152
def F16(x): """Rosenbrock function""" sum = 0 for i in range(len(x)-1): sum += 100*(x[i+1]-x[i]**2)**2+(x[i]+1)**2 return sum
7421ad45568a8b86aff41fc5c8466ae6ce7aeb9d
3,629,153
def jaccard_simple(annotation,segmentation): """ Compute region similarity as the Jaccard Index. Arguments: annotation (ndarray): binary annotation map. segmentation (ndarray): binary segmentation map. Return: jaccard (float): region similarity """ annotation = annotatio...
e1defc9cc0dedb812b0880c63c9aa218a6bc93b6
3,629,154
def shuffle_df(df): """ return: pandas.DataFrame | shuffled dataframe params: df: pandas.DataFrame """ return df.reindex(np.random.permutation(df.index))
b609158f62d271f07a8e3b5409f0b28cdc3f83d0
3,629,155
from typing import List def transform_from_sklearn( idx: pd.Index, vars_: List[str], vals: np.array, ) -> pd.DataFrame: """ Add index and column names to sklearn output. :param idx: data index :param vars_: names of feature columns :param vals: features data :return: dataframe wit...
7a37752c7647143f894c13e9a90febe925adbb7f
3,629,156
def from_package_str(item): """Display name space info when it is different, then diagram's or parent's namespace.""" subject = item.subject diagram = item.diagram if not (subject and diagram): return False namespace = subject.namespace parent = item.parent # if there is a par...
ab89c199aa886bff0ec88f6df37a655bb9ee7596
3,629,157
def calculateAverageValue(faceBlob, binaryLabelVolume): """Deprecated.""" total = 0.0 for labeledPoint in faceBlob.points(): total += float(at(binaryLabelVolume, labeledPoint.loc)) return float(total) / float(len(faceBlob.points()))
26f38c24a7b21ec4b54b5476f8af7544f701e209
3,629,159
import numpy def calc_m_inv_m_norm_by_unit_cell_parameters( unit_cell_parameters, flag_unit_cell_parameters: bool = False): """nM matrix.""" a, b = unit_cell_parameters[0], unit_cell_parameters[1] c = unit_cell_parameters[2] alpha, beta = unit_cell_parameters[3], unit_cell_parameters[4] ga...
0c4e1988ccd1ea9d055fbea58119efebac542875
3,629,160
def round(dt, rounding=None): """Round a datetime value using specified rounding method. Args: dt: `datetime` value to be rounded. rounding: `DatetimeRounding` value representing rounding method. """ if rounding is DatetimeRounding.NEAREST_HOUR: return round_to_hour(dt) elif...
3970f4ad47b73c48f134817ff9decf7363dfe906
3,629,163
def testid(prefix='',c=_default_conc, squishy=False,squishz=False,decimate=False,substr=False, subm=_default_subm,subr=_default_subr,subc=_default_subc, subrho=_default_subrho,version=-1): """Creates a standardized string that uniquely identifies a test. Args: prefi...
8383281ee2af3f0422d58f37f88e94288e5324e6
3,629,164
def calc_bearing(lat1, lon1, lat2, lon2): """ Calculate bearing in degrees from (lat1,lon1) towards (lat2, lon2) """ lat1, lon1, lat2, lon2 = map(np.radians, [lat1, lon1, lat2, lon2]) dlon = lon2 - lon1 a = np.arctan2( np.sin(dlon) * np.cos(lat2), np.cos(lat1) * np.sin(lat2) - np...
f2cf545de2460d1e56659d5c9a54011c46ac898c
3,629,165
def Block(data, num_filter, kernel, stride=(1,1), pad=(0,0), eps=1e-3, name=None): """ CNN block""" conv = mx.sym.Convolution(data=data, num_filter=num_filter, stride=stride, kernel=kernel, pad=pad, name='conv_%s' % name) bn = mx.sym.BatchNorm(data=conv, fix_gamma=False, eps=eps, mom...
0ec599725324b8528c3c7dfee4e13b6f4d850764
3,629,166
def flat(x, output_name="flatten"): """ takes a tensor of rank > 2 and return a tensor of shape [?,n]""" shape = x.get_shape().as_list() n = np.prod(shape[1:]) x_flat = tf.reshape(x, [-1, n]) return tf.identity(x_flat, name=output_name)
34c96ce4eb377d8bcbf25411115df11553b14bb7
3,629,167
def connect_to_database(): """ Attempt to connect to sqlite database. Return connection object.""" try: connection = sqlite3.connect('blackjack_terminal') print("DB Connected!") except Exception, e: print e sys.exit(1) return connection
a8df927370e395f08ae22aff0589b87db822220b
3,629,170
def div_up(a, b): """Return the upper bound of a divide operation.""" return (a + b - 1) // b
e297f2d08972ebc667d1f3eadca25ef885ef5453
3,629,171
from datetime import datetime def story_root(story): """story_root() Serves the root page of a story Accessed at '/story/<story' via a GET request """ # Gets the DocumentReference to the story document in Firestore story_ref = db.collection('stories').document(story) # Gets the DocumentS...
e9cc07349368324d6a8859390dc5bcfb7c52d71c
3,629,173
from numscons.core.utils import pkg_to_path def get_scons_pkg_build_dir(pkg): """Return the build directory for the given package (foo.bar). The path is relative to the top setup.py""" return pjoin(get_scons_build_dir(), pkg_to_path(pkg))
6e6e346fdd12f5f595f8c2938ce8fe14ae012716
3,629,174
def oklab_to_linear_srgb(lab): """Convert from Oklab to linear sRGB.""" return util.dot(LMS_TO_SRGBL, [c ** 3 for c in util.dot(OKLAB_TO_LMS3, lab)])
6c0bd205285d9e26c0c6cb27e689b288eee075c0
3,629,175
def rjust(text: str, length: int) -> str: """Like str.rjust() but ignore all ANSI controlling characters.""" return " " * (length - len(strip_ansi(text))) + text
e32de595293837c780f97098ee302ce4ce002117
3,629,176
def solar_elevation_angle(solar_zenith_angle): """Returns Solar Angle in Degrees, with Solar Zenith Angle, solar_zenith_angle.""" solar_elevation_angle = 90 - solar_zenith_angle return solar_elevation_angle
f896c5d0608171f3e5bd37cede1965fe57846d07
3,629,177
def vector3d_to_quaternion(x): """Convert a tensor of 3D vectors to a quaternion. Prepends a 0 to the last dimension, i.e. [[1,2,3]] -> [[0,1,2,3]]. Args: x: A `tf.Tensor` of rank R, the last dimension must be 3. Returns: A `Quaternion` of Rank R with the last dimension being 4. Rais...
2175bd7bf2a7f2cda4bd3d5603dfc04497966d3e
3,629,178
def record_read_permission_factory(record=None): """Pre-configured record read permission factory.""" PermissionPolicy = get_record_permission_policy() return PermissionPolicy(action='read', record=record)
e9cc5829345ad904c619569edd5d0670904faadc
3,629,179
import requests def fetch_66_cookie(): """ 获取 cookies :return: """ cookie_url = 'http://www.66ip.cn/' headers = { "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3", "Accept-Encoding": "gzip, deflat...
55225b4b132b16a7b97615c78f46034fac8cb0bb
3,629,180