content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import json def get_json(url, **kwargs): """Downloads json data and converts it to a dict""" raw = get(url, **kwargs) if raw == None: return None return json.loads(raw.decode('utf8'))
16504c03beaa1a5913f2256ad6a1871049694e14
14,600
def get_text(im): """ 得到图像中的文本部分 """ return im[3:24, 116:288]
86db2a16372aacb6cde29a2bf16c84f14f65d715
14,601
def homepage(): """Display tweets""" tweet_to_db() output = [a for a in Tweet.query.order_by(desc('time_created')).all()] # to display as hyper links for tweet in output: tweet.handle = linkyfy(tweet.handle, is_name=True) tweet.text = linkyfy(tweet.text) return render_template...
d37138ea2ed6bdf8a650e644943e330400417f57
14,602
def watch_list_main_get(): """ Render watch list page. Author: Jérémie Dierickx """ watchlist = env.get_template('watchlists.html') return header("Watch List") + watchlist.render(user_name=current_user.pseudo) + footer()
760c8f2acf4a3ea1791860568ae747b9bd35593c
14,603
def input_file(inp_str): """ Parse the input string """ # Parse the sections of the input into keyword-val dictionaries train_block = ioformat.ptt.symb_block(inp_str, '$', 'training_data') fform_block = ioformat.ptt.symb_block(inp_str, '$', 'functional_form') exec_block = ioformat.ptt.symb_bloc...
9ae7c55c59e6b89b43271836738fd4fffbf38455
14,604
import ck.net import hashlib import zipfile import os def download(i): """ Input: { (repo_uoa) (module_uoa) (data_uoa) (new_repo_uoa) - new repo UOA; "local" by default (skip_module_check) - if 'yes', do not check if module for a...
4853ea5b79cd8b2a015f85ab2f4297f6528fece3
14,605
def recursiveUpdate(target, source): """ Recursively update the target dictionary with the source dictionary, leaving unfound keys in place. This is different than dict.update, which removes target keys not in the source :param dict target: The dictionary to be updated :param dict source: The dicti...
e1c11d0801be9526e8e73145b1dfc7be204fc7d0
14,606
import time import requests import json def macro_bank_usa_interest_rate(): """ 美联储利率决议报告, 数据区间从19820927-至今 https://datacenter.jin10.com/reportType/dc_usa_interest_rate_decision https://cdn.jin10.com/dc/reports/dc_usa_interest_rate_decision_all.js?v=1578581921 :return: 美联储利率决议报告-今值(%) :rtype: ...
52885b4cfbb607d3ecbb0f89f19cac7e1f097ccd
14,607
def get_kwd_group(soup): """ Find the kwd-group sections for further analysis to find subject_area, research_organism, and keywords """ kwd_group = None kwd_group = extract_nodes(soup, 'kwd-group') return kwd_group
626a85b5274880d1e4520f4afe5a270e5f20832a
14,608
def read_transport_file(input_file_name): """ Reads File "input_file_name".dat, and returns lists containing the atom indices of the device atoms, as well as the atom indices of the contact atoms. Also, a dictionary "interaction_distances" is generated, which spcifies the maximum interaction distanc...
d62e3cc1dfbe2ac4865579dca86133bedb06182f
14,609
def handle_srv6_path(operation, grpc_address, grpc_port, destination, segments=None, device='', encapmode="encap", table=-1, metric=-1, bsid_addr='', fwd_engine='linux', key=None, update_db=True, db_conn=None, channel=None): """ Handle a SRv6 Path. ...
3181f9b4e99a6414c92614caee7af0ff133ad01d
14,610
def mask_outside_polygon(poly_verts, ax, facecolor=None, edgecolor=None, alpha=0.25): """ Plots a mask on the specified axis ("ax", defaults to plt.gca()) such that all areas outside of the polygon specified by "poly_verts" are masked. "poly_verts" must be a list of tuples of the verticies in the polyg...
1c46d12d7f3c92e3ff4522bb88713eae3c9138b1
14,611
def setup_data(cluster): """ Get decision boundaries by means of np.meshgrid :return: Tuple (vectors, centroids, X component of mesghgrid, Y component of meshgrid, ) """ feature_vectors, _, centroids, _, kmeans = cluster # Step size of the mesh. Decrease to increase the quality of the VQ. h...
edcfede8e8f7fc18fc9e7255127f0f14688df2f2
14,612
import time import os import numpy def Routing_Table(projdir, rootgrp, grid_obj, fdir, strm, Elev, Strahler, gages=False, Lakes=None): """If "Create reach-based routing files?" is selected, this function will create the Route_Link.nc table and Streams.shp shapefiles in the output directory.""" # Stackles...
4af012fadf2fa7f84ac945638db52413155f900d
14,613
from datetime import datetime def list_errors( conx: Connection, ) -> t.List[t.Tuple[int, datetime.datetime, str, str, str, str]]: """Return list of all errors. The list returned contains each error as an element in the list. Each element is a tuple with the following layout: (seq nr, date, ...
2aea677d8e69a76c5a6922d9c7e6ce3078ad7488
14,614
async def get_incident(incident_id): """ Get incident --- get: summary: Get incident tags: - incidents parameters: - name: id in: path required: true description: Object ID responses: 200: ...
f70703b43944dfa2385a2a35249dd692fe18a1ba
14,615
from typing import List def partition_vector(vector, sets, fdtype: str='float64') -> List[NDArrayNfloat]: # pragma: no cover """partitions a vector""" vectors = [] for unused_aname, aset in sets: if len(aset) == 0: vectors.append(np.array([], dtype=fdtype)) continue ...
e73494d146ec56a8287c0e0e3ec3dec7f7d93c37
14,616
def calculate_G4( n_numbers, neighborsymbols, neighborpositions, G_elements, theta, zeta, eta, Rs, cutoff, cutofffxn, Ri, normalized=True, image_molecule=None, n_indices=None, weighted=False, ): """Calculate G4 symmetry function. These are 3 body or a...
5a864c615d2b835da4bb3d99435b9e2e2a40e136
14,617
import argparse def parse_arguments(): """Parse command line arguments.""" parser = argparse.ArgumentParser() parser.add_argument( '--output', type=str, required=False, help='GCS URL where results will be saved as a CSV.') parser.add_argument( '--query', type=str, re...
9bbf5d16e94b5cac8ff230592d2cbe544e771e7a
14,618
def paths_from_root(graph, start): """ Generates paths from `start` to every other node in `graph` and puts it in the returned dictionary `paths`. ie.: `paths_from_node(graph, start)[node]` is a list of the edge names used to get to `node` form `start`. """ paths = {start: []} q = [start...
9b8399b67e14a6fbfe0d34c087317d06695bca65
14,619
from typing import Sequence from typing import Optional from typing import Callable from typing import Dict def list_to_dict(l:Sequence, f:Optional[Callable]=None) -> Dict: """ Convert the list to a dictionary in which keys and values are adjacent in the list. Optionally, a function `f` can be passed to apply...
a1f47582a2de8fa47bbf4c79c90165f8cf703ca1
14,620
def inner(a, b): """Computes an inner product of two arrays. Ordinary inner product of vectors for 1-D arrays (without complex conjugation). Parameters ---------- a, b : array_like If *a* and *b* are nonscalar, their shape must match. Returns ------- out : ndarray out....
248f1069251770073bc6bb4eedda0ef557aaeb9f
14,621
from typing import Sequence from re import T def remove_list_redundancies(lst: Sequence[T]) -> list[T]: """ Used instead of list(set(l)) to maintain order Keeps the last occurrence of each element """ return list(reversed(dict.fromkeys(reversed(lst))))
f17408e7c3e3f5b2994e943b668c81b71933a2c9
14,622
def concatenate(arrays, axis): """Concatenate along axis. Differs from numpy.concatenate in that it works if the axis doesn't exist. """ logger.debug('Applying asarray to each element of arrays.') arrays = [np.asarray(array) for array in arrays] logger.debug('Adding axes to each element of arra...
08fc2e45506273afef4c826611d270886b9b99d4
14,623
import os import subprocess def s7_blastn_xml(qry, base, threads): """ run blastn with xml output qry and base are absolute paths """ print("Step7 ... :" + qry) os.makedirs(os.path.join(hivdrm_work_dir, s7_prefix), exist_ok = True) qry_file = os.path.basename(qry) base_file = os.path.basename(base...
7f1ed3e5a581082c1f7f6ecb9ee06bc21c7f0f65
14,624
def bpformat(bp): """ Format the value like a 'human-readable' file size (i.e. 13 Kbp, 4.1 Mbp, 102 bp, etc.). """ try: bp = int(bp) except (TypeError, ValueError, UnicodeDecodeError): return avoid_wrapping("0 bp") def bp_number_format(value): return formats.number_f...
4c2b587b3aecd4dd287f7f04b3860f63440154a1
14,625
def get_module_id_from_event(event): """ Helper function to get the module_id from an EventHub message """ if "iothub-connection-module_id" in event.message.annotations: return event.message.annotations["iothub-connection-module-id".encode()].decode() else: return None
e183824fff183e3f95ef35c623b13245eb68a8b7
14,626
def pipe_literal_representer(dumper, data): """Create a representer for pipe literals, used internally for pyyaml.""" return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|')
b73e7d451ae50bc4638d3cb45546f2a197765717
14,627
def RecognitionNeuralNetworkModelSmall(ih, iw, ic, nl): """ A simple model used to test the machinery on TrainSmall2. ih, iw, ic - describe the dimensions of the input image mh, mw - describe the dimensions of the output mask """ dropout = 0.1 model = Sequential() model.add(Conv2D(32,...
e4ec0ccb958eb9b406c079aeb9526e5adc1f6978
14,628
def _quick_rec_str(rec): """try to print an identifiable description of a record""" if rec['tickets']: return "[tickets: %s]" % ", ".join(rec["tickets"]) else: return "%s..." % rec["raw_text"][0:25]
e666198de84fe9455ad2cee59f8ed85144589be0
14,629
from typing import Collection def A006577(start: int = 0, limit: int = 20) -> Collection[int]: """Number of halving and tripling steps to reach 1 in '3x+1' problem, or -1 if 1 is never reached. """ def steps(n: int) -> int: if n == 1: return 0 x = 0 while True: ...
47829838af8e2fdb191fdefa755e728db9c09559
14,630
def split_to_sentences_per_pages(text): """ splitting pdfminer outputted text into list of pages and cleanup paragraphs""" def split_into_sentences(line): """cleanup paragraphs""" return ifilter(None, (i.strip() for i in line.split('\n\n'))) return ifilter(None, imap(split_into_sentences...
b40ac7d6b4f3e9482897934999858271aeaf9494
14,631
def lookup(_id=None, article_id=None, user_id=None, mult=False): """ Lookup a reaction in our g.db """ query = {} if article_id: query["article_id"] = ObjectId(article_id) if user_id: query["user_id"] = ObjectId(user_id) if _id: query["_id"] = ObjectId(_id) if m...
5d3c064278da8419e6305508a3bf47bba60c818c
14,632
def connection(user='m001-student', password='m001-mongodb-basics'): """connection: This function connects mongoDB to get MongoClient Args: user (str, optional): It's user's value for URL ATLAS srv. Defaults to 'm001-student'. password (str, optional): It's password's value for URL ATLAS srv. D...
0714ffa01aa21dd71d6eefcadb0ebc2379cd3e6f
14,633
import random import asyncio async def get_selection(ctx, choices, delete=True, pm=False, message=None, force_select=False): """Returns the selected choice, or None. Choices should be a list of two-tuples of (name, choice). If delete is True, will delete the selection message and the response. If length o...
663f60c73bc6c1e3d7db5992b6dbb6d6953d0e24
14,634
import os def data_dir(): """ Get SUNCG data path (must be symlinked to ~/.suncg) :return: Path to suncg dataset """ if 'SUNCG_DATA_DIR' in os.environ: path = os.path.abspath(os.environ['SUNCG_DATA_DIR']) else: path = os.path.join(os.path.abspath(os.path.expanduser('~')), ".suncg...
8025d99b394e963b05afb430801c1baf7c2b894f
14,635
def total_variation(images, name=None): """Calculate and return the total variation for one or more images. (A mirror to tf.image total_variation) The total variation is the sum of the absolute differences for neighboring pixel-values in the input images. This measures how much noise is in the ima...
c12e822cd09ff6ea5f9bbc45ffa71121de5ff3e7
14,636
def get_vivareal_data(driver_path: str, address: str, driver_options: Options = None) -> list: """ Scrapes vivareal site and build a array of maps in the following format: [ { "preço": int, "valor_de_condominio": int, "banheiros": int, "quartos": int,...
e3495c05f39e7cb301fa90e62b5a398a69658e74
14,637
import logging def extract_image(data): """Tries and extracts the image inside data (which is a zipfile)""" with ZipFile(BytesIO(data)) as zip_file: for name in zip_file.namelist()[::-1]: try: return Image.open(BytesIO(zip_file.read(name))) except UnidentifiedIm...
2aa333d493a1a3ce637fb2d42bca85bbbb089728
14,638
import six def construct_getatt(node): """ Reconstruct !GetAtt into a list """ if isinstance(node.value, (six.text_type, six.string_types)): return node.value.split(".") elif isinstance(node.value, list): return [s.value for s in node.value] else: raise ValueError("Une...
657b957a06c79905b557dd397efea2c598d8c6b3
14,639
import os def check_root(): """ Check whether the program is running as root or not. Args: None Raises: None Returns: bool: True if running as root, else False """ user = os.getuid() return user == 0
a11285efc5ca430e5538b547b56468036611763f
14,640
def rss(x, y, w, b): """residual sum of squares for linear regression """ return sum((yi-(xi*wi+b))**2 for xi, yi, wi in zip(x,y, w))
955e0b5e3dcf8373fe5ef1b95244d06abe512084
14,641
def get_index(lang, index): """ Given an integer index this function will return the proper string version of the index based on the language and other considerations Parameters ---------- lang : str One of the supported languages index : int Returns ------- str ...
bcb3a88857b13eea95d5a1bb939c9c4e175ea677
14,642
def sampleFunction(x: int, y: float) -> float: """ Multiply int and float sample. :param x: x value :type x: int :param y: y value :type y: float :return: result :return type: float """ return x * y
f70708b3ece2574969834a62841da3e4506f704b
14,643
def n_elements_unique_intersection_np_axis_0(a: np.ndarray, b: np.ndarray) -> int: """ A lot faster than to calculate the real intersection: Example with small numbers: a = [1, 4, 2, 13] # len = 4 b = [1, 4, 9, 12, 25] # (len = 5) # a, b need to be unique!!! unique(concat(a,...
ce8e3cfd158205a0fa2c5f1d10622c6901bc3224
14,644
import logging def Setup(test_options): """Runs uiautomator tests on connected device(s). Args: test_options: A UIAutomatorOptions object. Returns: A tuple of (TestRunnerFactory, tests). """ test_pkg = test_package.TestPackage(test_options.uiautomator_jar, tes...
2d50c53d211bbddae495a89687cf0cf95b08b1ba
14,645
def barcode_junction_counts(inhandle): """Return count dict from vdjxml file with counts[barcode][junction]""" counts = dict() for chain in vdj.parse_VDJXML(inhandle): try: # chain may not have barcode counts_barcode = counts.setdefault(chain.barcode,dict()) except AttributeEr...
5cc29e44e34989fbd2afb4a2d34f63c7e7adf160
14,646
def is_following(user, actor): """ retorna True si el usuario esta siguiendo al actor :: {% if request.user|is_following:another_user %} You are already following {{ another_user }} {% endif %} """ return Follow.objects.is_following(user, actor)
963ccc2f75f19609943aba6b61a7522573665033
14,647
from typing import Union def rf_make_ones_tile(num_cols: int, num_rows: int, cell_type: Union[str, CellType] = CellType.float64()) -> Column: """Create column of constant tiles of one""" jfcn = RFContext.active().lookup('rf_make_ones_tile') return Column(jfcn(num_cols, num_rows, _parse_cell_type(cell_type...
8ed63c974613e0451a3d8c78eac964c93c6f8154
14,648
def get_block_hash_from_height(height): """ Request a block hash by specifying the height :param str height: a bitcoin block height :return: a bitcoin block address """ resource = f'block-height/{height}' return call_api(resource)
877f4c4268cb3c7c36bd530a38d4b32abbedcaf4
14,649
from typing import Tuple from typing import Set from typing import List def analyze_json( snippet_data_json: str, root_dir: str ) -> Tuple[Set[str], Set[str], Set[str], List[pdd.PolyglotDriftData]]: """Perform language-agnostic AST analysis on a directory This function processes a given directory's l...
9129b1fad5172f9b7054ba9b4e64cc4ece5ab09c
14,650
import json def list_clusters(event, context): """List clusters""" clusters = [] cluster_items = storage.get_cluster_table().scan() for cluster in cluster_items.get('Items', []): clusters.append(cluster['id']) return { "statusCode": 200, "body": json.dumps(clusters) ...
5f88ca446e8d07d7584b1dfd12fb64cddefc918c
14,651
def round(data): """Compute element-wise round of data. Parameters ---------- data : relay.Expr The input data Returns ------- result : relay.Expr The computed result. """ return _make.round(data)
e3adfdc29d9cc641ca33fb375649caf176098d75
14,652
def deserialize(member, class_indexing): """ deserialize """ class_name = member[0].text if class_name in class_indexing: class_num = class_indexing[class_name] else: return None bnx = member.find('bndbox') box_x_min = float(bnx.find('xmin').text) box_y_min = floa...
087102acec79ec5d0ecad91453885579c2395895
14,653
def interval_weighting(intervals, lower, upper): """ Compute a weighting function by finding the proportion within the dataframe df's lower and upper bounds. Note: intervals is of the form ((lower, upper, id), ...) """ if len(intervals) == 1: return np.asarray([1]) wts = np.ones(le...
5eaf974597ad13d2b2204526d84412a22a104bc2
14,654
def centroid_precursor_frame(mzml_data_struct): """ Read and returns a centroid spectrum for a precursor frame This function uses the SDK to get and return an MS1 centroid spectrum for the requested frame. Parameters ---------- mzml_data_struct : dict structure of the mzml data ...
24d6f19afeafcd731dd316c36aa4784d60224ee8
14,655
from typing import Union def floor_ts( ts: Union[pd.Timestamp, pd.DatetimeIndex], freq=None, future: int = 0 ) -> Union[pd.Timestamp, pd.DatetimeIndex]: """Floor timestamp to period boundary. i.e., find (latest) period start that is on or before the timestamp. Parameters ---------- ts : Time...
76114fba5f94bbdd40143ca48a901b01e4cdbece
14,656
import os def check_results(jobname, app_config): """" return T/F if there is a results file """ fp = results_file_path(jobname, app_config) # if results file exists and it's non-zero size, then true return( os.path.exists(fp) and os.path.getsize(fp) > 0)
9164f7da2e73adc430565e7faa5013ce835bcea9
14,657
import socket import time def create_geo_database(): """ Create a geo db. """ log.info("Starting to create the geo db") log.info("Waiting for the database to be ready") log.info(f"Testing connection on host: {ctx.geo_db_hostname} and port {ctx.geo_db_port}") # We need to sleep and retry u...
0d3337a9b274d3a4ecaed6f593b0db9064f3475e
14,658
import random def createNewForest(): """Returns a dictionary for a new forest data structure.""" forest = {'width': WIDTH, 'height': HEIGHT} for x in range(WIDTH): for y in range(HEIGHT): if (random.randint(1, 10000) / 100) <= INITIAL_TREE_DENSITY: forest[(x, y)] = TREE...
1c58bb3faeba7b866a7b406b742106adccb64a0f
14,659
def test_filter(): """ Base class filter function """ def test(): """ Test the filter function """ try: for i in _TEST_FRAME_.keys(): for j in range(10): test = _TEST_FRAME_.filter(i, "<", j) assert all(map(lambda x: x < j, test[i])) test = _TEST_FRAME_.filter(i, "<=", j) assert a...
5623ba98d8b06b2e2f395bf8387268f7857236e0
14,660
def exp_moving_average(values, window): """ Numpy implementation of EMA """ if window >= len(values): if len(values) == 0: sma = 0.0 else: sma = np.mean(np.asarray(values)) a = [sma] * len(values) else: weights = np.exp(np.linspace(-1., 0., window)...
1563ac9898296e253c7733d341d30ee36cfb822c
14,661
def parabolic(f, x): """ Quadratic interpolation in order to estimate the location of a maximum https://gist.github.com/endolith/255291 Args: f (ndarray): a vector a samples x (int): an index on the vector Returns: (vx, vy): the vertex coordinates of a parabola passing...
4373ee6390f3523d0fd69487c27e05522bd8c230
14,662
def arith_expr(draw): """ arith_expr: term (('+'|'-') term)* """ return _expr_builder(draw, term, '+-')
277361c91c5967b36ec24b87402d2444e40f2a31
14,663
import glob def extract_running_speed(module_params): """Writes the stimulus and pkl paths to the input json Parameters ---------- module_params: dict Session or probe unique information, used by each module Returns ------- module_params: dict Session or probe unique information,...
d04908a9161bebdc74b5a35f14568e50bf4f8559
14,664
def sliced_transposed_product( mat, block_size, axes=(-1,), precision=lax.Precision.DEFAULT, ): """Returns the blocked slices representing a symmetric contraction. Specifically, the output is a contraction of the input mat with itself, in the specified axes. Args: mat: The matrix...
1bb2016dd485b2da9e74d4a70c703e8fefacf8ff
14,665
import re def _is_ipython_line_magic(line): """ Determines if the source line is an IPython magic. e.g., %%bash for i in 1 2 3; do echo $i done """ return re.match(_IS_IPYTHON_LINE_MAGIC, line) is not None
90575b556f6f6d62bb82b6fb18b2bc979735e808
14,666
def osu_to_excel( osu_path: str, excel_path: str = '', n: int = None, compact_log: bool = False, display_progress=True, **kwargs ) -> str: """Export metadata and hitobjects in a xlsx file.""" metadata = from_osu( osu_path, n=n, compact_log=compact_log, display_progress=display_progress ) mode =...
5d26d70706ec74febc8be0c0d49eaf7f0c48186d
14,667
from pathlib import Path import os def get_cluster_env() -> ClusterEnv: """Get cardano cluster environment.""" socket_path = Path(os.environ["CARDANO_NODE_SOCKET_PATH"]).expanduser().resolve() state_dir = socket_path.parent work_dir = state_dir.parent repo_dir = Path(os.environ.get("CARDANO_NODE_R...
ef504a3b43c3a438a0e3c0ed10258a4541a78673
14,668
def convert_pybites_chars(text): """Swap case all characters in the word pybites for the given text. Return the resulting string.""" return "".join( char.swapcase() if char.lower() in PYBITES else char for char in text )
73dff55cc7cd2f1c85d1f51319c12f8335803dce
14,669
def get_meminfo(): """ Return the total memory (in MB). :return: memory (float). """ mem = 0.0 with open("/proc/meminfo", "r") as fd: mems = fd.readline() while mems: if mems.upper().find("MEMTOTAL") != -1: try: mem = float(mems.s...
5aaa671d7d407b1593099a2fb7a1f2fcb0a88542
14,670
def process_inline_semantic_match(placeholder_storage, match_object): """ Process a single inline-semantic match object. """ delimiter = match_object.group('delimiter') tag_name = TAG_NAME_FROM_INLINE_SEMANTIC_DELIMITER[delimiter] attribute_specification = match_object.group('attribute_specification')...
a1f66093ed361f5e7f924061a1c9770d880d4acc
14,671
async def insert_cd_inurl_name(cluster_id: str, iso_name: str): """ Find SR by Name """ try: try: session = create_session( _id=cluster_id, get_xen_clusters=Settings.get_xen_clusters() ) except KeyError as key_error: raise HTTPException( ...
7c6df12f6de461d559c63adb5e014708e2122760
14,672
def main_add(args): """Start the add-environment command and return exit status code.""" return add_env_spec(args.directory, args.name, args.packages, args.channel)
6358464086e3fc01553df301514976d04a44b3c4
14,673
def write(objct, fileoutput, binary=True): """ Write 3D object to file. (same as `save()`). Possile extensions are: - vtk, vti, npy, npz, ply, obj, stl, byu, vtp, vti, mhd, xyz, tif, png, bmp. """ obj = objct if isinstance(obj, Points): # picks transformation obj = objct.polydat...
51e595a83d54a90dd392d09a67289527cb8a4510
14,674
def instantiate_env_class(builder: IRBuilder) -> Value: """Assign an environment class to a register named after the given function definition.""" curr_env_reg = builder.add( Call(builder.fn_info.env_class.ctor, [], builder.fn_info.fitem.line) ) if builder.fn_info.is_nested: builder.fn_...
14e3113fe6ba3ec107fcd36e36c7dc525bf11cc5
14,675
import json def validate_recaptcha(token): """ Send recaptcha token to API to check if user response is valid """ url = 'https://www.google.com/recaptcha/api/siteverify' values = { 'secret': settings.RECAPTCHA_PRIVATE_KEY, 'response': token } data = urlencode(values).encode...
7be09a76cbf946edbe8b1d717b2e2e2cdef9a902
14,676
def aggregate_hts(style="all_modes_combined"): """Use the 'processed' version of the HTS table to summarize the flows. Using the 'style' parameter, you can: - aggregate by mode using 'by_mode' - aggregate by mode and o&d location types using 'by_mode_and_location_type' - aggre...
b200b312351408e4615a503f56f301c3b775f35a
14,677
def pix2sky(shape, wcs, pix, safe=True, corner=False): """Given an array of corner-based pixel coordinates [{y,x},...], return sky coordinates in the same ordering.""" pix = np.asarray(pix).astype(float) if corner: pix -= 0.5 pflat = pix.reshape(pix.shape[0], -1) coords = np.asarray(wcsutils.nobcheck(wcs).wcs_pix...
288d3f67080611773273aaed950385b19d7aebc8
14,678
def getRelativeSilenceVideo(videoPath): """Function to get relative silence videos before and after each video""" silVid = ['', ''] vidData = getVideoDataFromPath(videoPath) videoNameList = videoPath.split('/') tempVidName = videoNameList[0] + '/' + videoNameList[1] + '/' + videoNameList[2] + '/Sile...
b829915c4cfa7592e394914ba40457200b352ab4
14,679
def convert_to_xyxy_coordinates(boxes: tf.Tensor) -> tf.Tensor: """Convert boxes to their center coordinates y_cent, x_cent, h, w -> y_min, x_min, y_max, x_max Arguments: - *boxes*: A Tensor of shape [N, ..., (y_cent, x_cent, h, w)] Returns: A tensor of shape [N, ..., num_boxes, (y_min, x_m...
2412d3383d4335d707e220a52ac5e5198513d8ab
14,680
from typing import Optional import logging def ceilo2nc(full_path: str, output_file: str, site_meta: dict, keep_uuid: Optional[bool] = False, uuid: Optional[str] = None, date: Optional[str] = None) -> str: """Converts Vaisala / Lufft ceilometer data...
dcf5544c4f0e7cfde0dc48510b7e3f0717971510
14,681
import click def classify(mapper: object, files: list or dict, samples: list = None, fmt: str = None, demux: bool = None, trimsub: str = None, tree: dict = None, rankdic: dict = None, na...
1d1976dcf35617a3860af39d77fb206880071105
14,682
import re def get_better_loci(filename, cutoff): """ Returns a subset of loci such that each locus includes at least "cutoff" different species. :param filename: :param cutoff: :return: """ f = open(filename) content = f.read() f.close() loci = re.split(r'//.*|', conte...
e2d563c9d0568cef59ea0280aae61a78bf4a6e7b
14,683
import math def paginate_data(data_list, page=1 ,per_page=10): """将数据分页返回""" pages = int(math.ceil(len(data_list) / per_page)) page = int(page) per_page = int(per_page) has_next = True if pages > page else False has_prev = True if 1 < page <= int(pages) else False items = data_list[(page-1...
63a4602462e0c2e38329107b10b5d72b63c3108d
14,684
import torch def quat_to_rotmat(quat): """Convert quaternion coefficients to rotation matrix. Args: quat: size = [B, 4] 4 <===>(w, x, y, z) Returns: Rotation matrix corresponding to the quaternion -- size = [B, 3, 3] """ norm_quat = quat norm_quat = norm_quat / norm_quat.norm(p...
6590272c0ed3a97f8f5ef5eacd3605b0c7b91626
14,685
def has_multimethods(cls): """ Declare class as one that have multimethods.""" for name, obj in cls.__dict__.items(): if isinstance(obj, MethodDispatcher): obj.proceed_unbound_rules(cls) return cls
4248af44c0ba6b585a80a4eb0d8da1ca5e9f2299
14,686
def elastic_depth(f, time, method="DP2", lam=0.0, parallel=True): """ calculates the elastic depth between functions in matrix f :param f: matrix of size MxN (M time points for N functions) :param time: vector of size M describing the sample points :param method: method to apply optimization (defau...
574880a5cc3d26d756286a5d7a8959c67141678a
14,687
from typing import Any def run_coro_thread(func: callable, *args, **kwargs) -> Any: """ Run a Python AsyncIO coroutine function within a new event loop using a thread, and return the result / raise any exceptions as if it were ran normally within an AsyncIO function. .. Caution:: If you're w...
078b17d38552aa5d9a30efd1374d8f4e8f7e9b40
14,688
def get_all_ports(entity): """ Recursively descends through the entity hierarchy and collects all ports defined within the parameter or any of its children. Parameters ---------- entity : Entity The root from which to start collecting. Returns ------- list of Port ...
a490ba48d647a1d82a2c7ae7d75e61afb089c907
14,689
def deploy(**kwargs): """Deploy a PR into a remote server via Fabric""" return apply_pr(**kwargs)
26d11e6d6ab08e1298aa99203925c45b96535df9
14,690
import torch def word_list2tensor(word_list, dictionary): """ args word_list: [batch_size, seq_len, token_id] dictionary: Dictionary return source, target [batch_size, seq_len, token_id] """ word_list_padded = add_word_padding(word_list, dictionary) batch = torch.LongTensor(word_l...
6e484c282779bfd709030735268468f3bacde268
14,691
import six def canonicalize_monotonicity(monotonicity, allow_decreasing=True): """Converts string constants representing monotonicity into integers. Args: monotonicity: The monotonicities hyperparameter of a `tfl.layers` Layer (e.g. `tfl.layers.PWLCalibration`). allow_decreasing: If decreasing mono...
a9d0870d03f11d7bdff4c8f673cd78d072fa8478
14,692
def add_gdp(df, gdp, input_type="raw", drop=True): """Adds the `GDP` to the dataset. Assuming that both passed dataframes have a column named `country`. Parameters ---------- df : pd.DataFrame Training of test dataframe including the `country` column. gdp : pd.DataFrame Mapping betw...
72e2b5fe839f3dbc71ca2def4be442535a0adb84
14,693
import argparse def get_options(cmd_args): """ Argument Parser. """ parser = argparse.ArgumentParser( prog='activitygen.py', usage='%(prog)s -c configuration.json', description='SUMO Activity-Based Mobility Generator') parser.add_argument( '-c', type=str, dest='config', required=Tr...
e8ddde36e83df2ca46652e0f104c718e8f747715
14,694
from scipy.ndimage.filters import maximum_filter def no_background_patches(threshold=0.4, percentile=99.9): """Returns a patch filter to be used by :func:`create_patches` to determine for each image pair which patches are eligible for sampling. The purpose is to only sample patches from "interesting" regions...
b1ffd8b7bb2023c483da35565044b02f7fd96cd8
14,695
def start_thread(): """Start new thread with or without first comment.""" subject = request.form.get('subject') or '' comment = request.form.get('comment') or '' if not subject: return error('start_thread:subject') storage.start_thread(g.username, subject, comment) flash('New Thread Sta...
a8fabcddac91cc5cc6d5a63382e1ba433f425c20
14,696
def get_package_data(name, package=None): """Retrieve metadata information for the given package name""" if not package: package = models.Package(name=name) releases = {} else: releases = package.get_all_releases() client = xmlrpclib.ServerProxy('http://pypi.python.org/pypi') ...
98824594fdd245760387f912192037b2e024aadc
14,697
def _extract_xbstream( input_stream, working_dir, xbstream_binary=XBSTREAM_BINARY ): """ Extract xbstream stream in directory :param input_stream: The stream in xbstream format :param working_dir: directory :param xbstream_binary: Path to xbstream :return: True if extracted successfully ...
f5f95347de55c352eb568c5bb5cb17517040e20c
14,698
from sys import path import re def load_version(pkg_dir, pkg_name): """Load version from variable __version__ in file __init__.py with a regular expression""" try: filepath_init = path.join(pkg_dir, pkg_name, '__init__.py') file_content = read_file(filepath_init) re_for_version = re.co...
70ca891203b44f65263494d39390ec3500d00b4e
14,699