content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from web3.middleware import geth_poa_middleware def make_w3(gateway_config=None): """ Create a Web3 instance configured and ready-to-use gateway to the blockchain. :param gateway_config: Blockchain gateway configuration. :type gateway_config: dict :return: Configured Web3 instance. :rtype: :...
85119161c7842319718e7075192b277f810b4328
3,654,046
def _log2_ratio_to_absolute(log2_ratio, ref_copies, expect_copies, purity=None): """Transform a log2 ratio to absolute linear scale (for an impure sample). Does not round to an integer absolute value here. Math:: log2_ratio = log2(ncopies / ploidy) 2^log2_ratio = ncopies / ploidy ...
939a9e4ccb0a1fe9c8c2e6f369bb23c556f04a14
3,654,047
def fixt(): """ Create an Exchange object that will be re-used during testing. """ mesh = df.UnitCubeMesh(10, 10, 10) S3 = df.VectorFunctionSpace(mesh, "DG", 0) Ms = 1 A = 1 m = df.Function(S3) exch = ExchangeDG(A) exch.setup(S3, m, Ms) return {"exch": exch, "m": m, "A": A, ...
4e46550f1ef9e821e459612b82c0410b7459b09b
3,654,048
def touch_emulator(ev, x, y): """ This emulates a touch-screen device, like a tablet or smartphone. """ if ev.type == pygame.MOUSEBUTTONDOWN: if ev.button != 1: return None, x, y elif ev.type == pygame.MOUSEBUTTONUP: if ev.button != 1: return None, x, y ...
826b17c7bc9089acebdf3e1ea64fa0613e13e8ea
3,654,049
def invert_dict(d): """ Invert dictionary by switching keys and values. Parameters ---------- d : dict python dictionary Returns ------- dict Inverted python dictionary """ return dict((v, k) for k, v in d.items())
c70bfdb5ffa96cf07b1a4627aa484e3d5d0f4fea
3,654,051
def atom_present_in_geom(geom, b, tol=DEFAULT_SYM_TOL): """Function used by set_full_point_group() to scan a given geometry and determine if an atom is present at a given location. """ for i in range(len(geom)): a = [geom[i][0], geom[i][1], geom[i][2]] if distance(b, a) < tol: ...
ad4afd6ca3d419b69ef502d64e3e66635485d340
3,654,052
import locale def atof(value): """ locale.atof() on unicode string fails in some environments, like Czech. """ if isinstance(value, unicode): value = value.encode("utf-8") return locale.atof(value)
b0b2d2ea70c5e631ad2a1d25eb5c55d06cbdac1e
3,654,053
def r_group_list(mol, core_mol): """ This takes a mol and the common core and finds all the R-groups by replacing the atoms in the ligand (which make up the common core) with nothing. This fragments the ligand and from those fragments we are able to determine what our R-groups are. for any comm...
16df0f54a5bf374bd1e77d3443baa42aab2dd231
3,654,054
def set_execution_target(backend_id='simulator'): """ Used to run jobs on a real hardware :param backend_id: device name. List of available devices depends on the provider example usage. set_execution_target(backend_id='arn:aws:braket:::device/quantum-simulator/amazon/sv1') """ global dev...
2efb44723a804e39d998ddc3e7a7c3bdaa0440db
3,654,055
def segregate(str): """3.1 Basic code point segregation""" base = bytearray() extended = set() for c in str: if ord(c) < 128: base.append(ord(c)) else: extended.add(c) extended = sorted(extended) return bytes(base), extended
e274393735bf4f1d51a75c73351848cbfdd5f81f
3,654,056
def count_tetrasomic_indivs(lis) -> dict: """ Count number of times that a chromosome is tetrasomic (present in four copies) :returns counts_of_tetrasomic_chromosomes""" counts_of_tetrasomic_chromosomes = {k: 0 for k in chr_range} for kary_group in lis: for index, chr_type in enumerate(chr_rang...
598cd10bdbaeea061be0e259de756beba9d248b7
3,654,057
def make_image_grid(images: np.ndarray, nrow: int = 1) -> np.ndarray: """Concatenate multiple images into a single image. Args: images (np.array): Images can be: - A 4D mini-batch image of shape [B, C, H, W]. - A 3D RGB image of shape [C, H, W]. ...
1b367392c275a44e5c23ce19c96f5727015285f5
3,654,058
def drive_time_shapes(drive_time): """Simplify JSON response into a dictionary of point lists.""" isochrones = {} try: for shape in drive_time['response']['isoline']: uid = str(int(shape['range'] / 60)) + ' minutes' points = shape['component'][0]['shape'] point...
f8f5074d5326ba598c083fdcc228bdfb69f427a5
3,654,059
def compute_transformation_sequence_case_1(cumprod, local_shape, ind, sharded_leg_pos, pgrid): """ Helper function for `pravel`, see `pravel` for more details. """ ops = [] ndev = np.prod(pgrid) if ndev % cumprod[ind - 1] != 0: raise ValueError("reshaping not p...
0f88967a2fcc132af753a2c5dfbf2a9b8087877a
3,654,060
def fix_join_words(text: str) -> str: """ Replace all join ``urdu`` words with separate words Args: text (str): raw ``urdu`` text Returns: str: returns a ``str`` object containing normalized text. """ for key, value in WORDS_SPACE.items(): text = text.replace(key, value...
a13040b420db5b0daf27f3a2f6a1e93a9188c312
3,654,061
import statistics def constitutive_exp_normalization_raw(gene_db,constitutive_gene_db,array_raw_group_values,exon_db,y,avg_const_exp_db): """normalize expression for raw expression data (only for non-baseline data)""" #avg_true_const_exp_db[affygene] = [avg_const_exp] temp_avg_const_exp_db={} for...
38d5d39cb6a5532b84f08ddd0fbb27335e45897b
3,654,063
def parse_rummager_topics(results): """ Parse topics from rummager results """ pages = [] for result in results: pages.append( Topic( name=result['title'], base_path=result['slug'], document_type=DocumentType[result['format']] ...
d88355014c4a74e1ca7ca2ca1389850cba550612
3,654,064
def format_last_online(last_online): """ Return the upper limit in seconds that a profile may have been online. If last_online is an int, return that int. Otherwise if last_online is a str, convert the string into an int. Returns ---------- int """ if isinstance(last_online, str): ...
335ed9a37062964b785c75246c9f23f678b4a90e
3,654,065
from datetime import datetime import pkg_resources import requests import json def get_currency_cross_historical_data(currency_cross, from_date, to_date, as_json=False, order='ascending', interval='Daily'): """ This function retrieves recent historical data from the introduced `currency_cross` from Investing ...
6a01f89b128842497e76d0a3497b204ac6641080
3,654,066
def load_target(target_name, base_dir, cloud=False): """load_target load target from local or cloud Parameters ---------- target_name : str target name base_dir : str project base directory cloud : bool, optional load from GCS, by default False Returns ------- ...
2ea76be87afdf524b45f26e9f8271ec973e0951a
3,654,067
def gradient(pixmap, ca, cb, eff, ncols): """ Returns a gradient width the start and end colors. eff should be Gradient.Vertical or Gradient.Horizontal """ x=0 y=0 rca = ca.red() rDiff = cb.red() - rca gca = ca.green() gDiff = cb.green() - gca bca = ca.blue()...
63406959617a7192c35e05b8efc81dcedfa7d54a
3,654,068
def option_to_text(option): """Converts, for example, 'no_override' to 'no override'.""" return option.replace('_', ' ')
4b7febe0c4500aa23c368f83bbb18902057dc378
3,654,069
def login(email, password): """ :desc: Logs a user in. :param: email - Email of the user - required password - Password of the user - required :return: `dict` """ if email == '' or password == '': return {'success': False, 'message': 'Email/Password field left blank.'} ...
3ea350984d2c4206d66136e283b4784e08606352
3,654,070
def _cons8_89(m8, L88, L89, d_gap, k, Cp, h_gap): """dz constrant for edge gap sc touching edge, corner gap sc""" term1 = 2 * h_gap * L88 / m8 / Cp # conv to inner/outer ducts term2 = k * d_gap / m8 / Cp / L88 # cond to adj bypass edge term3 = k * d_gap / m8 / Cp / L89 # cond to adj bypass corner ...
b6e8b6331be394e9a10659029143997b097fae86
3,654,071
def categories_split(df): """ Separate the categories in their own columns. """ ohe_categories = pd.DataFrame(df.categories.str.split(';').apply( lambda x: {e.split('-')[0]: int(e.split('-')[1]) for e in x}).tolist()) return df.join(ohe_categories).drop('categories', axis=1)
93e6b1dc384162b63fbf5775d168c0e693829f97
3,654,072
def build_received_request(qparams, variant_id=None, individual_id=None, biosample_id=None): """"Fills the `receivedRequest` part with the request data""" request = { 'meta': { 'requestedSchemas' : build_requested_schemas(qparams), 'apiVersion' : qparams.apiVersion, }, ...
bfb0131f3ead563ffd1840119b6f7297a466d4dc
3,654,073
def is_router_bgp_configured_with_four_octet( device, neighbor_address, vrf, max_time=35, check_interval=10 ): """ Verifies that router bgp has been enabled with four octet capability and is in the established state Args: device('obj'): device to check vrf('vrf'): vrf to...
870600a1a5c68d5a4080d8a18966ddc107ae8a72
3,654,074
import six def cluster_absent( name='localhost', quiet=None): """ Machine is not running as a cluster node quiet: execute the command in quiet mode (no output) """ ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if ...
f19c4c18cd0812ee2f4426a458cfb49e4faba5e0
3,654,076
def link_symbols_in_code_blocks(path, blocks, symbols): """Link symbols appearing a sequence of blocks.""" return [link_symbols_in_code_block(path, block, symbols) for block in blocks]
4185e9a1c9b0c8ff2748e80390763b089e9f8831
3,654,077
def cem_model_factory( env, network=mlp, network_params={}, input_shape=None, min_std=1e-6, init_std=1.0, adaptive_std=False, model_file_path=None, name='cem'): """ Model for gradient method """ def build_graph(model, network=network, input_shape=inpu...
e9327a4f3711e19e71cc16658d6e93acba29da47
3,654,078
def get_job(job_id: UUID) -> Job: """ Get job by ID. Args: job_id (UUID): ID of the job to be returned. Returns: Job """ return JobRepository.get_one_by_id(model_id=job_id)
53e70843ce18e77b17e79bac83ba0225d6087e23
3,654,079
import pytz def localize_datetime(input_df, timezone=DEFAULT_TIMEZONE, tms_gmt_col=DEFAULT_TMS_GMT_COL): """ Convert datetime column from UTC to another timezone. """ tmz = pytz.timezone(timezone) df = input_df.copy() return (df.set_index(tms_gmt_col) .tz_lo...
0d6f8638199f0ccfcf61e025b38dbe84d9eab8ff
3,654,081
import contextlib import socket def get_available_port() -> int: """Finds and returns an available port on the system.""" with contextlib.closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock: sock.bind(('', 0)) _, port = sock.getsockname() return int(port)
c86de127fb237662052b8ce010e99d271836e1ef
3,654,082
def prettyprint_float(val, digits): """Print a floating-point value in a nice way.""" format_string = "%." + f"{digits:d}" + "f" return (format_string % val).rstrip("0").rstrip(".")
ba62671d9cb8061744fbf1e070e76c31d0ba185d
3,654,083
from typing import Any from typing import Dict def year_page(archive_id: str, year: int) -> Any: """ Get year page for archive. Parameters ---------- archive : str Must be an arXiv archive identifier. year: int Must be a two or four digit year. Returns ------- dict ...
9bd609718d782d3cca185929ebacebd0e353bb10
3,654,084
import scipy def vert_polyFit2(data, z, bin0, step=1, deg=2): """ Trying to use the vertical polynomial fit to clean up the data not reallly sure about what im doing though """ data = np.squeeze(data) z = np.squeeze(z) dz = np.nanmean(np.gradient(np.squeeze(z))) bin1 = int(np.ceil(bi...
ceeeac26b9eba625164a055deb96741c6d99702e
3,654,085
def is_downloadable(url): """ Does the url contain a downloadable resource """ h = requests.head(url, allow_redirects=True) header = h.headers content_type = header.get('content-type') print content_type if 'text' in content_type.lower(): return False if 'html' in content_typ...
74ccff9d967a3763c852a23d8775970ac9ff9e10
3,654,086
def dataframe_is_one_query_target_pair(dataframe): """ make sure there is only one query sequence and reference sequence in the given dataframe. Used to check that we aren't aggregating % identity numbers across bin alignment pairs. :param dataframe: :return: """ num_query_bins = len(d...
8a8aba9f4b2eaaca6971bf5c158d043a033d0ec8
3,654,087
def update_api_key( self, name: str, permission: str, expiration: int, active: bool, key: str = None, description: str = None, ip_list: str = None, ) -> bool: """Update existing API key on Orchestrator .. list-table:: :header-rows: 1 * - Swagger Section ...
9e37062475c3b83ab86c51355442cf6de0df1c34
3,654,088
def cleanGender(x): """ This is a helper funciton that will help cleanup the gender variable. """ if x in ['female', 'mostly_female']: return 'female' if x in ['male', 'mostly_male']: return 'male' if x in ['couple'] : return 'couple' else: return 'unknownGe...
23d71f2307aa829312f4a1d2a002ae2b55556050
3,654,089
def get_servers(): """ Retrieve all the discord servers in the database :return: List of servers """ session = Session() servers = session.query(Server).all() return servers
3953867d18c2e282ee11190a3ee1303126b2394e
3,654,090
def wait_till_postgres_responsive(url): """Check if something responds to ``url`` """ engine = sa.create_engine(url) conn = engine.connect() conn.close() return True
645c98799fa7d0347fc52850b7f3813fec74968c
3,654,091
def get_string_display(attr1, attr2, helper1, helper2, attribute_mode): """ get the attribute mode for string attribute mode can be: 'base', 'full', 'partial', 'masked' Note that some attribute does not have partial mode, in this case, partial mode will return masked mode Remeber to call has_par...
fa61332f82310ece349309f378126a4b3179483f
3,654,092
import re def is_doi(identifier: str) -> bool: """Validates if identifier is a valid DOI Args: identifier (str): potential doi string Returns: bool: true if identifier is a valid DOI """ doi_patterns = [ r"(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?![\"&\'])\S)+)", r"(10....
5c0bfe0527adbf53e89d302ee05feb80d285db64
3,654,093
def meshgrid_flatten(*X): """ Functionally same as numpy.meshgrid() with different output format. Function np.meshgrid() takes n 1d ndarrays of size N_1,...,N_n, and returns X_1,...,X_n n-dimensional arrays of shape (N_1, N_2,... N_n). This returns instead a 2d array of shape (N_1*...*N_n, n)....
a7136a7a4dadb6449fd5079c78f15b13da3721dd
3,654,094
from typing import Union import copy def transform_scale( features, factor: float, origin: Union[str, list] = "centroid", mutate: bool = False, ): """ Scale a GeoJSON from a given point by a factor of scaling (ex: factor=2 would make the GeoJSON 200% larger). If a FeatureCollection...
bacc6a365dbed0531d4516a736dd9ca2937b8cad
3,654,095
import importlib def create_agent(opt): """Create an agent from the options model, model_params and model_file. The input is either of the form "parlai.agents.ir_baseline.agents/IrBaselineAgent" (i.e. the path followed by the class name) or else just 'IrBaseline' which assumes the path above, and a cl...
6f5793ee0af7ed677f47c27ba5b94ad6f80ea957
3,654,096
def check_version(actver, version, cmp_op): """ Check version string of an active module against a required version. If dev/prerelease tags result in TypeError for string-number comparison, it is assumed that the dependency is satisfied. Users on dev branches are responsible for keeping their own p...
4d2cf92c412659044ad226aeeadb9145ceb75241
3,654,097
def dfa_intersection(dfa_1: dict, dfa_2: dict) -> dict: """ Returns a DFA accepting the intersection of the DFAs in input. Let :math:`A_1 = (Σ, S_1 , s_{01} , ρ_1 , F_1 )` and :math:`A_2 = (Σ, S_2 , s_{02} , ρ_2 , F_2 )` be two DFAs. Then there is a DFA :math:`A_∧` that runs simultaneously both ...
ea69f3cda2bd28f5b70d1724ffdd628daf1beffa
3,654,098
def change_status(request, page_id): """ Switch the status of a page. """ perm = PagePermission(request.user).check('change', method='POST') if perm and request.method == 'POST': page = Page.objects.get(pk=page_id) page.status = int(request.POST['status']) page.invalidate() ...
b65775d91c69cf4ac4d5a59d128581011986f1e7
3,654,099
def str2bytes(s): """ Returns byte string representation of product state. Parameters ---------- s : str Representation of a product state, in terms of a string. """ return bitarray2bytes(str2bitarray(s))
defb9f471ba6108a0d667b6f4e9522c8b6f38649
3,654,100
import re def find_links(text, image_only=False): """ Find Markdown links in text and return a match object. Markdown links are expected to have the form [some txt](A-url.ext) or ![Alt text](cool-image.png). Parameters ---------- text : str Text in which to search for links. ...
5f96672b48d3d911faf2e398c86f622676263d73
3,654,101
def least_one_row(data_frame): """ checking at least one row in dataframe Input: pandas dataframe Output: True or False """ if data_frame: return True return False
a72cbd3d504140547233481ec8340a8510e35f52
3,654,102
import math def generate_label_colors(labels: list, colors: list, palette='Set2'): """Matches labels with colors If there are more labels than colors, repeat and cycle through colors """ label_colors = defaultdict(dict) num_repeats = math.ceil(len(labels) / len(colors)) for label in enumerate(...
8b4b35498d4478604e81987b127ab099ebb0e70b
3,654,104
def index(): """ View root page function that returns the index page and its data """ # getting top headlines in sources topheadlines_sources = get_sources('top-headlines') business_sources = get_sources('business') entertainment_sources = get_sources('entertainment') title = 'Home - We...
df3c5d0471cde998f6ea5a0de2b41ab16ef775c6
3,654,106
def start_ltm(tup, taus, w=0.1, add_coh=False, use_cv=False, add_const=False, verbose=False, **kwargs): """Calculate the lifetime density map for given data. Parameters ---------- tup : datatuple t...
d24d2fdc9740a12766b5424a20c98f4ab14222eb
3,654,107
def manhattan_distance(origin, destination): """Return the Manhattan distance between the origin and the destination. @type origin: Location @type destination: Location @rtype: int >>> pt1 = Location(1,2) >>> pt2 = Location(3,4) >>> print(manhattan_distance(pt1, pt2)) 4 """ ret...
0bcfd7767e44b0dcc47890dc4bcb2c054abb4bde
3,654,108
from typing import Dict from typing import List import logging def find_best_resampler( features_train: pd.DataFrame, labels_train: pd.DataFrame, parameters: Dict ) -> List: """Compare several resamplers and find the best one to handle imbalanced labels. Args: features_train: Training data of ind...
29c14261e0c5131c8fad653bb286d03c73b8ddd7
3,654,110
def grid(dim, num): """Build a one-dim grid of num points""" if dim.type == "categorical": return categorical_grid(dim, num) elif dim.type == "integer": return discrete_grid(dim, num) elif dim.type == "real": return real_grid(dim, num) elif dim.type == "fidelity": re...
1d59936882cd15372e0c13c02d80cbe739650134
3,654,111
def path(graph, source, target, excluded_edges=None, ooc_types=ooc_types): """ Path of functions between two types """ if not isinstance(source, type): source = type(source) if not isinstance(target, type): target = type(target) for cls in concatv(source.mro(), _virtual_superclasses): ...
6bdf2adbfc754dc5350406570bc865ac17c088ce
3,654,112
def is_resource_sufficient(order_ingredients): """Return true or false""" for item in order_ingredients: if order_ingredients[item]>=resources[item]: print(f"Sorry not Enough {item} to Make Coffee.") return False return True
758ab17760aac8f32b4d5fb93e42e01bc780507b
3,654,113
import requests def get_gh_releases_api(project, version=None): """ """ # https://developer.github.com/v3/auth/ # self.headers = {'Authorization': 'token %s' % self.api_token} # https://api.github.com/repos/pygame/stuntcat/releases/latest repo = get_repo_from_url(project.github_repo) if no...
348857ab557277f7b26cb93866284ac899746524
3,654,114
import random import logging def weak_move(board): """Weak AI - makes a random valid move. Args: board: (Board) The game board. Returns: Array: Our chosen move. """ valid_moves = _get_moves(board, Square.black) # Return a random valid move our_move = valid_moves[random.randrange(0, len(valid_m...
6c978b58cca58baadaab5417b27adbf4444d59ff
3,654,115
def flow_to_image(flow): """ Input: flow: Output: Img array: Description: Transfer flow map to image. Part of code forked from flownet. """ out = [] maxu = -999. maxv = -999. minu = 999. minv = 999. maxrad = -1 for i in range(flow.shape[0])...
b7ed9cf684b4b818397f0329f3c7de1dbfa2ecd8
3,654,116
def parse_model_value(value, context): """ do interpolation first from context, "x is {size}" with size = 5 will be interpolated to "x is 5" then return interpolated string :param value: :param context: :return: """ return value.format(**context)
58cee6092bc03debe636ae8fa47878727457d334
3,654,117
def apply_tropomi_operator( filename, n_elements, gc_startdate, gc_enddate, xlim, ylim, gc_cache, build_jacobian, sensi_cache, ): """ Apply the tropomi operator to map GEOS-Chem methane data to TROPOMI observation space. Arguments filename [str] : TR...
c449ddaf8113a3adfcd0e501cacc245bcf0af495
3,654,118
import yaml from typing import cast def load_configuration(yaml: yaml.ruamel.yaml.YAML, filename: str) -> DictLike: """Load an analysis configuration from a file. Args: yaml: YAML object to use in loading the configuration. filename: Filename of the YAML configuration file. Returns: ...
6c3b9b54b6e22b40c61c901b2bcb3b6af4847214
3,654,119
def device_list(request): """ :param request: :return: """ device_list = True list = Device.objects.all() return render(request, "back/device_list.html", locals())
f4892f40831d25182b55414a666fbd62d6d978ef
3,654,120
def L008_eval(segment, raw_stack, **kwargs): """ This is a slightly odd one, because we'll almost always evaluate from a point a few places after the problem site """ # We need at least two segments behind us for this to work if len(raw_stack) < 2: return True else: cm1 = raw_stack[-...
71c42999ffc76bd28a61b640cf85086b0b9e8d69
3,654,121
def overwrite_ruffus_args(args, config): """ :param args: :param config: :return: """ if config.has_section('Ruffus'): cmdargs = dict() cmdargs['draw_horizontally'] = bool cmdargs['flowchart'] = str cmdargs['flowchart_format'] = str cmdargs['forced_tasks']...
6f947c362a37bfdc6df53c861783604999621a88
3,654,122
def read_sfr_df(): """Reads and prepares the sfr_df Parameters: Returns: sfr_df(pd.DataFrame): dataframe of the fits file mosdef_sfrs_latest.fits """ sfr_df = read_file(imd.loc_sfrs_latest) sfr_df['FIELD_STR'] = [sfr_df.iloc[i]['FIELD'].decode( "utf-8").rstrip() for i in range(le...
9d0d16929ffd5043853096c01cafa00747104b9f
3,654,123
def redshift(x, vo=0., ve=0.,def_wlog=False): """ x: The measured wavelength. v: Speed of the observer [km/s]. ve: Speed of the emitter [km/s]. Returns: The emitted wavelength l'. Notes: f_m = f_e (Wright & Eastman 2014) """ if np.isnan(vo): vo = 0 # propagate ...
0dee71d862d2dc4252033964a9adcb4428c5dfa9
3,654,124
import mmap def overlay_spectra_plot(array, nrow=5,ncol=5,**kwargs): """ Overlay spectra on a collapsed cube. Parameters ---------- array : 3D numpy array nrow : int Number of rows in the figure. ncol : int Number of columns in the figure. ...
8abbbbe7667c57bea50575a58bf11c3b080c8608
3,654,125
def digest_from_rsa_scheme(scheme, hash_library=DEFAULT_HASH_LIBRARY): """ <Purpose> Get digest object from RSA scheme. <Arguments> scheme: A string that indicates the signature scheme used to generate 'signature'. Currently supported RSA schemes are defined in `securesystemslib.keys.RS...
6eaf10657a0e80f2ddfa5eacbcc1bac72437ca51
3,654,126
def table(content, accesskey:str ="", class_: str ="", contenteditable: str ="", data_key: str="", data_value: str="", dir_: str="", draggable: str="", hidden: str="", id_: str="", lang: str="", spellcheck: str="", style: str="", tabindex: str="", title: str="", transl...
b27cf1b1897bdbc764fff76edc2e53fa0aca7861
3,654,128
def _ev_match( output_dir, last_acceptable_entry_index, certificate, entry_type, extra_data, certificate_index): """Matcher function for the scanner. Returns the certificate's hash if it is a valid, non-expired, EV certificate, None otherwise.""" # Only generate whitelist for non-precertific...
acd8416546d5f687fd1bfc1f0edfc099cde4408d
3,654,129
def axis_ratio_disklike(scale=0.3, truncate=0.2): """Sample (one minus) the axis ratio of a disk-like galaxy from the Rayleigh distribution Parameters ---------- scale : float scale of the Rayleigh distribution; the bigger, the smaller the axis ratio truncate : float the minimum val...
d001ef0b2f5896f4e7f04f314cd4e71ffd97a277
3,654,130
import numpy def rk4(y0, t0, te, N, deriv, filename=None): """ General RK4 driver for N coupled differential eq's, fixed stepsize Input: - y0: Vector containing initial values for y - t0: Initial time - te: Ending time - N: Number of steps - deriv...
93b7255fc95f06f765df12930efcf89338970ee6
3,654,131
from typing import Dict from typing import Tuple def create_txt_substitute_record_rule_command(client: Client, args: Dict) -> Tuple[str, Dict, Dict]: """ Args: client: Client object args: Usually demisto.args() Returns: Outputs """ name = args.get('name') rp_zone = arg...
ada3c412ec166eedd04edb2219396da6aef967ea
3,654,132
def pot_rho_linear(SP, t, rho0=1025, a=2e-4, b=7e-4, SP0=35, t0=15): """ Potential density calculated using a linear equation of state: Parameters ---------- SP : array-like Salinity [g/kg] t : array-like Temperature [°C] rho0 : float, optional Constant ...
47dd8248239d2147ff50d1b179d3fc4392c173cb
3,654,133
async def create_assc(conn : asyncpg.Connection, name : str, type : str, base : str, leader : int) -> Association: """Create an association with the fields given. type must be 'Brotherhood','College', or 'Guild'. """ psql = """ SELECT assc_id FROM associations ...
3089b6033e31325d7b3942d9d887b89cec21ca1c
3,654,135
def get_path_from_query_string(req): """Gets path from query string Args: req (flask.request): Request object from Flask Returns: path (str): Value of "path" parameter from query string Raises: exceptions.UserError: If "path" is not found in query string """ if req.arg...
7e279e8e33dbbaa6ceb18d4b9a61723826522ec3
3,654,137
import scipy def entropy_grassberger(n, base=None): """" Estimate the entropy of a discrete distribution from counts per category n: array of counts base: base in which to measure the entropy (default: nats) """ N = np.sum(n) entropy = np.log(N) - np.sum(n*scipy.special.digamma(n+1e-20))...
1dc5ced1f5bb43bce30fa9501632825648b19cb8
3,654,138
def get_param_layout(): """Get layout for causality finding parameters definition window Parameters ---------- Returns ------- `List[List[Element]]` Layout for causality finding parameters window """ box = [ [ sg.Text('Parameters') ],...
e09db05b848e71449d7d17004793e8ce167dca1a
3,654,139
def senti_histplot(senti_df): """histogram plot for sentiment""" senti_hist = ( alt.Chart(senti_df) .mark_bar() .encode(alt.Y(cts.SENTI, bin=True), x="count()", color=cts.SENTI,) .properties(height=300, width=100) ).interactive() return senti_hist
731fda9cf5af49fdbec7d1a16edbf65148e67d5a
3,654,140
def pd_df_sampling(df, coltarget="y", n1max=10000, n2max=-1, isconcat=1): """ DownSampler :param df: :param coltarget: binary class :param n1max: :param n2max: :param isconcat: :return: """ df1 = df[df[coltarget] == 0].sample(n=n1max) n2max = len(df[df[coltarget] == 1]) ...
2cec90c189d00a8cd3ec19224fa7a2685c135bf2
3,654,141
def get_deliverer(batch_size, max_staleness, session): """ Helper function to returns the correct deliverer class for the batch_size and max_stalennes parameters """ if batch_size < 1: return SimpleDeliverer(session) else: return BatchDeliverer(session, batch_size, max_staleness)
544740a5f38befc4d8123e7835ba758feac2d35b
3,654,143
import copy def trace_fweight_deprecated(fimage, xinit, ltrace=None, rtraceinvvar=None, radius=3.): """ Python port of trace_fweight.pro from IDLUTILS Parameters: ----------- fimage: 2D ndarray Image for tracing xinit: ndarray Initial guesses for x-trace invvar: ndarray, optional ...
e927113477a277ceb9acc8ce6af8bd1689c2913c
3,654,144
from datetime import datetime def home(): """Renders the card page.""" cardStack = model.CardStack() return render_template( 'cards.html', title ='POSTIN - Swipe', cardSet = cardStack.cardList, year=datetime.now().year, )
203021b1da4833418aafd3e3e20964e3b765a816
3,654,145
def index(request): """ User profile page. """ user = request.user profile = user.userprofile context = collect_view_data(request, 'profile') context['user'] = user context['profile'] = profile context['uform'] = UserForm(request, request.user, init=True) context['upform'] = User...
1a8cc98ba476e21986f79ec8e662bb222df79fae
3,654,147
def user_confirm_email(token): """Confirm a user account using his email address and a token to approve. Parameters ---------- token : str The token associated with an email address. """ try: email = ts.loads(token, max_age=86400) except Exception as e: logger.error(...
3f26a4872af9759165d0592ac8d966f2e27a9bf6
3,654,148
def num_zeros_end(num): """ Counts the number of zeros at the end of the number 'num'. """ iszero = True num_zeros = 0 i = len(num)-1 while (iszero == True) and (i != 0): if num[i] == "0": num_zeros += 1 elif num[i] != "0": ...
f227cce65e26a0684a10755031a4aeff2156015a
3,654,149
from typing import List def batch_summarize(texts: List[str]) -> List[str]: """Summarizes the texts (local mode). :param texts: The texts to summarize. :type texts: List[str] :return: The summarized texts. :rtype: List[str] """ if _summarizer is None: load_summarizer() asse...
7c05b8f612faab808fbeb1ef7c21f8b3b2487be5
3,654,150
def Vp_estimation(z, T, x, g=param.g): """ Estimation of the Vp profile from the results of solving the system. """ DT = T - T[-1] # temperature variation in the layer compared to T[ICB] drhoP = -param.rhoH**2. * g * z / Seismic_observations.calcK(z) drhoT = -param.rhoH * param.alpha * DT # *(Mp*...
4f1e1936cc98cfd84d87a651c8deac5bb7aa39e0
3,654,151
def pp_date(dt): """ Human-readable (i.e. pretty-print) dates, e.g. for spreadsheets: See http://docs.python.org/tutorial/stdlib.html e.g. 31-Oct-2011 """ d = date_to_datetime(dt) return d.strftime('%d-%b-%Y')
a6c8cd97785212afebb2b8948117815f5553dc24
3,654,152
import copy import math def optimizer_p(cd, path, i, obs, path_penalty): """Optimizer of the current path. Reduce the piece-wise path length in the free space of the environment.""" p_tmp = copy.deepcopy(path) p_tmp[i].x = p_tmp[i].x + cd[0] p_tmp[i].y = p_tmp[i].y + cd[1] r1 = math.sqrt((p_tmp[i-...
da126e3e7c0013748b1bc5b39c1b51aa2bf0d68b
3,654,153
import base64 def create_message(sender_address, receiver_address , subject, email_content): """Create a message for an email. Args: sender: Email address of the sender. to: Email address of the receiver. subject: The subject of the email message. message_text: The text of the email message. R...
3970272fda9650b5b59de9a57b2579374088b5c4
3,654,154
def get_latest_revision_number(request, package_id): """ returns the latest revision number for given package """ package = get_object_or_404(Package, id_number=package_id) return HttpResponse(simplejson.dumps({ 'revision_number': package.latest.revision_number}))
3f8053656cbd7e08336a4632f1deaf43e58bc3eb
3,654,156
from typing import Mapping def _make_mesh_tensors(inputs: Mapping[K, np.ndarray]) -> Mapping[K, tf.Tensor]: """ Computes tensors that are the Cartesian product of the inputs. This is around 20x faster than constructing this in Python. Args: inputs: A mapping from keys to NumPy arrays. R...
65a97e7f7d85668acd2af50ba9ed745190181018
3,654,157
def make_counters(): """Creates all of the VariantCounters we want to track.""" def _gt_selector(*gt_types): return lambda v: variantutils.genotype_type(v) in gt_types return VariantCounters([ ('All', lambda v: True), ('SNPs', variantutils.is_snp), ('Indels', variantutils.is_indel), ...
b7a943f045018556a2a5d0dbf5e093906d10242a
3,654,158