content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def showCatalog(): """This showCatalog handler will diplay the home page for both a user not logged in and one for a logged in user. """ categories = session.query(Category).order_by(asc(Category.name)) # Limit the query to a maximum of 10 and order by the most recent # items added, which is id...
e2a50c7478536fe573b6f7860e0976de3a832692
3,633,331
def is_fill_compute_seq(seq): """Test whether *seq* can be converted to a FillComputeSeq. True only if it is a FillCompute element or contains at least one such, and it is not a Source sequence. """ if is_source(seq): return False is_fcseq = False try: is_fcseq = any(map...
f6cca52b2ed7065ae950eca48071120c83a735bc
3,633,332
def upload_model(uploadfile, name=None): # noqa: E501 """upload_model # noqa: E501 :param uploadfile: The model YAML file to upload. Can be a GZip-compressed TAR file (.tgz, .tar.gz) or a YAML file (.yaml, .yml). Maximum size is 32MB. :type uploadfile: werkzeug.datastructures.FileStorage :param ...
95a759bc6d5cc806a8a8df1945816275784ab132
3,633,333
from mpl_toolkits.mplot3d import Axes3D import mcubes def visual_callback_3d(fig=None, plot_each=1): """ Returns a callback than can be passed as the argument `iter_callback` of `morphological_geodesic_active_contour` and `morphological_chan_vese` for visualizing the evolution of the levelsets. On...
1f69691a983f9afabbe53e761e95138a1aa64e40
3,633,334
def _erfint(x): """ Integral of the error function. Parameters ---------- x : float or array Argument. Returns ------- float or array Integral of the error function. """ return x * erf(x) - 1.0/np.sqrt(np.pi) * (1.0-np.exp(-x**2))
e397f62fb35caf5d71eaebd3eb9dc8ce0ba5c9d5
3,633,335
from typing import Optional from typing import Union def zeros(shape: Optional[Union[int, tuple, list]] = None) -> 'ArrayInterval': """ Instantiate an `ArrayInterval` filled with zeros. Note: The difference from numpy is that the argument shape is optional. When shape is None, some operations a...
2d6348e327798b3019c6fd2d42827c64660cad02
3,633,337
def anova_total_mean_square(Ns, means, sigmas): """ This function performs an average over multiple sets of observations, each with its own standard deviation. For example: 5 simulations compute RMSDs+-Sigma of the same protein. What is the aggregate? See: http://www.burtonsys.com/climate/composite_stan...
b3cc0aa7fd66521f6692bd10c66b1e7b00e59566
3,633,338
def compute_lsb(n_bits, fsr_min, fsr_max, half_bit=None): """ Computes the least significant bit (LSB) magnitude in the stage MDAC and sub-ADC to achieve a desired full scale range (FSR). The input FSR and output FSR are assumed to be the same so only one value is returned. :param n_bits: Number of...
03520c71de04e654841c47c40a109431d315163d
3,633,339
def proximity_matrix(rf, X, normalize=True): """ Calculate proximity matrix :param rf: :param X: :param normalize: :return: """ leaves = rf.apply(X) n_trees = leaves.shape[1] prox_mat = np.zeros((leaves.shape[0], leaves.shape[0])) for i in range(n_trees): a = leaves...
781c08f242e52afa7430761124a344456c0efec1
3,633,340
def upload_to_s3_v2(local_path: str, bucket_name: str, object_name: str): """ path_output: local dir file path bucket_name: name of s3 bucket key_path: key path + file name = object name """ s3 = boto3.client("s3") response = s3.upload_file(local_path, bucket_name, object_name) return re...
844b1c07daeb44f49e1071516da0802d843d4790
3,633,341
def marks(category, mark=None, category_marks=None, public=False): """Assign marks to a test or suite of tests, grouped by a category.""" def decorator(test_item): if mark is None and category_marks is None: raise ValueError("One of mark or category_marks must be defined") test_item...
2d47a8df4f610dbc081dd57fce169e2f89b88ca4
3,633,342
import secrets def get_random_ua(): """return a random user-agent string from file""" # stop condition, file does not exists, not readable... # + file operation with open('headers.txt') as hbuffer: all = hbuffer.readlines() return secrets.choice(all).strip()
0d6a924c07bbad2398966bed590bf3307f5c475d
3,633,343
def is_nondecreasing(arr): """ Returns true if the sequence is non-decreasing. """ return all([x <= y for x, y in zip(arr, arr[1:])])
593ac54669ef217e258380bf41ce067935ee53f0
3,633,344
def underscore_to_camelcase(value): """ Converts underscore notation (something_named_this) to camelcase notation (somethingNamedThis) >>> underscore_to_camelcase('country_code') 'countryCode' >>> underscore_to_camelcase('country') 'country' >>> underscore_to_camelcase('price_GBP') 'pri...
94bb5c007d3b50112c62ca9b3e97c5bf4f155fff
3,633,345
def findCenter(S): """Find the approximate center atom of a structure. The center of the structure is the atom closest to (0.5, 0.5, 0.5) Returns the index of the atom. """ best = -1 bestd = len(S) center = [0.5, 0.5, 0.5] # the cannonical center for i in range(len(S)): d = S....
634945a5560b3791f3835f3da090decd1b06b933
3,633,346
def add_noise(rots, level): """adds random noise to a rotation matrix.""" noised_rots = [[np.random.uniform(-level,level,4)]*23]*rots.shape[0] noised_rots = Quaternions(np.array(noised_rots)) return rots+noised_rots
8886f11b90a2d0098b4776100ee9834d433012fb
3,633,347
def content_tree_update(request): """Returns all content of a given contenttree.""" assert request.contenttree.patched, "contenttree should be patched here..." # SANITIZE JSON DATA jsoncontent = request.json_body['content'] data = remove_unvalidated_fields(jsoncontent, peerreview_update_schema) ...
dcfc1932aa9fec431e138f205a143b792b6130f7
3,633,348
def compute_overlap_region(db_ref, db_new): """ Computes the overlapping/shared region between two images. Outputs: - Corner coordinates of the overlapping region in the SRS - Corresponding pixel indexes in both input images """ cornerCoord_ref = gdal.Info(db_ref, format='json')['co...
664f1825c75c0b33d0b0c5ba4686d132790ad363
3,633,349
from typing import List import math def _calculate_team_size_score( projects: List[dict], assignments: List[AssignmentTuple], project: dict, student: dict ) -> int: """Calculates the weighted score based on how far away from the average team size this project would be after assigning the student A...
47fcb0ea3feb637b558e6df10abd0aa993dbf965
3,633,350
import string def encode(data): """ Encodes a string to the 'cstring' encoding supported by the replay DTD. Args: data: string value to be encoded Returns: String containing the encoded value Raises: None """ chars = string.letters + string.digits + " ?!:." retur...
9fc3482c53eed42678aa3c7cbbf915c85b28cc68
3,633,351
import types from typing import Dict from typing import Any from typing import List def gen_frame_symbol( data: types.PulseInstruction, formatter: Dict[str, Any], device: device_info.DrawerBackendInfo ) -> List[drawings.TextData]: """Generate a frame change symbol with instruction meta data from provided fram...
8b38222cd294f42eb58dfcc36b10361ce7869a81
3,633,352
def leanlauncher_download_version(version=LATEST_VERSION, path=DEFAULT_INSTALL_PATH): """ Installs the specified version of Minecraft to the specified path Parameters: version (str): the version of Minecraft to be installed, by default the latest path (str): the path to install Minecraft to, by default ~...
35193ec3ca5d1ad1b23b84d35fec002997bb948e
3,633,353
def Weierstrass_Enneper(f, g, z, imag_unit=1j): """ Compute the Weierstrass Enneper parametrization for given 'Weierstrass data'. :param sympy expression f: h'/g, with h the height function :param sympy expression g: Gauss map. :param sympy variable z: Complex variable. :param imag_unit: Represe...
a47648e52600fd5fff37fb0ee7477b67c587ad0b
3,633,354
def human_size(size_bytes): """ format a size in bytes into a 'human' file size, e.g. B, KB, MB, GB, TB, PB Note that bytes will be reported in whole numbers but KB and above will have greater precision. e.g. 43 B, 443 KB, 4.3 MB, 4.43 GB, etc """ suffixes_table = [('B', 0), ('KB', 1), ('MB', ...
d3489ee85c419711d82e35003426ef2915143c17
3,633,356
def html_color_to_rgba(html_colour, alpha): """ :param html_colour: Colour string like FF0088 :param alpha: Alpha value (opacity) :return: RGBA semitransparent version of colour for use in css """ html_colour = html_colour.upper() if html_colour[0] == '#': html_colour = html_colour[1...
4f28938aa89d62198cc3052a480e0e0744560a79
3,633,357
from typing import OrderedDict def _assign_category_colors(uses, cmap, use_colors=None, assigned_colors=None): """Set a dictionary of nice colors for the use blocks. Options allow specifing pre-defined elements for some categories.""" use_colors = OrderedDict() if use_colors is None else use_colors a...
085d0ca707990c84cd51464ee8f65f90500b7060
3,633,358
def GetClientContext(client_id, token): """Get context for the given client id. Get platform, os release, and arch contexts for the client. Args: client_id: The client_id of the host to use. token: Token to use for access. Returns: array of client_context strings """ client_context = [] clie...
3ecddfeb58e99d06951aab4fe359bc1291b43a2a
3,633,359
import math def calculate_slope_intercept(line): """ Calculating slope nd intercept for a line """ for x1, y1, x2, y2 in line: if x2-x1 == 0: return math.inf, 0 slope = (y2-y1)/(x2-x1) intercept = y1 - slope * x1 return slope, intercept
e21ff81a36cef7a995a98f7adf0302e8397a8139
3,633,360
def get_welcome_response(): """ If we wanted to initialize the session to have some attributes we could add those here """ session_attributes = {} card_title = "Welcome" speech_output = "I'm the Magic Conch Shell. Ask me a question" # If the user either does not reply to the welcome messag...
8a900efd3ef7129c1a9ff408e49591945dad83a1
3,633,361
from typing import Optional def rmcgs(A: np.ndarray, m: Optional[int] = None, r: Optional[int] = None) -> np.ndarray: """ Compute the product: B <- G * S * A where G has size m * r and elements from the standard normal distribution, rescaled by 1/sqrt(m), and S is a CountSketch of size r * n. The matrix ...
25325d1b2c75a07468fdce63fb5481da99c93105
3,633,362
def start_multi_svf(): """ This is function for satrt multi SVF GUI :return: result, details """ app.logger.info("Try to start multi SVF GUI for test") cli_rest_port_list = [] svf_num = int(request.form.get("svf_num")) try: cli_rest_port_list = StartMultiSvf(svf_num=svf_num, log...
1dd3585e5fcfa96d225645d382ee5ab064bc4073
3,633,363
import glob def get_files_by_pattern(root, pattern='a/b/*.ext', strip_root=False): """Optionally to only return matched sub paths.""" # Get the abspath of each directory images. ret = glob.glob(osp.join(root, pattern)) # exclude the root str, so the ret is spec['patterns']. such as ['images/train/*.jp...
905e4c4d08d228074a8036cdf5511f9eb7330f8c
3,633,364
import torch def gumbel_softmax(logits, temperature=1, hard=False): """ ST-gumple-softmax input: [*, n_class] return: flatten --> [*, n_class] an one-hot vector """ y = gumbel_softmax_sample(logits, temperature) if not hard: return y shape = y.size() _, ind = y.max(dim=-1...
4ce2b64115c4a4ce87677aa99e0422c00524c5d3
3,633,365
def _load_augmentation_aug_all(): """ Load image augmentation model """ def sometimes(aug): return iaa.Sometimes(0.5, aug) return iaa.Sequential( [ # apply the following augmenters to most images iaa.Fliplr(0.5), # horizontally flip 50% of all images ia...
e39a08f0166d8a6a379427a895b196891bf70fe1
3,633,366
import logging import traceback def zk_get_mq_servers(zookeeper_servers, logger = logging.getLogger(__name__)): """ Get list of mq servers from zookeeper :param zookeeper_servers: list of zookeeper servers :param logger: logger to use :return: list of mq servers or None """ mq_servers = No...
2201ac305ea1b44fe8baa0582bfc84bf39472dbe
3,633,367
from datetime import datetime def _make_todays_date() -> str: """ build today's date as a standard format """ return datetime.now().strftime("%a %d-%b")
fdb9bc420689081586ac19fe91a17ea871576d59
3,633,369
import re def add_review_suggestion_flags(df, text_col, result_col='result_binary'): """ attempt to add on some logical "manual review suggested" flags onto cases to reduce false positive/negative classifications. currently flags cases w...
e2083d65f54b82dd9eba19b6b2d32806e2cd086d
3,633,370
def create3DMatrix(data, trialTable, events, trialList, trialDur, fs, normalize, baselineDur=0.1): """ """ trials = trialTable.copy() trials = trials[trials['trialNum'].isin(trialList)] totalTrialNum = np.max(trials['trialNum']) m = trials.shape[0] print m, totalTrialNum electrodeNumber...
1627f506a03bb7f07c30c6c70581ac40bd64d7fc
3,633,371
def followed_list(username): """关注列表 """ current_user = models.get_current_user() user = models.get_user(username=username) page = request.args.get('page', 1, type=int) followed_list = user.followed.paginate(page, error_out=False) user_list = [i.followed for i in followed_list.items] ret...
5634ce5e7fc6b344f7ad2b3461e9f294cee225d3
3,633,372
def add_edge_degree(graph, k=3): """ Add k edges to defend based on top edge degree centrality entries :cite:`tong2012gelling`. :param graph: an undirected NetworkX graph :param k: number of edges to add :return: a list of edges to add """ info = defaultdict(list) info['added'] = get_c...
eded75ffc4eabe155124fe95023694df367f3d01
3,633,373
def number_of_fishers(): """ Prompt the user for the number of fishermen entering the draw.""" try: number = int(input("How many fishermen will enter the competition: ")) return number except ValueError: print("Please enter an integer for the number of competing fishermen")
bd3ff25865d67851c8a1742a8cfa808a317716f0
3,633,374
def plot_histogram(df, x, bins, xlabel=None, ylabel=None, title=None, figsize=(8, 5)): """ """ fig = plt.figure(figsize=figsize) ax = fig.gca() ax.hist(df[x], bins=bins, color='#8d1a93') ax.set_xlabel(xlabel, fontsize=16) ax.set_ylabel(ylabel, fontsize=16) ax.set_title(title, fontsize ...
42801361386edea3065974bdca2a589be0b964ef
3,633,375
def pygmo_gaco( criterion, x, lower_bounds, upper_bounds, *, population_size=None, batch_evaluator=None, n_cores=1, seed=None, discard_start_params=False, # stopping_max_iterations=STOPPING_MAX_ITERATIONS_GENETIC, kernel_size=63, speed_parameter_q=1.0, oracle=...
f8cf4e423b928393e4c028412da4f302376fb248
3,633,376
def get_project_by_id(project_id: str) -> Project: """ Get a project by its project_id, with project model and project data joined. :param project_id: project id of the project :return: Project with the project id """ query = ( Project.select(Project, ProjectModel, ProjectData) ...
2a8986c8e2541f43d30bee2cb1bcac14df68b716
3,633,377
def hist_similarity(image_1, image_2): """color hist based image similarity @param image_1: np.array(the first input image) @param image_2: np.array(the second input image) @return similarity: float(range from [0,1], the bigger the more similar) """ if image_1.ndim == 2 and image_2.ndim == ...
76358cff7b3a33f44fecefd289805a1fea88e1c4
3,633,378
def slotter_obj(): """ Return basic slotter object """ return Slotter()
f4b8805c8ca26bfc22da79b49a9c287c35428f86
3,633,379
def gaussian(wavelength, w, sigma, amp=1., norm=True): """ Computes a gaussian for a given central wavelength, sigma and amp .. math:: G = \\frac{A}{\sigma \sqrt{2 \pi}} \exp{\left( \\frac{ (w - w_0)^2 }{2 \sigma^2 } \\right) } Args: wavelength (np.ndarray): wavelength array to cal...
7e757691fbe27641a4cfd983678dd0ccd2cbdfbd
3,633,381
def summarize_samples(samples, run_parallel): """Back compatibility for existing pipelines. Should be replaced with summary when ready. """ return samples
20c742e751f9ea1f783572f031fe144baf73293e
3,633,382
def get_keywords(string): """Get keywords for a given string. Args: string (str): A string to get keywords for. Returns: (list): A list of keywords. """ keywords = string.lower().split(' ') keywords = [x.strip() for x in keywords if x] keywords = list(set(keywords)) retur...
8d4e0781701dc3574583baf417c573967638e86f
3,633,383
def calc_mass_loading_factor(OIII_results, OIII_error, hbeta_results, hbeta_error, hbeta_no_outflow_results, hbeta_no_outflow_error, statistical_results, z, header): """ Calculates the mass loading factor eta = M_out/SFR Using the calc_sfr.calc_sfr_koffee and the calc_mass_outflow_rate functions ...
6504b328e749e98eb4b3612533701e562973d882
3,633,384
def truecircle(radius, rho): """Create a "true" circular mask with anti-aliasing. Parameters ---------- samples : `int`, optional number of samples in the square output array radius : `float`, optional radius of the shape in the square output array. radius=1 will fill the rho :...
e721d99d99b89ca24637e20d9577b2725cc29525
3,633,386
def distancia(ponto1, ponto2): """ Calcula a distância entre dois pontos """ xdif = ponto2.getx() - ponto1.getx() ydif = ponto2.gety() - ponto1.gety() dif = (xdif**2 + ydif**2)**0.5 return dif
36a980a1081133fb6496585c25cca5782ceef06d
3,633,387
import time def foo(x, sleep_time): """Dummy function for the tests""" time.sleep(sleep_time) return [{"type": "objective", "name": "objective", "value": x}]
3d55a0b0776acec0badd10e38be724afc3015c2f
3,633,388
def aug_ims(ims, fliplr=0, flipud=0, T=0): """Augment images with flips and transposition.""" ims_aug = np.array(ims, copy=True) for i in range(len(ims_aug)): if fliplr: # flip left right ims_aug[i] = np.fliplr(ims_aug[i]) if flipud: # flip up down ims_aug[i] = np.f...
59f8c44f0efcb70c17f828351b0f59787c3dd677
3,633,389
def bt_search(btree, key): """基于二叉树查询操作""" bt = btree while bt is not None: entry = bt.data if key < entry.key: bt = bt.left elif key > entry.key: bt = bt.right else: return entry.values return None
1b358087c10a4d0d6fe79b023340fafeafb81914
3,633,390
def make_reply(msgname, types, arguments, major): """Helper method for constructing a reply message from a list or tuple Parameters ---------- msgname : str Name of the reply message. types : list of kattypes The types of the reply message parameters (in order). arguments : list...
9c55089e1d6fe6b5a4345f444f2551a2c493f2e3
3,633,391
def empty_coord(): """Return an empty coordinate tensor representing 1 residue-level pad character.""" coord_padding = np.zeros((NUM_COORDS_PER_RES, 3)) coord_padding[:] = GLOBAL_PAD_CHAR return coord_padding
e4d8c4f24ebed354f5b083a4fc072e354c79a149
3,633,392
def grib_clone(msgid_src): """ @brief Create a copy of a message. Create a copy of a given message (\em msgid_src) resulting in a new message in memory (\em msgid_dest) identical to the original one. \b Examples: \ref grib_clone.py "grib_clone.py" @param msgid_src id of message to be cloned...
c01b3f626d11be8d218fdcd598e472c5fe748272
3,633,393
def layernorm(x, epsilon=1e-5, name='lnconv'): """Layer Normalization for conv. x must be [NCHW]""" shape = x.get_shape().as_list() with tf.variable_scope(name): beta = tf.get_variable("beta", [1, shape[1], 1, 1], initializer=tf.constant_initializer(0.)) gamma = tf.get_variable("gamma", [1, ...
9ae3bb3f6e0238de92f167bf45b05e3095541665
3,633,394
def create_graph_from_edges(edges): """ Create a graph from the `edges` """ G = nx.Graph() for e in edges: p1 = e[0] p2 = e[1] dist = LA.norm(np.array(p2) - np.array(p1)) G.add_edge(p1, p2, weight=dist) return G
ac06c424fcfde720fbb4457c0baced0a0a41567d
3,633,395
def far_field(frequency, radius, current, r, theta): """ Calculate the electric and magnetic far fields for a small circular loop. :param r: The range to the field point (m). :param theta: The angle to the field point (rad). :param frequency: The operating frequency (Hz). :param radius: The radi...
29940432e3e4dbc427398a18e1d026d9e4c205c3
3,633,396
def rng_laplace(lambd=1, trunc=None): """ Generate random numbers from a Laplace distribution Parameters ---------- lambd: float The scale of the distribution trunc: None, tuple Specifies whether the distribution is truncated. If it's not None then it must be a 2-tuple i...
d4ad9c23c5edef20babe59671e0464ef70ed74ae
3,633,397
from typing import Sequence from typing import Dict from typing import List def settings_to_connections( settings: amicus.options.Configuration, suffixes: Sequence[str]) -> Dict[str, List[str]]: """[summary] Args: settings (amicus.options.Configuration): [description] suffixes (Sequen...
e2ec469014d5d26848d011feda717191ae8c452b
3,633,398
def radec_from_pointing_object(pointing, # default output in degrees as_radians=False, as_string=False): """Astropy object to ICRS format as strings""" pnt_radec = pointing.transform_to(ICRS()) if as_string: ...
8cdd5c6671ccfd12624df88dfdfce0f6e0f41856
3,633,399
def get_potentially_supported_ops(): """Gets potentially supported ops. Returns: list of str for op names. """ supported_ops = _get_potentially_supported_ops() op_names = [s.op for s in supported_ops] return op_names
4fcbc8fd8e10f28d7c10e8b7a9b9d9475ef6b4b6
3,633,400
def hard_sigmoid_me(input_, inplace: bool = False): """jit-scripted hard_sigmoid_me function""" return HardSigmoidJitAutoFn.apply(input_)
83cb4ed8802b5e6a275167c3a44e51719efe6212
3,633,401
def demoji(tokens): """ This function describes each emoji with a text that can be later used for vectorization and ML predictions :param tokens: :return: """ emoji_description = [] for token in tokens: detect = emoji.demojize(token) emoji_description.append(detect) retur...
ab0a200fca87b3b1dc22dfd6bbf374d35d7b8b50
3,633,402
from pathlib import Path async def get_journal_entries_by_permalink_handler( journal_permalink: str = Path(...), entry_permalink: str = Path(...), db_session: Session = Depends(db.yield_connection_from_env), ) -> RedirectResponse: """ Get specific journal entry by short link. """ try: ...
d6dcd12b7db6a57f518621212fda72c769e671aa
3,633,403
def ignore_pre_big_bang(run): """ Remove metrics before timestamp 0. """ return [m for m in run if m[TS] >= 0] #return [m for m in run if m[TS] >= 0 and m[TS] < MAX_TIME]
b5ff1cf5f3f67618c31da1defa5a397fbea8f9bb
3,633,404
def signUp(): """Sign up a new user. :field phone [int]: user phone number :field name [str]: user name :field password [str]: user password (will be encrypted) :returns [dict]: newly created user's info with auth token """ phone = handler.parse('phone', int) name = handler.parse('name'...
0ad7bb71135e86fe3f4d3873e510d4bb375c061c
3,633,405
def next_player(player,list_player_names,player_index,open_card,given_card): """ returns the next player >>> list_player_names=['Mark','John','Harry','Henry'] >>> player_index=0 >>> player='Mark' >>> next_player(player,list_player_names,player_index,('A', '♥', 11)) 'John' >>> player_index=3 ...
7c56bd1983b60ed2177914cc4203462c9b83f375
3,633,406
def loss_function(image, idx, c, omega): """ :param last_image: the previous generated frame :param outputs: Generated image :return: The sum of the style and content loss """ outputs = extractor(image) style_outputs = outputs["style"] content_outputs = outputs["content"] style_loss...
2c6dee61f1af7e48be34cbc47501062a0dc7fa03
3,633,407
def bra(seq, dim=2): """ Produces a multiparticle bra state for a list or string, where each element stands for state of the respective particle. Parameters ---------- seq : str / list of ints or characters Each element defines state of the respective particle. (e.g. [1,1,0,1] o...
1199ac8336963a785e2d258416733612dc7a5558
3,633,408
def rmse_diff(model_data, subj_data): """this rmse only consider diff""" R = np.array(model_data) D = np.array(subj_data) r_DIFF = np.round([np.mean(R[0:2])-np.mean(R[2:4]), R[0]-R[1], R[2]-R[3]], 4) d_DIFF = np.round([np.mean(D[0:2]) - np.mean(D[2:4]), D[0] - D[1...
f9b06e74a95663ad3036b7c658bb55880eba1a03
3,633,410
def preparation_time_in_minutes(number_of_layers: int) -> int: """Calculate the preparation time per layer. .:param number_of_layers: int number of layers. .:return: int time in minutes derived from 'PREPARATION_TIME'. Function that takes the actual number of layer of the lasagna and return how muc...
3377dbb30ef7f1ffdd41680b7f270baffb81a2ef
3,633,411
def eliminate(board, i, j): """ Propagates the effects of fixing a cell to the affected neighbors within the same square and vertical and horizontal lines """ value = board[i][j][0] # Horizontal propagation for k in range(n): if j!=k and value in board[i][k]: board[i][k]....
dd860418a1e57ed2484c20cf5765d926a653c9ab
3,633,412
def prep_tweet_body(tweet_obj, args, processed_text): """ Format the incoming tweet Args: tweet_obj (dict): Tweet to preprocess. args (list): Various datafields to append to the object. 0: subj_sent_check (bool): Check for subjectivity and sentiment. 1: subjectivity (num...
9163d7bb10e3bb31849090d8ebfe4d00c19db2df
3,633,413
import zlib import time import logging def send_mfg_inspector_data(inspector_proto, credentials, destination_url, payload_type): """Upload MfgEvent to steam_engine.""" envelope = guzzle_pb2.TestRunEnvelope() envelope.payload = zlib.compress(inspector_proto.SerializeToString()) enve...
e809e49c2babe215c547960f60d6edca495601d4
3,633,414
def cache_lookup_only(key): """Turns a function into a fallback for a cache lookup. Like the `cache` decorator, but never actually writes to the cache. This is good for when a function already caches its return value somewhere in its body, or for providing a default value for a value that is suppos...
c142de5fb967860f8a5108d9b65cf21e32e9e674
3,633,415
def social_distancing_policy(): """ Real Name: b'social distancing policy' Original Eqn: b'1-PULSE(social distancing start, FINAL TIME-social distancing start+1)*social distancing effectiveness' Units: b'dmnl' Limits: (None, None) Type: component b'' """ return 1 - functions.pulse( ...
8cd71fb4cdfcffb11bb488beee6f33a5495e2eeb
3,633,416
def mersenne_prime(n_max): """ This is the description of the function 4 ~ Loves it + 3 Parameters ---------- n_max : int for p up to n_max Returns ------- list list of q """ primes = [] for a in range(0,n_max): b = 2**a - 1 i...
4aff17a7ed6c22b2817d0c37d1fb6b9dbaf243c2
3,633,417
def import_locus_intervals(path, reference_genome='default', skip_invalid_intervals=False, contig_recoding=None, **kwargs) -> Table: """Import a locus interval list as a :class:`.Table`. Examples ---...
3d27332ac4194f5f823bb234016d3941751e2072
3,633,418
def speech_tagging(test_data, model, tags): """ Inputs: - test_data: (1*num_sentence) a list of sentences, each sentence is an object of line class - model: an object of HMM class Returns: - tagging: (num_sentence*num_tagging) a 2D list of output tagging for each sentences on test_data """ tagging = [] ######...
8390fc6ff0b1008d50b248da0d348ac31b42626a
3,633,419
def evaluate_if(hook_dict: dict, context: 'Context', append_hook_value: bool) -> bool: """Evaluate the when condition and return bool.""" if hook_dict.get('for', None) is not None and not append_hook_value: # We qualify `if` conditions within for loop logic return True if hook_dict.get('if',...
b9d733568abf9d4bd7e7b7ed6e1ac43582728080
3,633,420
def find_vgg_layer(arch, target_layer_name): """Find vgg layer to calculate GradCAM and GradCAM++ Args: arch: default torchvision densenet models target_layer_name (str): the name of layer with its hierarchical information. please refer to usages below. target_layer_name = 'features...
97e578e061a592f5762313f4b7aecc42cda39cb7
3,633,421
def plain_bst(): """Returns a plain binary search tree and a tuple of its nodes. The tree has the same structure as ref_bst.""" t = Tree.tree() n1 = Tree.tree().treeNode(1) n3 = Tree.tree().treeNode(3) n4 = Tree.tree().treeNode(4) n6 = Tree.tree().treeNode(6) n7 = Tree.tree().treeNode(7) ...
81667b4b122c88ec29146b5b739b44cbafda6c0f
3,633,422
def test_confirm_name(monkeypatch, single_with_trials): """Test name must be confirmed for update""" def incorrect_name(*args): return "oops" monkeypatch.setattr("builtins.input", incorrect_name) execute("db set test_single_exp status=broken status=interrupted", assert_code=1) def correc...
9b9aee3fccda50d886d5c3362e5f3e19806a1929
3,633,423
import torch def get_one_hot_reprs(batch_stds): """ Get one-hot representation of batch ground-truth labels """ batch_size = batch_stds.size(0) hist_size = batch_stds.size(1) int_batch_stds = batch_stds.type(torch.cuda.LongTensor) if gpu else batch_stds.type(torch.LongTensor) hot_batch_stds = tor...
84dbf251039144b2bad5f461f40cec830d9331ca
3,633,424
from typing import Tuple def absolute_confusion_from_incidence(true_incidence, predicted_incidence) -> Tuple[float, float, float, float]: """Return the absolute number of true positives, true negatives, false positives and false negatives. Parameters ---------- true_incidence: numpy.ndarray t...
d235363a249523347087940d803e7dfbfc01a6de
3,633,426
def test_every_iteration_model_updater_with_cost(): """ Tests that the model updater can use a different attribute from loop_state as the training targets """ class MockModel(IModel): def optimize(self): pass def set_data(self, X: np.ndarray, Y: np.ndarray): sel...
5775c0f2141f75cad46b143310f1fed64b508f37
3,633,427
def correlating_weight2_data(shots_discr, idx_qubit_ro, correlations, num_segments): """ """ correlations_idx = [ [idx_qubit_ro.index(c[0]), idx_qubit_ro.index(c[1])] for c in correlations] correl_discr = np.zeros((shots_discr.shape[0], len(correlations_idx))) correl_avg = np.zeros((num_seg...
4afb8c95f081e70fe50ed2b209e8e930ea0c4825
3,633,428
def create_test_network_6(): """Aligned network with dropout for test. The graph is similar to create_test_network_1(), except that the right branch has dropout normalization. Returns: g: Tensorflow graph object (Graph proto). """ g = tf.Graph() with g.as_default(): # An input test ima...
820bea3f33b0f56d1d6148ee55764eb504bb977a
3,633,429
import time def timedcall(fn, *args): """ Run a function and measure execution time. Arguments: fn : function to be executed args : arguments to function fn Return: dt : execution time result : result of function Usage example: You want to time the function call "C = foo(A...
60779c4f4b63796995d722133c304edf519ecd8f
3,633,430
from pybind11_tests import ord_char, ord_char16, ord_char32, ord_wchar, wchar_size def test_single_char_arguments(): """Tests failures for passing invalid inputs to char-accepting functions""" def toobig_message(r): return "Character code point not in range({0:#x})".format(r) toolong_message = "E...
dce3ef537fcc312d92b9f5ff5eb2ac00ff731a5e
3,633,431
def tokuda_gap(i): """Returns the i^th Tokuda gap for Shellsort (starting with i=0). The first 20 terms of the sequence are: [1, 4, 9, 20, 46, 103, 233, 525, 1182, 2660, 5985, 13467, 30301, 68178, 153401, 345152, 776591, 1747331, 3931496, 8845866, ...] h_i = ceil( (9*(9/4)**i-4)/5 ) for i>=0. If ...
710633e924cb6e31a866683b91da6489c781ba4a
3,633,432
def trimf(x, p): """ Triangular membership function generator. Parameters ---------- x : any sequence Independent variable. p: list of 4 values lower than p[0] and higher than p[3] it returns 0 between p[1] and p[2] it returns 1 Returns ------- y : 1d array ...
7df01e466e55186c4d9e74466440077a0824eb47
3,633,434
def band_atom_orbitals_spin_polarized( folder, atom_orbital_dict, output='band_atom_orbitals_sp.png', display_order=None, scale_factor=5, color_list=None, legend=True, linewidth=0.75, band_color='black', unprojected_band_color='gray', unprojected_linewidth=0.6, fontsize=1...
8ed107df12d8ef037116f0e87e8a62b6794ecbbb
3,633,435
from typing import List def _interpolate(mesh_1: Mesh, mesh_2: Mesh, steps: int = 1) -> List[Mesh]: """Interpolate two alike meshes. This is suitable to fill the blank frames of an animated object This function makes the assumption that same indices will be forming the same triangle. This functi...
7209e00ac3cfc7996ec7e8cd1b0184b6ada40dea
3,633,436
def dataset_service(): """ :rtype: dart.service.dataset.DatasetService """ return current_app.dart_context.get(DatasetService)
f2c8a3dfc39454449554930d2939cc45ed06f109
3,633,437
def calculate_concordance(aei_pvalues, eqtl_pvalues, threshold=0.05): """ Returns """ eqtl_pvalues_i = np.nanargmin(eqtl_pvalues) print(eqtl_pvalues_i) print(aei_pvalues.iloc[eqtl_pvalues_i]) if aei_pvalues.iloc[eqtl_pvalues_i] <= threshold: return(True) else: return(False)
f0371c81096ad9f1598c1291d853d717002e09e0
3,633,438