content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def hist_to_density_fullspace(counts, errs, bins, totalweight):
""" Normalize histogram to a unit integral density function
over total sum of event weights (not just the visible histogram range mass)
"""
norm = binwidth(bins) * totalweight
return counts/norm, errs/norm | 3b53b108326bd28f6649eabdc83238e92d4df856 | 3,622,900 |
def epochPoints(abf):
"""Return a list of time points where each epoch starts and ends."""
if abf.abfVersion["major"] == 1:
return []
position = int(abf.sweepPointCount/64)
epochPoints = [position]
for epochNumber, epochType in enumerate(abf._epochPerDacSection.nEpochType):
pointCoun... | 1eafc6a6cd7a3e68a5136ef6b92a4e7defae0648 | 3,622,901 |
from datetime import datetime
import pytz
import re
def process_comment(user, comment):
"""
Process a single comment.
* Updates metrics
* Sanitizes and extracts chunks from comment.
"""
text = Util.sanitize_text(comment.text) # Sanitize comment text.
user.corpus += text.lower() # Add ... | d59889451373b2302afdfa0fb256f1952a015be1 | 3,622,902 |
def attention_lm_moe_prepare_decoder(targets, hparams):
"""Prepare one shard of the model for the decoder.
Args:
targets: a Tensor.
hparams: run hyperparameters
Returns:
decoder_input: a Tensor, bottom of decoder stack
decoder_self_attention_bias: a Tensor, containing large negative values
t... | 598a7b3b03a596478fd7c30b1d7b23a47e1fc1d6 | 3,622,903 |
import math
def lat_meters(lat: float) -> float:
"""
Transform latitude degree to meters.
Parameters
----------
lat : float
This represent latitude value.
Returns
-------
float
Represents the corresponding latitude value in meters.
Examples
--------
Latit... | c31025552778b0039079d33e134e0b19077b83d4 | 3,622,904 |
def make_rpc_report(repo_dir, old_commit, new_commit,
args):
"""Create initial RST report header for OpenStack-Ansible."""
# Do we have a valid commit range?
# NOTE:
# An exception is thrown by osa_differ if these two commits
# are the the same, but it is sometimes necessary to ... | cc7900f21e6e80dc7da2ee0063032c51579eafc5 | 3,622,905 |
def generic_blockvisibility_workflow(visfunction, vis_list, additive=True, *args, **kwargs):
""" Definition of interface for create_generic_blockvisibility_graph_visfunction.
:func visfunction: Function to be applied
:param vis_list: List of vis_graphs
:param additive: Add to existing visibility? (True... | 62364879a081cc39289dada0c60f839e9082ca99 | 3,622,906 |
import re
def year_parse(s):
"""Parses a year from a string."""
regex = r"((?:19|20)\d{2})(?:$|[-/]\d{2}[-/]\d{2})"
try:
year = int(re.findall(regex, ustr(s))[0])
except IndexError:
year = None
return year | b4070f3842cb4d9d68f5b69d31a8088e2add5e38 | 3,622,907 |
def recompute_etas_P(D, dataloader):
"""Recomputes etas integrating dD/dx over P
"""
etas = 0
n_samples = 0
for data in dataloader:
_, _, Ep_grad2 = compute_objective_terms(data, D, need_penalty_terms=True)
# Only 1 term, i.e. integrate over P ((P+Q)/2 would work also)
etas +... | a33724c569e0843c6b646b39a3ffd031b4fed734 | 3,622,908 |
def parse(fp, encoding='utf8'):
"""
Read PSD file from file-like object.
:rtype: ParseResult
Example::
from psd_tools.reader.reader import parse
with open('/path/to/input.psd', 'rb') as fp:
result = parse(fp)
"""
header = psd_tools.reader.header.read(fp)
retu... | 063dcbb6be0d3fc085898fd1db353ac1f91dfeb9 | 3,622,909 |
def median(x):
"""返回数据 x 的中位数"""
n = len(x)
sorted_x = sorted(x)
midpoint = n // 2
if n % 2 == 0:
# 如果是奇数,返回中间值
return sorted_x[midpoint]
else:
# 如果是偶数,返回中间两个值的均值
lo = midpoint - 1
hi = midpoint
return (sorted_x[lo] + sorted_x[hi]) / 2 | f44d593f38ec14418d72513a68b4b8e2921afa5c | 3,622,910 |
def lost_to_gaia(gaia_ids):
"""Find villagers lost to specified gaia object types."""
query = """
select units.match_id, units.initial_player_number as number, units.destroyed::interval(0) as timestamp
from object_instances as gaia join object_instances as units on units.destroyed_by_instance_id... | 5c0dcba0c9852ce4a915a38a8b0fd24532479d16 | 3,622,911 |
def getFilteredLexicon(lexicondict, allwords):
""" Returns a lexicon with just the necessary words.
Assumes all wanted keys exist in the given lexicon """
return { word: lexicondict[word] for word in allwords } | db3c58b71df848ef5b1d49ebdd4670a552481c64 | 3,622,912 |
def post(item):
""" blog item """
name = item.split(".")[0] # No extension
return render_template(
"post.html",
html_tab_title=f"Villoro - {item}".replace(".html", ""),
**u.get_content()["blog"][name],
) | 298858dc75fb674c8ffa000dc0f22910bd430f14 | 3,622,913 |
def relu(x, name=None):
"""
relu activation.
.. math::
out = max(x, 0)
Parameters:
x (Tensor): The input Tensor with data type float32, float64.
name (str, optional): Name for the operation (optional, default is None).
For more information, please refer to :ref:`ap... | 119b51f4684018c0a1a7a9c0ea687fd1b5a34779 | 3,622,914 |
import unittest
def filter_suite(condition, suite):
"""Return tests for which ``condition`` is True in ``suite``.
:param condition: A callable receiving a test and returning True if the
test should be kept.
:param suite: A test suite that can be iterated. It contains either tests
or suit... | 9131d49d3f87a117d2b9625d521e932db2666860 | 3,622,915 |
def build_loss_fun():
"""Build the loss function."""
return get_loss_fun()() | d7b193191fa947c32729e7f396469e681d3f4e57 | 3,622,916 |
def deleteAccident(id=None, object=None):
""" delete the photos then delete the Accident
perm : object = the Accident object"""
if id:
accident = Accident.query.get(id)
elif object:
accident = object
if not accident:
return False
# delete the photos
deletePhoto(accident)
# delete the person
db.sessi... | f49d37b03ec26614934d649eb1a1f5dbd2320d82 | 3,622,917 |
def perms_canonical_labels(p, e=None):
"""
Relabel a list with a common conjugation such that two conjugated
lists are relabeled the same way.
INPUT:
- ``p`` is a list of at least 2 permutations
- ``e`` is None or a list of integer in the domain of the
permutations. If provided, then th... | 03e3450469239de160b0b596e9da7347ca2713a1 | 3,622,918 |
def trotterization(hamiltonian, time, trotter_order):
"""
Uses first order Trotter-Suzuki decomposition:
exp(iHt) = (exp(ih_1 t)exp(ih_2 t)exp(ih_n t))^N + O(t*delta_t),
where H = h_1 * h_2 * ... * h_n, delta_t is t/N
:param hamiltonian: is the Hamiltonian (H in the formula)
:param time: is... | 10041795dd82f5fea813870d9d7beb468e96c86c | 3,622,919 |
from typing import List
from typing import Tuple
import os
def text(img: Image, *, threshold: float = 0.8) -> Text:
"""Regcognize text line, background color should be black.
Args:
img (Image): Preprocessed text line.
Returns:
Text: Text content
"""
ret = ""
w, h = img.width... | acbf929f7ff1398f4f9ffe5fb7326a13c258e427 | 3,622,920 |
import torch
def collate_fn(batch):
"""Creates mini-batch tensors from the list of tuples (images,
triplets_local_indexes, triplets_global_indexes).
triplets_local_indexes are the indexes referring to each triplet within images.
triplets_global_indexes are the global indexes of each image... | c7267579e6e7f4fa54cca951b5cad15e4ce5283a | 3,622,921 |
def bit_size_decorator (bs) :
"""Return a decorator for `dusort`-ing by bit-size `bs`.
Integral byte sizes compare before sub-byte sizes, even sizes compare
before odd sizes, larger values compare before smaller values.
"""
return - byte_alignment ((bs + 4) >> 3), - bs | e8e3e1df1ea7aba24c6ecbff210c65b45c31696c | 3,622,922 |
import os
from sys import path
def get_unused_filename(existing_files, filename):
"""Provides filename similar to given, not in the given list.
If filename is /path/to/file.ext, then either it is returned unchanged if it
is not found in existing_files, or a new path is returned looking like
/path/to/file13.e... | 161a3773368870c6a7cf6b0d22d90f60b628ec41 | 3,622,923 |
def wavelength2rgb(wavelength: float, gamma: float = 0.8) -> tuple[float, float, float]:
"""
http://www.noah.org/wiki/Wavelength_to_RGB_in_Python
This converts a given wavelength into an approximate RGB value.
The given wavelength is in nanometers.
The range of wavelength is 380 nm through 750 nm.
... | 37317a5235bb3450ebf991439a7ca5ed40ede062 | 3,622,924 |
def bytes_to_long(in_bytes):
"""Converts a byte string into a long"""
hexstr = ''.join(["%0.2x" % ord(byte) for byte in in_bytes])
return int(hexstr, 16) | 89d82a72226457c3a1ac1438cab1071d3cbcd62d | 3,622,925 |
import logging
def addfile_handler(logger, filename=FILE_NAME, level=LOG_LEVEL, write_headers=False):
"""
Add a file handler to the input.
Parameters
----------
logger : logging.Logger or logging.Logger
Logger where to add the file handler.
filename : str, optional
Name of the... | b097f8dd29f4d888481c60489023591cc1dc852b | 3,622,926 |
import os
def equalization(estimator, dir_path):
"""Reads equalization FIR filter or CSV settings
Args:
estimator: ImpulseResponseEstimator
dir_path: Path to directory
Returns:
- Left side FIR as Numpy array or FrequencyResponse or None
- Right side FIR as Numpy array or ... | f759944d0fe61765bfdd88ac94e6756bd57969b4 | 3,622,927 |
def func():
"""Return a new matrix of given shape and type, without initializing entries.
Parameters
----------
shape : int or tuple of int
Shape of the empty matrix.
dtype : data-type, optional
Desired output data-type.
order : {'C', 'F'}, optional
Whether to store multi... | c48914045c296b25fbfef0f1e409b7bc40b1a677 | 3,622,928 |
def gcp_connect(module, provider, get_driver, user_agent_product, user_agent_version):
"""Return a Google libcloud driver connection."""
if not HAS_LIBCLOUD_BASE:
module.fail_json(msg='libcloud must be installed to use this module')
creds = _get_gcp_credentials(module,
... | da9118fbc52f2d712e85d8218100f8f74e8e72ad | 3,622,929 |
def create_c1_opt(optimizer_config, exp):
"""
Create an object for C1 optimal control.
Parameters
----------
optimizer_config : str
File path to a hjson file containing the C1 configuration.
lindblad : boolean
Include lindbladian dynamics.
Returns
-------
C1
... | e073f3f27dedb122a77baccd34725ec45faaae7a | 3,622,930 |
def build_datasets(df, patients_train, patients_val, print_stats=True, normalize=True):
"""
Build PyTorch datasets based on a data table and a patient-wise train-test split.
Args:
df (pandas dataframe): The data table from ADNI.
patients_train (iterable of strings): The patients to include ... | d52e4274d00a3c29a0fe35d72a3dd1d7cc6257d9 | 3,622,931 |
def choose_stance(info: GameInfo, my_car: Car, team, last_sent):
""" High level assignment of "stances"
Upon entering a stance, each Marujo is able to decide a few things to do
"""
ball = info.ball
teammates = info.get_teammates(my_car)
my_team = [my_car] + teammates
their_goal = ground(... | a4f131811916266172d89c3363e1727c40bb8d34 | 3,622,932 |
def javadoc(metadata, indent = 4):
"""
Returns a function to format a markdown syntax text block as a
javadoc comment section, given a set of metadata
Args:
metadata: A Metadata instance, representing the top-level root
of the metadata for cross-referencing
indent: baseline level of indentation f... | 2c05afa2bc20f622d2aedd60d4fc0ba4abd13725 | 3,622,933 |
import math
def deg2tilecoord(lat_deg, lon_deg, zoom):
"""
Convert latitude,longitude coordinates in degrees into tile coordinates for
given zoom.
"""
try:
lat_rad = math.radians(lat_deg)
n = 2.0 ** zoom
xtile = (lon_deg + 180.0) / 360.0 * n
ytile = (1.0 - math.log(... | 2328cba962f958dada14a559492bbf4c908e4718 | 3,622,934 |
import os
import sys
def mode_generate_algo_symlinks(args):
"""
Print commmands to create symlinks for hashfile for every known algorithm
:return:
"""
current = os.path.realpath(sys.argv[0])
bindir = os.path.dirname(current)
for algo in AVAILABLE_ALGORITHMS:
print('ln -s %s %s' % (... | af6c95c4dea9cad8a555217a6184954ea9f068ad | 3,622,935 |
def clean_data(row: dict) -> dict:
"""
Function to clean film permit row.
"""
eventid = row['eventid']
addresses = _split_addresses(row['parkingheld'])
addresses = [
_get_intersections(address) for address in addresses
]
startdate = _clean_datetime(row['startdatetime'])
endd... | e63e47f0795c4c1b3ec3df59d289e1b8e1f6d16a | 3,622,936 |
def project_featurestore():
"""
Gets the project's featurestore name (project_featurestore)
Returns:
the project's featurestore name
"""
project_name = hdfs.project_name()
featurestore_name = project_name.lower() + constants.FEATURE_STORE.FEATURESTORE_SUFFIX
return featurestore_nam... | f1669739f6ac5e443e6cf941122cb5c4263feb2c | 3,622,937 |
def find():
"""
List all busses and returns a list of baseboards detected
"""
l = []
try:
for b in usb.core.find(find_all=True, idVendor=FISCHER_LT_VENDOR, idProduct=FISCHER_LT_PRODUCT):
l.append(usb_device(b))
except:
pass
return l | 46b4c6acb32a20f4b1ad1b90225bc90ef91f3c3a | 3,622,938 |
import functools
def debug(func):
"""Print the function signature and return value"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
args_repr = [repr(a) for a in args] # Creates a list of positional arguments, repr() returns a string for each argument
... | ac3776d3e0d791442ef11913cc4e9ec36d80eabd | 3,622,939 |
def cli(ctx, library_id, access_in="", modify_in="", add_in="", manage_in=""):
"""Set the permissions for a library. Note: it will override all security for this library even if you leave out a permission type.
Output:
General information about the library
"""
return ctx.gi.libraries.set_library_permi... | 833f828b5405b29d577a8859da8a895791da22bc | 3,622,940 |
def type_encoding_table(tblname, arr):
"""Table of strings of all instructions."""
return string_table(tblname, (x[1] for x in arr)) | a9cdbdfd03e1a09269236f624c9aaa637885a615 | 3,622,941 |
def controller_unlock_foreign_drives(handle, controller_type,
controller_slot, security_key,
server_id=1):
"""
Unlocks on the given controller, drives encrypted on another controller.
Args:
handle (ImcHandle)
controll... | ad71c17d0f16608729e042edea900ed40e91a0b5 | 3,622,942 |
def create(i):
"""
Input: {
data_uoa - virtual environment name
(force_detect) - if 'yes' force to detect installed python again
(template) - if !='', use scripts from this venv.template entry
at the end of venv creation.
... | 0b125919f2e7fa079f2bce120a089e334de84818 | 3,622,943 |
def _item_to_zone(iterator, resource):
"""Convert a JSON managed zone to the native object.
:type iterator: :class:`~google.cloud.iterator.Iterator`
:param iterator: The iterator that has retrieved the item.
:type resource: dict
:param resource: An item to be converted to a managed zone.
:rty... | 97c8b6cc928239a1da33ef6cfa93b214cf025a77 | 3,622,944 |
def get_sklearn_primitives_names():
"""Helper to return names of all sklearn primitives."""
return [x for x in get_primitive_names() if ".SKlearn" in x] | afc446098c2e95f5c764d1038ac45a13ea219c0a | 3,622,945 |
def get_users():
"""Retrieve information about users"""
return "get users" | 40e2c1e8046beaa6d1b6f7875c2a3e3f7bad8e69 | 3,622,946 |
import grp
def import_sam_group(samldb, sid, gid, sid_name_use, nt_name, comment, domaindn):
"""Upgrade a SAM group.
:param samldb: SAM database.
:param gid: Group GID
:param sid_name_use: SID name use
:param nt_name: NT Group Name
:param comment: NT Group Comment
:param domaindn: Dom... | 05c005c01131684bad78fd45af0b82d4b1b2fedc | 3,622,947 |
import platform
import scipy
def version(silent=False):
"""NeuroKit2's version.
This function is a helper to retrieve the version of the package.
Examples
---------
>>> import neurokit2 as nk
>>>
>>> nk.version()
"""
if silent is False:
print(
"- OS: " + plat... | c03044b457096fd60e9f58196bbb7ab8e0fb74fb | 3,622,948 |
from typing import Any
def _str_to_type(content: str) -> Any:
"""Get skl2onnx type by string.
This is used to parse model defintion to skl2onnx I/O
Parameters
----------
content: str
The key representation of type.
Returns
----------
Any:
The type of the string key.
... | 05f166afd4543270fe6c38dcfb1bfb9da5c30846 | 3,622,949 |
def parse_tls_extension(data):
"""
This parses one extension from the given data (which may contain
multiple extension records).
:returns: parsed object along with unparsed data
:rtype: 2-element tuple containing a `py:TlsExtension` object and the
remaining data which has not yet been parsed
"""
t = data[0:2]... | 3eb297938cb3382334bb7087541f14766d5c6e39 | 3,622,950 |
def get_postgres_curie_prefix(curie):
"""The representation in postgres moves things to lowercase, and replaces . with _"""
if ':' not in curie:
raise ValueError(f'Curies ought to contain a colon: {curie}')
prefix = curie.lower().split(':')
prefix = '_'.join(prefix[0].split('.'))
return pref... | 314d59205fffd7e3dcdfb3a5ca7a81a12baffa76 | 3,622,951 |
def extract_svc2_features(trace):
"""
Extract all of the features for the svc model in the [svc.py](../attacks/svc.py) file.
@param trace is a trace of loading a web page in the following format `[(time, incoming)]`
where outgoing is 1 is incoming and -1
"""
features = []
get_packet_st... | 548c7f7eded2b9ce9d5f1dc9f8c6ddfa96cc02df | 3,622,952 |
import json
def parse_stations(html):
"""
Strips JS code, loads JSON
"""
html = html.replace('SLs.sls=', '').replace(';SLs.showSuggestion();', '')
html = json.loads(html)
return html['suggestions'] | f9fb64d21c0b206b4c034e0f8a5c560eccb9b9e4 | 3,622,953 |
def read_template(sitename, docname):
"""get the source of a specific template"""
# moet eigenlijk met read_data maar dan moet ik die eerst geschikt maken
with (WEBROOT / sitename / '.templates' / docname).open() as f_in:
data = ''.join(f_in.readlines()).replace('\r\n', '\n')
return data | eca5d8d3e10a9e32adc0b6e5de1cae95ae65faed | 3,622,954 |
import os
def _load_dataset():
"""Load data and tidy it a bit"""
fnirs_data_folder = mne.datasets.fnirs_motor.data_path()
fnirs_raw_dir = os.path.join(fnirs_data_folder, 'Participant-1')
raw_intensity = mne.io.read_raw_nirx(fnirs_raw_dir,
verbose=True).load_dat... | 3f9988da4107cc391651436a6640c0efe8ba95a2 | 3,622,955 |
def boxplot(
data,
order=None,
colors=None,
at=None,
ax=None,
showfliers=False,
capprops=dict(linewidth=0),
boxprops=dict(linewidth=1, linestyle='-'),
medianprops=dict(linewidth=2, color='k'),
whiskerprops=dict(linewidth=1, linestyle='-'),
**box_args
):
"""Boxplot.
... | 8a23a9ac1277ae6e21cf70e660e26be4837b6d91 | 3,622,956 |
def peer(socket_path=None):
"""
>>> p.peer()
>>> try:
>>> p.startup()
>>> # do something with p
>>> finally:
>>> p.shutdown()
or
>>> with peer() as p:
>>> # do something with p
>>>
"""
if socket_path not in _instances:
_instances[socket_path] = UBusPeer(socket_path)
return _instances[s... | aa74c08623955ae4e298df318364ce030e100ad3 | 3,622,957 |
import os
def train_images(size,num,learning_rate,layers):
"""
Trains the neural net for num batches of size number of images in each
"""
count = 0
os.chdir('..')
root = os.getcwd()
answer_array = read_answers()
average_error = 0
global batches
global network
if network is ... | 27a3d82e6d7c3d44e3791667179fc0a6b9787156 | 3,622,958 |
def actors(request):
"""
Return list of actors for datalist in app.js.
View isn't rendered; only used to return json to app.js.
"""
search_for = request.GET.get('name', default='').lower()
LIMIT = 20
actor_list = []
actors = Name.objects.filter(
Q(lowercase_name__startswith=sea... | f82289521581f020b64c2d8ca58a6b7d4c766cc3 | 3,622,959 |
def get_opt_d(series, ds=None, lag=1, thres=1e-5, max_size=10000,
p_thres=1e-2, autolag=None, verbose=1, **kwargs):
"""Find minimum value of degree of stationary differntial
Args:
series (pd.Series)
ds (array-like, optional): Defaults to np.linspace(0, 1, 100)\
Search ... | 4316dfc00f35b79167792a6603cad9857c633c64 | 3,622,960 |
def agentPortrayal(agent):
"""
Función que define como se visualizarán los agentes en pantalla
Parámetros:
agent - agente(s) que se visualizarán
Retorno:
portrayal - diccionario con las especificaciones de como se visualizarán los agentes
"""
portrayal = {
"Filled": "true",
... | 9d496c921808da8d78230ee40e95ef41a8ec2e7d | 3,622,961 |
def transform_image_batch(image_batch, input_meta_type, output_meta_type):
"""."""
output_batch = np.empty(image_batch.shape, dtype=output_meta_type.dtype)
for i in range(len(image_batch)):
image_with_meta = add_meta_to_image(image_batch[i], meta_type=input_meta_type)
output_batch[i] = trans... | e1a8b4a870db5b8cd6befb74e466f21889c60cac | 3,622,962 |
import json
def json_to_str(json_obj):
"""JSONをstr型へ変換"""
return json.dumps(json_obj, separators=(",", ":"), ensure_ascii=False) | 1ef38962b264991287f5b468489b20bd85be30ff | 3,622,963 |
def get_color(orig_label=None,
gt_label=None,
target_label=None,
adv_label=None,
targeted_attack=False):
"""Get color according to different possible correctness combinations."""
if ((gt_label is None or orig_label == gt_label) and
(adv_label is None or ... | 8a05dde4c60582bc2559f182423e795d2ecc1c1d | 3,622,964 |
import click
def __get_params(ctx):
"""
Get parameters from config file.
:param click.core.Context ctx: Context object of click.
:return: parameters
:rtype LogParam
"""
# load parameters from ini file
p = params.LogParam()
ret = p.read_ini()
if not ret:
click.echo('ログ取得... | 7e54402371a8718800eb91d62d56871b14ede8bf | 3,622,965 |
from typing import Dict
from typing import Optional
from typing import List
def _create_sub_keys(
spec: config_pb2.MetricsSpec
) -> Dict[Optional[metric_types.AggregationType],
List[Optional[metric_types.SubKey]]]:
"""Creates sub keys per aggregation type."""
result = {}
if spec.HasField('binarize... | c1770f80769d131e1043efd51ab6b56b7081831e | 3,622,966 |
import binascii
def int2bytes(integer_number: int) -> bytes:
"""整数还原为原始的二进制字节流, 默认方式: 大端, 和struct功能一致
还原方式从高位按位截取
"""
hex_str = int2hex(integer_number)
if len(hex_str) % 2 != 0:
hex_str = '0%s' % hex_str
return binascii.a2b_hex(hex_str) | 154163c4be8e0d7d3afda534687e6a043aade651 | 3,622,967 |
def get_user(request):
"""
Returns the user model instance associated with the given request session.
If no user is retrieved an instance of `VerbaAnonymousUser` is returned.
"""
user = None
try:
user_id = request.session[SESSION_KEY]
token = request.session[AUTH_TOKEN_SESSION_KE... | f55ddf9ee0c7d75bd8c9dd1f70273b757114944c | 3,622,968 |
def set_mode():
""" Select the game mode """
# This is an error checking version of reading user input
# This will be explained in class - pay attention!!
# Understanding try/except cases is important for
# verifying user input
# handle game crashing
try:
app.write("Please select a s... | 7e3ac1eb7fdeefe1e0df2fc06fab1290309cd166 | 3,622,969 |
def get_comment(pk):
"""
This method returns a comment by its id.
"""
try:
return Comment.objects.get(pk=pk)
except Comment.DoesNotExist:
raise NotFound({"error": "Comment not found."}) | 68378741ea7d2df442998ca75502683cfa2a3e77 | 3,622,970 |
def inverse_multi_quadratic_rbf(r, kappa):
"""
Computes the Inverse-Multi-Quadratic Radial Basis Function between two points with distance `r`.
Parameters
----------
r : float
Distance between point `x1` and `x2`.
kappa : float
Shape parameter.
Returns
-------
phi :... | 3c556be2ab0507fbfbd005ddbea7ae462b78663c | 3,622,971 |
def clean_list(dirtylist):
"""Takes a list of algorithm names as the user put them in.
Turns abbreviations in to their non-abbreviated form.
Returns a list of the corresponding encoders or encrypters in the same
order as given in the input list.
Returns an empty list if any of the input... | 0aea1b2549818a4f236299ad1ea4d1769c15023d | 3,622,972 |
from typing import Optional
from pathlib import Path
import os
import wget
import zipfile
def _download_RegNetwork(
root_dir: Optional[Path] = None, network_type: str = "human"
) -> str:
"""
Downloads RegNetwork regulatory interactions to the root directory. Returns the filepath.
:param root_dir: Pat... | baeb112d09614871d73e1e3af26c58502443e291 | 3,622,973 |
import os
import logging
import torch
import io
import PIL
import json
def search_phase(args, base_dir, run_id):
"""Performs NAS.
Code is mostly copied from train_search.py but modified to only work with GAEA PC-DARTS.
Best genotype is selected according to training accuracy for single-level search and ac... | e63edd334e83f994a6a3eb8a4e91ba20a3a69725 | 3,622,974 |
from datetime import datetime
def days_between(T_begin, T_end):
"""
格式如下
:param T_begin: 2018-01-01
:param T_end: 2018-01-01
:return:
"""
b = datetime.strptime(T_begin, time_format)
e = datetime.strptime(T_end, time_format)
return (e - b).days | 07542029d2231aeca43ef9ed849dc070bff4ccae | 3,622,975 |
import re
def read_cpr(path):
"""Read and parse a CPR file. Return masks, which are (id, RLE data).
Note: Python 3.6.4 docs say its XML module is not secure, se we use regexp.
"""
# Example: <Mask id="123">[12 34 56]</Mask>
mask_pattern = r'<Mask\s.*?id="(.*?)".*?>.*?\[(.*?)\].*?</Mask>'
text... | b5781607c150d0521d816c9027660e2b5e4b0fe0 | 3,622,976 |
def category_from_dict(category_dictionary: dict):
"""
The method converts a dictionary of Category to a Category object.
:param category_dict: A dictionary that contains the keys of a Category.
:type category_dict: dict
:rtype: ibmpairs.catalog.Category
:raises ... | b6913c685b4236769b08969c0d1ada6831b87ad4 | 3,622,977 |
import math
def schaffer6(phenome):
"""The bare-bones Schaffer function 6."""
sum_of_squares = phenome[0] ** 2 + phenome[1] ** 2
result = math.sin(math.sqrt(sum_of_squares)) ** 2 - 0.5
result /= (1.0 + 0.001 * sum_of_squares) ** 2
result += 0.5
return result | 80f19b28ebf4511a0670dfa622ffd3c55e8ec670 | 3,622,978 |
import os
def load_lmc_data():
""" Return LMC star formation history per unit steradian
Returns
-------
lmc_sfh : np structured array
LMC star formation history
dtype: [('region','<S10'),
('log_age','<f8'),
('sfh_z008','<f8'),
('sfh_z004... | 5d27b67d255b48b7b623c193e8bf4cd79a8d2523 | 3,622,979 |
import math
def pseudo(flight_data_df, mass, ke, kd, v0, dt=1./25, release_frame=0, units=Units.KM_PER_HOUR):
"""Return a dataframe of pseudo airspeed and angle given an input dataframe with watts and rise
Parameters
----------
flight_data_df: pandas.DataFrame
Must have frame, rise, and watts... | ce45bf3266bed1041f5c5def428529393c457e4e | 3,622,980 |
def n_7(x):
"""Max z_0.5c, z_LE, or z_TE of wing at centreline"""
# z_max(LE/TE) = z + abs(c_0/2 * tan(twist_0))
z_le_te = x[1] + np.abs(x[2] / 2 * np.tan(np.radians(x[4])))
# z_max_50% chord = z + 0.5 * t/c * c
z_50 = x[1] + 0.5 * x[3] * x[2]
# Check if diamond centre is higher than LE/TE
... | 4010c2b10b02c5a2469962c20bd491c34e5a41f8 | 3,622,981 |
from astropy.time import Time
from dateutil.parser import isoparser
def dateobs2night(dateobs):
"""
Convert DATE-OBS ISO8601 UTC string to YEARMMDD int night of KPNO sunset
"""
# use astropy to flexibily handle multiple valid ISO8601 variants
try:
mjd = Time(dateobs).mjd
except ValueEr... | 4630c213a2dcc456e286d93f626304409e584f66 | 3,622,982 |
def write_fm_rectangle(path: StrOrPath,
dx: Num,
dy: Num,
x0: Num = 0,
x1: Num = 18,
y0: Num = 1,
y1: Num = 5) -> AnyByStrDict:
"""Create a rectangular Delft3D flexible mesh grid... | 2f48a56f99c7cce24e498ad348862bef117ef42e | 3,622,983 |
def take_before_exclusive(iterable, predicate):
"""Yield items up to but excluding including the first match.
If no matching item is present, the result is empty.
Args:
iterable: An iterable series of items.
predicate: A function of one argument used to select the last item.
Returns:... | 3f62a1575541dfcd071424fca4b290f3f50cc518 | 3,622,984 |
def root_graphql_schema_query():
"""
Get the graphql schema.
Dig up the introspection query string from file, run it through graphql,
and jsonify the result.
"""
return flask.send_file(flask.current_app.schema_file) | c636882df1af171aed938a9f8e73c870098bd410 | 3,622,985 |
def write_vol(model, file_name, data_label, nsteps, file_format):
"""
Writes out the model as a 3d volume grid
Parameters
----------
model : GeologicalModel object
Geological model to export
file_name : string
Name of file that model is exported to, including path, but without t... | 44553ff9419221f17b50e98301c70089150eb1a9 | 3,622,986 |
import os
def kolibri_version():
"""
Returns the major.minor version of Kolibri if it exists
"""
with open(os.path.join(kolibri_dir, 'VERSION'), 'r') as version_file:
# p4a only likes digits and decimals
return version_file.read().strip() | 8875b1f7da6378f2c032513cfc2eb5a9345b1e33 | 3,622,987 |
import inspect
import http
def GetJSONRPCCallerIP():
"""Retrieve the IP address of the JSON RPC caller.
This is a hack that depends on the implementation details of jsonrpclib.
We know that JSON-RPC over HTTP requires a SimpleHTTPServer and
SimpleJSONRPCRequestHandler dervies from SimpleXMLRPCRequestHandler,... | c2174a1c670bc0ad8d3df67d0b1dc47865bed3cb | 3,622,988 |
import os
import uuid
import resource
import time
def _start_redis_instance(executable,
session_dir_path,
bind_address,
port,
redis_max_clients=None,
num_retries=20,
... | adac518114849432c68fe522c629b0e8f9d7d4e7 | 3,622,989 |
import sys
from datetime import datetime
def timestamp_to_datetime(timestamp):
"""
Parses the given timestamp.
The expected timestamp formats are the following:
- `2019-04-28T15:14:38+00:00`
- `2019-07-17T18:52:50.758993+00:00`
- `2019-07-17T18:52:50.758000+00:00`
... | f4dbea1313ad98f72a5a6e4e31c6bf19f5f1d692 | 3,622,990 |
from collections import namedtuple
from sys import version as sys_version
from matplotlib import __version__ as matplotlib_version
from numpy import __version__ as numpy_version
from pyproj import __version__ as pyproj_version
from shapefile import __version__ as pyshp_version
import _geoslib
from mpl_toolkits.basemap ... | 5e84cbf1b17432b856762b6d2f6dff83012b4a70 | 3,622,991 |
def build_received_request(qparams):
""""Fills the `receivedRequest` part with the request data"""
request = {
'meta': {
'requestedSchemas' : build_requested_schemas(qparams),
'apiVersion' : None,
},
# 'query': None
}
return request | 16e1f243ac5b447be2208a7a2612e590b2f81afd | 3,622,992 |
import os
def stdoutpath():
"""
Path to output logfile.
Returns
-------
stdout : str
Path to ouput file.
"""
stdoutfile=pdbid()+".stdout.log"
stdout = os.path.join(output_dir(), stdoutfile)
return stdout | eaef26a068f6aa27f944e92f48c6ac1ce23b945e | 3,622,993 |
from typing import Dict
def _read_static_tables_eia() -> Dict[str, pd.DataFrame]:
"""Build dataframes of static EIA tables for use as foreign key constraints.
There are many values specified within the data that are essentially
constant, but which we need to store for data validation purposes, for use
... | fbb49226a542db5be2a74d9b294e4193476332aa | 3,622,994 |
def build_filters(tbinfogolden):
"""
Build for each tb in tbinfo a filter
"""
filter_return = []
"""Each assembler string"""
for tb in tbinfogolden["assembler"]:
tb_filter = []
"""remove first split, as it is empty"""
split = tb.split("[ ")
"""For each line"""
... | fdbf2c0b64c9582a00acb38c8395d249dfeb6f56 | 3,622,995 |
from typing import Optional
def init_dml_stmt(
ir_stmt: irast.MutatingStmt,
*,
ctx: context.CompilerContextLevel,
parent_ctx: context.CompilerContextLevel,
) -> DMLParts:
"""Prepare the common structure of the query representing a DML stmt.
Args:
ir_stmt:
IR of the DML sta... | 122daa6c2329159b8ee00c339deec9a26edc616c | 3,622,996 |
import random
def DeriveTargetEdge(inp_edge_set):
""" the random index will be between 1 to n where n is the set cardinality
set does not support indexing
so we have to pop the edges one by one until we obtain the desired edge """
# comment - sourya
"""
rand_index = random.randint(1, len(inp_edge_set))
... | 2879bf5e17565d42f57006daf71153b92c760bab | 3,622,997 |
from typing import cast
def ca_stc_get_digest_name_by_id(slot, digest_id):
"""
Get name of digest by its ID
:param slot: slot id
:param digest_id: digest id
:return: digest name
"""
h_slot = CK_SLOT_ID(slot)
c_digest_id = CK_ULONG(digest_id)
c_name_len = CK_BYTE(CRYPTO_NAME_BUFFER... | 3c547181d04608c39a18a169490ac824fb391972 | 3,622,998 |
from pathlib import Path
def data_root_directory():
"""Get a path to the top level data directory. Checks whether you have created the local store of data at the expected
location and returns that as default if found, otherwise returns the location on the shared folder
Returns:
(pathlib Path): A ... | f687ffcf05aa74c521624467c3be7ec108de6a46 | 3,622,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.