content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def notifications_view(request):
"""
Show a user their notifications.
"""
page_name = "Your Notifications"
# Copy the notifications so that they are still unread when we render the page
notifications = list(request.user.notifications.all())
request.user.notifications.mark_all_as_read()
r... | 3f85d7ef1dd10dabcfe191694f90f357a9944567 | 79,586 |
def withinBoundary(dists, x_max, y_max, slope=2):
"""Classifies points as within or outside of a refined boundary.
Numba JIT compiled for speed.
Also used to assign new points in :func:`~PopPUNK.models.RefineFit.assign`
Args:
dists (numpy.array)
Core and accessory distances to clas... | e708b232e00714462039fd1ef9e382fae8f3bb33 | 79,587 |
import json
import urllib
def request_mock(*args, **kwargs):
"""A mock urlopen requests sent in the requests package."""
# Create the mock response object.
class MockResponse:
def __init__(self, json_data):
self.json_data = json_data
def read(self):
return self.j... | 5b31a68e259c0a0535da4b42dfca45115798e976 | 79,589 |
def conv_factor(sigma2):
"""
Internal support routine to compute conversion factor.
"""
return c0 + c1 / (c2 - sigma2) + c3 / (c4 - sigma2) | 924b403f2ead22e23c4bbe50fbff9836ad4a92f0 | 79,591 |
def parse_manifest(manif, manifest_info, opts):
"""
parse V2 or V3 manifest for annotations
"""
if manifest_info is None:
annotation_info = {
'annotations': [],
'by_target': dict(),
'motivations': set()
}
manifest_info = {
'annotati... | a22ffce67651adb9352c742eb3e45b1127280289 | 79,592 |
def cov_nearest_factor_homog(cov, rank):
"""
Approximate an arbitrary square matrix with a factor-structured
matrix of the form k*I + XX'.
Parameters
----------
cov : array-like
The input array, must be square but need not be positive
semidefinite
rank : positive integer
... | a4cc9ecf2c0c9252f5dc68c534aaed99e0767b2d | 79,594 |
import torch
def positional_encoding(g, pos_enc_dim):
"""
Graph positional encoding v/ Laplacian eigenvectors
"""
# Laplacian
A = g.adjacency_matrix_scipy(return_edge_ids=False).astype(float)
N = sp.diags(dgl.backend.asnumpy(g.in_degrees()).clip(1) ** -0.5, dtype=float)
L = sp.eye... | 7aaf852fa4a4ba8ebeff559df1dc59190d71bc71 | 79,595 |
from typing import Iterable
from typing import Union
from pathlib import Path
from typing import IO
from typing import List
from typing import Dict
def _parse_multiple(paths: Iterable[Union[str, Path, IO]]) -> List[Node]:
"""Merge nodl files into one large node list.
:param paths: List of nodl files to parse... | 0175346fb74761cf7256167bf8579ba219cd78bc | 79,596 |
def head_to_tree(head, len_):
"""
Convert a sequence of head indexes into a tree object.
"""
head = head[:len_].tolist()
root = None
nodes = [Tree() for _ in head]
for i in range(len(nodes)):
h = head[i]
nodes[i].idx = i
nodes[i].dist = -1 # just a filler
i... | 4121acb0eb1724aaf07c111a1facce13c2c7393d | 79,597 |
def delete_student(nuid): # noqa: E501
"""Delete student
This can only be done by the logged in student. # noqa: E501
:param nuid: The nuid that needs to be deleted
:type nuid: str
:rtype: None
"""
delete_string = """
DELETE FROM student
WHERE nuid = "{}"
""".form... | bf5f6f5c0ab159728a93cbad13075a6db9bb43bc | 79,599 |
def aoki_hess(x):
"""
Second-Order derivative - Hessian Matrix of aoki function(Nabia - 2)
"""
g_xx = 6 * np.square(x[0]) - 2*x[1] + 1
g_xy = -2 * x[0]
g_yy = 1
H = np.diag((2,2))
H[0][0] = g_xx
H[0][1] = g_xy
H[1][0] = g_xy
H[1][1] = g_yy
return H | 9451e3ae547c3cc16c746d7c1da5adfbfa14c56f | 79,602 |
from typing import Callable
import time
def collect_metrics(func: Callable):
"""Wraps the function to store total call time and number of calls in call_metrics.
:param func: Function to be wrapped
:return: Wrapped function that stores execution information to call_metrics.
"""
@wraps(func)
d... | 4fc53a1b64cafbe7d2a0c9e4f8f2130067e102c1 | 79,603 |
import requests
def edit_department(department_id):
"""
Returns rendered template to edit department.
:param department_id: department id
:return: rendered template to edit department
"""
url = f'{HOST}api/department/{department_id}'
department = requests.get(url).json()
form = Departm... | 25db1c024f87f1ce24ac0e695ae83d6afc3d4ea4 | 79,604 |
from typing import Type
def copy_media(eaf_1: Type[Eaf], eaf_3: Type[Eaf]):
"""
Copy the media file info from file 1 into the new file
:param eaf_1: Source Eaf object which has the media linked file
:param eaf_3: Destination Eaf object
:return:
"""
# Get all the media for the first file
... | ebb5329da1ba90dd4d169b2da448a0c69b1fc82a | 79,605 |
from core.models.coreproxy import DimMapTypeProxy, ModelMapProxy
def validate_map(user_id, source_config, dest_config, mapdetails):
"""
validate mapdetails
"""
message = []
# job_id = config.get('job_id', None)
if not mapdetails or len(mapdetails) < 0:
message.append('Invalid map d... | a1a270a3d7274e8d14a5fa3650fded47a615a7ba | 79,606 |
def ldns_pkt_tsig_sign(*args):
"""LDNS buffer."""
return _ldns.ldns_pkt_tsig_sign(*args) | 5fc3bff2945c5ab26c198229cf0ef3bcaf696aa3 | 79,607 |
from typing import Union
from datetime import datetime
from typing import List
def datetime_to_list(datetime_obj: Union[date, datetime]) -> List[int]:
""" Takes in a date or datetime, returns a list of datetime components. """
datetime_component_list = [datetime_obj.year, datetime_obj.month, datetime_obj.day]... | 342666cfa83b2a3d9370a309f9ab9161c061d1c7 | 79,608 |
from .sources.ncbigene import get_ncbigene_id_to_name_mapping
from typing import Mapping
def get_id_name_mapping(prefix: str, **kwargs) -> Mapping[str, str]:
"""Get an identifier to name mapping for the OBO file."""
if prefix == 'ncbigene':
logger.info('[%s] loading mappings', prefix)
return g... | 2225899daf99a056a9949c2bbbe5036f9df1b2ef | 79,609 |
def sim_read_counts(contigs, chr_type,
n_reads=1e5, n_inds=74, sex_ratio=50/(50+22), hom_ref=False):
"""
sex_ratio -- The proportion of individuals that have two copies of the
first sex chromosome.
hom_ref -- The reference is homogametic, so all reads from the
... | f2a9e3e451525cc6e1a886757712659c624f717a | 79,610 |
def PolsIF_End_inner(t):
"""Number of policies: End of period"""
if t == t0:
return outer.PolsIF_End(t)
else:
return PolsIF_Beg1(t-1) - PolsDeath(t-1) - PolsSurr(t-1) | 94dbb72921e9518a10b215e9cc17194e82a01de4 | 79,611 |
from ..db import Database, DatacubeResource, DatasetResource
def config_to_resources(config):
""" Return `tilezilla` resources from a configuration dict
Args:
config (dict): `tilezilla` configuration
Return:
tuple[TileSpec, str, Database, DatacubeResource, DatasetResource]: A
... | d61142b03db942aaa5936f69daf5f08b5176dfd0 | 79,612 |
def eta(start, completed, total):
""" Function returning an ETA. """
# Computation
took = time_since(start)
time_per_step = took / completed
remaining_steps = total - completed
remaining_time = time_per_step * remaining_steps
return user_friendly_time(remaining_time) | b3185abfafbd59976787db1584c754f6d00ef05c | 79,614 |
def identity(x):
"""Simple identity
"""
return x | abebf1ea2ef1579164a9ead43348c10fbfc1a43e | 79,615 |
def trapz_deriv(y, x):
"""trapezoidal integration and derivatives with respect to integrand or variable."""
dI_dy = np.gradient(x)
dI_dy[0] /= 2
dI_dy[-1] /= 2
dI_dx = -np.gradient(y)
dI_dx[0] = -0.5*(y[0] + y[1])
dI_dx[-1] = 0.5*(y[-1] + y[-2])
return dI_dy, dI_dx | ca15db9d586128dd16d09cc0113eff511ad60fb6 | 79,616 |
from typing import Mapping
def is_upload(association):
"""
Indicates whether the association corresponds to an upload object.
"""
upload_keys = set([
'created_at', 'id', 'job_id', 'updated_at', 'upload_content_type',
'upload_file_name', 'upload_file_size', 'upload_updated_at'
])
... | d2adf1ea3077b2021a448f7f5ecbb28ab342b3cc | 79,618 |
from typing import Tuple
def cell_to_coordinates(cell: int) -> Tuple[float]:
"""Convert cell number to x,y coordinates."""
cells_width = (cell) % 11
cells_height = (cell) // 11
x_coord = START_WIDTH + cells_width * WIDTH_STEP
y_coord = START_HEIGHT + cells_height * HEIGHT_STEP
return x_coord... | 20e1da3db284599a4909c5b4cdde7654a1fa31d7 | 79,619 |
def seed_meteringpoints(
session: db.Session,
token_subject: str
):
"""
Insert dummy meteringpoints into the database
"""
for meteringpoint in METERINGPOINTS:
dispatcher(m.MeteringPointUpdate(
meteringpoint=meteringpoint,
))
dispatcher(m.MeteringPoin... | f07af63c26af5e4ea131293ae7fadfa1a502df49 | 79,620 |
from typing import List
from datetime import datetime
def get_google_calendar_events() -> List[dict]:
"""
Retrieves all available google calendar events.
:return: List of events.
"""
# Authenticate and get calendar resource object
creds: account.Credentials = account.Credentials.from_service_... | 2bbc53d81c937e9ad2ea362e19b25304fc1f1665 | 79,621 |
def lenprefix(data, nbytes=2):
"""Prefix `data` with its length, in `nbytes` big-endian bytes.
If `data` is a string, it is first converted to bytes as UTF-8.
"""
assert type(data) in (str, bytes)
if type(data) is str:
data = bytes(data, "utf8")
return len(data).to_bytes(nbytes, "big") +... | b59e9aff1c7500fdcfa1482012ee9bab16c04022 | 79,622 |
def loss_grad_softmax_vectorized(W, X, y, reg):
""" Compute the loss and gradients using softmax with vectorized version"""
loss = 0
grad = np.zeros_like(W)
dim, num_train = X.shape
scores = W.dot(X) # [K, N]
# Shift scores so that the highest value is 0
scores -= np.max(scores)
scores... | 16ed1c9ee712ae2acb62c21ba1477acd90140509 | 79,624 |
from typing import List
import asyncio
def parallel_get_github_endpoint(endpoint_list: List[dict], github_token: str, verbose: bool = True) -> dict:
"""
Similar to get_github_endpoint, but launches requests in parallel, returning a dictionary where
the keys are the original endpoint URLs, and the values a... | 8f05815b08ae7eebf536390a62bddaeddb3bb78a | 79,625 |
def get_names(path: str) -> _List[str]:
"""
Returns the possible names of the embedded files in a Windows path.
:param path: str: File path to write the data.
:return: List[str]
"""
# Checks whether the inputs are valid
if not isinstance(path, str):
raise TypeError('`path` must be ... | 937fabb046bfcd8685c65cdd3047a6f98c5c5a5b | 79,627 |
from typing import Optional
import socket
def format_register_str(register: str, value: Optional[int]) -> str:
"""Returns the given value as a string representation of the given register."""
bytesize = REGISTER_INFO[register][0]
if value is None:
return "x" * (2 * bytesize)
if bytesize == 4:... | 7ebb6f311102064033f7d5bb97bdebede39e8d46 | 79,628 |
import click
def validate_ecc_rsa_id(ctx, param, value):
"""
Check a given id can be initialised as an RSA or ECC key object
:param value:
a given Object ID
:raises:
- click.BadParameter - in case the given object id can't be initialised
"""
try:
obj = objects.ECCKey(... | 2eb8177dc4bba325f0a05c5786b5d128e26ea552 | 79,630 |
from typing import List
def _create_path_from_parts(path_parts: List[str]) -> str:
"""Creates the typical path format from a list of the individual parts
Args:
path_parts (List[str]): list containing the parts of a path
Ex.: ['home', 'usr', 'dir1']
Returns:
... | 4e8f38f98c2d5da9db5d4607b49c0a70cc8c9c33 | 79,631 |
def execute_memory_address_decoder(program):
"""Execute program as a memory address decoder."""
memory = {}
mask = ''
for line in program:
if line.startswith('mask'):
mask = parse_mask(line)
else:
address, value = parse_assignment_line(line)
result_add... | e5c60f57af9c7868446a7f7c5699f039d205b27a | 79,632 |
def get_or_del_node(request):
"""Gets or Deletes a node."""
name = request.matchdict['name']
queue = request.registry['queue']
if 'delete' in request.params:
check_auth(request)
queue.delete_node(name)
return HTTPFound(location='/nodes')
return queue.get_node(name) | d56a4b4ef851eaedcc49809288f947a28537e633 | 79,633 |
def conv3x3_block(in_channels,
out_channels,
stride=1,
padding=1,
dilation=1,
groups=1,
bias=False,
use_bn=True,
bn_eps=1e-5,
activation='mish'):
"""
... | 8f1d4658c5f6daef951fda551f9fc054e00cd346 | 79,634 |
def group_points(input, idx, name=None):
"""
**Group Points Layer**
This operator group input points with index.
Args:
input (Variable): The input tensor of three_interp operator. This
is a 3-D tensor with shape of [B, N, C].
idx (Variable): The index tensor o... | d66c56c49b4b29fb60feb958c35ea8ecb4f2d576 | 79,635 |
from typing import Any
from datetime import datetime
import uuid
def json_serialize(obj: Any) -> str:
"""JSON serializer for objects not serializable by default json."""
if isinstance(obj, (datetime, date)):
return obj.strftime('%Y-%m-%d %H:%M:%S UTC')
if issubclass(type(obj), datetime) and hasatt... | f2313d5c2ff6c2b7cee7a7465b69475eac79a033 | 79,636 |
def _table_sort_by(table, sort_exprs):
"""
Sort table by the indicated column expressions and sort orders
(ascending/descending)
Parameters
----------
sort_exprs : sorting expressions
Must be one of:
- Column name or expression
- Sort key, e.g. desc(col)
- (column ... | e03fdf80ea25e18ae10f4d1665371deeb80bb064 | 79,637 |
def shortest_path_heap(graph, start_vertex):
""" Computes shortest path using a dijkstra algorithm and speeding it up
using a heap data structure.
Note! The reason dijkstra doesn't work with negative-length edges is
because the algorithm may take the negative edges in considerations
multiple times ... | 9176f292d3ecf58691a0eb8a7610bcd8ea585816 | 79,638 |
def tie(p, ptied = None):
"""Tie one parameter to another."""
if (ptied == None): return p
for i in range(len(ptied)):
if ptied[i] == '': continue
cmd = 'p[' + str(i) + '] = ' + ptied[i]
exec(cmd)
return p | 621100a4cb3cf1a576e8d71c2870d0cf79959d77 | 79,640 |
def pre_prepare_ifgs(ifg_paths, params):
"""
nan and mm convert ifgs
"""
ifgs = [Ifg(p) for p in ifg_paths]
for i in ifgs:
i.open(readonly=False)
nan_and_mm_convert(i, params)
return ifgs | 4e2e9a229981d57d6d6e9f604dfec561bad63342 | 79,641 |
def get_timezone_helper():
"""Get a TimezoneHelper initialized with current GUI settings."""
# XXX: timezone could be user-specific - change the lookup here if this is done
tz = TimezoneHelper()
try:
root = db.get_db().getRoot()
tzname = root.getS(ns_ui.uiConfig, rdf.Type(ns_ui.UiConfi... | 1cf8c00a2ce4fbb6aa0b26d0e51bdb98469e51ba | 79,642 |
import signal
import time
def timeout(seconds, *args):
"""
Simple decorator to stop a function after a specified time limit.
Adapted from
https://stackoverflow.com/questions/35490555/python-timeout-decorator
Example:
>>> @timeout(10)
def infloop():
while true:
... | 4ed0ec8d53d655fe82bc0b983391acf5716fc290 | 79,643 |
def hamming_distance(w1: str, w2: str)->int:
"""Compute the hamming distance between the given strings"""
d = 0
for i in range(len(w1)):
if i >= len(w2):
return d + len(w1) - len(w2)
if w1[i] != w2[i]:
d += 1
return d | 3eda58c4c56a1b8fbb79719051c650884a396f68 | 79,644 |
def make_vec_env(env_id, env_type, num_env, seed,
wrapper_kwargs=None,
env_kwargs=None,
start_index=0,
reward_scale=1.0,
flatten_dict_observations=True,
gamestate=None,
initializer=None,
... | 3190e0b0a1208aac85575e0c83c6ae6404b00e41 | 79,645 |
def game_save_settings(request, game_id):
"""Save state of the game as json"""
state = check_received_data(request, GAME_STATE)
if not state:
response = {ERROR: GAME_STATE_INVALID}
try:
save_game_state(request, game_id, state)
response = {'state': state}
except:
respo... | 4a38a7971a54699b19bcdc2614db5b820fde34fa | 79,646 |
def start_date(start):
""" Given the start only, calculate TMIN, TAVG, and TMAX for all dates greater than
and equal to the start date.
"""
results = session.query(measurement.date, func.avg(measurement.tobs), func.max(measurement.tobs),func.min(measurement.tobs)).\
filter(measurement.date... | 4a55564ae2db75b50b5931e97f16e9e71f622a69 | 79,647 |
def get_role_name_by_role_code(role_code):
"""
将角色编码转换为角色名
"""
role_code_name_dict = dict(ROLECODE_CHOICES)
return _(role_code_name_dict.get(role_code, '')) | 6b634517a3a20b61e908fdb9d4f24d2dfdc5ce38 | 79,648 |
from typing import Tuple
def num_repetitions_in_sentence_pair(src_sentence: Tokens,
trg_sentence: Tokens,
adjacent: bool = True,
ngram_order: int = 1) -> Tuple[int, int]:
"""
:param src_sentence: Li... | b4fee3c4321eb37a1535a3986fe41337ccc0fd4a | 79,649 |
from typing import Union
from typing import List
from typing import Dict
def to_output(dataframe: Union[pd.DataFrame, List[pd.DataFrame]]) -> Dict:
"""Converts your data to a json serializable output format complying with the schedules feature.
Args:
dataframe (Union[List[pd.DataFrame, pd.DataFrame]]... | 53c214fbd4a6136c75b52bdba015da07f0a38091 | 79,650 |
def is_happy(num):
"""Determine if num is happy or sad."""
validate_integers(num)
while True:
if num == 1:
return True
if num == 89:
return False
num = happy_step(num) | 5bcfae67616c478d83d81c4b78b50b04b21df36b | 79,651 |
def crime_filter(df, categories, column="Straftat"):
"""Construct filter for crimes listed in [categories]
Args:
df ([type]): [description]
column (str, optional): [description]. Defaults to "Straftat".
Returns:
[type]: [description]
"""
filt = df[column] == categories[0]
... | 1800933bc879f6153d5fcf640327cd9ad86e6d62 | 79,652 |
def btsearch(f, b, f0=None, maxiter=20, tau=0.5):
"""
Backtracking search
Arguments:
f -- function f(x)
b -- end point
f0 -- f(0)
"""
x = b
for i in range(maxiter):
fx = f(x)
if fx.F > f0:
x *= tau
else:
return x, fx
raise Value... | 2125e7c48b157dee68ff2b3cca0dd3b277e6f662 | 79,653 |
import re
def break_down(compound, forgiving=True):
"""
Breaks a string representing a chemical formula down into constituent parts.
Things in parentheses are considered one part.
Any string of a capital letter followed by lower case letters is considered to be
an irriducible element.
Any ... | d09c038423f5a89d75499c1395e31c3328c9df17 | 79,654 |
def jsonify_exception(error: HTTPException) -> Response:
"""Render exceptions as JSON."""
exc_resp = error.get_response()
response: Response = jsonify(reason=error.description)
response.status_code = exc_resp.status_code
return response | 821599c4747949920f6d149dd57a294b6d9c5445 | 79,655 |
def getPhoto(dic):
"""Returns the Link for Photo.
dic -- Dictionary from the JSON with all values.
"""
return str(dic["content"]["$t"]).split(',')[2].split(' ')[2].strip() | 8199baba971a0f3ca7ff73ea8f3499c98e95bf2b | 79,656 |
def note_and_bend(mycents, middle_note=60):
"""Take a cent value and return a MIDI note and bend.
Scale to '0 cents = middle-C' if middle_c=True.
"""
note, remain = divmod(mycents + 50, 100.0)
note = int(note + middle_note)
bend = 8192 + int(round((remain - 50) * 40.96))
return note, bend | 69ce2fb0e8089061f2c14e6e2828ccb0feef122a | 79,657 |
import re
import math
def directory(request, category):
""" Returns a directory of all authors/companies/genres in the database """
data = {}
data["category"] = category
""" This can possibly be cached in some way, it's not going to change
often.
"""
data_list = []
if category == "com... | f18391f0a06a09114e73aeed3ba363d20b873406 | 79,659 |
def cgc_posneg(header='', data_dir='.', extension='.obfs', save=True,
recurse=0, save_dir=None, posfile='pos', negfile='neg'):
"""
This preprocessing function uses the cgc directory README scheme
to split files into separate data sets of positive and negative
samples.
... | 46d7853b6c9c46bdd99e1735fd92815583ec7c22 | 79,660 |
def exported_diff(cy_basefile, cy_difffile, col_header, diff_ppis=None,
justids=False):
"""
Makes a new cy_ file labeling whether that interaction is also found in the
cy_difffile (or the diff_ppis--pass None for cy_difffile in that case).
"""
def cy_ppi_to_pair(p):
return (p[0].spli... | 2d06bf70369964d209f71c37857701548f94c776 | 79,661 |
def create_model(opt):
"""Create a model given the option.
This function warps the class CustomDatasetDataLoader.
This is the main interface between this package and 'train.py'/'test.py'
Example:
>>> from models import create_model
>>> model = create_model(opt)
"""
model = find... | 96e23d9a3e4d3caff912bbe254eb8d8a079dcc69 | 79,663 |
def _convert_coords_dt_to_np_coords(coords_dt):
"""convert coord_dt to numpy coords """
return coords_dt.view(int).reshape(-1, 3) | 90db6d289834a1764acc53154a2d5d6d8a03538d | 79,664 |
def split_ingredient_str(s: str) -> ('fraction.Fraction', 'unit.Unit', str):
"""
Examples:
>>> split_ingredient_str('1 1/2 large onions, finely sliced')
(3/2, <SpecialUnit.NONE: 'None'>, 'large onions, finely sliced')
# >>> split_ingredient_str('One 10-inch-long beef tenderloin roast c... | 52f27ee7fe3e4514adf3e16461d1b8b8e71fe755 | 79,666 |
def read_row(width):
"""Reads a grid row of the specific width."""
row = list(input().strip())
if len(row) != width:
raise ValueError('wrong row width')
return row | 5b55f0a5df2c1d966b970705d5b1bbbc8a1aec12 | 79,667 |
def levenshtein(a, b):
"""Calculates the Levenshtein distance between a and b."""
n, m = len(a), len(b)
if n > m: # pragma: no cover
# Make sure n <= m, to use O(min(n,m)) space
a, b = b, a
n, m = m, n
current = range(n + 1)
for i in range(1, m + 1):
previous, curre... | 059550b6c3b5f02875ce71f4720368987d8b0c7f | 79,668 |
from typing import Optional
from typing import Type
def _axis_intervals(
window: int,
groups=None,
positions=None,
step: Optional[int]=1,
n: Optional[int]=None,
target_chunk_size: Optional[int]=None,
dtype: Type=np.int32
):
"""Get axis intervals for overlapping computations
... | 13d24cb29aab7c5f001c7c39b21d080fd8ff4046 | 79,669 |
def multiplicative_inverse_factors(a_value, m_modulus):
"""[Summary: Returns a list of all the values of 'x'
that solve the equation 'ax mod n = 1'.]
Arguments:
a_value {[int]} -- [description]
m_modulus {[int]} -- [description]
"""
mult_inverse_list = list()
for test_mult_inverse i... | f91d28c760963861ef173ef3907f9b77867b3451 | 79,670 |
def propagation_matrix(adj, alpha=0.85, sigma=1, nodes=None):
"""
Computes the propagation matrix (1-alpha)(I - alpha D^{-sigma} A D^{sigma-1})^{-1}.
Parameters
----------
adj : sp.spmatrix, shape [n, n]
Sparse adjacency matrix.
alpha : float
(1-alpha) is the teleport probabili... | 91911eaaaf32e3bd084346cb161d57ccc533f783 | 79,671 |
def laplacian(input_mat, dx):
"""
Parameters
----------
input_mat :
dx :
Returns
-------
"""
top = input_mat[0:-2, 1:-1, 1:-1]
left = input_mat[1:-1, 0:-2, 1:-1]
bottom = input_mat[2:, 1:-1, 1:-1]
right = input_mat[1:-1, 2:, 1:-1]
center = input_... | 8a1edb5a8715340f2f466d6990beca3ff96de64d | 79,672 |
def frozensets(elements=None, min_size=None, average_size=None, max_size=None):
"""This is identical to the sets function but instead returns
frozensets."""
return lists(
elements=elements, min_size=min_size, average_size=average_size,
max_size=max_size, unique=True
).map(frozenset) | 980583ca731a8555a72e801241fc73734a21fa79 | 79,673 |
def sum_abs_of_all_without_range(sequence):
"""
Same specification as sum_abs_of_all above,
but with a different implementation.
"""
# ------------------------------------------------------------------
# EXAMPLE 2. Iterates through a sequence of numbers, summing them.
# Same as Example ... | 21fdb3d5d4edf6a920a3e0523b8af5948c6244f4 | 79,674 |
from typing import Optional
from typing import Dict
from typing import Any
def focused_module(*, timeout:Optional[float] = None) -> Dict[str,Any]:
"""Returns the name and other information about the currently-focused module."""
return __get_designated_connection().focused_module(timeout=timeout) | bb5b38871d576079e6d40d9d876d93302f3bd41a | 79,675 |
def GCD(numbers : list):
"""Computes Greatest Common Divisor of the numbers in the list
Since gcd(a, b, c, d) = gcd(a, gcd(b, gcd(c, d)))
"""
numbers = sorted(numbers)
if len(numbers) == 0:
return None
elif len(numbers) == 1:
return numbers[0]
elif len(numbers) == 2:
... | f18198ceb2dbfac48d5f600462c8b8f01ded2499 | 79,676 |
import copy
import random
def mutate_disable_connection(a):
"""
なんか適当なコネクションを選んでとりあえず無効化する
"""
agent = copy.deepcopy(a)
agent.reset()
if(agent.num_of_active_connection <= agent.connection_num_lower_limit):
return agent
else:
while(True):
n = random.randint(0, le... | 24af5809937cd896f22d40d620529c46edd86db0 | 79,677 |
from re import T
import torch
def norm_truncate_rsample(
μ: T, σ: T, ll: bool = False, a: float = -1.0, b: float = 1.0
):
"""
Takes an rsample from a truncated normal distribution given the mean μ and
the variance σ. Sample is same sized as μ and σ.
Args:
μ: Means
σ: Variances
... | 5112164539747966f8dec3d80e5ed8c8f32bbf21 | 79,679 |
def compute_ap(recall, precision):
""" Compute the average precision, given the recall and precision curves
# Arguments
recall: The recall curve (list)
precision: The precision curve (list)
# Returns
Average precision, precision curve, recall curve
"""
# Append sentinel v... | f7ba1562a188a1d18175cd45223f33fba55d257a | 79,680 |
def load_engine(engine_options=None):
"""Load engine for analysing games"""
# Use the open-soure engine Stockfish
engine = chess.uci.popen_engine('stockfish')
# Important to use UCI (Universal Chess Interface)
engine.uci()
if engine_options:
engine.setoption(engine_options)
# Use an ... | 9d4246d6bd1cf245c759cbcc890d86c2f0194ca9 | 79,681 |
def image_label(x, **kw):
"""Use important defect as image label.
Args:
x (str, list): image path or list of dict.
Returns:
str(image label) or dict.
"""
if isinstance(x, str):
return gen_code_by_path(x)
mode = kw.get("mode", "max_score")
if mode == "complex":
... | da8a86e53ebddd0b89a177a0d76ab7f4d1aa0562 | 79,682 |
from pathlib import Path
from typing import List
from datetime import datetime
from typing import Optional
import logging
def adjust_data(filepath: Path,
wards: List[str],
startdate: datetime,
enddate: datetime,
keep_internal: bool = False,
... | a1d45c3198d750c108f6787bdf138aa8663ec010 | 79,683 |
def read_hhr(fn):
"""Read the output of hh-suite applications
Just uses their parser (added to this repo for convenience)
"""
hh_data = hh_reader.read_result(fn)
return pd.DataFrame.from_dict(hh_data) | fa9f9e885ed201eeabe31cf73b60c051222b98ad | 79,685 |
def create_empty_network():
"""
Create an empty network
:return: a Network object that will later contain all the network components.
"""
return _SupNetwork() | e4445107f6985fc9a35caa5bef939ed61edb117c | 79,686 |
def check_item(line_lst):
"""Function that takes file lines as input list and compare with exisitng file"""
top_level_1 = {'HEAD', 'TRLR', 'NOTE'}
top_level_2 = {'INDI', 'FAM'}
tag_indi = {'NAME', 'SEX', 'BIRT', 'DEAT', 'FAMC', 'FAMS'}
tag_fam = {'MARR', 'HUSB', 'WIFE', 'CHIL', 'DIV'}
tag_date =... | 56ca880f802698196881b2f1ed0836e0cf90c229 | 79,687 |
def index2onehot(index, N):
"""
Transforms index to one-hot representation, for example
Input: e.g. index = [1, 2, 0], N = 4
Output: [[0, 1, 0, 0], [0, 0, 1, 0], [1, 0, 0, 0]]
"""
L = index.shape[0]
onehot = np.zeros((N, L))
for l in np.arange(L):
onehot[index[l], l] = 1
... | 59f6aae4788dbdfaafdf8ef535e50aae9e69bc28 | 79,688 |
def _get_boolean(data, position, dummy0, dummy1, dummy2):
"""Decode a BSON true/false to python True/False."""
end = position + 1
boolean_byte = data[position:end]
if boolean_byte == b'\x00':
return False, end
elif boolean_byte == b'\x01':
return True, end
raise InvalidBSON('inva... | 5e27f9ce536d50f2cf16264c9e21eaf1b491fbe1 | 79,689 |
from operator import eq
from operator import le
from operator import ge
def OperatorFromStr():
""" Module for program-wide constant maps (e.g., dicts that should never change) """
return {"=": eq,
"le": le,
"ge": ge} | 1767821ea0b734312b41a49e5226df682aece430 | 79,690 |
def galileo(
salary_compound_rate : float,
salary_plateau : float,
base_spending : float,
increase_savings_weight : float,
initial_year : int,
year_of_retirement : int,
year_of_death : int,
retirement_income : float,
rrsp_interest_rate : float,
tfsa_interest_rate : float,
... | 599eca362572a9d49d71261f73d7ffe347ceaec4 | 79,692 |
def get_organisms():
"""Get route for available organisms"""
return jsonify([org.to_json() for org in Organism.query.all()]) | c8a9c4f445f3232dcc2d774bce8ad89ba2176e58 | 79,693 |
def foveat_img(im, fixs, fov_params):
"""
im: input image
fixs: sequences of fixations of form [(x1, y1), (x2, y2), ...]
This function outputs the foveated image with given input image and fixations.
"""
sigma = 0.248
prNum = 6
As = pyramid(im, sigma, prNum)
height, width, _ = i... | ca4009f7edb76926cb6d0f6fa2d02e88f7cff688 | 79,695 |
def LH_matvec(v: tn.Tensor, lR: tn.Tensor, A_L: tn.Tensor) -> tn.Tensor:
"""
The linear operator used as A in Ax = b to solve for LH. Defining this
function inline would result in greatly degraded performance with Jax due to
extra traces.
Args:
v: Current guess solution for LH.
lR: left fixed point of... | e0a15604c5aab4f8356bbf2d34b7afe5cba61026 | 79,696 |
import copy
def label_f1(tar_path: list, pre_path: list, length: list, tags: list, tag_map: dict, prefix: str):
"""
Compute the Precision, Recall, and F1 Score
"""
c_tar_path = copy.deepcopy(tar_path)
c_pre_path = copy.deepcopy(pre_path)
origin = 0.
found = 0.
right = 0.
new_tar ... | 270de9b1e9045b8246b865767e0512ca8bacbc3c | 79,697 |
import inspect
from typing import cast
from typing import List
def many(parser: Parser) -> Parser:
"""Many function.
Receives one parser object.
And repeats parsing for success.
Must succeed at least once.
Parameters
----------
parser
The Parser object.
Returns
-------
... | 7cdd4c131809918f78adba8b93d106be451354a9 | 79,698 |
import json
import http
def get_runner(request):
"""
Set a time to a People.
Accept only POST request with parameters:
:arg int num:
The bib number of the runner
:arg str/time time:
A time format (like hh:mm:ss)
:returns:
A JSON data with some runner informations.
... | a48d7469949d486caa200ccba94d748e07052d77 | 79,699 |
def ReadNrrdAsSitkImage(seg_nrrd_path:str, base_image_path:str):
"""Read .nrrd format segmentation file as SimpleITK image.
Parameters
----------
seg_nrrd_path:
file path of .nrrd format segmentation file
base_image_path:
file path of the base image of the seg... | 8f41f17941bc981103c7343830208bcd02923f2f | 79,700 |
def clear_user_metadata(request):
"""clear user metadata"""
WorkspaceUtil.clear_session_data(request)
return HttpResponseRedirect(reverse('view_session_info')) | d5238dbb51ceaa100f4770c4186422a8acbfb8eb | 79,701 |
def dummy_npgettext(context, singular, plural, n):
"""
Mimic ``npgettext()`` function. This is a passthrough function with teh
same signature as ``npgettext()``. It can be used to simulate translation
for applications that are untranslated, without the overhead of calling the
real ``npgettext()`` fu... | 5e83ee77f5511b91ec25277e9c7ca5932295cd39 | 79,702 |
def getPressure(q):
"""Use this function to solve for pressure of the 2D Eulers equations.
q is set up as:
q[0] = rho
q[1] = rho*u
q[2] = rho*v
q[3] = rho*e
P = (GAMMA-1)*(rho*e-(1/2)*(rho*u^2+rho*v^2))
"""
return gM1*(q[3]-(q[1]*q[1]+q[2]*q[2])/(2*q[0])) | c89de95bbf1a8021e7754ab4ec7f8b67ff41b21f | 79,703 |
def small_cnn() -> Sequential:
"""A very small custom convolutional neural network with image input dimensions of 224x224x3.
Returns
-------
Sequential
The keras Sequential model.
"""
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation="relu", input_shape=(224... | f4bc23c762f05fb2337e6d17800539e09933f203 | 79,704 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.