content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def from_dict(
d,
mapping=None,
type_map=None,
ignore_fields=None,
infer_date=False,
convert_hyphens=False,
schema=None,
table=None,
partitions=None,
s3_key=None,
case_map=False,
case_insensitive=False,
ignore_malformed_json=True,
ignore_nested_arrarys=True,
n... | 76d8c4cca52ed23d858e91a82804f81fc96709c8 | 48,422 |
from typing import Callable
import functools
def stop_on_shutdown_event(f: Callable[[Agent, Event], None]):
"""
Decorator which can be used to wrap the handle_event method.
If a system_shutdown event is received, stop running without calling handle_event.
"""
@functools.wraps(f)
def wrapper(... | a948098e80c56ff69badce5cc754abaab9ff6fda | 48,423 |
def generate_full_uri(request=None, suffix=None):
"""
生成绝对链接
:param request:
:param suffix:
:return:
"""
url = suffix or ''
if request:
request_host = request.get_host()
host, *sub_path = request_host.split("/", 1)
base_uri = '{scheme}://{host}'.format(scheme=requ... | bf48fa0ef933f8194baefb20408cb7be16131f92 | 48,424 |
def bins_to_str(lbin):
"""
Return a list of unicode characters into a message
:lbin:list(bin), a list of characters
"""
sbin = ''.join(lbin)
lbin8 = wrap(sbin, 8)
message = chr(int(lbin8[0],2))
for c in lbin8[1:]:
message+=chr(int(c,2))
return message | 47bbd7d7881e5d9ad3e0369216653719048b8156 | 48,425 |
def _log_commit_progress(table_size, no_chunks):
"""Shim to avoid sgr spamming output with commit progress for small images"""
return table_size > 500000 or no_chunks > 100 | 82394d325bb755045ca7057ebbe53520024edeab | 48,426 |
import binascii
def display_string_dump(elf_file, section_spec):
""" Display a strings dump of a section. section_spec is either a
section number or a name.
"""
section = _section_from_spec(elf_file, section_spec)
if section is None:
print("Section '%s' does not exist in the file!" % s... | 1d3d1d864d99a0acfc69db387dbadab81f83e111 | 48,428 |
import pandas
def get_backend() -> Optional[str]:
"""
Returns the current pandas plotting backend,
or ``None`` if pandas is not available.
Typically the result will be ``"matplotlib"``.
:return: str or None
"""
try:
except ImportError: # pragma: no cover
return None
ret... | cd4a2adecd42b45faf95dd7963958e4f16b06eeb | 48,429 |
def PolygonACD(array, value):
"""
used by libcvcaller.py
inputs:
array
value
outputs:
array?
"""
try:
return libcv.PolygonACD(array, value)
except:
print "libcv failed in PolygonACD"
return [] | be6f41703f51ad24ee7215a66ea7285db2c5ed82 | 48,431 |
def root(request):
"""
Tutorial > Root
"""
return HttpResponsePermanentRedirect(reverse('explore.views.tutorials')) | df5fcb264220c76e90a2f1e570162095c1c974fb | 48,433 |
import logging
def extract_spectral_data_from_df(df):
"""
takes a dataframe where each columns is a spectral sensor. Expands each columns into a dataframe and returns a
dictionary of dataframes
:param df: dataframe of binary format spectral data
:return: dictionary of dataframes of expanded spectr... | deef70f237aaea683ee0d25eadf982c0bb984c5e | 48,434 |
def gsfLoadScaleFactor(
p_sf, subrecord_id: c_int, c_flag: c_char, precision: c_double, offset: c_int
) -> int:
"""
:param p_sf: POINTER(gsfpy3_09.gsfRecords.c_gsfScaleFactors)
:param subrecord_id: c_int
:param c_flag: c_char
:param precision: c_double
:param offset: c_int
:return: 0 if ... | ce01379ee1b83bb2f5362cfd189908f53e49a17e | 48,435 |
def get_ip(request, real_ip_only=False, right_most_proxy=False):
"""
Returns client's best-matched ip-address, or None
@deprecated - Do not edit
"""
best_matched_ip = None
for key in defs.IPWARE_META_PRECEDENCE_ORDER:
value = request.META.get(key, request.META.get(key.replace('_', '-'), ... | 744c8693d4882b3e0431fb640efef87b27042bd5 | 48,436 |
import re
def parse_textfile(input_text):
"""This funtion converts text into a list of available emission maps, a dict of emission data and a dict of
metadata. The expected input is:
input_text: str
"""
list_available_maps = ''
dict_data = {}
dict_meta = {}
start_data_row = -1
end... | 1a6a6b308effb2e44a7b019284f4c65f8c18a4f3 | 48,437 |
import torch
def auto_annotate(img_paths):
"""
Auto annotates a list of images using DETR.
Args:
"""
detr = torch.hub.load('facebookresearch/detr', 'detr_resnet50', pretrained=True)
detr.eval()
annotations = []
for img_path in img_paths:
res = predict(detr, img_path)
... | 092adb3e8ff4c0aca4a313c85865cada4481ad2a | 48,438 |
def get_sample_info(fin):
"""
Read in information from phenotype file
Create a dictionary to store each column
"""
f = open(fin,'r')
f = f.read().split('\n')
f = map(lambda x: x.rstrip(), f)
if '' in f:
f.remove('')
header = f[0].split('\t') # list
c = f[1:]
# Check... | 707dab056b36ffe4a77bf64d6a78081a59bc5a8b | 48,439 |
def parseVarMap(text):
"""Parse a string of the form [ namelist, slicelist ]"""
n = 0
m = _ListStart.match(text)
if m is None:
raise CDMSError("Parsing cdms_filemap near " + text[0:_NPRINT])
result = []
n += m.end()
s, nconsume = parselist(text[n:], parseName)
result.append(s)
... | fe8e1ae02d748b0ac992727755368b3764a12e47 | 48,440 |
import typing
def pins_to_sessions(
tsm: SMContext,
pins: typing.List[str],
sites: typing.List[int] = [],
fill_pin_site_info=True,
):
"""
get the sessions for the selected pins
Args:
tsm (SMContext): tsm context for nidcpower
pins (typing.List[str]): desired pins for which... | 500ac4ca729194e7d60ffaa703c527dfc8ca1c01 | 48,441 |
def get_V_hs_min(V_vent_g_i):
"""(39)
Args:
V_vent_g_i: 暖冷房区画iの全般換気量(m3/h)
Returns:
熱源機の最低風量(m3/h)
"""
return np.sum(V_vent_g_i[:5], axis=0) | 36dfc56b74d69de3b3c6dbf55383b2579dc00eeb | 48,442 |
def _warn(warn_message, *args, **kwargs):
"""
Inputs: warn_message- the warning message
Used to override "warnings.formatwarning" to output only the warning
message.
"""
return f'{warn_message}\n\n' | cf88c86af6492142c6f3d364f8cdf1f5cb39da1d | 48,444 |
def rotate_half(x):
"""Helper that splits a tensor at last dim into half and rotate it."""
x1, x2 = jnp.split(x, 2, axis=-1)
x = jnp.concatenate([-x2, x1], axis=-1)
return x | 58478e8875dba60a6aba7da42c4c3cf8f401a3f7 | 48,445 |
def Mag(*argv):
"""Return the magnitude of one or more vectors
This method computes the vector magnitude of the Numpy arrays in
*args*. Each array in *args* must have the same number of dimensions.
The arrays may be a mixture of staggered and unstaggered arrays. I.e.
for any axis the dimension le... | cdb5b1f492c5456f7bb02fe39d509ad3f881c74c | 48,446 |
def sort_map(map):
"""
resume = {}
sort = []
for i in range(len(map)):
for j in range(len(map[i])):
resume[(i, j)] = map[i][j]
srtd = [k for k in sorted(resume.values())]
for e in srtd:
sort.append(list(list(resume.keys())[list(resume.values()).index(e)]))
sr... | fdb60775f264437a7fed632ce7261029544a3be3 | 48,448 |
def encode2str(key=JWT_SECRET_KEY, algorithm="HS256", headers=None, json_encoder=None, **kwargs) -> str:
"""
生成json web token
:param key: 签名密钥
:param headers: token头信息
:param json_encoder:
:param kwargs:
:return:
"""
return encode(key=key, algorithm=algorithm, headers=headers, json_... | ad76064b78cdc9e2952ccc25ac44e94bc65b5564 | 48,449 |
def parallel_preprocess(
input_data, preprocess_pipeline, word_tokenize=None, num_pool=-1
):
"""
Process data in parallel using multiple CPUs.
Args:
input_data (list): List if input strings to process.
preprocess_pipeline (list): List of functions to apply on the input data.
word... | 97ad5dfc5d9ecb304d16bc21fd16214550679284 | 48,450 |
def get_selection_value(source_obj, field, value):
"""Get the string of a selection field using
fields_get method to get the string
@param source_obj: Model that contains the field
@type source_obj: RecordSet
@param field: Database name of the field
@type field: str or unicode
@param value:... | 952966e150900ddcf0afd838bf357b0b3054d047 | 48,451 |
import scipy
import time
def visualize6(M, name, nozero=False, k=2., useall=False, lim=1e-2, conc='c_w_l',W=46,color='crimson'):
""" visualize variation in the the profile shape"""
if useall:
val, c_w_l, idx = conditionVal2(name=name, nozero=nozero, conc=conc)
else:
val, c_w_l, idx = cond... | 0507e5c8c4f8632ac42f11bc468da6e61a8ee51a | 48,453 |
def max_key(dict):
""" Returns the maximum key in an integer-keyed dictionary.
Args:
dict (dict): The integer-keyed dictionary.
Returns:
int: The maximum key.
"""
output = 0
for key, value in dict.items():
output = max(output, int(key))
return output | 059a26fa690aaca2df2b0a7e251c206aa5e7276b | 48,454 |
def terminal_path_lengths(neurite):
"""Get the path lengths to each terminal point."""
return _map_sections(sf.section_path_length, neurite, Section.ileaf) | c34bb84d15d320aab7d836d5a83f2f46e39f57e1 | 48,455 |
def seperator(digits):
"""Seperate thousands into list container. e.g ['1', '000'] for 1000."""
strdigits = str(digits)
sep = []
while len(strdigits) > 3:
sep.insert(0, strdigits[-3: len(strdigits)])
strdigits = strdigits[0:-3]
# if strdigits not empty at the end of loop
if strdi... | 5a75e73521900a5a600d4bac8496811b9a3a371d | 48,456 |
def generate_analysis_list(analysis_ids, public_only=False):
"""Get general analysis information
Parameters
----------
analysis_ids : list of ints
The analysis ids to look for. Non-existing ids will be ignored
public_only : bool, optional
If true, return only public analyses. Defaul... | 51ceaa1db2e13d77b8aac838782e58307a11f07d | 48,457 |
import pickle
import torch
def all_gather_list(data, group=None, max_size=16384):
"""Gathers arbitrary data from all nodes into a list.
Similar to :func:`~torch.distributed.all_gather` but for arbitrary Python
data. Note that *data* must be picklable.
Args:
data (Any): data from the local work... | 6dc6db3a4fb484609cf2ccb2e30cf41397b5de23 | 48,459 |
def build_get_method_query_valid_request(
**kwargs # type: Any
):
# type: (...) -> HttpRequest
"""Get method with unencoded query parameter with value 'value1&q2=value2&q3=value3'.
See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request builder
into your code flow.
... | 20a9d193fcde98bf0ca96b4530c8e8490b897651 | 48,460 |
def build_adj_neighborhoods(L, K, symmetric=True):
"""Build Adjacent Neighborhoods with periodic boundary conditions"""
V = []
M = (K-1)/2
for i in range(L):
if symmetric:
start = np.floor(i-M)
else:
start = i
Vi = [int(((start + j) % L)+1) for j in range(... | 0889f44a0ba04f486166d9a2c7cd813ec8a390ad | 48,461 |
def maximum_iou(evt_gt, evt_pr, input_events, **kwargs):
"""Implements Maximum Intersection over Union from
Startsev, M., Agtzidis, I., & Dorr, M. (2019). 1D CNN with BLSTM for automated
classification of fixations, saccades, and smooth pursuits.
Behavior research methods, 51(2), 556-572.
"""
ev... | 8474a4d9bcefc6756c0ce09a87e2ba1a6cf8977d | 48,464 |
def _tpos_to_gpos(transcript, start, end=None):
"""Compute the equivalent gene position for a transcript position.
Args:
transcript: `pyensembl.Transcript` instance
start (int): position relative to the transcript
end (int): optional, second position relative to the transcript
... | e5e4d3e6a00e19e317e77fb5065ba5a77dc33579 | 48,465 |
from typing import Tuple
from typing import List
def parse_func(x: str) -> Tuple[str, List[str]]:
"""
Parses out the components of a function string.
:returns: First element is the name of the function, second argument are the function arguments.
"""
try:
name = x.split("(")[0]
arg... | 36830c95cb5238f6e7bea4f5693f28e651f0c0fb | 48,466 |
def volume_get_all(context, marker=None, limit=None, sort_keys=None,
sort_dirs=None, filters=None, offset=None):
"""Retrieves all volumes.
If no sort parameters are specified then the returned volumes are sorted
first by the 'created_at' key and then by the 'id' key in descending
ord... | fb53703e2c899bc18ed82871211cd13ce78aee60 | 48,467 |
from typing import Tuple
import re
def get_views(string : str) -> Tuple[int, int]:
"""A helper function that takes a string reresentation of total something and
daily amount of that same thing and returns both as a tuple of ints.
Parameters
------------
string : str
The string containing ... | 898d4faa89be8dcb40aede5d62fa1e4e03fb550c | 48,469 |
def set_input(interpreter, size, resize):
"""Copies a resized and properly zero-padded image to the input tensor.
Args:
interpreter: Interpreter object.
size: original image size as (width, height) tuple.
resize: a function that takes a (width, height) tuple, and returns an RGB
image resized to t... | be6b56549f1db8dce0ed81465b8e64d4e4387f02 | 48,470 |
import requests
from bs4 import BeautifulSoup
def crawl_naver_datalab():
"""
datalab.naver.com/robots.txt
(21/11/05)
User-Agent: *
Allow: /$
Allow: /index.naver
Disallow: /
"""
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, l... | 9824d3b15ab5139dbdf23c16fc40969d569224b6 | 48,471 |
def all_datasets():
"""
Return all data sets from the data set table.
:return: a list of dictionaries {name: (string), description: (string), id: (int) }
"""
#print('all_datasets: current_user:', current_user)
return db.session.query(Dataset).all() | 04365adc5250b8357dd1952d7e822292088a52ee | 48,472 |
import numpy
def min_dist(coord, surface):
"""Return minimum distance between coord and surface."""
d = surface - coord
d2 = numpy.sum(d * d, 1)
return numpy.sqrt(min(d2)) | 970da8ac11e8a3a1e087874a8ea3b0137fda5827 | 48,473 |
def get_keys_by_mode(mode):
"""Filtres `KEYS` by mode."""
return (key for key in KEYS if mode in key.modes) | 521d18aa1cf478628362ca596a923262f2c18b57 | 48,474 |
def bytes2np(bytesarray):
"""
bytes two numpy->array
:param bytesarray:
:return:
"""
nparr = np.frombuffer(bytesarray, np.uint8)
img_np = cv2.imdecode(nparr, cv2.IMREAD_COLOR) # cv2.IMREAD_COLOR in OpenCV 3.1
return img_np | b5dac7a661bc776fccd962817edb7b9eee843081 | 48,475 |
def cohort_membership(cohort_id):
"""
If full_detail flag is set to 'true', it returns a json with
a list of wikiusers grouped by username.
Otherwise, it renders the html with basic cohort information.
"""
session = db.get_session()
try:
cohort = g.cohort_service.get_for_display(
... | c5c5d9b4a1508e75156b8bb10bbf8668fc879505 | 48,476 |
def quote_identifier(dialect: Dialect, name: str) -> str:
"""
Add quotes around an identifier (e.g. a table or column name), and escape special characters in the name.
Note that the result of this function is not always a valid column name and/or table name. e.g. The
following string can be quoted by t... | c9a5791944c60cf6fe71451753331314830e5114 | 48,477 |
import ast
def mesh_update_attributes(mesh):
"""Update the attributes of a mesh.
Parameters
----------
mesh : :class:`compas.datastructures.Mesh`
A mesh object.
Returns
-------
bool
True if the update was successful.
False otherwise.
"""
names = sorted(me... | 08f36da20d74d3177c8cce6ef5d22e0e63f03d92 | 48,478 |
def load_data(database_filepath):
"""
Loading Data From Database.
Splitting X And Y Columns As TimeSeries Data By Calling get_rolling_data Method.
Parameters:
database_filepath (str): Filepath Where Database Is Located.
Returns:
X (DataFrame): Features
Y (DataFrame): Labe... | 74e9aadc9d3726572a72c6a96dcbbf30159f9fd1 | 48,479 |
import time
import torch
def test_exception_early_stop_asap():
"""Even the first partitions have finished to process, the partition before
the failed partition should be killed as soon as possible.
"""
class ExpectedException(Exception):
pass
class Pass(nn.Module):
def forward(sel... | 0f5326f427d582215ecb6d1a48a53891b8854087 | 48,480 |
def recover_path(shortest_path: tuple, path_to: dict, action_to: dict, time_to: dict) -> list:
"""Recover and return the path from start to goal."""
path = [time_to[shortest_path], shortest_path, action_to[shortest_path]]
previous = path_to[shortest_path]
while previous:
path.append(previous)
... | aa1a9431a30f35c48d3c54bad3d5b828bc853459 | 48,481 |
import time
def wait_timeout(proc):
"""
This function waits for a process to finish, else raises exception after timeout
"""
start = time.time()
end = start + float(sys_experiment_timeout)
interval = min(float(sys_experiment_timeout) / 1000.0, .25)
while True:
result = proc.poll()
... | 6bfba442550cec13db0f43e61c91c15ce5ba0c76 | 48,482 |
def polaritySanitizer(polarity):
"""Sanitize input polarity values.
Renames the, case-insensitive, values 'positive', 'pos', or '+' to 'positive'
and 'negative', 'neg', or '-' to 'negative'.
Errors on unrecognized polarity value.
Arguments:
polarity (str): unsanitized polarity type
""... | e328345ea48a9441f9ab323fd6a3ff5ca06f07d5 | 48,483 |
from typing import List
import socket
def get_certificate_chain(host: str, port: int) -> List[str]:
"""Connect to the host on the port and obtain certificate chain"""
func_name: str = "get_certificate_chain"
cert_chain: list = []
soc = socket(AF_INET, SOCK_STREAM, proto=0)
soc.settimeout(3)
... | 34248e5bf1bcb30815d42d2769e44b53d3b3a3f8 | 48,485 |
def evaluation_step(loss_from_logits_fn, model,
per_device_batch: dt.BatchedTrainTocopoData,
rng: jnp.ndarray):
"""An evaluation step, running on each device.
Note the use of `pmean` to combine gradients and loss across devices (and
hosts).
Args:
loss_from_logits_fn... | cf0b05a70c864bf3c0e59077e1271f806dfea7fd | 48,486 |
def read_pkg_ini(path):
"""Read and check the `flit.ini` file with data about the package.
"""
cp = _read_pkg_ini(path)
return _validate_config(cp, path) | 2f2a9cff18dd74797972f0163bf46d35aa838148 | 48,487 |
def verifyCallback(connection, x509, errnum, errdepth, ok):
"""
Check SSL certificates.
@return (bool) True when the certificates are valid, else False.
"""
if not ok:
print 'invalid cert from subject:', x509.get_subject()
return False
else:
#Certs are fine
p... | 8aff15199e8d728219cad4e2d22957f0b9f1ef50 | 48,488 |
import urllib
import mimetypes
def build_file_response(path, content_type=None):
"""
path (str) : Path to file relative to www-root folder next to your server script
content_type (str) : Mimetype; if set to None mimetype will automatically be determined
----
Return (bytes) HTTP response containing... | e3f45c079c42581d46a85374c61ed83ec77ad053 | 48,490 |
def NewSimulationRunAddDatastoreInit(builder, datastoreInit):
"""This method is deprecated. Please switch to AddDatastoreInit."""
return AddDatastoreInit(builder, datastoreInit) | cc6d53f586f6624323ca1a6613f0d31cfef5a0b5 | 48,491 |
def build_condensed_graph(G, min_epsilon, min_cluster_size, dont_merge=[]):
"""
Finds nodes in the graph that have edges weight weights above min_epsilon,
and both children have a size larger than min_cluster_size.
"""
def filter_node(n):
return G.nodes[n]['size'] > min_cluster_size
de... | 9c90e014e742102ff1f2d9c45c948afdb9d5fbae | 48,492 |
import types
from typing import Dict
import collections
def morph(doclike: types.DocLike) -> Dict[str, Dict[str, int]]:
"""
Count the number of times each value for a morphological feature appears
as a token annotation in ``doclike``.
Args:
doclike
Returns:
Mapping of morphologic... | db0426c78fe86916cb6aa821452d0862aeb3de2e | 48,493 |
import torch
import time
def validate(val_loader, model, criterion, verbose, args):
"""
验证
"""
batch_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
# top5 = AverageMeter()
recall = AverageMeter()
aver_acc = AverageMeter()
aver_loss = AverageMeter()
ave... | 77e7c1ec1171a27ea255a449f0bccb4e61eff63b | 48,494 |
def _tx_executor(contract_function):
""" modifies the contract instance interface function such that whenever a transaction is performed
it automatically waits until the transaction in included in the blockchain
(unless wait=False is specified, in the case the default the api acts as usual)
"""
... | b4844e1c754cbaade30ae879884e0a9699d154b7 | 48,495 |
import math
def L2Norm(inputList):
"""
Return the norm of the supplied list
"""
return math.sqrt(SumSquare(inputList)) | fda95b956f819e057601cb5c1ec8a4bfb8863554 | 48,497 |
import json
def parse_json_file_to_dict(path):
"""
Convert JSON file into a project-specific representation of the data
internally.
NOTE: it's not the most Pythonic or elegant code you will find. It was
written "just to work".
"""
with open(path, 'r') as json_file:
json_contents =... | 16870e556dac0c469aec3aa67d8984a86d2c5430 | 48,498 |
def hash_table_size(item, tablesize):
"""
A hashing technique that involves
1. Converting the characters in a string to a list of ordinal values
2. Get the sum of the list
3. Get the remained by doing a modulo using tablesize
item - string
tablesize
"""
ordinal_list = [ord(i)... | cf47a023c35693681485331878dfd3eb9164a7bf | 48,499 |
def get_scheduler_plugin(name):
"""Return a scheduler plugin
:param str name: The name of the scheduler plugin.
:rtype: SchedulerPlugin
"""
if _SCHEDULER_PLUGINS is None:
raise SchedulerPluginError("No scheduler plugins loaded.")
if name not in _SCHEDULER_PLUGINS:
raise Schedul... | 948f0a9215c053ea0cf5e6905dd8cfbcef4bf9f4 | 48,500 |
def ferret_custom_axes(id):
"""
Custom axis information for stats_probplot_values Ferret PyEF
"""
size = 1
for axis in ( pyferret.X_AXIS, pyferret.Y_AXIS, pyferret.Z_AXIS,
pyferret.T_AXIS, pyferret.E_AXIS, pyferret.F_AXIS ):
axis_info = pyferret.get_axis_info(id, pyferret.... | 8b6624008ef5d1f3e8a5462f10fb5c4419c3d58c | 48,501 |
def get_service_bus_namespace(name=None,resource_group_name=None,opts=None):
"""
Use this data source to access information about an existing ServiceBus Namespace.
:param str name: Specifies the name of the ServiceBus Namespace.
:param str resource_group_name: Specifies the name of the Resource Grou... | 656687d571e39771921a15ef445ba7689bb82b3f | 48,502 |
def get_raasi(raagam_index=None):
"""
Get raasi of the specified raagam index
@param raagam_index:ID of the raaga
@return: raasi
"""
if raagam_index==None:
raagam_index=settings.RAAGA_INDEX
return _get_raaga_attribute("Raasi",raagam_index) | 1f8b43f382ac8212526808aa459bd0e8d6461a11 | 48,504 |
def _player_id(player):
"""Lookup and return the NHL API player ID for an idividual player"""
players = _all_player_ids()
player_id = players.get(player)
if not player:
raise JockBotNHLException(f"Player Not Found {player}")
return player_id | 06a23a11dbd8e27c42107136f33853337f14b431 | 48,506 |
def mk_minus(ctx, x):
"""
mk_minus(Int_ctx ctx, Int_net x) -> Int_net
Parameters
----------
ctx: Int_ctx
x: Int_net
"""
return _api.mk_minus(ctx, x) | 0cf8ec3e9e4f17aed8685023a55dde4e9d85b402 | 48,507 |
def cred_secret_issue_proof(params, num_privs, num_pubs):
""" The proof that the mixed public / private credential issuing is correct """
G, _, _, _ = params
n = num_privs + num_pubs
# Contruct the proof
zk = ZKProof(G)
## The variables
bCx0 = zk.get(Gen, "bCx_0")
u, g, h, Cx0, pub = ... | 81ede9c55280376024364b9eb7b74fafda945786 | 48,508 |
def makePlane(w, l):
"""
4 points make a plane about the origin of size w, l
"""
return [mathutils.Vector(x) for x in [(-w/2, -l/2, 0), (-w/2, l/2, 0), (w/2, l/2, 0), (w/2, -l/2, 0)]] | 0b80b7a560d444167f78f97719807e9119b7bd9b | 48,510 |
def calculate_gravity(a: Body3D, b: Body3D):
"""
Calculate the acceleration of body A due to the force of gravity applied by body B.
"""
def gravity(pos_a, pos_b):
if pos_a < pos_b:
return 1
elif pos_a > pos_b:
return -1
else:
return 0
retu... | a31a73b3299a700763a7dd03a2ff35dbe5ac400e | 48,511 |
def _get_first_window(split_text):
"""Get first :const:`~gensim.parsing.keywords.WINDOW_SIZE` tokens from given `split_text`.
Parameters
----------
split_text : list of str
Splitted text.
Returns
-------
list of str
First :const:`~gensim.parsing.keywords.WINDOW_SIZE` tokens... | 3a556236ce9c59ba906c94f7a48f78639e55f09c | 48,512 |
def scope_access_level(app, uid, wid, scid):
"""Check the access level of the given player to the given world and
scope.
If the scope is global, the world creator has creator access, everybody
else is a visitor.
If the scope is personal, the owner has creator access. (This is actually
in the sco... | 1e1828daa9608c028651a986fca1ecc741a41b72 | 48,513 |
def member_to_badge_proximity(fileobject, time_bins_size='1min', tz='US/Eastern'):
"""Creates a member-to-badge proximity DataFrame from a proximity data file.
Parameters
----------
fileobject : file or iterable list of str
The proximity data, as an iterable of JSON strings.
time_b... | 01b730c158714e8e071c97bd0f7e3cdb2d6e407b | 48,514 |
from .. import __producer_version__
def get_producer_version():
"""
Internal helper function to return the producer version
"""
return __producer_version__ | 7f9a8df4269feba968ebc945098c33f721ee9d8e | 48,515 |
def consensus_tree() -> str:
"""Gets the consensus tree page.
:return: The consensus tree page.
"""
# Set the default options
if "analyoption" not in session:
session["analyoption"] = constants.DEFAULT_ANALYZE_OPTIONS
if "bctoption" not in session:
session["bctoption"] = constan... | 401bae7670836eb79962eeccb45a063012f2c69b | 48,516 |
def fitgaussian(data):
"""Returns (height, x, y, width_x, width_y)
the gaussian parameters of a 2D distribution found by a fit"""
xx, yy, dx, dy, angle = fastfit.d4s(data)
# For some reason x and y are exchanged
params = [np.max(data), yy, xx, dy/4, dx/4, -angle, np.min(data)]
errorfunction = la... | 4b995cec58530d57644f9f0e01f100cb89279ecd | 48,517 |
def mapped_state(state):
"""
Mapped a given state into the state as neural network input, insert trivial vehicles until vehs_num = 18
:param state: given state
:return: new state
"""
num_diff = 18 - len(state)
for i in range(num_diff):
state.append([0, 0, 0, 0, 0, 2])
return sta... | 1732565f6ef307fb67c92f2adac9c81591acf4c5 | 48,518 |
def uniform_non_negative_integers_with_sum(count, sum_):
"""Returns list of size `count` of integers >= 0, summing to `sum_`."""
positive = uniform_positive_integers_with_sum(count, sum_ + count)
return [i - 1 for i in positive] | 4c080fec7627a61c0dea16ba9aa08b9664b75c73 | 48,520 |
from .profiles import display_profile_rc
def cms_create_display_profile() -> qc3const.PyCapsule:
"""Artificial functionality. The function emulates built-in display
profile reading profile resource attached to the package.
Returns a handle to lcms built-in display profile wrapped
as a Python object.
... | 0a064603ad5a1c509fae82b219b3bf0977a3f837 | 48,521 |
import nomenclator.utilities
def mocked_has_multiple_views(mocker):
"""Return mocked 'nomenclator.utilities.has_multiple_views' function."""
return mocker.patch.object(nomenclator.utilities, "has_multiple_views", ) | be763e2c76b30a2ad82325483c3456b336f8f5f2 | 48,522 |
def pre_post_process_layer(prev_out,
out,
process_cmd,
dropout_rate=0.,
epsilon=1e-12,
name=''):
"""
Add residual connection, layer normalization and droput to the out tensor
... | 264c24e6300d8322fb24496b33d255c14337fb2f | 48,523 |
def create_renderer(window, attach_callbacks=True):
"""
This is a helper function that wraps the appropriate version of the Pyglet
renderer class, based on the version of pyglet being used.
"""
# Determine the context version
# Pyglet < 2.0 has issues with ProgrammablePipeline even when the cont... | db588ad1365464e8101cbfaff3e0fa586ce7c67b | 48,526 |
def pct(n, d, mul=100.0, **kwargs):
""" Percentage by the same logic.
You can override mul and nan if you like.
"""
return rat(n, d, mul=mul, **kwargs) | 023b765c4a76843992a87e7f055ada5c32903aad | 48,528 |
def findIKhandles():
""" Returns a list of all IK handles in the scene """
return mc.ls(type="ikHandle") | 4c56380fb80f8201d34a5d47c264cf1972e22c11 | 48,529 |
def when_all(*desired_flags):
"""
Register the decorated function to run when all of ``desired_flags`` are active.
Note that handlers whose conditions match are triggered at least once per
hook invocation.
For backwards compatibility, this decorator can pass arguments, but it is
recommended to... | 1e1b60d91924ff3ad206827611e796df52c3ccbb | 48,530 |
from typing import Optional
def ingest_dns_record_by_fqdn(
neo4j_session: neo4j.Session, update_tag: int, fqdn: str, points_to_record: str, record_label: str,
dns_node_additional_label: Optional[str] = None,
) -> None:
"""
Creates a :DNSRecord node in the graph from the given FQDN and performs DNS res... | 89949fe77f1324116fecb21a826a00ebce334fa9 | 48,531 |
def detail_url(profile_id):
"""Return profile detail url"""
return reverse('profile-detail', args=[profile_id]) | 641549d9a1f0d6183531b81ede83da455e458188 | 48,532 |
def main() -> int:
"""Main code"""
parser = _get_parser()
args = parser.parse_args()
spec_url = args.spec_url
spec_file = args.spec_file
enforce_defaults = args.enforce_defaults
schema = _load_spec(spec_file, spec_url)
validator = _create_validator(schema, enforce_defaults)
file_p... | ef92b9e2ab99f6d75903c8d50993938147e5d065 | 48,534 |
from typing import Union
from typing import Sequence
import re
def inis2dict(ini_paths: Union[str, Sequence[str]]) -> dict:
"""
Take one or more ini files and return a dict with configuration from all,
interpolating bash-style variables ${VAR} or ${VAR:-DEFAULT}.
:param ini_paths: path or paths to .i... | df31c79f09ebe1980bb270c59d58410d54773649 | 48,535 |
def run_empty_query(dataset_name: str):
"""Returns basic stats (group and row count, etc.) over the dataset. A GET request since no query is passed."""
query = {}
should_stream = bool_request_arg('stream')
return do_run_query(dataset_name, query, should_stream) | 3c78b5266326c9a360be09cf666937c741444e07 | 48,536 |
import json
def read_training_schema():
"""Responsible for reading the schema from schema_training.json
"""
params=read_params()
path = params['data_schemas']['training_schema']
with open(path) as f:
schema=json.load(f)
LengthOfDateStampInFile = schema['LengthOfDateStampInFile']
Le... | 08b0938d86a9234591723dc6b092b25b2adfd88b | 48,538 |
def propagate(w,b,X,Y):
"""
实现前向传播的代价函数及反向传播的梯度
输入:
w -- 权重,一个numpy数组,大小为(图片长度*图片高度*3,1)
b -- 偏差,一个标量
X -- 训练数据,大小为(图片长度*图片高度*3,1)
Y -- 真实“标签”向量,大小为(1,样本数量)
输出:
cost -- 逻辑回归的负对数似然代价函数
dw -- 相对于w的损失梯度,因此与w的形状相同
db -- 相对于b的损失梯度,因此与b的形状相同
"""
m = X.shape[1]
#... | 6c84f8fbff0992f29a50518d787cdcad2332d32f | 48,539 |
def extend_segments(X_conv, X_cont, peaks, min_diff_trav, cqt_window, sr, bin_thresh_segment, perc_tail):
"""
The segments surfaced by the convolution have tails that fade to 0, we want the binarizing
threshold to be lower for these tails than the rest of the array
"""
new_cont = X_cont.copy()
a... | c0a5f6f379be96a80dd28cc944c14b3689004786 | 48,540 |
def minus(a, b, rm_na=False):
""" show whats in list b which isn't in list a """
if rm_na:
a=rm_na(a)
b=rm_na(b)
s = set(b)
return [x for x in a if x not in b]
#return list(set(a).difference(set(b))) | 3c2074872f623b4e837005ab6407bd24ab2b164c | 48,541 |
def moveeffect_059(score: int, move: Move, user: Pokemon, target: Pokemon, battle: AbstractBattle) -> int:
"""
Move Effect Name: Averages the user's and target's Defense/Special Defense.
"""
adef = user.base_stats.get("def", 0)
aspd = user.base_stats.get("spd", 0)
odef = target.base_stats.get(... | 121417b863b0e0dd6f6ef0fe5c43a951828ddd17 | 48,542 |
import re
def re_group(regexp, text):
"""search for regexp in text, return 1st group on match"""
m = re.search(regexp, text)
if m: return m.group(1) | 107a0cca5cf0c303ec817e84db0d5238ca00115d | 48,543 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.