content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def escape_html(text: str) -> str: """Replaces all angle brackets with HTML entities.""" return text.replace('<', '&lt;').replace('>', '&gt;')
f853bcb3a69b8c87eb3d4bcea5bbca66376c7db4
3,646,244
import random def pptest(n): """ Simple implementation of Miller-Rabin test for determining probable primehood. """ bases = [random.randrange(2,50000) for _ in range(90)] # if any of the primes is a factor, we're done if n<=1: return 0 for b in bases: if n%b==0: return 0...
3a74cfebb6b14659a34ab0b6c761efd16d2736fa
3,646,245
def schedule_conv2d_NCHWc(outs): """Schedule for conv2d_NCHW[x]c Parameters ---------- outs : Array of Tensor The computation graph description of conv2d_NCHWc in the format of an array of tensors. The number of filter, i.e., the output channel. Returns ------- sch ...
a24cb4f6e1dd3d8891bc82df75f53c8afe709727
3,646,246
def calc_E_E_hs_d_t(W_dash_k_d_t, W_dash_s_d_t, W_dash_w_d_t, W_dash_b1_d_t, W_dash_ba1_d_t, W_dash_b2_d_t, theta_ex_d_Ave_d, L_dashdash_ba2_d_t): """1時間当たりの給湯機の消費電力量 (1) Args: W_dash_k_d_t(ndarray): 1時間当たりの台所水栓における節湯補正給湯量 (L/h) W_dash_s_d_t(ndarray): 1時間当たりの浴室シャワー水栓における節湯補正給湯量 ...
00cf40b221d2a24081d9c362fb5e8474057ddb93
3,646,247
import functools def keras_quantile_loss(q): """Return keras loss for quantile `q`.""" func = functools.partial(_tilted_loss_scalar, q) func.__name__ = f'qunatile loss, q={q}' return func
173a9410c2994bd02e5845a85cc2050489ce2d12
3,646,248
from typing import Mapping from typing import Union def _reactions_table(reaction: reaction_pb2.Reaction, dataset_id: str) -> Mapping[str, Union[str, bytes, None]]: """Adds a Reaction to the 'reactions' table. Args: reaction: Reaction proto. dataset_id: Dataset ID. Returns: Dict ...
b09df06a13d1f1d42ab22da1c6bcc00c48c2e81d
3,646,250
from typing import List from typing import Dict from typing import Any import time import json def get_incidents_for_alert(**kwargs) -> list: """ Return List of incidents for alert. :param kwargs: Contains all required arguments. :return: Incident List for alert. """ incidents: List[Dict[str,...
48d2519d5e5aa25d6b0fc6a6e2c959489e861e1c
3,646,251
def pbar(*args, **kwargs): """ Progress bar. This function is an alias of :func:`dh.thirdparty.tqdm.tqdm()`. """ return dh.thirdparty.tqdm.tqdm(*args, **kwargs)
3de7101becc015e402aa067c676104f34679e549
3,646,252
import torch def calc_driver_mask(n_nodes, driver_nodes: set, device='cpu', dtype=torch.float): """ Calculates a binary vector mask over graph nodes with unit value on the drive indeces. :param n_nodes: numeber of driver nodes in graph :param driver_nodes: driver node indeces. :param device: the d...
2d2a08a86629ece190062f68dd25fc450d0fd84e
3,646,253
from typing import List def all_fermions(fields: List[Field]) -> bool: """Checks if all fields are fermions.""" boolean = True for f in fields: boolean = boolean and f.is_fermion return boolean
eb54d5ad5b3667e67634b06d2943e2d14c8a0c61
3,646,254
def open_file(name): """ Return an open file object. """ return open(name, 'r')
8921ee51e31ac6c64d9d9094cedf57502a2aa436
3,646,255
import math def _bit_length(n): """Return the number of bits necessary to store the number in binary.""" try: return n.bit_length() except AttributeError: # pragma: no cover (Python 2.6 only) return int(math.log(n, 2)) + 1
bea6cb359c7b5454bdbb1a6c29396689035592d7
3,646,256
def read_dwd_percentile_old(filename): """ Read data from .txt file into Iris cube :param str filename: file to process :returns: cube """ # use header to hard code the final array shapes longitudes = np.arange(-179.5, 180.5, 1.) latitudes = np.arange(89.5, -90.5, -1.) data ...
4d8366606c4e00eb43aa2c6a50a735617c7ca242
3,646,257
import base64 def media_post(): """API call to store new media on the BiBli""" data = request.get_json() fname = "%s/%s" % (MUSIC_DIR, data["name"]) with open(fname, "wb") as file: file.write(base64.decodestring(data["b64"])) audiofile = MP3(fname) track = {"file": data["name"], "title...
ff2aa7df2cdc6ea9bf3d657c7bb675e824639107
3,646,258
from pathlib import Path def obtain_stores_path(options, ensure_existence=True) -> Path: """ Gets the store path if present in options or asks the user to input it if not present between parsed_args. :param options: the parsed arguments :param ensure_existence: whether abort if the path does not e...
8bb3ff96cdc57f85058ad7cd3c96552462b8de9f
3,646,259
def compute_roc(distrib_noise, distrib_signal): """compute ROC given the two distribributions assuming the distributions are the output of np.histogram example: dist_l, _ = np.histogram(acts_l, bins=n_bins, range=histrange) dist_r, _ = np.histogram(acts_r, bins=n_bins, range=histrange) tprs, fp...
d9a970435fd7b0dc79cfb4eca24a6e6779ce9300
3,646,261
def zoom(clip, screensize, show_full_height=False): """Zooms preferably image clip for clip duration a little To make slideshow more movable Parameters --------- clip ImageClip on which to work with duration screensize Wanted (width, height) tuple show_full_height S...
668ef2b598432fc18510a5a69b73e400eec42b17
3,646,262
import typing def create( host_address: str, topics: typing.Sequence[str]) -> Subscriber: """ Create a subscriber. :param host_address: The server notify_server address :param topics: The topics to subscribe to. :return: A Subscriber instance. """ return Subscriber(create_...
40221a3be496528115afdc2eda063a006e08aadd
3,646,263
def solution(n): """ Return the product of a,b,c which are Pythagorean Triplet that satisfies the following: 1. a < b < c 2. a**2 + b**2 = c**2 3. a + b + c = 1000 >>> solution(1000) 31875000 """ product = -1 d = 0 for a in range(1, n // 3): """Solving t...
a0bf0f0bde50f536f6c91f2b52571be38e494cea
3,646,264
def with_metaclass(meta, *bases): """A Python 2/3 compatible way of declaring a metaclass. Taken from `Jinja 2 <https://github.com/mitsuhiko/jinja2/blob/master/jinja2 /_compat.py>`_ via `python-future <http://python-future.org>`_. License: BSD. Use it like this:: class MyClass(with_metacla...
0fe8e95fe29821e4cda8b66ff54ddd1b73e51243
3,646,266
def energy(particles): """total kinetic energy up to a constant multiplier""" return np.sum([particle.size ** 2 * np.linalg.norm(particle.speed) ** 2 for particle in particles])
29cae5c46d053f6fa558ba7a839d8b647c86d236
3,646,267
def post_adaptation_non_linear_response_compression_matrix(P_2, a, b): """ Returns the post adaptation non linear response compression matrix. Parameters ---------- P_2 : numeric or array_like Point :math:`P_2`. a : numeric or array_like Opponent colour dimension :math:`a`. ...
6b7f8bcc62142e99c63c0e7a9b073e25f3c36e8c
3,646,268
def forward(network, x): """ 入力信号を出力に変換する関数 Args: network: ネットワークのDict x: Inputの配列 Returns: 出力信号 """ w1, w2, w3 = network['W1'], network['W2'], network['W3'] b1, b2, b3 = network['B1'], network['B2'], network['B3'] # 1層目 a1 = np.dot(x, w1) + b1 z1 = si...
93c79a049e4c45f31a502aa81f840e48ff41d229
3,646,269
from typing import List def join_with_and(words: List[str]) -> str: """Joins list of strings with "and" between the last two.""" if len(words) > 2: return ", ".join(words[:-1]) + ", and " + words[-1] elif len(words) == 2: return " and ".join(words) elif len(words) == 1: return ...
ecb2c1fa060657f2ea4173c4382a81c9b42beeb9
3,646,270
from nipype.interfaces.base import Bunch def condition_generator(single_sub_data, params_name, duration = 2): """Build a bunch to show the relationship between each onset and parameter Build a bunch for make a design matrix for next analysis. This bunch is for describing the relationship between each ons...
6a4743043a49b6a1703c3b42840256a58e07f3bd
3,646,271
from typing import Callable from typing import Any def one_hot( encoding_size: int, mapping_fn: Callable[[Any], int] = None, dtype="bool" ) -> DatasetTransformFn: """Transform data into a one-hot encoded label. Arguments: encoding_size {int} -- The size of the encoding mapping_fn {Callabl...
48758666885969c10b5e6ef46f2d392cd06800a2
3,646,273
def is_url_relative(url): """ True if a URL is relative, False otherwise. """ return url[0] == "/" and url[1] != "/"
91e1cb756a4554973e53fd1f607515577bc63294
3,646,274
def _split_link_ends(link_ends): """ Examples -------- >>> from landlab.grid.unstructured.links import _split_link_ends >>> _split_link_ends(((0, 1, 2), (3, 4, 5))) (array([0, 1, 2]), array([3, 4, 5])) >>> _split_link_ends([(0, 3), (1, 4), (2, 5)]) (array([0, 1, 2]), array([3, 4, 5])) ...
3aee58b5e4e928d45a33026c0b9e554c859d0d6f
3,646,276
from heapq import heappop, heappush def dijkstra(vertex_count: int, source: int, edges): """Uses Dijkstra's algorithm to find the shortest path in a graph. Args: vertex_count: The number of vertices. source : Vertex number (0-indexed). edges : List of (cost, edge) (0-indexed...
d33f8dc28bf07154ffd7582a5bdd7161e195f331
3,646,277
def plot_labels(labels, lattice=None, coords_are_cartesian=False, ax=None, **kwargs): """ Adds labels to a matplotlib Axes Args: labels: dict containing the label as a key and the coordinates as value. lattice: Lattice object used to convert from reciprocal to Cartesian coordinates ...
b0172061e043fcaef38d2503be67333862da3acf
3,646,279
def contains(poly0, poly1): """ Does poly0 contain poly1? As an initial implementation, returns True if any vertex of poly1 is within poly0. """ # check for bounding box overlap bb0 = (min(p[0] for p in poly0), min(p[1] for p in poly0), max(p[0] for p in poly0), max(p[1] for p in poly...
26ea4bd17a55ed05afa049a9aaab5237f0965674
3,646,280
def new_halberd(game_state): """ A composite component representing a Sword item. """ c = Composite() set_item_components(c, game_state) set_melee_weapon_component(c) c.set_child(Description("Halberd", "A long stick with a with an axe-head at one end." ...
1e6ccdce08a5e4e26c6dc8d09db38ef4b6d7b2f0
3,646,282
from typing import List def get_regional_services(service_list: List[AWSService] = None) -> List[AWSService]: """List all services which are tied to specific regions.""" services = service_list or get_services() return [s for s in services if s.is_regional]
d856acfc24430102ccb72a76eedbc47ace842894
3,646,283
def f_setup_config(v_config_filename): """This function read the configuration file""" df_conf_file = pd.read_csv(v_config_filename, delimiter="|", header=0) api_key = df_conf_file[df_conf_file.CONFIG_VAR == 'API_KEY']['VALUE'].values[0] data_dir = df_conf_file[df_conf_file.CONFIG_VAR == 'DATA_DIR']['V...
b2e9a8e822a2c582549055184cc8096f174fdb3b
3,646,285
def choose_username(email): """ Chooses a unique username for the provided user. Sets the username to the email parameter umodified if possible, otherwise adds a numerical suffix to the email. """ def get_suffix(number): return "" if number == 1 else "_"+str(number).zfill(3) user_mo...
594c060df6df5c89c7c08a2e3979960866cc5688
3,646,286
def lms2rgb(image): """ Convert an array of pixels from the LMS colorspace to the RGB colorspace. This function assumes that each pixel in an array of LMS values. :param image: An np.ndarray containing the image data :return: An np.ndarray containing the transformed image data """ return np...
736d7101a4c4256725fd4f09c6a453c418c1ae81
3,646,287
def __apply_to_property_set (f, property_set): """ Transform property_set by applying f to each component property. """ properties = feature.split (property_set) return '/'.join (f (properties))
5091065f90b602a775c24eca9e2ab3bc6861e0c8
3,646,288
def calc_eta_FC(Q_load_W, Q_design_W, phi_threshold, approach_call): """ Efficiency for operation of a SOFC (based on LHV of NG) including all auxiliary losses Valid for Q_load in range of 1-10 [kW_el] Modeled after: - **Approach A (NREL Approach)**: http://energy.gov/eere/fuelcells/d...
0cd14d976d773dc34d7ea96e80db4267e33aac1f
3,646,291
from typing import Tuple def erdos_renyi( num_genes: int, prob_conn: float, spec_rad: float = 0.8 ) -> Tuple[np.ndarray, float]: """Initialize an Erdos Renyi network as in Sun–Taylor–Bollt 2015. If the spectral radius is positive, the matrix is normalized to a spectral radius of spec_rad and the scal...
87e29376ec79ea9198bb3c668fdc31fc61216a26
3,646,292
import _ctypes def IMG_LoadTextureTyped_RW(renderer, src, freesrc, type): """Loads an image file from a file object to a texture as a specific format. This function allows you to explicitly specify the format type of the image to load. The different possible format strings are listed in the documenta...
ef9f963e71b7419ec790bd3fdb06eb470d30972b
3,646,293
def soft_l1(z: np.ndarray, f_scale): """ rho(z) = 2 * ((1 + z)**0.5 - 1) The smooth approximation of l1 (absolute value) loss. Usually a good choice for robust least squares. :param z: z = f(x)**2 :param f_scale: rho_(f**2) = C**2 * rho(f**2 / C**2), where C is f_scale :return: """ loss...
95813cd59c99ab94e6b4693237dc85f5b7d31b14
3,646,294
def calculate_hit_box_points_detailed(image: Image, hit_box_detail: float = 4.5): """ Given an image, this returns points that make up a hit box around it. Attempts to trim out transparent pixels. :param Image image: Image get hit box from. :param int hit_box_detail: How detailed to make the hit bo...
dd74e18fac1fe96728837ce8af62c38461592baa
3,646,295
async def open_local_endpoint( host="0.0.0.0", port=0, *, queue_size=None, **kwargs ): """Open and return a local datagram endpoint. An optional queue size argument can be provided. Extra keyword arguments are forwarded to `loop.create_datagram_endpoint`. """ return await open_datagram_endpoint(...
a3b03408bbe35972b0588912a0628df2be9cddc5
3,646,296
from typing import Union def parse_bool(value: Union[str, bool]) -> bool: """Parse a string value into a boolean. Uses the sets ``CONSIDERED_TRUE`` and ``CONSIDERED_FALSE`` to determine the boolean value of the string. Args: value (Union[str, bool]): the string to parse (is converted to lowercas...
86bb61b82eb71627f3563584779f3a17ea1bc8b7
3,646,297
from datetime import datetime import traceback import requests def send_rocketchat_notification(text: str, exc_info: Exception) -> dict: """ Sends message with specified text to configured Rocketchat channel. We don't want this method to raise any exceptions, as we don't want to unintentionally break any...
c466621cfd8ead8f6773bc1c461fb779c0374937
3,646,298
def get_number_of_forms_all_domains_in_couch(): """ Return number of non-error, non-log forms total across all domains specifically as stored in couch. (Can't rewrite to pull from ES or SQL; this function is used as a point of comparison between row counts in other stores.) """ all_forms =...
a30f5e6410dc3b91c3a962169fad20e2a8d4a8fb
3,646,299
def compute_wolfe_gap(point_x, objective_function, feasible_region): """Compute the Wolfe gap given a point.""" grad = objective_function.evaluate_grad(point_x.cartesian_coordinates) v = feasible_region.lp_oracle(grad) wolfe_gap = grad.dot(point_x.cartesian_coordinates - v) return wolfe_gap
f2b09a232063599aa7525a70e6d3a0d8bafb57e7
3,646,300
async def get(ip, community, oid, port=161, timeout=DEFAULT_TIMEOUT): # type: (str, str, str, int, int) -> PyType """ Delegates to :py:func:`~puresnmp.aio.api.raw.get` but returns simple Python types. See the "raw" equivalent for detailed documentation & examples. """ raw_value = await raw....
6682d9877ac4d5b287088fd17d626011b95b6c31
3,646,301
def preprocess_image(image, params): """Preprocess image tensor. Args: image: tensor, input image with shape [cur_batch_size, height, width, depth]. params: dict, user passed parameters. Returns: Preprocessed image tensor with shape [cur_batch_size, height, ...
4e5a563610c2ecdcd29fa5c077025100625b767b
3,646,302
def get_vlim(xarr: xr.DataArray, alpha: float) -> dict: """Get vmin, vmax using mean and std.""" mean = xarr.mean() std = xarr.std() return {"vmin": max(0., mean - alpha * std), "vmax": mean + alpha * std}
4f6c87f290ab23db56fe67f700136a49e2b52363
3,646,303
def count_consumed_symbols(e): """Count how many symbols are consumed from each sequence by a single sequence diff entry.""" op = e.op if op == DiffOp.ADDRANGE: return (0, len(e.valuelist)) elif op == DiffOp.REMOVERANGE: return (e.length, 0) elif op == DiffOp.PATCH: return (1...
63a3d97840fae49a7ff3279e10e553d82dfcf801
3,646,304
def maha_dist_sq(cols, center, cov): """Calculate squared Mahalanobis distance of all observations (rows in the vectors contained in the list cols) from the center vector with respect to the covariance matrix cov""" n = len(cols[0]) p = len(cols) assert len(center) == p # observation matri...
9e54a7f49ed3b977b351007991f3fe263306a20a
3,646,305
def get_form_target(): """ Returns the target URL for the comment form submission view. """ if get_comment_app_name() != DEFAULT_COMMENTS_APP and hasattr(get_comment_app(), "get_form_target"): return get_comment_app().get_form_target() else: return urlresolvers.reverse("comments.view...
d7e6ad126a35109d589d7f2734a4bd3e56df748f
3,646,306
def secret_page(username=None, password=None): """ Returns the HTML for the page visited after the user has logged-in. """ if username is None or password is None: raise ValueError("You need to pass both username and password!") return _wrapper(""" <h1> Welcome, {username}! </h1> <...
3bd81f30f0bf63290c6ee24cf3bccb7090fd406c
3,646,307
import collections def user(username): """ displays a single user """ all_badgers = loads(r_server.get('all_badgers')) this_badger = all_badgers[username] this_badger_sorted = collections.OrderedDict(sorted(this_badger.items(), reverse=True)) days = days_in_a_row(this_badger) kwargs = {'badger...
27cf03175184cc839a64d931aa3477a0196c24aa
3,646,308
import numpy def ifft(a, axis): """ Fourier transformation from grid to image space, along a given axis. (inverse Fourier transform) :param a: numpy array, 1D or 2D (`uv` grid to transform) :param axis: int; axes over which to calculate :return: numpy array (an image in `lm` coordinate space...
3a96d6b615c8da63deaeca5e98a4f82f18fec8dd
3,646,309
import random def transitions_and_masks_to_proposals(t1, t2, m1, m2, max_samples=10, max_ccs=6): """ assumes set-based...
146b937e7a46d6d051b10f900574378874535932
3,646,310
import requests import re def exists(url): """Check based on protocol if url exists.""" parsed_url = urlparse(url) if parsed_url.scheme == "": raise RuntimeError("Invalid url: %s" % url) if parsed_url.scheme in ('http', 'https'): r = requests.head(url, verify=False) if r.statu...
bb91fd5fb93ec6441125a1aa4874ad6d7f103535
3,646,312
def inverse_chirality_symbol(symbol): """ Inverses a chirality symbol, e.g., the 'R' character to 'S', or 'NS' to 'NR'. Note that chiral double bonds ('E' and 'Z') must not be inversed (they are not mirror images of each other). Args: symbol (str): The chirality symbol. Returns: st...
e87fae6ad9169efac0b3c95f53dfb92e0c450909
3,646,313
from typing import Optional def delete( request: HttpRequest, wid: Optional[int] = None, workflow: Optional[Workflow] = None, ) -> JsonResponse: """Delete a workflow.""" if request.method == 'POST': # Log the event Log.objects.register( request.user, Log.WOR...
07b6de0d66a5101660f1bf4aa37abe4be71568ff
3,646,315
def at_threshold(FPR, TPR, parameter, threshold): """ False positive rate (FPR) and True positive rate (TPR) at the selected threshold. :param FPR: False positive rates of given receiver operating characteristic (ROC) curve :param TPR: True positive rate of given receiver operating characteristic (ROC) ...
d66edc0e43a18a5fdf8b6d216e4130aef8a7b17b
3,646,316
def _check_kl_estimator(estimator_fn, distribution_fn, num_samples=10000, rtol=1e-1, atol=1e-3, grad_rtol=2e-1, grad_atol=1e-1): """Compares the estimator_fn output and gradient to exact KL.""" rng_key = jax.random.PRNGKey(0) def expected_kl(params): distribution_a = distribution_fn(*...
b4e34f35f6531f795c8621fee2082993c3b518bd
3,646,317
def relative_bias(simu, reco, relative_scaling_method='s1'): """ Compute the relative bias of a reconstructed variable as `median(reco-simu)/relative_scaling(simu, reco)` Parameters ---------- simu: `numpy.ndarray` reco: `numpy.ndarray` relative_scaling_method: str see `ctaplot....
1bc611b1ea135d593bc9b8c83a02a50eeaf18a7e
3,646,318
from typing import Dict from typing import Any def addon_config() -> Dict[str, Any]: """Sample addon config.""" return { "package-name": "djangocms-blog", "installed-apps": [ "filer", "easy_thumbnails", "aldryn_apphooks_config", "parler", ...
f4266735ef2f0809e5802abed54dfde4c1cbd708
3,646,319
def join_mutations_regions( out_path: str, sample1_id: int, sample2_id: int, mutations_file: File, regions_file: File ) -> File: """ Join mutations and regions together to compute an allele frequence. """ def iter_mut_points(muts): for pos, count in muts: yield pos, "mut", count...
4d712a914e2f4c221df982fbd3352eb4f572ad11
3,646,320
def credibility_interval(post, alpha=1.): """Calculate bayesian credibility interval. Parameters: ----------- post : array_like The posterior sample over which to calculate the bayesian credibility interval. alpha : float, optional Confidence level. Returns: -------- ...
b31009918324980ba2ffc53a1f29af1f4e421f95
3,646,321
def svn_ra_invoke_replay_revstart_callback(*args): """ svn_ra_invoke_replay_revstart_callback(svn_ra_replay_revstart_callback_t _obj, svn_revnum_t revision, void replay_baton, svn_delta_editor_t editor, void edit_baton, apr_hash_t rev_props, apr_pool_t pool) -> svn_error_t """ ret...
4c792a16d6dcdbb588062f1f47b3caed84bbd610
3,646,322
import click def tree(ctx, rootpage): """Export metadata of a page tree.""" if not rootpage: click.serror("No root page selected via --entity!") return 1 outname = getattr(ctx.obj.outfile, 'name', None) with api.context() as cf: results = [] try: #page = c...
d055d8dc5fc5a3a267500362ca89b6e895d9d50f
3,646,323
import math def to_half_life(days): """ Return the constant [1/s] from the half life length [day] """ s= days * 3600*24 return -math.log(1/2)/s
af7724dfb9442bf1f5e931df5dd39b31d0e78091
3,646,324
import struct def Send (dst_ip, data, sequence=0, spoof_source=False, dst_port=MDNS_PORT, src_port=MDNS_PORT, dns_name=TEST_QUERY): """ Send one packet of MDNS with data. :param dst_ip: IP as string. :param data: Data as bytes/string. :param sequence: Number to use for sequence. Int. :param spoof_source: Defaul...
9541c71d52dcbaa09ffba1aa1bf4d4d422d66ed6
3,646,325
from units.models import Unit def accreds_logs_list(request): """Display the list of accreds""" main_unit = Unit.objects.get(pk=settings.ROOT_UNIT_PK) main_unit.set_rights_can_select(lambda unit: Accreditation.static_rights_can('LIST', request.user, unit)) main_unit.set_rights_can_edit(lambda unit:...
41961a3cd4f351d13ae5132cfb37e83be7050cc5
3,646,326
from typing import Counter def build_dict(file_name, max_vocab_size): """ reads a list of sentences from a file and returns - a dictionary which maps the most frequent words to indices and - a table which maps indices to the most frequent words """ word_freq = Counter() with open(file_name) ...
ec2067e1fbf8d0f6845024ae69f8531c1f776348
3,646,327
import functools import logging def from_net(func): """ 为进行相似度数据收集的函数装饰,作用是忽略env中的数据获取模式,改变数据获取模式, 只使用网络数据模式进行数据收集,完成整个任务后,再恢复之前的数据获取模式 :param func: 进行相似度应用且有数据收集行为的函数 """ @functools.wraps(func) def wrapper(*args, **kwargs): # 临时保存env设置中的g_data_fetch_mode fetch_mode = ABuE...
68c3a9302d83cf0e02a74c104fd2b5894b85020a
3,646,328
def embedding_lookup(ids, params): """ Returns the embeddings lookups. The difference of this function to TensorFlow's function is that this function expects the ids as the first argument and the parameters as the second; while, in TensorFlow, is the other way around. :param ids: the ids :...
ef85f95cfa5d2a426616ee9203707877ae202051
3,646,330
def in_auto_mode(conx: Connection) -> bool: """Determine whether the controller is in AUTO or one of the MANUAL modes. Wraps the Karel IN_AUTO_MODE routine. NOTE: this method is moderately expensive, as it executes a Karel program on the controller. :returns: True if the controller is in AUTO...
c2819344130a1562fab5a9ece177f8b400a15fbc
3,646,331
def pref(pref_name, default=None): """Return a preference value. Since this uses CFPreferencesCopyAppValue, Preferences can be defined several places. Precedence is: - MCX - /var/root/Library/Preferences/com.github.salopensource.sal.plist - /Library/Preferences/com.github.salopensou...
10102f3dde316e473d5943fee059f729d6e9454c
3,646,332
def tRange(tStart, tStop, *, timedelta=300): """ Generate datetime list between tStart and tStop with fixed timedelta. Parameters ---------- tStart: datetime start time. tStop: datetime stop time. Keywords -------- timedelta: int time delta in seconds (defaul...
4dec7a624bcd2b349d361831993b8108e99725a8
3,646,333
import numpy def TransformInversePoints(T,points): """Transforms a Nxk array of points by the inverse of an affine matrix""" kminus = T.shape[1]-1 return numpy.dot(points-numpy.tile(T[0:kminus,kminus],(len(points),1)),T[0:kminus,0:kminus])
7e04a741c6ad0ec08e40ab393a703a1878ef784a
3,646,334
def act_func(act): """function that can choose activation function Args: act: (str) activation function name Returns: corresponding Pytorch activation function """ return nn.ModuleDict([ ['relu', nn.ReLU(inplace=True)], ['leaky_relu', nn.LeakyReLU(negative_slope=0.01...
ffd0e6f2ec3ea419c4c3fbb618e4734d59420826
3,646,335
def ajax_get_hashtags(): """Flask Ajax Get Hashtag Route.""" f = request.args.get('f', 0, type=int) t = request.args.get('t', 0, type=int) hashtags_list = get_hashtags() try: if t == 0: return jsonify(dict(hashtags_list[f:])) elif t > len(hashtags_list): ret...
3c9249a5fefb93d422c6e2c4be56394711bf1d7a
3,646,336
def extract_pdf_information(pdf_path): """ Print and return pdf information """ # read binary with open(pdf_path, 'rb') as f: pdf = PdfFileReader(f) information = pdf.getDocumentInfo() number_of_pages = pdf.getNumPages() txt = f""" Information about {pdf_path}: Aut...
bec3667aba872f8e7bf53da09a9fb1905bcf5eec
3,646,337
def normalize_string(subject: str) -> str: """Deprecated function alias""" logger.warn("normalize_string is deprecated") return string_to_title(subject)
6531a6e7211c61d8439bfa8ddc0e609c35b8b6f3
3,646,338
import inspect def get_default_args(func): """ Return dict for parameter name and default value. Parameters ---------- func : Callable A function to get parameter name and default value. Returns ------- Dict Parameter name and default value. Examples --------...
dcc75dceae1385868866d668aa021584547190df
3,646,339
def sec_to_time(seconds): """Transform seconds into a formatted time string. Parameters ----------- seconds : int Seconds to be transformed. Returns ----------- time : string A well formatted time string. """ m, s = divmod(seconds, 60) h, m = divmod(m, 60) r...
59fcfe2f53d11ea7daac736b59b5eaeb72172dba
3,646,340
def power_oos(dmap_object, Y): """ Performs out-of-sample extension to calculate the values of the diffusion coordinates at each given point using the power-like method. Parameters ---------- dmap_object : DiffusionMap object Diffusion map upon which to perform the out-of-sample extension. ...
4de7d75324cd05a7d1ada0e8f6e724ecd551930c
3,646,341
def detect_face_landmarks(image, face_rect=None): """ detect face landmarks, if face_rect is None, the face_rect is the same size as image -> object :param image: :param face_rect: where the face is """ if(face_rect == None): face_rect = dlib.rectangle(0, 0, image.sh...
70c299ae2ce98409e2359e11fa9def0d35e7554f
3,646,342
from typing import Iterable from typing import Mapping def ensure_iterable(obj): """Ensure ``obj`` is either a sequential iterable object that is not a string type. 1. If ``obj`` is :const:`None` return an empty :class:`tuple`. 2. If ``obj`` is an instance of :class:`str`, :class:`bytes`, or ...
56c2db3d87c5927b1f2dbb51b64e7be73956d2b8
3,646,343
def test_dist(**kwargs): """ Test Distance """ a = np.random.random((2, 3)) d = ahrs.utils.metrics.euclidean(a[0], a[1]) result = np.allclose(d, np.linalg.norm(a[0] - a[1])) return result
46a9343fda3445fe0f07bfbb41fc321e6572e4a7
3,646,344
def get_pca(coords): """ Parameters ----------- coords : 2D np.array of points Returns --------- new_coords : 2D np.array of points keeps original number of dimension as input coords variance_ratio : tuple """ pca = PCA(n_components=3) # pca.fit(coords) # ...
a0bce6a7c4b50139502cbdedc6f0f456f21d26b6
3,646,345
def get_form_info(email): """Gets all existing application form info from the database.""" user_id = get_user_id(email) if not user_id: return (False, "Invalid user ID. Please contact the organizers.") query = """ SELECT * FROM applications WHERE user_id = %s AND application_year = %s ""...
f612b83aeb63ff138cc637dc04446ce59f6ecc6b
3,646,346
import logging def getLog(): """simple wrapper around basic logger""" return logging
b51942d2ed02f9ea7faf0a626715ec07e1677c88
3,646,347
from datetime import datetime def _date(defval, t): """ 支持的格式: unix 时间戳 yyyy-mm-dd 格式的日期字符串 yyyy/mm/dd 格式的日期字符串 yyyymmdd 格式的日期字符串 如果年月日其中有一项是0,将被转换成 1 """ if t is None: return defval if isinstance(t, (int, float)): return datetime.fromtimes...
e8a1121da89d9dc46bdce5d1b8c70ec973909abb
3,646,348
import math def compute_lat_long_distance(point1, point2): """ Compute the distance between two records that have fields 'lat' and 'lon'. See details and reference implementation at http://andrew.hedges.name/experiments/haversine/ :param point1: a record with { 'lat', 'lon' } :param point2: a rec...
8058df18106636a0bc6c1f7471f912e07e61ae21
3,646,349
import logging def entropy_analysis(data_df): """ Masked Shannon entropy analysis for sequences Parameters ---------- data_df: pandas.DataFrame merged Pandas dataframe Returns ------- H_list: list entropy values for all positions null_freq_list: list masked ...
8b1d887f2c39b39a833c13780864bd47d0d8d648
3,646,350
import re def get_requirements(filename): """ Helper function to read the list of requirements from a file """ dependency_links = [] with open(filename) as requirements_file: requirements = requirements_file.read().strip('\n').splitlines() requirements = [req for req in requirements if...
292d45ab8e7f8523734326869bb1dd05c6f395f1
3,646,351
def nigam_and_jennings_response(acc, dt, periods, xi): """ Implementation of the response spectrum calculation from Nigam and Jennings (1968). Ref: Nigam, N. C., Jennings, P. C. (1968) Digital calculation of response spectra from strong-motion earthquake records. National Science Foundation. :para...
4e9853b660d85d12701bafe9e328bc91499df73a
3,646,352
def binary_hamiltonian(op, nqubits, qubits1, qubits2, weights, device=None): """Generates tt-tensor classical Ising model Hamiltonian (two-qubit interaction terms in a single basis). Hamiltonian of the form: H = sum_i omega_i sigma_ind1(i) sigma_ind2(i) where omega_i are the Hamiltonian weights, s...
50360d50123c44719a8875a59d02e913cd95f2ad
3,646,353
def map_entry(entry, fields): """ Retrieve the entry from the given fields and replace it if it should have a different name within the database. :param entry: is one of the followings: - invalid field name - command (i.g. $eq) - valid field with no attribute name - vali...
05d392f3ab387381b0f114db05834d642350d817
3,646,354
def seqlogo_hairpin(N, target='none', ligand='theo', pam=None): """ Randomize the stem linking the aptamer to the sgRNA and the parts of the sgRNA that were the most conserved after being randomized in previous screens. Specifically, I identified these conserved positions by looking at a sequenc...
a6be46325d80a23e5afa820b042fa4c878370e45
3,646,355
from typing import Dict from typing import Any def azure_firewall_ip_group_list_command(client: AzureFirewallClient, args: Dict[str, Any]) -> CommandResults: """ List IP groups in resource group or subscription. Args: client (AzureFirewallClient): Azure Firewall API client. args (dict): Co...
c52108af9903f952adf316b11098f726d7280153
3,646,356