content
stringlengths
22
815k
id
int64
0
4.91M
def email_search(request): """ Generate email search results. :param request: Django request object (Required) :type request: :class:`django.http.HttpRequest` :returns: :class:`django.http.HttpResponse` """ query = {} query[request.GET.get('search_type', '')]=...
5,306,100
def test_smash(): """ Check that a smash leaves the block on the appropriate level and that after a smash, the y_row value of the piece on the board resets to 0. """ board = TetrisBoard() board.board[19][3] = 5 #Puts a green block on the 20th row and 4th column. board.new_piece(0) #Places a ...
5,306,101
def updateRelations(obj, event): """Re-register relations, after they have been changed. """ catalog = component.queryUtility(ICatalog) intids = component.queryUtility(IIntIds) if catalog is None or intids is None: return # check that the object has an intid, otherwise there's nothing ...
5,306,102
def builddir_content_updates(param_dict, osimage, version, debug): """ Summary: Updates builddir contents: - main exectuable has path to libraries updated - builddir DEBIAN/control file version is updated to current - updates the version.py file if version != to __version__ ...
5,306,103
def haversine_centimetres(Olon, Olat, Dlon, Dlat, earth_radius=EARTH_RADIUS): """ 通过两经纬度点计算地表实际距离 """ d_lat = np.radians(Dlat - Olat) d_lon = np.radians(Dlon - Olon) a = (np.sin(d_lat / 2.) * np.sin(d_lat / 2.) + np.cos(np.radians(Olat)) * np.cos(np.radians(Dlat)) * np.sin(d_lo...
5,306,104
def find_largest_digit(n): """ :param n: (int) to find the largest digit in it :return: the largest digit of n """ if n < 0: n = n - (2*n) return helper(n, 0)
5,306,105
def extract_urls(lines): """Parses text for possible URLs. Args: lines: iterable containing text Returns: list of validated URLs """ links = [] for line in lines: split_words = (word for word in line.split(' ') if not word.isalnum()) for word in split_words: ...
5,306,106
def unit_predict_by_trees(X: np.ndarray, list_trees: list) -> constants.TYPING_TUPLE_TWO_ARRAYS: """ It predicts a posterior distribution over `X`, given `list_trees`. :param X: inputs. Shape: (n, d). :type X: numpy.ndarray :param list_trees: a list of decision trees. :type list_trees: list ...
5,306,107
def delta_cholesky(shape, inputs, var_name, summary=False, dropout=0., is_training=None): """ A Cholesky factor (parameter or prediction). :param shape: [B, T, d] :param inputs: if None, then we return a Cholesky trainable parameter for a d-by-d covariance and tile it to the given shape [B, T, d...
5,306,108
def register(linter): """ Required method to auto register this checker """ linter.register_checker(TripleDoublequotesChecker(linter))
5,306,109
def is_even(number): """Check if a number is even.""" return Bool(number % 2 == 0)
5,306,110
def aumentar(v=0, t=0, formato=False): """Função que adiciona uma porcetagem (t) em cima de um valor (v) e retorna o valor formatado em número corrente.""" p = v + (v * t / 100) return p if formato is False else moeda(p)
5,306,111
def parse_dependencies(dataset, use_lemmas=False): """ Recovers Head word, head word TAG and dependencies. """ new_dataset = [] for entry in dataset: if use_lemmas: to_use = "lemmas" else: to_use = "tokens" mapped_head = [entry["features"][to_use][i] f...
5,306,112
def get_eval_map(env:ExpRLEnv, trainer:SemAntExpTrainer, M:int,depth_projection_net:DepthProjectionNet, step:int, objectName:str): """Given the environment and the configuration, compute the global top-down wall and seen area maps by sampling maps for individual locations along a uniform grid in the enviro...
5,306,113
def elo_update(white_elo, black_elo, points, k=25, f=400): """ :param white_elo: :param black_elo: :param points: 1 if White wins, 0 if Black wins :param k: K-Factor, how much to update :param f: F-Factor :return: """ d = black_elo - white_elo expected_points = elo_expect...
5,306,114
def rotated_to_icrs(): """Transformation matrix from rotated coordinates to ICRS Cartesian.""" return matrix_transpose(ICRS_ROT_MATRIX)
5,306,115
def create(isamAppliance, comment='', check_mode=False, force=False): """ Create a new snapshot """ if force is True or _check(isamAppliance, comment=comment) is False: if check_mode is True: return isamAppliance.create_return_object(changed=True) else: return isa...
5,306,116
def _dict_to_example(instance: Dict[Text, Any]) -> tf.train.Example: """Decoded parquet to tf example.""" # Note that when convert to tf.Feature, Parquet data might lose precision. feature = {} for key, value in instance.items(): # TODO(jyzhao): support more types. if value is None: feature[key] =...
5,306,117
def section_f(): """ Retry Logic for Credit Cards """ results = collections.OrderedDict() results['section'] = 'f' order = Order(message_type='AC', cc_num='4788250000028291', order_id='601', cc_expiry='1116', amount='10.00'...
5,306,118
def inner(tensor0: BKTensor, tensor1: BKTensor) -> BKTensor: """Return the inner product between two tensors""" N = torch.numel(tensor0[0]) tensor0_real = tensor0[0].contiguous().view(N) tensor0_imag = tensor0[1].contiguous().view(N) tensor1_real = tensor1[0].contiguous().view(N) tensor1_imag = ...
5,306,119
def stft_to_wav(stft, hparams): """inverse the stft to produce the wav file data""" _, hop_length, win_length = get_params(hparams) return librosa.istft( _i_phase_and_magnitude(stft), hop_length=hop_length, win_length=win_length )
5,306,120
def freeze(c): """ 会触发一个MissingURLGeneratorWarning的警告,因为只让部分路由生成静态页面了,忽略警告即可。 """ freezer.freeze()
5,306,121
def try_parse(value: Any): """Attempts to turn a string value into it's Python data representation via json.loads. Has special handling for strings 'True', 'False', and 'None'. :param value: The value. If a string, attempts to parse as JSON, if not or on parse error returns the ...
5,306,122
def d3plus_data_documents(document_list, field): """ Compute data suitable for feeding to d3plus/geo_map from OPSExchangeDocument data model. Obtains a list of document objects of type OPSExchangeDocument and a field name designating which object attribute to use for the country information, e.g. "...
5,306,123
def annotations_from_executor( executor: local_executors.Kubernetes) -> Dict[str, str]: """Get Pod annotations from the executor for TPUs.""" if executor.cloud_provider != local_executors.GOOGLE_KUBERNETES_ENGINE_CLOUD_PROVIDER: return {} if executor.requirements.accelerator in xm.TpuType: tpu_runtim...
5,306,124
def send_socket_request(request): """Send json request server and take response.""" # pylint: disable=invalid-name crypted = crypt.encrypt(request, config.SERVER_PUBLIC_RSA_KEY) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((config.HOST, config.PORT)) s.send(crypted) respon...
5,306,125
def show_process_time(t1_start, t1_stop, t2_start, t2_stop): """ function to show elapsed time. """ print('\n') print('Elapsed time: {0:.4f} [sec]'.format(t1_stop - t1_start)) print('CPU process time: {0:.4f} [sec]'.format(t2_stop - t2_start)) print('Done.')
5,306,126
def prepare_batch_multimodal(batch, device=None, non_blocking=False): """Prepare batch for multimodal network training: pass to a device with options. Assumes the shape returned by a `MultimodalDataset` subclass. Args: batch: data to be sent to device. device: optional) (default: None) device t...
5,306,127
def rotate_list(a: list, rotate_amount: int) -> None: """Rotate a list to right by `rotate_amount`. Args: a: The list to be ratated. rotate_amount: The amount by which `a` to be rotated. Raises: IndexError: if the given list `a` is None. """ if not a: raise IndexErr...
5,306,128
def update_order_prices(order): """Update prices in order with given discounts and proper taxes.""" for line in order: # type: OrderLine if line.variant: unit_price = line.variant.base_price unit_price = TaxedMoney(unit_price, unit_price) line.unit_price = unit_price...
5,306,129
def ObjectLocalization(objImg: np.ndarray, targetImg: np.ndarray) -> np.ndarray: """ https://docs.opencv.org/master/dc/dc3/tutorial_py_matcher.html Feature based object detection return: Homography matrix M (objImg->targetImg), if not found return None """ img1 = objImg img2 = targetImg ...
5,306,130
def get_look_attrs(node): """Returns attributes of a node that are important for the look. These are the "changed" attributes (those that have edits applied in the current scene). Returns: list: Attribute names to extract """ # When referenced get only attributes that are "changed sin...
5,306,131
def test_check_xavgcharwidth(): """ Check if OS/2 xAvgCharWidth is correct. """ check = CheckTester(opentype_profile, "com.google.fonts/check/xavgcharwidth") test_font_path = TEST_FILE("nunito/Nunito-Regular.ttf") test_font = TTFont(test_font_path) assert_PASS(check(test_fo...
5,306,132
def get_max_document_bytes(env: Dict[str, str]) -> int: """Get the maximum number of bytes a document allowed to be stored in S3.""" try: mb_count = int(env.get( ENV__MAX_DOCUMENT_SIZE_MB, str(DEFAULT_MAX_DOCUMENT_SIZE_MB), )) except ValueError: mb_count = DEFAULT_MAX_DOC...
5,306,133
def by_deep_time_per_call(stat): """Sorting by inclusive elapsed time per call in descending order.""" return -stat.deep_time_per_call if stat.deep_hits else -stat.deep_time
5,306,134
def assert_event_okay(event): """Make sure that the given event is valid. As an OAuth provider, we should check that the client_id and redirect_uri are okay. Since these are hardcoded for us, the check is easy. Also, we only support implicit grants, so that check is easy too. """ assert event["...
5,306,135
def parseDirectiveArguments(data): """Makes a list whose elements are delimited by commas in an input string. Commas inside a scope started with brackets, parens, single- or double-quotes, are skipped. Scopes delimited by brackets or parentheses are assumed to be well formed. I.e. we simply coun...
5,306,136
def process_findings(findings: list, outputs: list, **kwargs): """Process all findings from json file and send to outputs sepecified""" for output in outputs: try: ElectricEyeOutput.get_provider(output)().write_findings(findings=findings, **kwargs) except Exception as e: ...
5,306,137
def color_map_cyclic(color_normalized: float) -> np.ndarray: """ Maps normalized value to color, cyclic. Note: For JIT to work, this must be declared at the top level. @param color_normalized: Normalized color value @return: R, G, B """ hue = (color_normalized + 1 / 6) % 1 x = hue * 6 ...
5,306,138
def ca_validate_input(input_json: Dict, ecosystem: str) -> Tuple[List[Dict], List[Package]]: """Validate CA Input.""" logger.debug('Validating ca input data.') if not input_json: error_msg = "Expected JSON request" raise BadRequest(error_msg) if not isinstance(input_json, dict): ...
5,306,139
def save_pressure_to_postgresql( username, systolic, diastolic, timestamp, arm, pulse=None ): """ save username(unique), systolic, diastolic, timestamp, date, arm """ connection = config() cursor = connection.cursor() try: postgres_insert_users = """INSERT INTO users (use...
5,306,140
def _convert_to_kube_env( env: infra_validator_pb2.EnvVar) -> k8s_client.V1EnvVar: """Convert infra_validator_pb2.EnvVar to kubernetes.V1EnvVar.""" if not env.name: raise ValueError('EnvVar.name must be specified.') if env.HasField('value_from'): if env.value_from.HasField('secret_key_ref'): val...
5,306,141
def _prep_cnv_file(cns_file, svcaller, work_dir, data): """Create a CSV file of CNV calls with log2 and number of marks. """ in_file = cns_file out_file = os.path.join(work_dir, "%s-%s-prep.csv" % (utils.splitext_plus(os.path.basename(in_file))[0], ...
5,306,142
def compute_candid_score(cur, conn, parent_id, tl_start_date, tl_end_date, threshold_percentile=0.5, tf_type='raw'): """ This function computes the CANDID TF-IDF score for each user. CANDID_TF-DF = TF-DF <explain computation here> :param cur: Cursor to database :param conn: connection to database ...
5,306,143
def is_release(semver): """is a semver a release version""" return not (semver.build or semver.prerelease)
5,306,144
def wait_hostname_resolution(sm_hosts): """Wait for the hostname resolution of the container. This is known behavior as the cluster boots up and has been documented here: https://docs.aws.amazon.com/sagemaker/latest/dg/your-algorithms-training-algo-running-container.html#your-algorithms-training-algo-runni...
5,306,145
def solve_value_fn(env: gym.Env, gamma: float) -> np.ndarray: """ Solve the value function for each state in an environment :param env: gym environment :param gamma: discount factor :return: """ # Transition matrix n_states = env.get_num_states() P_trans = env.get_transition_matrix()...
5,306,146
def CH4_rf(emission, years, tstep=0.01, kind='linear', decay=True): """Transforms an array of methane emissions into radiative forcing with user-defined time-step. emission: an array of emissions, should be same size as years years: an array of years at which the emissions take place ...
5,306,147
def search_v1(db, config): """ API v1 route to perform a fulltext search on flats. Example:: POST /api/v1/search Data: { "query": "SOME_QUERY" } .. note:: Filtering can be done through the ``filter`` GET param, according to JSON API spec (http://js...
5,306,148
def train(n_epochs, loaders, model, optimizer, criterion, use_cuda, save_path): """returns trained model""" print(f"Training model...") # initialize tracker for minimum validation loss valid_loss_min = np.Inf for epoch in range(1, n_epochs+1): # initialize variables to monitor training...
5,306,149
def caclf(_freq, _pdos, T, dmu=0.0, energyunit='J'): """ Calculate thermal free energy from phonon density of states (p DOS) Parameters _freq : phonon frequency -pdos : phobob DOS dmu : to be used external phonon chemical potential Returns f : vibrational free energy ...
5,306,150
def run(ctx, mode, **configuration): """Run labels processing.""" prepare_session(ctx) session = ctx.obj['session'] config = ctx.obj['config_file'] config_file = setup_config(config) repos = get_repos(config_file, configuration, session) all_errors = 0 new_labels = config_file['labels'] ...
5,306,151
def bn_update(loader, model, verbose=False, subset=None, **kwargs): """ BatchNorm buffers update (if any). Performs 1 epochs to estimate buffers average using train dataset. :param loader: train dataset loader for buffers average estimation. :param model: model being update :...
5,306,152
def compare_performance( test_stats_per_model: List[dict], output_feature_name: Union[str, None] = None, model_names: Union[str, List[str]] = None, output_directory: str = None, file_format: str = 'pdf', **kwargs ) -> None: """Produces model comparison barplot visuali...
5,306,153
def store_film_params(gammas, betas, contrasts, metadata, model, film_layers, depth): """Store FiLM params. Args: gammas (dict): betas (dict): contrasts (list): list of the batch sample's contrasts (eg T2w, T1w) metadata (list): model (nn.Module): film_layers (li...
5,306,154
def get_tfidf(train_context_path, vocabulary): """ Inputs: path to contexts used for training Outputs: TF-IDF sparse matrix. Each row corresponds to a document Each column corresponds to a word in the vocabulary Because the output is a sparse matrix, each r...
5,306,155
def GetFunctionAttr(ea, attr): """ Get a function attribute @param ea: any address belonging to the function @param attr: one of FUNCATTR_... constants @return: -1 - error otherwise returns the attribute value """ func = idaapi.get_func(ea) if func: return _IDC_Get...
5,306,156
def ifmeth(parser, token): """ Used to mark template blocks for Swagger/OpenAPI output. If the specified method matches the *current* method in Swagger/OpenAPI generation, show the block. Otherwise, the block is omitted. {% ifmeth GET %} Make a GET request to... {% endifmeth %}...
5,306,157
def atan(space, x): """atan(x) Return the arc tangent (measured in radians) of x. """ return math1(space, math.atan, x)
5,306,158
def install_plugin(pkgpath, plugin_type, install_path, register_func): """Install specified plugin. :param pkgpath: Name of plugin to be downloaded from online repo or path to plugin folder or zip file. :param install_path: Path where plugin will be installed. :param register_func: Method used to regis...
5,306,159
async def test_setup_get(hass): """Test setup with valid configuration.""" respx.get("http://localhost", status_code=200, content="{}") assert await async_setup_component( hass, "sensor", { "sensor": { "platform": "rest", "resource": "http:...
5,306,160
def load_policy(graph_def, input_observation_name, input_state_name, output_state_name, output_pd_params_name, tf_sampling_fn): """Load a policy from a graph file. Args: graph_def: Graph definition. input_observation_name: Name...
5,306,161
def get_df(model): """ Return pyomo results as pandas dataframe Usage: df1 = uma.get_df(model.variable) """ df = pd.DataFrame() df_dict = {v.name: np.array([v[index].value for index in v]) for v in model.component_objects(pyomo.Var, active=True)} max_length = max([le...
5,306,162
def login_after_user_is_added_to_ldap(self, server): """Check that user can login as soon as it is added to LDAP. """ user = {"cn": "myuser", "userpassword": "myuser"} with When(f"I add user to LDAP and try to login"): add_user_to_ldap_and_login(user=user, server=server)
5,306,163
def get_SMS_PGV(stat_codes, loc, absVal=True): """ Note: If stat_codes list is not sorted use get_SMS_Rrups to get a list of stat_codes sorted according to Rrup values stat_codes: list containing SMS codes loc: location of .000, .090 and .ver data files return: array(len...
5,306,164
def test_populate(stubbed_blockhash): """Test populating transaction with a message and two signatures.""" account_keys = [str(PublicKey(i + 1)) for i in range(5)] msg = Message( MessageArgs( account_keys=account_keys, header=MessageHeader( num_readonly_signed...
5,306,165
def binary_benchmark(self, function): """ :param function: :type function: """ getattr(self, function)() # Strip stripper = os.environ[self.compiler_bin].replace("gcc", "strip") while not stripper.endswith("strip"): stripper = stripper[0:-1] flags = [] flags.append(se...
5,306,166
def identity(obj): """ Identity function computing no operation Parameters ---------- obj : object any object Returns ------- obj the input object itself """ return obj
5,306,167
def deploy(path='static'): """ Deploy the stuff to S3. """ require('settings', provided_by=[production, staging]) sync = 'aws s3 sync %s/ %s --acl "public-read" --cache-control "max-age=5" --region "us-east-1"' for bucket in S3_BUCKETS: local(sync % (path, 's3://%s/' % (bucket)))
5,306,168
def _multiply_gradients(grads_and_vars, gradient_multipliers): """Multiply specified gradients.""" multiplied_grads_and_vars = [] for grad, var in grads_and_vars: if var in gradient_multipliers or var.name in gradient_multipliers: key = var if var in gradient_multipliers else var.name grad *= cons...
5,306,169
def cliques_containing_node(G, nodes=None, cliques=None): """Returns a list of cliques containing the given node. Returns a single list or list of lists depending on input nodes. Optional list of cliques can be input if already computed. """ if cliques is None: cliques = list(find_cliques(G...
5,306,170
def copy_exam_1_to_2(request, id_structure): """ Copy primary exam to secondary exams """ structure_concerned = StructureObject.objects.get(id=id_structure) exams = Exam.objects.filter( id_attached=structure_concerned.id, code_year=currentyear().code_year) exams_1 = exams.filter(session=...
5,306,171
def is_Gamma1(x): """ Return True if x is a congruence subgroup of type Gamma1. EXAMPLES:: sage: from sage.modular.arithgroup.all import is_Gamma1 sage: is_Gamma1(SL2Z) False sage: is_Gamma1(Gamma1(13)) True sage: is_Gamma1(Gamma0(6)) False s...
5,306,172
def get_table_service(): """Return the TableService instance for this request initializing it if it doesn't exist.""" table_service = getattr(g, 'table_service', None) if table_service is None: table_service = g.table_service = TableService( account_name=app.config['AZURE_STORAGE_ACCOUNT...
5,306,173
def __project_geometry(geometry, crs=None, to_crs=None, to_latlong=False): """ Project a shapely Polygon or MultiPolygon from lat-long to UTM, or vice-versa Parameters ---------- geometry : shapely Polygon or MultiPolygon the geometry to project crs : dict the starting coord...
5,306,174
def save_notifications(username, message, url): """ Format and save notifications """ user = username and User.objects.filter( username=username).first() or None models.Notifications(user=user, message=message, url=url).save()
5,306,175
def who_includes(includeDict, name): """Finds all files who includes name, and recurses outwards.""" nameSet = set() dependencySet = set() recurse_who_includes(includeDict, name, nameSet, dependencySet) result = "digraph G{\n" result += 'graph[fontname="Helvetica",fontsize=13,ranksep=3.000...
5,306,176
def check_segmentation_return_types(seg: SegmentationExtractor): """ Parameters ---------- seg:SegmentationExtractor """ assert isinstance(seg.get_num_rois(), int) assert isinstance(seg.get_num_frames(), int) assert isinstance(seg.get_num_channels(), int) assert isinstance(seg.get_sa...
5,306,177
def get_built_dependencies(dependency_dir, dists=None): """ Generator to yield the nevra of all deps that should be prebuilt in koji. The string yielded by this generator can be used to lookup a particular koji build :param dependency_dir: The directory from which the dependencies should be read :t...
5,306,178
def get_irods_tree(investigation): """Return HTML for iRODS collections""" irods_backend = get_backend_api('omics_irods', conn=False) if not irods_backend: return '' ret = '<ul><li>{}<ul>'.format(settings.IRODS_SAMPLE_COLL) for study in investigation.studies.all(): ret += '<li>{}'.fo...
5,306,179
def qa_fast_png(csf, gm, wm, outdir): """ FAST (FMRIB's Automated Segmentation Tool) segments a 3D image of the brain into different tissue types (Grey Matter, White Matter, CSF, etc.) Mark different colors of white matter, gray matter, cerebrospinal fluid in a '3 by 3' picture, i.e. QA for FAST ...
5,306,180
def get_acq_final_days(df, criteria, correct_amount, session_length): """ This function returns the last days for the Acquisition test. The function grabs all the rows that meet the minimum correct trials amount and the maximum session length amount. Then it calculates the first instance when the animal ...
5,306,181
def get_mean_amplitude_spectrum(img_paths:list, save_path:Optional[str]='./mean_power_spectrum_grey.npy'): """Calculate the mean power spectrum over all images. parameters: - img_paths: a list containing the paths to all images. - save_path: path to save mean power spectrum to""" # get sha...
5,306,182
def log_images_with_confidence( heap_dict: Mapping[int, list[HeapItem]], label_names: Sequence[str], epoch: int, tag: str) -> None: """ Args: heap_dict: dict, maps label_id to list of HeapItem, where each HeapItem data is a list [img, target, top3_conf, top3_p...
5,306,183
def create_needle_model(name, length, radius, tip_radius): """ Create a model that can be used to represent the style/probe. """ # TODO: Set colour show_markers = False create_model_module_logic = slicer.modules.createmodels.logic() needle = create_model_module_logic.CreateNeedle( le...
5,306,184
def res_pairs(num_res, nearn): """ computes res-res pairs included for which to calculate minimum distance features state num of residues, and nearest neighbour skip e.g. i+3 is nearn=3 """ res=[] for i in range(num_res-nearn): for j in range(i+nearn,num_res): res.append([i+1...
5,306,185
def merge_unreal_context_event(unreal_context, event, project): """Merges the context from an Unreal Engine 4 crash with the given event.""" runtime_prop = unreal_context.get('runtime_properties') if runtime_prop is None: return message = runtime_prop.pop('error_message', None) if messa...
5,306,186
def get_arguments(): """Parse all the arguments. Returns: A list of parsed arguments. """ parser = argparse.ArgumentParser(description="Binary class segmentation segmentation model modified on U-Net") parser.add_argument("--batch_size", type=int, default=BATCH_SIZE, he...
5,306,187
def api_image(): """Flask Application Image API Returns: Super hero image JSON response """ if 'id' in flask.request.args: id = int(flask.request.args['id']) rs = session.query(Image).filter_by(id=id).first() if not rs is None: return flask.jsonify({...
5,306,188
def Packet_genReadGpsCompassBaseline(errorDetectionMode, buffer, size): """Packet_genReadGpsCompassBaseline(vn::protocol::uart::ErrorDetectionMode errorDetectionMode, char * buffer, size_t size) -> size_t""" return _libvncxx.Packet_genReadGpsCompassBaseline(errorDetectionMode, buffer, size)
5,306,189
def get_transition_mass(pile_height: float) -> float: """ Returns the mass of transition piece (in kg). :return: """ transition_length = [15, 20, 15, 20, 15, 24, 20, 30, 20, 31] transition_weight = [150, 250, 150, 250, 160, 260, 200, 370, 250, 420] fit_transition_weight = np.polyfit(transiti...
5,306,190
def get_image_code(): """ 获取图片验证码 :return: """ code_id = request.args.get('code_id') name, text, image = captcha.generate_captcha() try: redis_store.setex('ImageCode_' + code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text) except Exception as e: current_app.logg...
5,306,191
def delete_container_view(request, container): """ Deletes a container """ response = delete_container(request, container) if response: messages.add_message(request, messages.SUCCESS, _('Container deleted.')) else: messages.add_message(request, messages.ERROR, _('Access denied.')) ...
5,306,192
def full_dataset_individual_left_canonical_mps_compression_with_reconstruction(all_data, partition, max_bond_dimension): """ Performs a full left canonical MPS decomposition, and subsequent vector reconstruction, of every vector within a dataset (i.e. every row in a matrix) See "The density matrix reno...
5,306,193
def setup_platform(hass, config, add_devices, discovery_info=None): """ setup the sensor platform for smappee """ smappee = hass.data[DATA_SMAPPEE] dev = [] for sensor in SENSOR_TYPES: dev.append(SmappeeSensor(smappee, sensor)) add_devices(dev) return True
5,306,194
def set_balances_data(markets_summaries, balances): """balances table data setup""" # get btc price bitcoin_usdt_price = None for bitcoin_only in markets_summaries['result']: if bitcoin_only['Market']['MarketName'] == 'USDT-BTC': bitcoin_usdt_price = bitcoin_only['Summary']['Last'] ...
5,306,195
def test_user_get_scoreboard(): """Can a registered user can load /scoreboard""" app = create_ctfd() with app.app_context(): register_user(app) client = login_as_user(app) r = client.get('/scoreboard') assert r.status_code == 200
5,306,196
def extract(key, items): """Return the sorted values from dicts using the given key. :param key: Dictionary key :type key: str | unicode :param items: Items to filter. :type items: [dict] :return: Set of values. :rtype: [str | unicode] """ return sorted(item[key] for item in items)
5,306,197
def quat2ypr_rads(quat): """quat2ypr_rads(vec4f quat) -> vec3f""" return _libvncxx.quat2ypr_rads(quat)
5,306,198
def BM_stack(imageStack, blockwidth, delay, max_shift, canny = True, progressSignal = None, *args, **kwargs): """ gets optical flow of a complete imagestack, based on blockmatching unit is px/frame as no scale is given here yet blockwidth is width of square macroblock max_shift ...
5,306,199