content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def templateSummary(): """ """ # Load Model tablename = "survey_template" s3db[tablename] s3db.survey_complete crud_strings = s3.crud_strings[tablename] def postp(r, output): if r.interactive: if len(get_vars) > 0: dummy, template_id = get_vars.viewi...
6151e040b8e1c2491b3e282d0bb90fe278bf6dd8
32,710
def get_main_image(): """Rendering the scatter chart""" yearly_temp = [] yearly_hum = [] for city in data: yearly_temp.append(sum(get_city_temperature(city))/12) yearly_hum.append(sum(get_city_humidity(city))/12) plt.clf() plt.scatter(yearly_hum, yearly_temp, alpha=0.5) plt...
b9845a44b868353e878b53beb6faf9c17bdf07d6
32,712
def get_PhotoImage(path, scale=1.0): """Generate a TKinter-compatible photo image, given a path, and a scaling factor. Parameters ---------- path : str Path to the image file. scale : float, default: 1.0 Scaling factor. Returns ------- img : `PIL.ImageTk.PhotoImage ...
02402574e0641a1caced9fe0b07434db5c84dee5
32,713
import gc def MCLA(hdf5_file_name, cluster_runs, verbose = False, N_clusters_max = None): """Meta-CLustering Algorithm for a consensus function. Parameters ---------- hdf5_file_name : file handle or string cluster_runs : array of shape (n_partitions, n_samples) verbose : bool, o...
f7059c0afd6f346d82ec36eae90f6c3fa8459dad
32,714
from datetime import datetime def iso_date(iso_string): """ from iso string YYYY-MM-DD to python datetime.date Note: if only year is supplied, we assume month=1 and day=1 This function is not longer used, dates from lists always are strings """ if len(iso_string) == 4: iso_string =...
7f29b22744d384187e293c546d4c28790c211e99
32,716
def summary_dist_xdec(res, df1, df2): """ res is dictionary of summary-results DataFrames. df1 contains results variables for baseline policy. df2 contains results variables for reform policy. returns augmented dictionary of summary-results DataFrames. """ # create distribution tables groupe...
408bf1c8916d5338dbc01f41acb57dcc37e009e9
32,717
def moore_to_basu(moore, rr, lam): """Returns the coordinates, speeds, and accelerations in BasuMandal2007's convention. Parameters ---------- moore : dictionary A dictionary containg values for the q's, u's and u dots. rr : float Rear wheel radius. lam : float Steer...
f599c2f5226dc4a12de73e1ddc360b6176d915ed
32,719
def get_username(sciper): """ return username of user """ attribute = 'uid' response = LDAP_search( pattern_search='(uniqueIdentifier=' + sciper + ')', attribute=attribute ) return response[0]['attributes'][attribute][0]
9da92bb2f1b0b733a137ed0bf62d8817c9c13ed8
32,720
def number_to_string(s, number): """ :param s: word user input :param number: string of int which represent possible anagram :return: word of alphabet """ word = '' for i in number: word += s[int(i)] return word
7997b20264d0750e2b671a04aacb56c2a0559d8c
32,721
def mean(num_lst): """ Calculates the mean of a list of numbers Parameters ---------- num_lst : list List of numbers to calculate the average of Returns ------- The average/mean of num_lst Examples -------- >>> mean([1,2,3,4,5]) 3.0 """ ...
bc6f86fc793bad165afc8f319a3094f3fae91361
32,722
import pandas def development_create_database(df_literature, df_inorganics, df_predictions, inp): """ Create mass transition database. Create mass transition database based on literature, inorganic and prediction data. Parameters ---------- df_literature : dataframe Dataframe wit...
58b52d84ca98d770d3ace4a0b4dae4b369883284
32,723
import requests from typing import IO import hashlib def _stream_to_file( r: requests.Response, file: IO[bytes], chunk_size: int = 2**14, progress_bar_min_bytes: int = 2**25, ) -> str: """Stream the response to the file, returning the checksum. :param progress_bar_min_bytes: Minimum number of ...
44d0529a5fdb0a14ac4dcddbfecf23442678a75a
32,724
def get_user(key: str, user: int, type_return: str = 'dict', **kwargs): """Retrieve general user information.""" params = { 'k': key, 'u': user, 'm': kwargs['mode'] if 'mode' in kwargs else 0, 'type': kwargs['type_'] if 'type_' in kwargs else None, 'event_days': kwargs['event_days'] if 'event_days' in kwargs els...
1b7a5c144267c012a69aff2f02f771d848e8883a
32,725
def infer_schema(example, binary_features=[]): """Given a tf.train.Example, infer the Spark DataFrame schema (StructFields). Note: TensorFlow represents both strings and binary types as tf.train.BytesList, and we need to disambiguate these types for Spark DataFrames DTypes (StringType and BinaryType), so we requ...
bd952c278fafa809342b27755e2208b72bd25964
32,726
import collections def create_batches_of_sentence_ids(sentences, batch_equal_size, max_batch_size): """ Groups together sentences into batches If max_batch_size is positive, this value determines the maximum number of sentences in each batch. If max_batch_size has a negative value, the function dynamically create...
8db116e73e791d7eb72f080b408bb52d60481db7
32,728
def com_com_distances_axis(universe, mda_selection_pairs, fstart=0, fend=-1, fstep=1, axis='z'): """Center of mass to Center of mass distance in one dimension (along an axis). This function computes the distance between the centers of mass between pairs of MDAnalysis atoms selections across the the MD traje...
7005d13e1f18597865ca5c5dc14ec09efd7c63e1
32,729
def min_vertex_cover(G, sampler=None, **sampler_args): """Returns an approximate minimum vertex cover. Defines a QUBO with ground states corresponding to a minimum vertex cover and uses the sampler to sample from it. A vertex cover is a set of vertices such that each edge of the graph is incident ...
b8681077d0bbb8504cdf5c96250e668bbcfe6d4e
32,730
def quantile_bin_array(data, bins=6): """Returns symbolified array with equal-quantile binning. Parameters ---------- data : array Data array of shape (time, variables). bins : int, optional (default: 6) Number of bins. Returns ------- symb_array : array Conver...
87d8c64a30581b700d1a4674e4527882be99444f
32,732
import _socket def wrap_socket(sock: _socket.socket) -> AsyncSocket: """ Wraps a standard socket into an async socket """ return AsyncSocket(sock)
70a6829bdf9048514ffe5bd5b831952f1ecd8e89
32,733
def _calculate_outer_product_steps(signed_steps, n_steps, dim_x): """Calculate array of outer product of steps. Args: signed_steps (np.ndarray): Square array with either pos or neg steps returned by :func:`~estimagic.differentiation.generate_steps.generate_steps` function n_steps (i...
18aeadc5cb7866e6b99b5da9a2b9e6bc6ebb7c44
32,734
def compute_lima_on_off_image(n_on, n_off, a_on, a_off, kernel): """Compute Li & Ma significance and flux images for on-off observations. Parameters ---------- n_on : `~gammapy.maps.WcsNDMap` Counts image n_off : `~gammapy.maps.WcsNDMap` Off counts image a_on : `~gammapy.maps.Wc...
a9bde10722cbed4dab79f157ee478c9b5ba35d86
32,735
def data_preprocess(ex, mode='uniform', z_size=20): """ Convert image dtype and scale imge in range [-1,1] :param z_size: :param ex: :param mode: :return: """ image = ex['image'] image = tf.image.convert_image_dtype(image, tf.float32) image = tf.reshape(image, [-1]) image = i...
95131b5e03afbc0a3c797570a48d49ca93f15116
32,736
def p2wpkh(pubkey: PubKey, network: str = 'mainnet') -> bytes: """Return the p2wpkh (bech32 native) SegWit address.""" network_index = _NETWORKS.index(network) ec = _CURVES[network_index] pubkey = to_pubkey_bytes(pubkey, True, ec) h160 = hash160(pubkey) return b32address_from_witness(0, h160, ne...
ecb4c60871e0dc362d3576d2f02d8e07cd47614e
32,737
import re def is_not_from_subdomain(response, site_dict): """ Ensures the response's url isn't from a subdomain. :param obj response: The scrapy response :param dict site_dict: The site object from the JSON-File :return bool: Determines if the response's url is from a subdomain """ root...
d3fa99cc8a91942de5f3ec9cb8249c62c7488821
32,738
import random def get_affiliation(): """Return a school/organization affiliation.""" return random.choice(AFFILIATIONS)
41356c95447352b9ab96db5783efb5ce511e0d00
32,739
def update_item_feature(train, num_item, user_features, lambda_item, nz_users_indices, robust=False): """ Update item feature matrix :param train: training data, sparse matrix of shape (num_item, num_user) :param num_item: number of items :param user_features: factorized user features, dense matrix ...
95b56754830cdcd8ddbfcabc25adcad1698903af
32,740
def generate_mutation(model, mutation_type): """ Generate a model mutation. Create the mutation class Parameters: model (dict): the model dictionary from settings mutation_type (str): the mutation type (create, delete, update) Returns: graphene.Mutation.Field: the mutation field ""...
1e1c39a76508c8f33179087786c08203af57c036
32,741
def _wf_to_char(string): """Wordfast &'XX; escapes -> Char""" if string: for code, char in WF_ESCAPE_MAP: string = string.replace(code, char.encode('utf-8')) string = string.replace("\\n", "\n").replace("\\t", "\t") return string
9270f4ff5a03265956d006bd08d04e417a0c5a14
32,743
from datetime import datetime def agg_15_min_load_profile (load_profile_df): """ Aggregates 1-Hz load profile by taking average demand over 15-min increments. """ s_in_15min = 15 * 60 # prepare idx slices start_idxs = np.arange(0, len(load_profile_df), s_in_15min) end_idxs = np....
6a92abf10b6f976d4b48bc7e6bfb4c0e44b1f4c5
32,744
def get_gitbuilder_hash(project=None, branch=None, flavor=None, machine_type=None, distro=None, distro_version=None): """ Find the hash representing the head of the project's repository via querying a gitbuilder repo. Will return None in the case of a 404...
980abab1d3ff8bf1acdd0aec43f6ce5d5a2b6c45
32,746
def get_b16_add_conv_config(): """Returns the ViT-B/16 configuration.""" config = ml_collections.ConfigDict() config.patches = ml_collections.ConfigDict({'size': (16, 16)}) config.split = 'non-overlap' config.slide_step = 12 config.hidden_size = 768 config.transformer = ml_collections.Config...
eae5f7f33acaf5931b11c7ed2f6d1b554c8a5254
32,747
def real_proto(request) -> programl_pb2.ProgramGraph: """A test fixture which enumerates one of 100 "real" protos.""" return request.param
84f604626a1545e370aa92ab509329cc23e26aa5
32,748
def flat(arr): """Return arr flattened except for last axis.""" shape = arr.shape[:-1] n_features = arr.shape[-1] return arr.reshape(np.product(shape), n_features)
8b9dd1b92c4fffe087345fa74fbc535e2ee41fbf
32,749
from datetime import datetime import time def wait_while(f_logic, timeout, warning_timeout=None, warning_text=None, delay_between_attempts=0.5): """ Внутренний цик выполняется, пока вычисление `f_logic()` трактуется как `True`. """ warning_flag = False start_time = datetime.now() while True:...
0261083b54b1572833ea146663862fce5fe690a5
32,751
def acute_lymphocytic_leukemia1(): """Human Acute Lymphocytic Leukemia dataset (Patient 1). This dataset was introduced in :cite:`Gawad_2014` and was used in: * :cite:`B-SCITE` Figure 5. * :cite:`infSCITE` Figure S16. The size is n_cells × n_muts = 111 × 20 Returns ------- :class:`an...
76f15e7a19da71fe5e4451104698dfaffdbf1799
32,752
def extract_module(start_queue, g, locality="top", max_to_crawl=100, max_depth=10): """ ([rdflib.URI], rdflib.Graph) -> rdflib.Graph resource (rdflib.URI): resource for which we extract module g (rdflib.Graph): RDF graph """ ontomodule = Graph() ontomodule.namespace_manager = g.namespace_m...
78e60670a8c8ed53471062380d5a9cf0aab70848
32,753
import torch def softmax(x): """Softmax activation function Parameters ---------- x : torch.tensor """ return torch.exp(x) / torch.sum(torch.exp(x), dim=1).view(-1, 1)
739219efe04174fe7a2b21fb8aa98816679f8389
32,754
def comp_raw_bool_eqs(eq1str, eq2str): """ Will compare two boolean equations to see if they are the same. The equations can be written using the characters '&', '+' and '!' for 'and', 'or' and 'not' respectively. """ (eqn1, eqn1vars) = OqeFuncUtils.get_vars_bool_eqn(eq1str) (eqn2, eqn2v...
ce7af289add4294bf8a2a7835414cfb51358bc92
32,755
def get_integrated_scene(glm_files, start_scene=None): """Get an integrated scene. Given a set of GLM files, get a scene where quantities are summed or averaged or so. """ ms = satpy.MultiScene.from_files( glm_files, "glm_l2", time_threshold=10, group...
71744bc23f961e630013ace0a85b1788f92924ff
32,756
def _pt_to_test_name(what, pt, view): """Helper used to convert Sublime point to a test/bench function name.""" fn_names = [] pat = TEST_PATTERN.format(WHAT=what, **globals()) regions = view.find_all(pat, 0, r'\1', fn_names) if not regions: sublime.error_message('Could not find a Rust %s fun...
580cacda4b31dff3fd05f4218733f5f0c6388ddb
32,757
def load_log_weights(log_weights_root, iw_mode): """Loads the log_weights from the disk. It assumes a file structure of <log_weights_root>/<iw_mode>/*.npy of mulyiple npy files. This function loads all the weights in a single numpy array, concatenating all npy files. Finally, it caches the result in a file ...
78f633d55e1d3eedc31851a315294e6a15d381a0
32,758
import requests import logging def pipelines_is_ready(): """ Used to show the "pipelines is loading..." message """ url = f"{API_ENDPOINT}/{STATUS}" try: if requests.get(url).status_code < 400: return True except Exception as e: logging.exception(e) sleep(1)...
219b0935092d09311a05816cf0c4345f9abee9f6
32,759
import cmath def gamma_from_RLGC(freq,R,L,G,C): """Get propagation constant gamma from RLGC transmission line parameters""" w=2*np.pi*freq return cmath.sqrt((R+1j*w*L)*(G+1j*w*C))
9e4f09dc233f87b3fa52b9c7488b7fb65791289d
32,761
from typing import Optional from typing import List from typing import Union from pathlib import Path def get_abs_paths(paths: Optional[List[Union[str, Path]]]) -> List[Union[str, Path]]: """Extract the absolute path from the given sources (if any). :param paths: list of source paths, if empty this functions...
93a785fbf679664b96c5228a9cf008cba7793765
32,762
async def async_setup_gateway_entry(hass: core.HomeAssistant, entry: config_entries.ConfigEntry) -> bool: """Set up the Gateway component from a config entry.""" host = entry.data[CONF_HOST] euid = entry.data[CONF_TOKEN] # Connect to gateway gateway = IT600Gateway(host=host, euid=euid) try: ...
d70644b2c4423798007272777bb9c081e79fc778
32,763
import requests def import_from_github(username, repo, commit_hash): """Import a GitHub project into the exegesis database. Returns True on success, False on failure. """ url = 'https://api.github.com/repos/{}/{}/git/trees/{}?recursive=1'.format( username, repo, commit_hash) headers = {'Ac...
a685fc79ad374ab499823696102d22b5d49201ed
32,764
def substructure_matching_bonds(mol: dm.Mol, query: dm.Mol, **kwargs): """Perform a substructure match using `GetSubstructMatches` but instead of returning only the atom indices also return the bond indices. Args: mol: A molecule. query: A molecule used as a query to match against. ...
1b6f4f7e17defae555ea750941be5ec71047cc87
32,767
def remove_element(nums, val): """ :type nums: List[int] :type val: int :rtype: int """ sz = len(nums) while sz > 0 and nums[sz - 1] == val: sz -= 1 i = 0 while i < sz: if nums[i] == val: nums[i], nums[sz - 1] = nums[sz - 1], nums[i] sz -= 1 ...
4d29e8a8d43f191fe83ab0683f5dff005db799ec
32,768
def get_fm_file(file_name): """Read facilitymatcher file into dataframe. If not present, generate the file via script""" file_meta = set_facilitymatcher_meta(file_name, category='') df = load_preprocessed_output(file_meta, paths) if df is None: log.info('%s not found in %s, writing facility ...
b83743b8f56376148b12fc13c3731471cd24b6a5
32,769
def call_dot(instr): """Call dot, returning stdout and stdout""" dot = Popen('dot -T png'.split(), stdout=PIPE, stderr=PIPE, stdin=PIPE) return dot.communicate(instr)
f77c9f340f3fcbebb101c5f59d57c92b56147a11
32,770
def add_bank_member_signal( banks_table: BanksTable, bank_id: str, bank_member_id: str, signal_type: t.Type[SignalType], signal_value: str, ) -> BankMemberSignal: """ Add a bank member signal. Will deduplicate a signal_value + signal_type tuple before writing to the database. Callin...
214f064f152648c78d7ee5c6b56fb81c62cb4164
32,771
from typing import List def map_zones(full_system) -> List[Zone]: """Map *zones*.""" zones = [] if full_system: for raw_zone in full_system.get("body", dict()).get("zones", list()): zone = map_zone(raw_zone) if zone: zones.append(zone) return zones
e5996460bc66a2882ac1cabee79fdff6e4da71cd
32,774
def betternn(x, keep_prob): """ Builds a network that learns to recognize digits :param x: input tensor of shape (N_examples, 784) as standard MNIST image is 28x28=7845 :param keep_prob: probability for dropout layer :return: y - a tensor of shape (N_examples, 10) with values equal to probabilit...
83b1155daa564b257fc1379811ddbde72d18ec4f
32,775
def get_valid_scsi_ids(devices, reserved_ids): """ Takes a list of dicts devices, and list of ints reserved_ids. Returns: - list of ints valid_ids, which are the SCSI ids that are not reserved - int recommended_id, which is the id that the Web UI should default to recommend """ occupied_ids ...
a5b4341fbee75e7d555c917587678dc5ea918b9f
32,776
def check_password_and_delete(target: dict, password) -> dict: """ :param target: :param password: :return: """ if "password" in target: if md5(str(password).encode()).hexdigest() == target["password"]: target = dell(target["password"]) Bash().delete({ ...
c06f5064d8a85065c3312d09bda9b9602b772ae1
32,777
def lingodoc_trigger_to_BIO(doc): """ :type doc: nlplingo.text.text_theory.Document """ ret = [] for sentence in doc.sentences: token_labels = [] for token_index, token in enumerate(sentence.tokens): token_labels.append(EventTriggerFeatureGenerator.get_event_type_of_toke...
7237650ef6e9649b3d0e14867d907c9f6aa5b71a
32,778
def build_coiled_coil_model(): """Generates and returns a coiled-coil model.""" model_and_info = build_and_record_model( request, model_building.HelixType.ALPHA) return jsonify(model_and_info)
9eeca3d1de581559129d3a4fe529c4e13727bd71
32,779
def get_input_fn(config, is_training, num_cpu_threads=4): """Creates an `input_fn` closure to be passed to TPUEstimator.""" input_files = [] for input_pattern in config.pretrain_tfrecords.split(","): input_files.extend(tf.io.gfile.glob(input_pattern)) def input_fn(params): """The actu...
23992d8d4fd1bd09f12aa4c28c695a47edca420e
32,780
def control_modes_available(): """API to call the GetCtrlModesCountSrv service to get the list of available modes in ctrl_pkg (autonomous/manual/calibration). Returns: dict: Execution status if the API call was successful, list of available modes and error reason if call fails. ...
eec46b860791d305cce14659a633b461c73143f0
32,781
def reproject_bbox(source_epsg=4326, dest_epsg=None, bbox=None): """ Basic function to reproject given coordinate bounding box (in WGS84). """ # checks # reproject bounding box l, b, r, t = bbox return transform_bounds(src_crs=source_epsg, dst_crs=dest_e...
449a1cb793cb2239ed9d46449d03f77500fab031
32,782
from bs4 import BeautifulSoup import re def parse_cluster_card_info(soup: BeautifulSoup): """ App lists from GET requests follow a redirect to the /cluster page, which contains different HTML and selectors. :param soup: A BeautifulSoup object of an app's card :return: A dictionary of available ba...
0d4d0ba75a4e29b4d33e1f1a4e40239adcd80626
32,784
def get_joint_occurrence_df(df, row_column, col_column, top_k=10): """ Form a DataFrame where: - index is composed of top_k top values in row_column. - columns are composed of top_k top values in col_column. - cell values are the number of times that the index and column values occur together in...
19701a0a355733c1eb8d3aa3046fc6e00daed120
32,785
def get_total_obs_num_samples(obs_length=None, num_blocks=None, length_mode='obs_length', num_antennas=1, sample_rate=3e9, block_size=134217728, ...
0d5c3de03723c79d31c7f77ece29226daaf4f442
32,786
def number( x: Scalar, c: str = 'csl', w: int = 5, ) -> str: """ Return a notation of the number x in context c. Input: x (Scalar): number c (str): context w (int): width of the output string Output: s (str): notation of x """ S = 0 if x>=0 else 1 # ...
3a36d66f9166e82bb51e39e483f9366f83f72ff8
32,788
def remove_helm_repo(repos_array): """ Execute 'helm repo remove' command on input values repos_array is an array of strings as: ['stable', 'local', 'nalkinscloud', ...] :param repos_array: array of strings :return: return code and value from execution command as dict """ status = 0 ...
4b2a778122caaabf1b7cca971d2d9f2b57dbf84e
32,789
def evaluate_fio(baselines: dict, results: dict, test_name: str, failures: int, tolerance: int) -> int: """ Evaluate the fio test results against the baseline. Determine if the fio test results meet the expected threshold and display the outcome with appropriate units. Parameters ...
d5ad4ca319163409a526fe9d8b43be13de49680a
32,790
def f1_3D(x1, x2, x3): """ x1 dependant from example 2.1 in iterative methods """ return -0.2*x2 - 0.2*x3 + 0.8
09e5a337f5fa62a4c3cddd9ae0dd701867c52b22
32,791
import typing def encrypt(message: typing.Union[str, bytes], n: int, e: int) -> bytes: """ Encrypt MESSAGE with public key specified by N and E """ pub_key = rsa.PublicKey(n, e) if isinstance(message, str): message = message.encode("utf-8") elif isinstance(message, bytes): pass...
fb89606b0d3263c5d10479970868c5336d14679b
32,792
def _safe_div(numerator, denominator): """Divides two tensors element-wise, returning 0 if the denominator is <= 0. Args: numerator: A real `Tensor`. denominator: A real `Tensor`, with dtype matching `numerator`. Returns: 0 if `denominator` <= 0, else `numerator` / `denominator` """ t = tf.trued...
04e9856b1283bf83cd63bb56c65f1d1e2667bcc6
32,793
def build_embedding_model(): """ Build model by stacking up a preprocessing layer and an encoding layer. Returns ------- tf.keras.Model The embedding model, taking a list of strings as input, and outputting embeddings for each token of the input strings """ # Links for the...
ecf835f8543d9815c3c88b5b596c0c14d9524b66
32,794
def event_date_row(event_names_and_dates): """ Returns the third row of the attendance csv. This is just a list of event dates. :param list[(str, datetime)] event_names_and_dates: A list of names and dates for each event that should appear on the csv :returns: the row to be printed :rt...
5b51eaef8cde99040a1aff9a0c6abaaef5e52896
32,795
def moving_tajima_d(ac, size, start=0, stop=None, step=None, min_sites=3): """Calculate the value of Tajima's D in moving windows of `size` variants. Parameters ---------- ac : array_like, int, shape (n_variants, n_alleles) Allele counts array. size : int The window size (number of...
df5217180cf5b25ccb09ee88974d82290bff43ce
32,796
def sample_member(user, name='Attila'): """ Create and return a sample tag :param user: :param name: :return: """ return Member.objects.create(user=user, name=name)
ac171a5da2495436596bd6e597b0b9ea498c8bcf
32,797
import uuid def _create_feed(client, customer_id): """Creates a page feed with URLs Args: client: an initialized GoogleAdsClient instance. customer_id: a client customer ID str. Returns: A FeedDetails instance with information about the newly created feed. """ # Retrieve ...
738e940abd1a7ec90382c4011b26d757c8a916a4
32,798
def cal_pj_task_ind(_st_date, _ed_date): """ 计算产品研发中心资源投入到非产品事务的指标。 :param _st_date: 起始日期 :param _ed_date: 截止日期 :return: 统计指标 """ global extTask _pj_info = handler.get_project_info("project_t") # logging.log(logging.WARN, ">>> cal_pj_task_ind( %s, %s )" % (_st_date, _ed_date)) ...
7a998a01a87abbc1f80147cf067b231429124001
32,799
def get_page_index(obj, amongst_live_pages=True): """ Get oage's index (a number) within its siblings. :param obj: Wagtail page object :param amongst_live_pages: Get index amongst live pages if True or all pages if False. :return: Index of a page if found or None if page d...
fd1950533a398019ab0d3e208a1587f86b134a13
32,801
import requests def contact_ocsp_server(certs): """Sends an OCSP request to the responding server for a certificate chain""" chain = convert_to_oscrypto(certs) req = create_ocsp_request(chain[0], chain[1]) URI = extract_ocsp_uri(certs[0]) data = requests.post(URI, data=req, stream=True, headers={'...
15c32e72d41e6db275f5ef1d91ee7ccf05eb8cde
32,802
import warnings def reset_index_inplace(df: pd.DataFrame, *args, **kwargs) -> pd.DataFrame: """ Return the dataframe with an inplace resetting of the index. This method mutates the original DataFrame. Compared to non-inplace resetting, this avoids data copying, thus providing a potential speedup...
6c10d67ffdaf195c0a9eea3ae473bb0e93e6e9ef
32,803
def get_current_user(): """Get the current logged in user, or None.""" if environment.is_local_development(): return User('user@localhost') current_request = request_cache.get_current_request() if local_config.AuthConfig().get('enable_loas'): loas_user = current_request.headers.get('X-AppEngine-LOAS-Pe...
3b80285c87358dc33595ca97ecee3cf38cf96034
32,805
import calendar import time def genericGetCreationDate(page): """ Go to each date position and attempt to get date """ randSleep() allDates = [] signaturePositions = findSignatures(page) for p in signaturePositions: timestamp = getTimestampFromSERP(p, page) # print('times...
3d3f6e9a0b1ce9b49f887ba4d1d99493b75d2f9e
32,806
def depth(data): """ For each event, it finds the deepest layer in which the shower has deposited some E. """ maxdepth = 2 * (data[2].sum(axis=(1, 2)) != 0) maxdepth[maxdepth == 0] = 1 * ( data[1][maxdepth == 0].sum(axis=(1, 2)) != 0 ) return maxdepth
aa48c88c516382aebe2a8b761b21f650afea82b1
32,807
def transform_user_extensions(user_extension_json): """ Transforms the raw extensions JSON from the API into a list of extensions mapped to users :param user_extension_json: The JSON text blob returned from the CRXcavator API :return: Tuple containing unique users list, unique extension list, and exten...
89d91781028eb4335fff2c9bca446f50b5e91a3f
32,809
def shower_array_rot(shower_array, alt, az): """ Given a series of point on the Z axis, perform a rotation of alt around Y and az around Z Parameters ---------- shower_array: numpy array of shape (N,3) giving N points coordinates alt: altitude shower direction - float az: azimuth shower dir...
d98a6a4589b8945e8dff1272608307915f499fd6
32,810
from typing import Optional def get_dscp_configuration(dscp_configuration_name: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetDscpConfigurationResult: """ Use this data source t...
80e0a388581cd7028c7a8351737808e578778611
32,811
def aggregate_returns(df_daily_rets, convert_to): """ Aggregates returns by week, month, or year. Parameters ---------- df_daily_rets : pd.Series Daily returns of the strategy, noncumulative. - See full explanation in tears.create_full_tear_sheet (returns). convert_to : str ...
7ccf2763420df055a59f15b679ba2c8265744a41
32,812
import random def impute(x,nu): """ Impute to missing values: for each row of x this function find the nearest row in eucledian distance in a sample of nu rows of x and replace the missing value of the former row with the corrisponding values of the...
e13562e28eaafcfaa7848eae9cca7ac9d435d1f4
32,814
def get_data_splits(comment_type_str=None, ignore_ast=False): """Retrieves train/validation/test sets for the given comment_type_str. comment_type_str -- Return, Param, Summary, or None (if None, uses all comment types) ignore_ast -- Skip loading ASTs (they take a long time)""" dataset, high_level...
b9451c5539c7ce235b7bb7f3251e3caa8e4b77c7
32,815
from typing import Tuple def get_slide_roi_masks(slide_path, halo_roi_path, annotation_name, slide_id:str=None, output_dir:str=None) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: """get roi masks from slides Given a slide, halo annotation xml file, generate labels from xml polygons, then crop ...
b79e9b8d93416c404110b56582b4ae1e9030bd7c
32,816
def generate_stop_enex_nb(entries: tp.Array2d, ts: tp.Array, stop: tp.MaybeArray[float], trailing: tp.MaybeArray[bool], entry_wait: int, exit_wait: int, pick_first:...
a34108bd324498e70155f5dcc8c8c4364982c43f
32,817
def mangle_type(typ): """ Mangle Numba type """ if typ in N2C: typename = N2C[typ] else: typename = str(typ) return mangle_type_c(typename)
944952e184d1d33f9424c9e1118920f69f757e86
32,818
def lorentz(sample_len=1000, sigma=10, rho=28, beta=8 / 3, step=0.01): """This function generates a Lorentz time series of length sample_len, with standard parameters sigma, rho and beta. """ x = np.zeros([sample_len]) y = np.zeros([sample_len]) z = np.zeros([sample_len]) # Initial conditi...
c8dc9de84dde15453fe99ed8fb55eddcdd628648
32,819
def draw_lane_lines_on_all_images(images, cols=2, rows=3, figsize=(15, 13)): """ This method calls draw_windows_and_fitted_lines Fn for each image and then show the grid of output images. """ no_of_images = len(images) fig, axes = plt.subplots(rows, cols, figsize=figsize) indexes = range(cols * r...
27975a95836b784fece0547375b4d79868bbd3b6
32,820
import re def get_field_order(address, latin=False): """ Returns expected order of address form fields as a list of lists. Example for PL: >>> get_field_order({'country_code': 'PL'}) [[u'name'], [u'company_name'], [u'street_address'], [u'postal_code', u'city']] """ rules = get_validation_r...
d86c36ab1026fdad6e0b66288708786d8d2cb906
32,821
def env_start(): """ returns numpy array """ global maze, current_position current_position = 500 return current_position
ed377adedc48159607a4bb08ea6e3624575ec723
32,822
def bootstrap_acceleration(d): """ Bootstrap (BCA) acceleration term. Args: d : Jackknife differences Returns: a : Acceleration """ return np.sum(d**3) / np.sum(d**2)**(3.0/2.0) / 6.0
fbd9a05934d4c822863df0ba0b138db840f34955
32,823
def normalize_map(x): """ normalize map input :param x: map input (H, W, ch) :return np.ndarray: normalized map (H, W, ch) """ # rescale to [0, 2], later zero padding will produce equivalent obstacle return x * (2.0/255.0)
f750df26c8e6f39553ada82e247e21b2e3d6aabd
32,824
def today(): """Get the today of int date :return: int date of today """ the_day = date.today() return to_int_date(the_day)
81c497cdf33050b6e8de31b0098d10acfb555444
32,825
from datetime import datetime def contact(request): """Renders the contact page.""" assert isinstance(request, HttpRequest) return render( request, 'app/contact.html', { 'title':'联系我们', 'message':'你可以通过以下方式和我们取得联系', 'year':datetime.now().year, ...
65056534556a8503d897b38468b43da968d4223d
32,826
import math def plagdet_score(rec, prec, gran): """Combines recall, precision, and granularity to a allow for ranking.""" if (rec == 0 and prec == 0) or prec < 0 or rec < 0 or gran < 1: return 0 return ((2 * rec * prec) / (rec + prec)) / math.log(1 + gran, 2)
f8debf876d55296c3945d0d41c7701588a1869b6
32,827
def continuum(spec,bin=50,perc=60,norder=4): """ Derive the continuum of a spectrum.""" nx = len(spec) x = np.arange(nx) # Loop over bins and find the maximum nbins = nx//bin xbin1 = np.zeros(nbins,float) ybin1 = np.zeros(nbins,float) for i in range(nbins): xbin1[i] = np.mean(x[i...
42709c9361707ef8b614030906e9db5ea38087b3
32,828