max_stars_repo_path
stringlengths 4
245
| max_stars_repo_name
stringlengths 7
115
| max_stars_count
int64 101
368k
| id
stringlengths 2
8
| content
stringlengths 6
1.03M
|
---|---|---|---|---|
tests/conftest.py
|
natpacket/curl-impersonate
| 1,065 |
144299
|
def pytest_addoption(parser):
# Where to find curl-impersonate's binaries
parser.addoption("--install-dir", action="store", default="/usr/local")
parser.addoption("--capture-interface", action="store", default="eth0")
|
utils/queuer.py
|
anoidgit/zero
| 111 |
144339
|
<reponame>anoidgit/zero
# coding: utf-8
"""
The Queue function mainly deals with reading and preparing dataset in a multi-processing manner.
We didnot use the built-in tensorflow function Dataset because it lacks of flexibility.
The function defined below is mainly inspired by https://github.com/ixlan/machine-learning-data-pipeline.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from multiprocessing import Process, Queue
TERMINATION_TOKEN = "<DONE>"
def create_iter_from_queue(queue, term_token):
while True:
input_data_chunk = queue.get()
if input_data_chunk == term_token:
# put it back to the queue to let other processes that feed
# from the same one to know that they should also break
queue.put(term_token)
break
else:
yield input_data_chunk
def combine_reader_to_processor(reader, preprocessor):
for data_chunk in reader:
yield preprocessor(data_chunk)
class EnQueuer(object):
def __init__(self,
reader,
preprocessor,
worker_processes_num=1,
input_queue_size=5,
output_queue_size=5
):
if worker_processes_num < 0:
raise ValueError("worker_processes_num must be a "
"non-negative integer.")
self.worker_processes_number = worker_processes_num
self.preprocessor = preprocessor
self.input_queue_size = input_queue_size
self.output_queue_size = output_queue_size
self.reader = reader
# make the queue iterable
def __iter__(self):
return self._create_processed_data_chunks_gen(self.reader)
def _create_processed_data_chunks_gen(self, reader_gen):
if self.worker_processes_number == 0:
itr = self._create_single_process_gen(reader_gen)
else:
itr = self._create_multi_process_gen(reader_gen)
return itr
def _create_single_process_gen(self, data_producer):
return combine_reader_to_processor(data_producer, self.preprocessor)
def _create_multi_process_gen(self, reader_gen):
term_tokens_received = 0
output_queue = Queue(self.output_queue_size)
workers = []
if self.worker_processes_number > 1:
term_tokens_expected = self.worker_processes_number - 1
input_queue = Queue(self.input_queue_size)
reader_worker = _ParallelWorker(reader_gen, input_queue)
workers.append(reader_worker)
# adding workers that will process the data
for _ in range(self.worker_processes_number - 1):
# since data-chunks will appear in the queue, making an iterable
# object over it
queue_iter = create_iter_from_queue(input_queue,
TERMINATION_TOKEN)
data_itr = combine_reader_to_processor(queue_iter, self.preprocessor)
proc_worker = _ParallelWorker(data_chunk_iter=data_itr,
queue=output_queue)
workers.append(proc_worker)
else:
term_tokens_expected = 1
data_itr = combine_reader_to_processor(reader_gen, self.preprocessor)
proc_worker = _ParallelWorker(data_chunk_iter=data_itr,
queue=output_queue)
workers.append(proc_worker)
for pr in workers:
pr.daemon = True
pr.start()
while True:
data_chunk = output_queue.get()
if data_chunk == TERMINATION_TOKEN:
term_tokens_received += 1
# need to received all tokens in order to be sure that
# all data has been processed
if term_tokens_received == term_tokens_expected:
for pr in workers:
pr.join()
break
continue
yield data_chunk
class _ParallelWorker(Process):
"""Worker to execute data reading or processing on a separate process."""
def __init__(self, data_chunk_iter, queue):
super(_ParallelWorker, self).__init__()
self._data_chunk_iterable = data_chunk_iter
self._queue = queue
def run(self):
for data_chunk in self._data_chunk_iterable:
self._queue.put(data_chunk)
self._queue.put(TERMINATION_TOKEN)
|
tests/builtins/test_callable.py
|
akubera/batavia
| 1,256 |
144348
|
<reponame>akubera/batavia
from .. utils import TranspileTestCase, BuiltinFunctionTestCase
class CallableTests(TranspileTestCase):
pass
class BuiltinCallableFunctionTests(BuiltinFunctionTestCase, TranspileTestCase):
function = "callable"
|
evosax/restarts/simple_restart.py
|
mahi97/evosax
| 102 |
144376
|
import chex
from .restarter import RestartWrapper
from .termination import spread_criterion
class Simple_Restarter(RestartWrapper):
def __init__(
self,
base_strategy,
stop_criteria=[spread_criterion],
):
"""Simple Restart Strategy - Only reinitialize the state."""
super().__init__(base_strategy, stop_criteria)
@property
def restart_params(self) -> chex.ArrayTree:
"""Return default parameters for strategy restarting."""
re_params = {"min_num_gens": 50, "min_fitness_spread": 0.1}
return re_params
def restart_strategy(
self,
rng: chex.PRNGKey,
state: chex.ArrayTree,
params: chex.ArrayTree,
) -> chex.ArrayTree:
"""Simple restart by state initialization."""
new_state = self.base_strategy.initialize(rng, params)
return new_state
|
cloudmarker/test/test_main.py
|
TinLe/cloudmarker
| 208 |
144393
|
"""Tests for package execution."""
import importlib
import unittest
from unittest import mock
class MainTest(unittest.TestCase):
"""Tests for package execution."""
@mock.patch('sys.argv', ['cloudmarker', '-c', '-n'])
def test_main(self):
# Run cloudmarker package with only the default base
# configuration and ensure that it runs without issues.
module = importlib.import_module('cloudmarker.__main__')
self.assertEqual(type(module).__name__, 'module')
|
jobtastic/tests/test_settings.py
|
Praseetha-KR/jobtastic
| 467 |
144407
|
<reponame>Praseetha-KR/jobtastic
from __future__ import print_function
import mock
import django
from unittest import skipIf
from celery import Celery, states
from celery.backends.cache import DummyClient
from django.conf import settings
from django.test import TestCase
from jobtastic.task import JobtasticTask
from werkzeug.contrib.cache import MemcachedCache
try:
from django.core.cache import caches
except ImportError:
pass
def add(self, key, value, timeout=None):
"""
Fake atomic add method for memcache clients
"""
self.set(key, value, timeout)
return True
@skipIf(django.VERSION < (1, 7),
"Django < 1.7 doesn't support django.core.cache.caches")
class DjangoSettingsTestCase(TestCase):
def setUp(self):
# Define the class in setup so it has the same cache
# scope as the test
class ParrotTask(JobtasticTask):
"""
Just return whatever is passed in as the result.
"""
significant_kwargs = [
('result', str),
]
herd_avoidance_timeout = 0
def calculate_result(self, result, **kwargs):
return result
self.task = ParrotTask
self.kwargs = {'result': 42}
self.key = self.task._get_cache_key(**self.kwargs)
def test_sanity(self):
# The task actually runs
with self.settings(CELERY_ALWAYS_EAGER=True):
async_task = self.task.delay(result=1)
self.assertEqual(async_task.status, states.SUCCESS)
self.assertEqual(async_task.result, 1)
def test_default_django_cache(self):
with self.settings(CELERY_ALWAYS_EAGER=False):
app = Celery()
app.config_from_object(settings)
self.task.bind(app)
app.finalize()
async_task = self.task.delay(**self.kwargs)
self.assertEqual(async_task.status, states.PENDING)
self.assertTrue('herd:%s' % self.key in caches['default'])
def test_custom_django_cache(self):
with self.settings(
CELERY_ALWAYS_EAGER=False,
JOBTASTIC_CACHE='shared',
CACHES={'default':
{'BACKEND':
'django.core.cache.backends.locmem.LocMemCache',
'LOCATION': 'default'},
'shared':
{'BACKEND':
'django.core.cache.backends.locmem.LocMemCache',
'LOCATION': 'shared'}}):
app = Celery()
app.config_from_object(settings)
self.task.bind(app)
app.finalize()
async_task = self.task.delay(**self.kwargs)
self.assertEqual(async_task.status, states.PENDING)
self.assertTrue('herd:%s' % self.key in caches['shared'])
self.assertTrue('herd:%s' % self.key not in caches['default'])
@mock.patch('jobtastic.cache.CACHES', ['Werkzeug'])
@mock.patch.object(DummyClient, 'add', add, create=True)
def test_default_werkzeug_cache(self):
with self.settings(CELERY_ALWAYS_EAGER=False):
app = Celery()
app.config_from_object(settings)
self.task.bind(app)
app.finalize()
async_task = self.task.delay(**self.kwargs)
cache = MemcachedCache(app.backend.client)
self.assertEqual(async_task.status, states.PENDING)
self.assertNotEqual(cache.get('herd:%s' % self.key), None)
|
ChatBot/chatbot_search/chatbot_tfserving/indexAnnoy.py
|
yongzhuo/nlp_xiaojiang
| 1,379 |
144409
|
<reponame>yongzhuo/nlp_xiaojiang<filename>ChatBot/chatbot_search/chatbot_tfserving/indexAnnoy.py
# !/usr/bin/python
# -*- coding: utf-8 -*-
# @time : 2021/4/18 21:04
# @author : Mo
# @function: annoy search
from annoy import AnnoyIndex
import numpy as np
import os
class AnnoySearch:
def __init__(self, dim=768, n_cluster=100):
# metric可选“angular”(余弦距离)、“euclidean”(欧几里得距离)、 “ manhattan”(曼哈顿距离)或“hamming”(海明距离)
self.annoy_index = AnnoyIndex(dim, metric="angular")
self.n_cluster = n_cluster
self.dim = dim
def k_neighbors(self, vectors, k=18):
""" 搜索 """
annoy_tops = []
for v in vectors:
idx, dist = self.annoy_index.get_nns_by_vector(v, k, search_k=32*k, include_distances=True)
annoy_tops.append([dist, idx])
return annoy_tops
def fit(self, vectors):
""" annoy构建 """
for i, v in enumerate(vectors):
self.annoy_index.add_item(i, v)
self.annoy_index.build(self.n_cluster)
def save(self, path):
""" 存储 """
self.annoy_index.save(path)
def load(self, path):
""" 加载 """
self.annoy_index.load(path)
if __name__ == '__main__':
### 索引
import random
path = "model.ann"
dim = 768
vectors = [[random.gauss(0, 1) for z in range(768)] for i in range(10)]
an_model = AnnoySearch(dim, n_cluster=32) # Length of item vector that will be indexed
an_model.fit(vectors)
an_model.save(path)
tops = an_model.k_neighbors([vectors[0]], 18)
print(tops)
del an_model
### 下载, 搜索
an_model = AnnoySearch(dim, n_cluster=32)
an_model.load(path)
tops = an_model.k_neighbors([vectors[0]], 6)
print(tops)
"""
# example
from annoy import AnnoyIndex
import random
dim = 768
vectors = [[random.gauss(0, 1) for z in range(768)] for i in range(10)]
ann_model = AnnoyIndex(dim, 'angular') # Length of item vector that will be indexed
for i,v in enumerate(vectors):
ann_model.add_item(i, v)
ann_model.build(10) # 10 trees
ann_model.save("tet.ann")
del ann_model
u = AnnoyIndex(dim, "angular")
u.load('tet.ann') # super fast, will just mmap the file
v = vectors[1]
idx, dist = u.get_nns_by_vector(v, 10, search_k=50 * 10, include_distances=True)
print([idx, dist])
"""
### 备注说明: annoy索引 无法 增删会改查
|
source/paraphrase.py
|
xl8-ai/LASER
| 2,941 |
144419
|
#!/usr/bin/python
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
#
# LASER Language-Agnostic SEntence Representations
# is a toolkit to calculate multilingual sentence embeddings
# and to use them for document classification, bitext filtering
# and mining
#
# --------------------------------------------------------
#
# Python tool to search for paraphrases in FAISS index
import re
import sys
import os.path
import tempfile
import argparse
import faiss
import time
import pdb
import numpy as np
from collections import namedtuple
# get environment
assert os.environ.get('LASER'), 'Please set the enviornment variable LASER'
LASER = os.environ['LASER']
sys.path.append(LASER + '/source/lib')
from indexing import IndexLoad, IndexTextOpen, IndexTextQuery, SplitOpen, SplitAccess
from embed import SentenceEncoder, EncodeLoad, EncodeFile, EncodeTime
from text_processing import Token, BPEfastApply
SPACE_NORMALIZER = re.compile("\s+")
Batch = namedtuple('Batch', 'srcs tokens lengths')
# calculate L2 distance between [x]
# and the vectors referenced in idxs
# x should be already normalized
def IndexDistL2(X, E, D, I, thresh=1.0, dtype=np.float32, sort=True):
nb, nK = I.shape
dim = X.shape[1]
dist_l2 = np.empty((nb, nK), dtype=np.float32)
y = np.empty((1, dim), dtype=dtype)
for i in range(nb):
for k in range(nK):
if D[i, k] <= thresh:
# get embedding from disk
np.copyto(y, SplitAccess(E, I[i, k]))
faiss.normalize_L2(y)
dist_l2[i, k] = 1.0 - np.dot(X[i], y[0])
else:
# exclude sentences which already have a huge FAISS distance
# (getting embeddings from disk is very time consumming)
dist_l2[i, k] = 1.0
if sort:
# re-sort according to L2
idxs = np.argsort(dist_l2[i], axis=0)
dist_l2[i] = dist_l2[i][idxs]
I[i] = I[i][idxs]
return dist_l2, I
###############################################################################
#
# Apply an absolute threshold on the distance
#
###############################################################################
def MarginAbs(em, ofp, params, args, stats):
D, I = params.idx.search(em, args.kmax)
thresh = args.threshold_faiss
if args.embed:
D, I = IndexDistL2(em, params.E, D, I, args.threshold_faiss)
thresh = args.threshold_L2
for n in range(D.shape[0]):
prev = {} # for deduplication
for i in range(args.kmax):
txt = IndexTextQuery(params.T, params.R, I[n, i])
if (args.dedup and txt not in prev) and D[n, i] <= thresh:
prev[txt] = 1
ofp.write('{:d}\t{:7.5f}\t{}\n'
.format(stats.nbs, D[n, i], txt))
stats.nbp += 1
# display source sentece if requested
if (args.include_source == 'matches' and len(prev) > 0):
ofp.write('{:d}\t{:6.1f}\t{}\n'
.format(stats.nbs, 0.0, sentences[n].replace('@@ ', '')))
if args.include_source == 'always':
ofp.write('{:d}\t{:6.1f}\t{}\n'
.format(stats.nbs, 0.0, sentences[n].replace('@@ ', '')))
stats.nbs += 1
###############################################################################
#
# Apply an threshold on the ratio between distance and average
#
###############################################################################
def MarginRatio(em, ofp, params, args, stats):
D, I = params.idx.search(em, args.margin_k)
thresh = args.threshold
if args.embed:
D, I = IndexDistL2(em, params.E, D, I, args.threshold_faiss)
thresh = args.threshold_L2
Mean = D.mean(axis=1)
for n in range(D.shape[0]):
if D[n, 0] / Mean[n] <= args.threshold:
if args.include_source == 'matches':
ofp.write('{:d}\t{:6.1f}\t{}\n'
.format(stats.nbs, 0.0, sentences[n].replace('@@ ', '')))
txt = IndexTextQuery(params.T, params.R, I[n, 0])
ofp.write('{:d}\t{:7.5f}\t{}\n'.format(stats.nbs, D[n, 0], txt))
stats.nbp += 1
stats.nbs += 1
if args.include_source == 'always':
ofp.write('{:d}\t{:6.1f}\t{}\n'
.format(stats.nbs, 0.0, sentences[n].replace('@@ ', '')))
###############################################################################
def MarginDist(em, ofp, params, args, stats):
print('ERROR: MarginAbs not implemented')
sys.exit(1)
###############################################################################
def buffered_read(fp, buffer_size):
buffer = []
for src_str in fp:
buffer.append(src_str.strip())
if len(buffer) >= buffer_size:
yield buffer
buffer = []
if len(buffer) > 0:
yield buffer
###############################################################################
parser = argparse.ArgumentParser('LASER: paraphrase tool')
parser.add_argument('--encoder', type=str, required=True,
help='encoder to be used')
parser.add_argument('--encoding', default='utf-8',
help='Character encoding for input/output')
parser.add_argument('--token-lang', type=str, default='--',
help="Language of tokenizer ('--' for no tokenization)")
parser.add_argument('--bpe-codes', type=str, default=None, required=True,
help='BPE codes')
parser.add_argument('--buffer-size', type=int, default=100,
help='Buffer size (sentences)')
parser.add_argument('--max-tokens', type=int, default=12000,
help='Maximum number of tokens to process in a batch')
parser.add_argument('--max-sentences', type=int, default=None,
help='Maximum number of sentences to process in a batch')
parser.add_argument('--cpu', action='store_true',
help='Use CPU instead of GPU')
parser.add_argument('--index', type=str, required=True,
help='FAISS index')
parser.add_argument('--nprobe', type=int, default=128,
help='FAISS: value of nprobe')
parser.add_argument('--text', type=str, required=True,
help='File with indexed texts')
parser.add_argument(
'--dim', type=int, default=1024,
help='Dimension of specified sentence embeddings')
parser.add_argument(
'--embed', type=str, default=None,
help='Sentence embeddings, true L2 distance will be calculated when specified')
parser.add_argument('-i', '--input', type=str, required=True,
help='Input text file')
parser.add_argument('-p', '--output', type=str, default='--',
help='Output paraphrases')
parser.add_argument('--kmax', type=int, default=10,
help='Max value of distance or margin of each paraphrase')
parser.add_argument('--dedup', type=int, default=1,
help='Deduplicate list of paraphrases')
parser.add_argument('--include-source', default='never',
choices=['never', 'matches', 'always'],
help='Include source sentence in the list of paraphrases')
parser.add_argument('--margin',
choices=['absolute', 'distance', 'ratio'],
default='ratio', help='Margin function')
parser.add_argument('-T', '--threshold-margin', type=float, default=0.9,
help='Threshold on margin')
parser.add_argument('--threshold-faiss', type=float, default=0.4,
help='Threshold on FAISS distance')
parser.add_argument('--threshold-L2', type=float, default=0.2,
help='Threshold on L2 distance')
parser.add_argument('--margin-k', type=int, default=4,
help='Number of nearest neighbors for margin calculation')
parser.add_argument('--verbose', action='store_true',
help='Detailed output')
print('\nLASER: paraphrase tool')
args = parser.parse_args()
# index,
# memory mapped texts, references and word counts
# encoder
params = namedtuple('params', 'idx T R W M E enc')
# open text and reference file
params.T, params.R, params.W, params.M = IndexTextOpen(args.text)
# Open on-disk embeddings for L2 distances
if args.embed:
params.E = SplitOpen(args.embed, ['en'],
args.dim, np.float32, verbose=False)
# load FAISS index
params.idx = IndexLoad(args.index, args.nprobe)
# load sentence encoder
params.enc = EncodeLoad(args)
margin_methods = {'absolute': MarginAbs,
'distance': MarginDist,
'ratio': MarginRatio}
with tempfile.TemporaryDirectory() as tmpdir:
ifile = args.input
if args.token_lang != '--':
ifile = os.path.join(tmpdir, 'tok')
Token(args.input,
ifile,
lang=args.token_lang,
romanize=True if args.token_lang == 'el' else False,
lower_case=True, gzip=False,
verbose=args.verbose, over_write=False)
if args.bpe_codes:
bpe_file = os.path.join(tmpdir, 'bpe')
BPEfastApply(ifile,
bpe_file,
args.bpe_codes,
verbose=args.verbose, over_write=False)
ifile = bpe_file
print(' - processing (batch size is {:d})'.format(args.buffer_size))
ifp = open(ifile, 'r', encoding=args.encoding, errors='surrogateescape')
if args.output == '--':
ofp = sys.stdout
else:
ofp = open(args.output, 'w', encoding=args.encoding, errors='surrogateescape')
stats = namedtuple('stats', 'ns np')
stats.nbs = 0
stats.nbp = 0
t = time.time()
for sentences in buffered_read(ifp, args.buffer_size):
embed = params.enc.encode_sentences(sentences)
faiss.normalize_L2(embed)
# call function for selected margin method
margin_methods.get(args.margin)(embed, ofp, params, args, stats)
if stats.nbs % 1000 == 0:
print('\r - {:d} sentences {:d} paraphrases'
.format(stats.nbs, stats.nbp), end='')
ifp.close()
if args.output != '--':
ofp.close()
print('\r - {:d} sentences {:d} paraphrases'
.format(stats.nbs, stats.nbp), end='')
EncodeTime(t)
|
autoelective/client.py
|
lhydave/PKUAutoElective
| 566 |
144424
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# filename: client.py
# modified: 2019-09-09
from requests.models import Request
from requests.sessions import Session
from requests.cookies import extract_cookies_to_jar
class BaseClient(object):
default_headers = {}
default_client_timeout = 10
def __init__(self, *args, **kwargs):
if self.__class__ is __class__:
raise NotImplementedError
self._timeout = kwargs.get("timeout", self.__class__.default_client_timeout)
self._session = Session()
self._session.headers.update(self.__class__.default_headers)
@property
def user_agent(self):
return self._session.headers.get('User-Agent')
def _request(self, method, url,
params=None, data=None, headers=None, cookies=None, files=None,
auth=None, timeout=None, allow_redirects=True, proxies=None,
hooks=None, stream=None, verify=None, cert=None, json=None):
# Extended from requests/sessions.py for '_client' kwargs
req = Request(
method=method.upper(),
url=url,
headers=headers,
files=files,
data=data or {},
json=json,
params=params or {},
auth=auth,
cookies=cookies,
hooks=hooks,
)
prep = self._session.prepare_request(req)
prep._client = self # hold the reference to client
proxies = proxies or {}
settings = self._session.merge_environment_settings(
prep.url, proxies, stream, verify, cert
)
# Send the request.
send_kwargs = {
'timeout': timeout or self._timeout, # set default timeout
'allow_redirects': allow_redirects,
}
send_kwargs.update(settings)
resp = self._session.send(prep, **send_kwargs)
return resp
def _get(self, url, params=None, **kwargs):
return self._request('GET', url, params=params, **kwargs)
def _post(self, url, data=None, json=None, **kwargs):
return self._request('POST', url, data=data, json=json, **kwargs)
def set_user_agent(self, user_agent):
self._session.headers["User-Agent"] = user_agent
def persist_cookies(self, r):
"""
From requests/sessions.py, Session.send()
Session.send() 方法会首先 dispatch_hook 然后再 extract_cookies_to_jar
在该项目中,对于返回信息异常的请求,在 hooks 校验时会将错误抛出,send() 之后的处理将不会执行。
遇到的错误往往是 SystemException / TipsException ,而这些客户端认为是错误的情况,
对于服务器端来说并不是错误请求,服务器端在该次请求结束后可能会要求 Set-Cookies
但是由于 send() 在 dispatch_hook 时遇到错误而中止,导致后面的 extract_cookies_to_jar
未能调用,因此 Cookies 并未更新。下一次再请求服务器的时候,就会遇到会话过期的情况。
在这种情况下,需要在捕获错误后手动更新 cookies 以确保能够保持会话
"""
if r.history:
# If the hooks create history then we want those cookies too
for resp in r.history:
extract_cookies_to_jar(self._session.cookies, resp.request, resp.raw)
extract_cookies_to_jar(self._session.cookies, r.request, r.raw)
def clear_cookies(self):
self._session.cookies.clear()
|
042_centernet/20_tensorflow_models/openvino_load_test.py
|
IgiArdiyanto/PINTO_model_zoo
| 1,529 |
144427
|
<reponame>IgiArdiyanto/PINTO_model_zoo<gh_stars>1000+
from openvino.inference_engine import IENetwork, IECore
import cv2
import numpy as np
import pprint
ie = IECore()
vino_model_path = f'saved_model/openvino/FP16'
vino_model = 'saved_model'
net = ie.read_network(model=f'{vino_model_path}/{vino_model}.xml', weights=f'{vino_model_path}/{vino_model}.bin')
exec_net = ie.load_network(network=net, device_name='CPU', num_requests=2)
input_blob = next(iter(net.input_info))
out_blob = [o for o in net.outputs]
pprint.pprint('input_blob:')
pprint.pprint(input_blob)
pprint.pprint('out_blob:')
pprint.pprint(out_blob)
cap = cv2.VideoCapture('person.png')
ret, frame = cap.read()
frame_h, frame_w = frame.shape[:2]
width = 320
height = 320
im = cv2.resize(frame.copy(), (width, height))
im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
im = im.transpose((2, 0, 1))
im = im[np.newaxis, :, :, :]
inputs = {input_blob: im}
exec_net.requests[0].wait(-1)
exec_net.start_async(request_id=0, inputs=inputs)
if exec_net.requests[0].wait(-1) == 0:
res = [
exec_net.requests[0].output_blobs[out_blob[0]].buffer,
exec_net.requests[0].output_blobs[out_blob[1]].buffer,
exec_net.requests[0].output_blobs[out_blob[2]].buffer,
exec_net.requests[0].output_blobs[out_blob[3]].buffer,
exec_net.requests[0].output_blobs[out_blob[4]].buffer,
exec_net.requests[0].output_blobs[out_blob[5]].buffer,
]
pprint.pprint('res:')
pprint.pprint(out_blob[0])
pprint.pprint(res[0].shape)
pprint.pprint(res[0])
pprint.pprint(out_blob[1])
pprint.pprint(res[1].shape)
pprint.pprint(res[1])
pprint.pprint(out_blob[2])
pprint.pprint(res[2].shape)
pprint.pprint(res[2])
pprint.pprint(out_blob[3])
pprint.pprint(res[3].shape)
pprint.pprint(res[3])
pprint.pprint(out_blob[4])
pprint.pprint(res[4].shape)
pprint.pprint(res[4])
pprint.pprint(out_blob[5])
pprint.pprint(res[5].shape)
pprint.pprint(res[5])
person = res[5][0][0]
print('person:', person)
ymin = int(person[0] * frame_h)
xmin = int(person[1] * frame_w)
ymax = int(person[2] * frame_h)
xmax = int(person[3] * frame_w)
cv2.rectangle(frame, (xmin, ymin), (xmax, ymax), (255, 0, 0))
KEYPOINT_EDGES = [
(0, 1),
(0, 2),
(1, 3),
(2, 4),
(0, 5),
(0, 6),
(5, 7),
(7, 9),
(6, 8),
(8, 10),
(5, 6),
(5, 11),
(6, 12),
(11, 12),
(11, 13),
(13, 15),
(12, 14),
(14, 16),
]
print('res1:', res[1].shape)
bone_y = res[1][0][0][0]
bone_x = res[1][0][1][0]
print('bone_x.shape:', bone_x.shape)
print('bone_x:', bone_x)
print('bone_y.shape:', bone_y.shape)
print('bone_y:', bone_y)
for keypoint_x, keypoint_y in zip(bone_x, bone_y):
cv2.circle(
frame,
(int(keypoint_x * frame_w), int(keypoint_y * frame_h)),
2,
(0, 255, 0))
for keypoint_start, keypoint_end in KEYPOINT_EDGES:
cv2.line(
frame,
(int(bone_x[keypoint_start] * frame_w), int(bone_y[keypoint_start] * frame_h)),
(int(bone_x[keypoint_end] * frame_w), int(bone_y[keypoint_end] * frame_h)),
(0, 255, 0),
2)
cv2.namedWindow('centernet')
cv2.imshow('centernet', frame)
cv2.waitKey(0)
cv2.destroyAllWindows()
|
lightreid/losses/focal_loss.py
|
nataliamiccini/light-reid
| 296 |
144439
|
"""
@author: <NAME>
@contact: <EMAIL>
"""
import torch
import torch.nn as nn
from torch.autograd import Variable
from .build import LOSSes_REGISTRY
@LOSSes_REGISTRY.register()
class FocalLoss(nn.Module):
"""
reference: https://github.com/clcarwin/focal_loss_pytorch
"""
def __init__(self, gamma=0, size_average=True):
super(FocalLoss, self).__init__()
self.gamma = gamma
self.size_average = size_average
def forward(self, input, target):
if input.dim() > 2:
input = input.view(input.size(0), input.size(1), -1) # N,C,H,W => N,C,H*W
input = input.transpose(1, 2) # N,C,H*W => N,H*W,C
input = input.contiguous().view(-1, input.size(2)) # N,H*W,C => N*H*W,C
target = target.view(-1, 1)
logpt = F.log_softmax(input)
logpt = logpt.gather(1, target)
logpt = logpt.view(-1)
pt = Variable(logpt.data.exp())
loss = -1 * (1 - pt) ** self.gamma * logpt
if self.size_average:
return loss.mean()
else:
return loss.sum()
|
recipes/tinyalsa/all/conanfile.py
|
dvirtz/conan-center-index
| 562 |
144444
|
<gh_stars>100-1000
from conans import ConanFile, tools, AutoToolsBuildEnvironment
from conans.errors import ConanInvalidConfiguration
import os
class TinyAlsaConan(ConanFile):
name = "tinyalsa"
license = "BSD-3-Clause"
url = "https://github.com/conan-io/conan-center-index"
homepage = "https://github.com/tinyalsa/tinyalsa"
topics = ("conan", "tiny", "alsa", "sound", "audio", "tinyalsa")
description = "A small library to interface with ALSA in the Linux kernel"
options = {"shared": [True, False], "with_utils": [True, False]}
default_options = {'shared': False, 'with_utils': False}
settings = "os", "compiler", "build_type", "arch"
@property
def _source_subfolder(self):
return "source_subfolder"
def configure(self):
if self.settings.os != "Linux":
raise ConanInvalidConfiguration("Only Linux supported")
del self.settings.compiler.libcxx
del self.settings.compiler.cppstd
def source(self):
tools.get(**self.conan_data["sources"][self.version])
os.rename("{name}-{version}".format(name=self.name, version=self.version), self._source_subfolder)
def build(self):
with tools.chdir(self._source_subfolder):
env_build = AutoToolsBuildEnvironment(self)
env_build.make()
def package(self):
self.copy("NOTICE", dst="licenses", src=self._source_subfolder)
with tools.chdir(self._source_subfolder):
env_build = AutoToolsBuildEnvironment(self)
env_build_vars = env_build.vars
env_build_vars['PREFIX'] = self.package_folder
env_build.install(vars=env_build_vars)
tools.rmdir(os.path.join(self.package_folder, "share"))
if not self.options.with_utils:
tools.rmdir(os.path.join(self.package_folder, "bin"))
with tools.chdir(os.path.join(self.package_folder, "lib")):
files = os.listdir()
for f in files:
if (self.options.shared and f.endswith(".a")) or (not self.options.shared and not f.endswith(".a")):
os.unlink(f)
def package_info(self):
self.cpp_info.libs = ["tinyalsa"]
if self.options.with_utils:
bin_path = os.path.join(self.package_folder, "bin")
self.output.info('Appending PATH environment variable: %s' % bin_path)
self.env_info.path.append(bin_path)
|
graphgym/custom_graphgym/optimizer/example.py
|
Kenneth-Schroeder/pytorch_geometric
| 12,651 |
144447
|
<filename>graphgym/custom_graphgym/optimizer/example.py
import torch.optim as optim
from torch_geometric.graphgym.register import register_optimizer, \
register_scheduler
from torch_geometric.graphgym.optimizer import OptimizerConfig, SchedulerConfig
def optimizer_example(params, optimizer_config: OptimizerConfig):
if optimizer_config.optimizer == 'adagrad':
optimizer = optim.Adagrad(params, lr=optimizer_config.base_lr,
weight_decay=optimizer_config.weight_decay)
return optimizer
register_optimizer('adagrad', optimizer_example)
def scheduler_example(optimizer, scheduler_config: SchedulerConfig):
if scheduler_config.scheduler == 'reduce':
scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer)
return scheduler
register_scheduler('reduce', scheduler_example)
|
tools/accuracy_checker/openvino/tools/accuracy_checker/annotation_converters/common_object_detection.py
|
TolyaTalamanov/open_model_zoo
| 2,201 |
144465
|
<reponame>TolyaTalamanov/open_model_zoo<filename>tools/accuracy_checker/openvino/tools/accuracy_checker/annotation_converters/common_object_detection.py
"""
Copyright (c) 2018-2022 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import numpy as np
from .format_converter import BaseFormatConverter, ConverterReturn
from ..utils import read_txt, check_file_existence
from ..config import PathField, BoolField
from ..representation import DetectionAnnotation
class CommonDetectionConverter(BaseFormatConverter):
__provider__ = 'common_object_detection'
@classmethod
def parameters(cls):
params = super().parameters()
params.update({
'images_dir': PathField(optional=True, is_directory=True, description='Images directory'),
'annotation_dir': PathField(optional=False, is_directory=True, description='Annotation directory'),
'labels_file': PathField(description='Labels file'),
'pairs_file': PathField(
optional=True, description='matching between images and annotations'
),
'has_background': BoolField(optional=True, default=False, description='Indicator of background'),
'add_background_to_label_id': BoolField(
optional=True, default=False, description='Indicator that need shift labels'
)
})
return params
def configure(self):
self.images_dir = self.get_value_from_config('images_dir')
self.annotation_dir = self.get_value_from_config('annotation_dir')
self.labels_file = self.get_value_from_config('labels_file')
self.has_background = self.get_value_from_config('has_background')
self.shift_labels = self.get_value_from_config('add_background_to_label_id')
self.pairs_file = self.get_value_from_config('pairs_file')
def convert(self, check_content=False, progress_callback=None, progress_interval=100, **kwargs):
content_errors = None if not check_content else []
image_ann_pairs = []
if self.pairs_file:
pairs_list = read_txt(self.pairs_file)
for line in pairs_list:
image_path, annotation_path = line.split(' ')
image_path = image_path.split('@')[-1]
annotation_path = annotation_path.split('@')[-1]
image_ann_pairs.append((image_path, annotation_path))
else:
annotation_files = self.annotation_dir.glob('*.txt')
for ann_file in annotation_files:
image_ann_pairs.append((ann_file.name.replace('txt', 'jpg'), ann_file.name))
num_iterations = len(image_ann_pairs)
annotations = []
for idx, (identifier, annotation_file) in enumerate(image_ann_pairs):
labels, x_mins, y_mins, x_maxs, y_maxs = self.parse_annotation(annotation_file)
annotations.append(DetectionAnnotation(identifier, labels, x_mins, y_mins, x_maxs, y_maxs))
if check_content:
if self.images_dir is None:
self.images_dir = self.annotation_dir.parent / 'images'
check_file_existence(self.images_dir / identifier)
content_errors.append('{}: does not exist'.format(self.images_dir / identifier))
if progress_callback and idx % progress_interval == 0:
progress_callback(idx * 100 / num_iterations)
return ConverterReturn(annotations, self.get_meta(), content_errors)
def parse_annotation(self, annotation_file):
labels, x_mins, y_mins, x_maxs, y_maxs = [], [], [], [], []
for line in read_txt(self.annotation_dir / annotation_file):
label, x_min, y_min, x_max, y_max = line.split()
labels.append(int(label) + self.shift_labels)
x_mins.append(float(x_min))
y_mins.append(float(y_min))
x_maxs.append(float(x_max))
y_maxs.append(float(y_max))
return np.array(labels), np.array(x_mins), np.array(y_mins), np.array(x_maxs), np.array(y_maxs)
def get_meta(self):
labels = read_txt(self.labels_file)
label_map = {}
for idx, label_name in enumerate(labels):
label_map[idx + self.has_background] = label_name
meta = {'label_map': label_map}
if self.has_background:
meta['label_map'][0] = 'background'
meta['background_label'] = 0
return meta
|
tests/dataset_tests/preprocessors_tests/test_wle_util.py
|
pfnet/chainerchem
| 184 |
144484
|
import numpy as np
import pytest
from chainer_chemistry.dataset.preprocessors import wle_util
def test_to_index():
values = ['foo', 'bar', 'buz', 'non-exist']
mols = [['foo', 'bar', 'buz'], ['foo', 'foo'], ['buz', 'bar']]
actual = wle_util.to_index(mols, values)
expect = np.array([np.array([0, 1, 2], np.int32),
np.array([0, 0], np.int32),
np.array([2, 1], np.int32)])
assert len(actual) == len(expect)
for a, e in zip(actual, expect):
np.testing.assert_array_equal(a, e)
def test_to_index_non_existence():
values = ['foo', 'bar']
mols = [['strange_label']]
with pytest.raises(ValueError):
wle_util.to_index(mols, values)
def test_compress_relation_axis_2_dim():
arr = np.random.uniform(size=(10, 2))
actual = wle_util.compress_relation_axis(arr)
np.testing.assert_array_equal(actual, arr)
def test_compress_relation_axis_3_dim():
arr = np.array(
[
[
[1, 0],
[2, 0],
],
[
[1, 1],
[0, 0]
]
]
)
arr = np.swapaxes(arr, 0, 1)
ret = wle_util.compress_relation_axis(arr)
actual = ret != 0
expect = np.array(
[[True, True],
[True, False]]
)
np.testing.assert_array_equal(actual, expect)
def test_compress_relation_axis_invalid_ndim():
arr = np.zeros(3)
with pytest.raises(ValueError):
wle_util.compress_relation_axis(arr)
arr = np.zeros((1, 2, 3, 4))
with pytest.raises(ValueError):
wle_util.compress_relation_axis(arr)
@pytest.fixture
def small_molecule():
# a-b-c d
atom_array = ['a', 'b', 'c', 'd']
neighbors = np.array(
[
[0, 1, 1, 2], # first end of edges
[1, 0, 2, 1] # second end of edges
]
)
return atom_array, neighbors
def test_get_neighbor_representation_with_focus_atom(small_molecule):
atom_array, neighbors = small_molecule
expects = ['a-b', 'b-a.c', 'c-b', 'd-']
for i in range(len(expects)):
actual = wle_util.get_neighbor_representation(
i, atom_array, neighbors, True)
assert actual == expects[i]
def test_get_neighbor_representation_without_focus_atom(small_molecule):
atom_array, neighbors = small_molecule
expects = ['b', 'a.c', 'b', '']
for i in range(len(expects)):
actual = wle_util.get_neighbor_representation(
i, atom_array, neighbors, False)
assert actual == expects[i]
@pytest.mark.parametrize('label, expect', [
('a-b', 'a'),
('a-b.c', 'a'),
('aa-b', 'aa'),
('a-', 'a'),
('aa-', 'aa'),
])
def test_get_focus_node_label(label, expect):
actual = wle_util.get_focus_node_label(label)
assert actual == expect
@pytest.mark.parametrize('label', ['aa', 'a-a-a', 'a--'])
def test_get_focus_node_label_invalid(label):
with pytest.raises(ValueError):
wle_util.get_focus_node_label(label)
|
tda/client/__init__.py
|
zhangted/tda-api
| 986 |
144504
|
from .synchronous import Client
from .asynchronous import AsyncClient
|
compressible/problems/hse.py
|
SebastianoF/pyro2
| 151 |
144507
|
from __future__ import print_function
import numpy as np
import sys
import mesh.patch as patch
from util import msg
def init_data(my_data, rp):
""" initialize the HSE problem """
msg.bold("initializing the HSE problem...")
# make sure that we are passed a valid patch object
if not isinstance(my_data, patch.CellCenterData2d):
print("ERROR: patch invalid in hse.py")
print(my_data.__class__)
sys.exit()
# get the density, momenta, and energy as separate variables
dens = my_data.get_var("density")
xmom = my_data.get_var("x-momentum")
ymom = my_data.get_var("y-momentum")
ener = my_data.get_var("energy")
gamma = rp.get_param("eos.gamma")
grav = rp.get_param("compressible.grav")
dens0 = rp.get_param("hse.dens0")
print("dens0 = ", dens0)
H = rp.get_param("hse.h")
# isothermal sound speed (squared)
cs2 = H*abs(grav)
# initialize the components, remember, that ener here is
# rho*eint + 0.5*rho*v**2, where eint is the specific
# internal energy (erg/g)
xmom[:, :] = 0.0
ymom[:, :] = 0.0
dens[:, :] = 0.0
# set the density to be stratified in the y-direction
myg = my_data.grid
p = myg.scratch_array()
for j in range(myg.jlo, myg.jhi+1):
dens[:, j] = dens0*np.exp(-myg.y[j]/H)
if j == myg.jlo:
p[:, j] = dens[:, j]*cs2
else:
p[:, j] = p[:, j-1] + 0.5*myg.dy*(dens[:, j] + dens[:, j-1])*grav
# set the energy
ener[:, :] = p[:, :]/(gamma - 1.0) + \
0.5*(xmom[:, :]**2 + ymom[:, :]**2)/dens[:, :]
def finalize():
""" print out any information to the user at the end of the run """
pass
|
sdk/storage/azure-storage-file-datalake/azure/storage/filedatalake/_list_paths_helper.py
|
rsdoherty/azure-sdk-for-python
| 207 |
144509
|
<gh_stars>100-1000
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from azure.core.paging import PageIterator
from azure.core.exceptions import HttpResponseError
from ._deserialize import process_storage_error, get_deleted_path_properties_from_generated_code
from ._generated.models import BlobItemInternal, BlobPrefix as GenBlobPrefix
from ._shared.models import DictMixin
from ._shared.response_handlers import return_context_and_deserialized
class DeletedPathPropertiesPaged(PageIterator):
"""An Iterable of deleted path properties.
:ivar str service_endpoint: The service URL.
:ivar str prefix: A path name prefix being used to filter the list.
:ivar str marker: The continuation token of the current page of results.
:ivar int results_per_page: The maximum number of results retrieved per API call.
:ivar str continuation_token: The continuation token to retrieve the next page of results.
:ivar str location_mode: The location mode being used to list results. The available
options include "primary" and "secondary".
:ivar current_page: The current page of listed results.
:vartype current_page: list(~azure.storage.filedatalake.DeletedPathProperties)
:ivar str container: The container that the paths are listed from.
:ivar str delimiter: A delimiting character used for hierarchy listing.
:param callable command: Function to retrieve the next page of items.
"""
def __init__(
self, command,
container=None,
prefix=None,
results_per_page=None,
continuation_token=None,
delimiter=None,
location_mode=None):
super(DeletedPathPropertiesPaged, self).__init__(
get_next=self._get_next_cb,
extract_data=self._extract_data_cb,
continuation_token=continuation_token or ""
)
self._command = command
self.service_endpoint = None
self.prefix = prefix
self.marker = None
self.results_per_page = results_per_page
self.container = container
self.delimiter = delimiter
self.current_page = None
self.location_mode = location_mode
def _get_next_cb(self, continuation_token):
try:
return self._command(
prefix=self.prefix,
marker=continuation_token or None,
max_results=self.results_per_page,
cls=return_context_and_deserialized,
use_location=self.location_mode)
except HttpResponseError as error:
process_storage_error(error)
def _extract_data_cb(self, get_next_return):
self.location_mode, self._response = get_next_return
self.service_endpoint = self._response.service_endpoint
self.prefix = self._response.prefix
self.marker = self._response.marker
self.results_per_page = self._response.max_results
self.container = self._response.container_name
self.current_page = self._response.segment.blob_prefixes + self._response.segment.blob_items
self.current_page = [self._build_item(item) for item in self.current_page]
self.delimiter = self._response.delimiter
return self._response.next_marker or None, self.current_page
def _build_item(self, item):
if isinstance(item, BlobItemInternal):
file_props = get_deleted_path_properties_from_generated_code(item)
file_props.file_system = self.container
return file_props
if isinstance(item, GenBlobPrefix):
return DirectoryPrefix(
container=self.container,
prefix=item.name,
results_per_page=self.results_per_page,
location_mode=self.location_mode)
return item
class DirectoryPrefix(DictMixin):
"""Directory prefix.
:ivar str name: Name of the deleted directory.
:ivar int results_per_page: The maximum number of results retrieved per API call.
:ivar str location_mode: The location mode being used to list results. The available
options include "primary" and "secondary".
:ivar str file_system: The file system that the deleted paths are listed from.
:ivar str delimiter: A delimiting character used for hierarchy listing.
"""
def __init__(self, **kwargs):
self.name = kwargs.get('prefix')
self.results_per_page = kwargs.get('results_per_page')
self.file_system = kwargs.get('container')
self.delimiter = kwargs.get('delimiter')
self.location_mode = kwargs.get('location_mode')
|
tests/cli/tap.py
|
joshuataylor/great_expectations
| 6,451 |
144525
|
"""
A basic generated Great Expectations tap that validates a single batch of data.
Data that is validated is controlled by BatchKwargs, which can be adjusted in
this script.
Data are validated by use of the `ActionListValidationOperator` which is
configured by default. The default configuration of this Validation Operator
saves validation results to your results store and then updates Data Docs.
This makes viewing validation results easy for you and your team.
Usage:
- Run this file: `python {}`.
- This can be run manually or via a scheduler such as cron.
"""
import sys
import great_expectations as ge
# tap configuration
context = ge.DataContext(
"/private/var/folders/_t/psczkmjd69vf9jz0bblzlzww0000gn/T/pytest-of-taylor/pytest-1812/empty_data_context0/great_expectations"
)
suite = context.get_expectation_suite("sweet_suite")
batch_kwargs = {
"path": "/private/var/folders/_t/psczkmjd69vf9jz0bblzlzww0000gn/T/pytest-of-taylor/pytest-1812/filesystem_csv0/f1.csv",
"datasource": "1_datasource",
}
# tap validation process
batch = context.get_batch(batch_kwargs, suite)
results = context.run_validation_operator("action_list_operator", [batch])
if not results["success"]:
print("Validation Failed!")
sys.exit(1)
print("Validation Succeeded!")
sys.exit(0)
|
venv/Lib/site-packages/numpy/typing/tests/data/fail/flatiter.py
|
EkremBayar/bayar
| 603 |
144527
|
<reponame>EkremBayar/bayar<gh_stars>100-1000
from typing import Any
import numpy as np
from numpy.typing import _SupportsArray
class Index:
def __index__(self) -> int:
...
a: "np.flatiter[np.ndarray]"
supports_array: _SupportsArray
a.base = Any # E: Property "base" defined in "flatiter" is read-only
a.coords = Any # E: Property "coords" defined in "flatiter" is read-only
a.index = Any # E: Property "index" defined in "flatiter" is read-only
a.copy(order='C') # E: Unexpected keyword argument
# NOTE: Contrary to `ndarray.__getitem__` its counterpart in `flatiter`
# does not accept objects with the `__array__` or `__index__` protocols;
# boolean indexing is just plain broken (gh-17175)
a[np.bool_()] # E: No overload variant of "__getitem__"
a[Index()] # E: No overload variant of "__getitem__"
a[supports_array] # E: No overload variant of "__getitem__"
|
tests/Unit/Elliptic/Systems/Elasticity/BoundaryConditions/LaserBeam.py
|
nilsvu/spectre
| 117 |
144559
|
# Distributed under the MIT License.
# See LICENSE.txt for details.
import numpy as np
from numpy import sqrt, exp, pi
def normal_dot_minus_stress(x, n, beam_width):
n /= np.linalg.norm(n)
r = sqrt(np.linalg.norm(x)**2 - np.dot(x, n)**2)
beam_profile = exp(-(r / beam_width)**2) / pi / beam_width**2
return np.tensordot(-n, beam_profile, axes=0)
def normal_dot_minus_stress_linearized(x, n, beam_width):
return np.zeros(3)
|
tests/test_sorted_list.py
|
mrsndmn/PyGM
| 169 |
144563
|
<reponame>mrsndmn/PyGM<filename>tests/test_sorted_list.py
import bisect
import random
from array import array
import pytest
from pygm import SortedList
def test_len():
assert len(SortedList([1, 2, 3])) == 3
assert len(SortedList([3, 1, 4, 3])) == 4
assert len(SortedList([1] * 10)) == 10
def test_init():
assert SortedList() == []
assert SortedList([]) == []
assert SortedList((1, 2, 3, 2)) == [1, 2, 2, 3]
assert SortedList({1: 'a', 2: 'b', 3: 'c'}) == [1, 2, 3]
assert SortedList({1, 5, 5, 10}) == [1, 5, 10]
assert SortedList(range(5, 0, -1)) == [1, 2, 3, 4, 5]
assert SortedList({1, 5, 5, 10}, 'f') == [1., 5., 10.]
assert SortedList(array('f', (1, 2, 2, 3))) == [1., 2., 2., 3.]
assert SortedList(array('d', (1, 2, 2, 3))) == [1., 2., 2., 3.]
assert SortedList(array('H', (1, 2, 2, 3))) == [1, 2, 2, 3]
assert SortedList(array('Q', (1, 2, 2, 3))) == [1, 2, 2, 3]
assert SortedList([-5, -1, -5, 5], 'h') == [-5, -5, -1, 5]
assert SortedList(SortedList([1]), 'H').stats()['typecode'] == 'H'
with pytest.raises(TypeError):
SortedList([0], '@')
with pytest.raises(TypeError):
SortedList(lambda x: x + 10)
with pytest.raises(ValueError):
SortedList("ciao")
def test_compare():
assert not SortedList([1] * 10) == SortedList([1] * 100)
assert SortedList([-5, -4, -3, -2, -1]) > SortedList([-10, -5])
assert SortedList([2, 4, 8, 10]) >= SortedList([1, 4, 7, 10])
assert SortedList([10, 100, 1000]) != SortedList([10, 100])
assert SortedList([10, 100, 1000]) <= SortedList([10, 100, 10000])
assert SortedList([10, 100, 1000]) < SortedList([100, 1000, 1000])
with pytest.raises(TypeError):
SortedList() < (lambda: 5)
def test_contains():
assert 5 in SortedList(range(100))
assert 50 not in SortedList(list(range(50)) + list(range(51, 100)))
assert 500. in SortedList([1., 1.] * 10 + [500.] * 2 + [1000.] * 5)
def test_reversed():
assert list(reversed(SortedList(range(50)))) == list(reversed(range(50)))
assert list(reversed(SortedList([1, 3, 3, 2, 1]))) == [3, 3, 2, 1, 1]
def test_repr():
assert '1, ..., 1' in repr(SortedList([1] * 10000))
assert '1.5, ..., 1.5' in repr(SortedList([1.5] * 10000))
assert '[-1, 0, 0, 1]' in repr(SortedList([1, 0, 0, -1]))
def test_getitem():
assert SortedList([3, 1, 4, 3])[2] == 3
assert SortedList(range(100))[50] == 50
assert SortedList([1, 4, 9, 7] * 10)[2:5] == [1, 1, 1]
assert SortedList(range(1, 100))[:5] == [1, 2, 3, 4, 5]
assert SortedList(range(1, 10))[1::2] == [2, 4, 6, 8]
def test_iter():
assert next(iter(SortedList([0, 1, 4, 10]))) == 0
assert {x for x in SortedList([0, 1, 3, 3, 4, 10])} == {0, 1, 3, 4, 10}
assert [x for x in SortedList([-10, 0, 10, 100])] == [-10, 0, 10, 100]
def test_bisect():
random.seed(42)
l = sorted([random.randint(-100, 100) for _ in range(500)])
sl = SortedList(l)
for x in range(-105, 105):
assert sl.bisect_left(x) == bisect.bisect_left(l, x)
assert sl.bisect_right(x) == bisect.bisect_right(l, x)
l = sorted([random.randint(-1000, 1000) for _ in range(100)])
for eps in [16, 32, 64, 128, 256]:
sl = SortedList(l, 'i', eps)
for x in range(-100, 100):
assert sl.bisect_left(x) == bisect.bisect_left(l, x)
assert sl.bisect_right(x) == bisect.bisect_right(l, x)
def test_find():
l = SortedList([0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233] * 100)
assert l.find_lt(5) == 3
assert l.find_lt(22) == 21
assert l.find_le(14) == 13
assert l.find_le(89) == 89
assert l.find_gt(55) == 89
assert l.find_gt(54) == 55
assert l.find_ge(5) == 5
assert l.find_ge(4) == 5
assert l.find_lt(0) is None
assert l.find_le(-10) is None
assert l.find_gt(233) is None
assert l.find_ge(500) is None
def test_rank():
l = SortedList([0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233] * 10)
assert l.rank(-5) == 0
assert l.rank(0) == 10
assert l.rank(1) == 30
assert l.rank(4) == 50
assert l.rank(500) == len(l)
def test_count():
l = SortedList(range(100))
assert l.count(-100) == 0
assert l.count(1000) == 0
for x in l:
assert l.count(x) == 1
l = SortedList([1, 2, 4, 8, 16, 32] * 100)
assert l.count(-100) == 0
assert l.count(1000) == 0
for x in range(6):
assert l.count(2 ** x) == 100
def test_range():
l = SortedList(range(0, 100, 2))
assert list(l.range(10, 20, (False, False))) == [12, 14, 16, 18]
assert list(l.range(10, 20, (False, True))) == [12, 14, 16, 18, 20]
assert list(l.range(10, 20, (True, False))) == [10, 12, 14, 16, 18]
assert list(l.range(10, 20, (True, True))) == [10, 12, 14, 16, 18, 20]
def test_index():
l = sorted([0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233] * 10)
sl = SortedList(l)
for x in set(l):
assert sl.index(x) == l.index(x)
assert sl.index(1) == 10
assert sl.index(1, 10) == 10
assert sl.index(1, 10, 11) == 10
with pytest.raises(ValueError):
sl.index(18)
sl.index(233, 10, -20)
def test_add():
assert SortedList([1, 1, 3]) + SortedList([5, 1]) == [1, 1, 1, 3, 5]
assert SortedList([1, 1, 2, 3]) + [5, 1] == [1, 1, 1, 2, 3, 5]
def test_sub():
assert SortedList([1, 1, 3]) - SortedList([5, 1]) == [1, 3]
assert SortedList([1, 1, 2, 3, 8]) - [1, 1, 1] == [2, 3, 8]
def test_drop_duplicates():
assert SortedList([2, 3, 8]).drop_duplicates() == [2, 3, 8]
assert SortedList([2, 3, 8] * 10).drop_duplicates() == [2, 3, 8]
def test_copy():
assert len(SortedList().copy()) == 0
assert SortedList([4, 1, 3, 3, 2]).copy() == [1, 2, 3, 3, 4]
|
AppDB/appscale/datastore/fdb/stats/buffer.py
|
loftwah/appscale
| 790 |
144570
|
<filename>AppDB/appscale/datastore/fdb/stats/buffer.py
import datetime
import logging
import monotonic
import random
import time
from collections import defaultdict
import six
from tornado import gen
from tornado.ioloop import IOLoop
from tornado.locks import Lock as AsyncLock
from appscale.datastore.fdb.polling_lock import PollingLock
from appscale.datastore.fdb.stats.containers import ProjectStats
from appscale.datastore.fdb.stats.entities import fill_entities
from appscale.datastore.fdb.utils import (
fdb, MAX_FDB_TX_DURATION, ResultIterator)
logger = logging.getLogger(__name__)
class ProjectStatsDir(object):
"""
A ProjectStatsDir handles the encoding and decoding details for a project's
stats entries.
The directory path looks like (<project-dir>, 'stats').
"""
DIR_NAME = u'stats'
def __init__(self, directory):
self.directory = directory
def encode_last_versionstamp(self):
return self.directory.pack((u'last-versionstamp',)), b'\x00' * 14
def encode_last_timestamp(self):
key = self.directory.pack((u'last-timestamp',))
value = fdb.tuple.pack((int(time.time()),))
return key, value
def decode(self, kvs):
project_stats = ProjectStats()
last_timestamp = None
for kv in kvs:
path = self.directory.unpack(kv.key)
section = path[0]
if section == u'last-versionstamp':
continue
if section == u'last-timestamp':
last_timestamp = datetime.datetime.utcfromtimestamp(
fdb.tuple.unpack(kv.value)[0])
continue
project_stats.update_from_kv(section, path[1:], kv.value)
return project_stats, last_timestamp
@classmethod
def directory_path(cls, project_id):
return project_id, cls.DIR_NAME
class StatsBuffer(object):
AVG_FLUSH_INTERVAL = 30
BATCH_SIZE = 20
SUMMARY_INTERVAL = 120
_LOCK_KEY = u'stats-lock'
def __init__(self, db, tornado_fdb, directory_cache, ds_access):
self._db = db
self._tornado_fdb = tornado_fdb
self._directory_cache = directory_cache
self._buffer_lock = AsyncLock()
self._ds_access = ds_access
summary_lock_key = self._directory_cache.root_dir.pack((self._LOCK_KEY,))
self._summary_lock = PollingLock(
self._db, self._tornado_fdb, summary_lock_key)
# By project
self._last_summarized = {}
# By project
self._buffers = defaultdict(ProjectStats)
def start(self):
self._summary_lock.start()
IOLoop.current().spawn_callback(self._periodic_flush)
IOLoop.current().spawn_callback(self._periodic_summary)
@gen.coroutine
def update(self, project_id, mutations):
with (yield self._buffer_lock.acquire()):
for old_entry, new_entry, index_stats in mutations:
self._buffers[project_id].update(old_entry, new_entry, index_stats)
@gen.coroutine
def _periodic_flush(self):
while True:
try:
yield gen.sleep(random.random() * self.AVG_FLUSH_INTERVAL)
yield self._flush()
except Exception:
# TODO: Exponential backoff here.
logger.exception(u'Unexpected error while flushing stats')
yield gen.sleep(random.random() * 2)
continue
@gen.coroutine
def _flush(self):
if all(buffer_.empty for buffer_ in six.itervalues(self._buffers)):
return
with (yield self._buffer_lock.acquire()):
tr = self._db.create_transaction()
for project_id, buffer_ in six.iteritems(self._buffers):
stats_dir = yield self._project_stats_dir(tr, project_id)
buffer_.apply(tr, stats_dir.directory)
vs_key, vs_value = stats_dir.encode_last_versionstamp()
tr.set_versionstamped_value(vs_key, vs_value)
ts_key, ts_value = stats_dir.encode_last_timestamp()
tr[ts_key] = ts_value
yield self._tornado_fdb.commit(tr)
logger.debug(u'Finished flushing stats')
self._buffers.clear()
@gen.coroutine
def _periodic_summary(self):
while True:
try:
yield self._summary_lock.acquire()
tr = self._db.create_transaction()
deadline = monotonic.monotonic() + MAX_FDB_TX_DURATION - 1
last_summarized = {}
# TODO: This can be made async.
project_ids = self._directory_cache.root_dir.list(tr)
summarized_projects = []
for project_id in project_ids:
stats_dir = yield self._project_stats_dir(tr, project_id)
last_vs_key = stats_dir.encode_last_versionstamp()[0]
last_versionstamp = yield self._tornado_fdb.get(
tr, last_vs_key, snapshot=True)
if (not last_versionstamp.present() or
last_versionstamp.value == self._last_summarized.get(project_id)):
continue
last_summarized[project_id] = last_versionstamp.value
results = yield ResultIterator(
tr, self._tornado_fdb, stats_dir.directory.range(),
snapshot=True).list()
project_stats, last_timestamp = stats_dir.decode(results)
entities = fill_entities(project_id, project_stats, last_timestamp)
for pos in range(0, len(entities), self.BATCH_SIZE):
yield [self._ds_access._upsert(tr, entity)
for entity in entities[pos:pos + self.BATCH_SIZE]]
if monotonic.monotonic() > deadline:
yield self._tornado_fdb.commit(tr)
tr = self._db.create_transaction()
deadline = monotonic.monotonic() + MAX_FDB_TX_DURATION - 1
summarized_projects.append(project_id)
yield self._tornado_fdb.commit(tr)
self._last_summarized.update(last_summarized)
if summarized_projects:
logger.debug(u'Finished summarizing stats for '
u'{}'.format(summarized_projects))
yield gen.sleep(self.SUMMARY_INTERVAL)
except Exception:
logger.exception(u'Unexpected error while summarizing stats')
yield gen.sleep(random.random() * 20)
@gen.coroutine
def _project_stats_dir(self, tr, project_id):
path = ProjectStatsDir.directory_path(project_id)
directory = yield self._directory_cache.get(tr, path)
raise gen.Return(ProjectStatsDir(directory))
|
pytorch_ipynb/helper_plotting.py
|
XiaoshengLin/deeplearning-models
| 16,182 |
144612
|
<filename>pytorch_ipynb/helper_plotting.py
# imports from installed libraries
import os
import matplotlib.pyplot as plt
import numpy as np
import torch
def plot_training_loss(minibatch_loss_list, num_epochs, iter_per_epoch,
results_dir=None, averaging_iterations=100):
plt.figure()
ax1 = plt.subplot(1, 1, 1)
ax1.plot(range(len(minibatch_loss_list)),
(minibatch_loss_list), label='Minibatch Loss')
if len(minibatch_loss_list) > 1000:
ax1.set_ylim([
0, np.max(minibatch_loss_list[1000:])*1.5
])
ax1.set_xlabel('Iterations')
ax1.set_ylabel('Loss')
ax1.plot(np.convolve(minibatch_loss_list,
np.ones(averaging_iterations,)/averaging_iterations,
mode='valid'),
label='Running Average')
ax1.legend()
###################
# Set scond x-axis
ax2 = ax1.twiny()
newlabel = list(range(num_epochs+1))
newpos = [e*iter_per_epoch for e in newlabel]
ax2.set_xticks(newpos[::10])
ax2.set_xticklabels(newlabel[::10])
ax2.xaxis.set_ticks_position('bottom')
ax2.xaxis.set_label_position('bottom')
ax2.spines['bottom'].set_position(('outward', 45))
ax2.set_xlabel('Epochs')
ax2.set_xlim(ax1.get_xlim())
###################
plt.tight_layout()
if results_dir is not None:
image_path = os.path.join(results_dir, 'plot_training_loss.pdf')
plt.savefig(image_path)
def plot_accuracy(train_acc_list, valid_acc_list, results_dir):
num_epochs = len(train_acc_list)
plt.plot(np.arange(1, num_epochs+1),
train_acc_list, label='Training')
plt.plot(np.arange(1, num_epochs+1),
valid_acc_list, label='Validation')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.tight_layout()
if results_dir is not None:
image_path = os.path.join(
results_dir, 'plot_acc_training_validation.pdf')
plt.savefig(image_path)
def show_examples(model, data_loader, unnormalizer=None, class_dict=None):
for batch_idx, (features, targets) in enumerate(data_loader):
with torch.no_grad():
features = features
targets = targets
logits = model(features)
predictions = torch.argmax(logits, dim=1)
break
fig, axes = plt.subplots(nrows=3, ncols=5,
sharex=True, sharey=True)
if unnormalizer is not None:
for idx in range(features.shape[0]):
features[idx] = unnormalizer(features[idx])
nhwc_img = np.transpose(features, axes=(0, 2, 3, 1))
if nhwc_img.shape[-1] == 1:
nhw_img = np.squeeze(nhwc_img.numpy(), axis=3)
for idx, ax in enumerate(axes.ravel()):
ax.imshow(nhw_img[idx], cmap='binary')
if class_dict is not None:
ax.title.set_text(f'P: {class_dict[predictions[idx].item()]}'
f'\nT: {class_dict[targets[idx].item()]}')
else:
ax.title.set_text(f'P: {predictions[idx]} | T: {targets[idx]}')
ax.axison = False
else:
for idx, ax in enumerate(axes.ravel()):
ax.imshow(nhwc_img[idx])
if class_dict is not None:
ax.title.set_text(f'P: {class_dict[predictions[idx].item()]}'
f'\nT: {class_dict[targets[idx].item()]}')
else:
ax.title.set_text(f'P: {predictions[idx]} | T: {targets[idx]}')
ax.axison = False
plt.tight_layout()
plt.show()
def plot_confusion_matrix(conf_mat,
hide_spines=False,
hide_ticks=False,
figsize=None,
cmap=None,
colorbar=False,
show_absolute=True,
show_normed=False,
class_names=None):
if not (show_absolute or show_normed):
raise AssertionError('Both show_absolute and show_normed are False')
if class_names is not None and len(class_names) != len(conf_mat):
raise AssertionError('len(class_names) should be equal to number of'
'classes in the dataset')
total_samples = conf_mat.sum(axis=1)[:, np.newaxis]
normed_conf_mat = conf_mat.astype('float') / total_samples
fig, ax = plt.subplots(figsize=figsize)
ax.grid(False)
if cmap is None:
cmap = plt.cm.Blues
if figsize is None:
figsize = (len(conf_mat)*1.25, len(conf_mat)*1.25)
if show_normed:
matshow = ax.matshow(normed_conf_mat, cmap=cmap)
else:
matshow = ax.matshow(conf_mat, cmap=cmap)
if colorbar:
fig.colorbar(matshow)
for i in range(conf_mat.shape[0]):
for j in range(conf_mat.shape[1]):
cell_text = ""
if show_absolute:
cell_text += format(conf_mat[i, j], 'd')
if show_normed:
cell_text += "\n" + '('
cell_text += format(normed_conf_mat[i, j], '.2f') + ')'
else:
cell_text += format(normed_conf_mat[i, j], '.2f')
ax.text(x=j,
y=i,
s=cell_text,
va='center',
ha='center',
color="white" if normed_conf_mat[i, j] > 0.5 else "black")
if class_names is not None:
tick_marks = np.arange(len(class_names))
plt.xticks(tick_marks, class_names, rotation=90)
plt.yticks(tick_marks, class_names)
if hide_spines:
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')
if hide_ticks:
ax.axes.get_yaxis().set_ticks([])
ax.axes.get_xaxis().set_ticks([])
plt.xlabel('predicted label')
plt.ylabel('true label')
return fig, ax
|
Tests/test_class.py
|
psydox/Pyjion
| 1,137 |
144634
|
<reponame>psydox/Pyjion<filename>Tests/test_class.py
def test_add():
class Number:
def __add__(self, other):
return 4 + other
def __radd__(self, other):
return other + 4
a = Number()
assert 3 + a == 7
assert a + 3 == 7
def test_inheritance():
class Node(object):
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def add_n(self, n):
self.a += n
def __repr__(self):
value = self.a
value = repr(value)
return '%s(tag=%r, value=%s)' % (self.__class__.__name__, self.b, value)
class ChildNode(Node):
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
class GrandchildNode(ChildNode):
d = 101000
node = GrandchildNode(101001, 101002, 101003)
x = repr(node)
assert x == "GrandchildNode(tag=101002, value=101001)"
node.add_n(10000)
|
mne/utils/tests/test_testing.py
|
rylaw/mne-python
| 1,953 |
144641
|
<reponame>rylaw/mne-python
import os.path as op
import numpy as np
import pytest
from mne.datasets import testing
from mne.utils import (_TempDir, _url_to_local_path, buggy_mkl_svd)
def test_buggy_mkl():
"""Test decorator for buggy MKL issues."""
from unittest import SkipTest
@buggy_mkl_svd
def foo(a, b):
raise np.linalg.LinAlgError('SVD did not converge')
with pytest.warns(RuntimeWarning, match='convergence error'):
pytest.raises(SkipTest, foo, 1, 2)
@buggy_mkl_svd
def bar(c, d, e):
raise RuntimeError('SVD did not converge')
pytest.raises(RuntimeError, bar, 1, 2, 3)
def test_tempdir():
"""Test TempDir."""
tempdir2 = _TempDir()
assert (op.isdir(tempdir2))
x = str(tempdir2)
del tempdir2
assert (not op.isdir(x))
def test_datasets(monkeypatch, tmpdir):
"""Test dataset config."""
# gh-4192
fake_path = tmpdir.mkdir('MNE-testing-data')
with open(fake_path.join('version.txt'), 'w') as fid:
fid.write('9999.9999')
monkeypatch.setenv('_MNE_FAKE_HOME_DIR', str(tmpdir))
monkeypatch.setenv('MNE_DATASETS_TESTING_PATH', str(tmpdir))
assert testing.data_path(download=False, verbose='debug') == str(fake_path)
def test_url_to_local_path():
"""Test URL to local path."""
assert _url_to_local_path('http://google.com/home/why.html', '.') == \
op.join('.', 'home', 'why.html')
|
nsf/nde/transforms/conv_test.py
|
davidreiman/nsf
| 231 |
144642
|
<filename>nsf/nde/transforms/conv_test.py<gh_stars>100-1000
import torch
import unittest
from nde import transforms
from nde.transforms.transform_test import TransformTest
class OneByOneConvolutionTest(TransformTest):
def test_forward_and_inverse_are_consistent(self):
batch_size = 10
c, h, w = 3, 28, 28
inputs = torch.randn(batch_size, c, h, w)
transform = transforms.OneByOneConvolution(c)
self.eps = 1e-6
self.assert_forward_inverse_are_consistent(transform, inputs)
if __name__ == '__main__':
unittest.main()
|
bplustree/memory.py
|
EdwardWooCN/bplustree
| 760 |
144655
|
<filename>bplustree/memory.py<gh_stars>100-1000
import enum
import io
from logging import getLogger
import os
import platform
from typing import Union, Tuple, Optional
import cachetools
import rwlock
from .node import Node, FreelistNode
from .const import (
ENDIAN, PAGE_REFERENCE_BYTES, OTHERS_BYTES, TreeConf, FRAME_TYPE_BYTES
)
logger = getLogger(__name__)
class ReachedEndOfFile(Exception):
"""Read a file until its end."""
def open_file_in_dir(path: str) -> Tuple[io.FileIO, Optional[int]]:
"""Open a file and its directory.
The file is opened in binary mode and created if it does not exist.
Both file descriptors must be closed after use to prevent them from
leaking.
On Windows, the directory is not opened, as it is useless.
"""
directory = os.path.dirname(path)
if not os.path.isdir(directory):
raise ValueError('No directory {}'.format(directory))
if not os.path.exists(path):
file_fd = open(path, mode='x+b', buffering=0)
else:
file_fd = open(path, mode='r+b', buffering=0)
if platform.system() == 'Windows':
# Opening a directory is not possible on Windows, but that is not
# a problem since Windows does not need to fsync the directory in
# order to persist metadata
dir_fd = None
else:
dir_fd = os.open(directory, os.O_RDONLY)
return file_fd, dir_fd
def write_to_file(file_fd: io.FileIO, dir_fileno: Optional[int],
data: bytes, fsync: bool=True):
length_to_write = len(data)
written = 0
while written < length_to_write:
written += file_fd.write(data[written:])
if fsync:
fsync_file_and_dir(file_fd.fileno(), dir_fileno)
def fsync_file_and_dir(file_fileno: int, dir_fileno: Optional[int]):
os.fsync(file_fileno)
if dir_fileno is not None:
os.fsync(dir_fileno)
def read_from_file(file_fd: io.FileIO, start: int, stop: int) -> bytes:
length = stop - start
assert length >= 0
file_fd.seek(start)
data = bytes()
while file_fd.tell() < stop:
read_data = file_fd.read(stop - file_fd.tell())
if read_data == b'':
raise ReachedEndOfFile('Read until the end of file')
data += read_data
assert len(data) == length
return data
class FakeCache:
"""A cache that doesn't cache anything.
Because cachetools does not work with maxsize=0.
"""
def get(self, k):
pass
def __setitem__(self, key, value):
pass
def clear(self):
pass
class FileMemory:
__slots__ = ['_filename', '_tree_conf', '_lock', '_cache', '_fd',
'_dir_fd', '_wal', 'last_page', '_freelist_start_page',
'_root_node_page']
def __init__(self, filename: str, tree_conf: TreeConf,
cache_size: int=512):
self._filename = filename
self._tree_conf = tree_conf
self._lock = rwlock.RWLock()
if cache_size == 0:
self._cache = FakeCache()
else:
self._cache = cachetools.LRUCache(maxsize=cache_size)
self._fd, self._dir_fd = open_file_in_dir(filename)
self._wal = WAL(filename, tree_conf.page_size)
if self._wal.needs_recovery:
self.perform_checkpoint(reopen_wal=True)
# Get the next available page
self._fd.seek(0, io.SEEK_END)
last_byte = self._fd.tell()
self.last_page = int(last_byte / self._tree_conf.page_size)
self._freelist_start_page = 0
# Todo: Remove this, it should only be in Tree
self._root_node_page = 0
def get_node(self, page: int):
"""Get a node from storage.
The cache is not there to prevent hitting the disk, the OS is already
very good at it. It is there to avoid paying the price of deserializing
the data to create the Node object and its entry. This is a very
expensive operation in Python.
Since we have at most a single writer we can write to cache on
`set_node` if we invalidate the cache when a transaction is rolled
back.
"""
node = self._cache.get(page)
if node is not None:
return node
data = self._wal.get_page(page)
if not data:
data = self._read_page(page)
node = Node.from_page_data(self._tree_conf, data=data, page=page)
self._cache[node.page] = node
return node
def set_node(self, node: Node):
self._wal.set_page(node.page, node.dump())
self._cache[node.page] = node
def del_node(self, node: Node):
self._insert_in_freelist(node.page)
def del_page(self, page: int):
self._insert_in_freelist(page)
@property
def read_transaction(self):
class ReadTransaction:
def __enter__(self2):
self._lock.reader_lock.acquire()
def __exit__(self2, exc_type, exc_val, exc_tb):
self._lock.reader_lock.release()
return ReadTransaction()
@property
def write_transaction(self):
class WriteTransaction:
def __enter__(self2):
self._lock.writer_lock.acquire()
def __exit__(self2, exc_type, exc_val, exc_tb):
if exc_type:
# When an error happens in the middle of a write
# transaction we must roll it back and clear the cache
# because the writer may have partially modified the Nodes
self._wal.rollback()
self._cache.clear()
else:
self._wal.commit()
self._lock.writer_lock.release()
return WriteTransaction()
@property
def next_available_page(self) -> int:
last_freelist_page = self._pop_from_freelist()
if last_freelist_page is not None:
return last_freelist_page
self.last_page += 1
return self.last_page
def _traverse_free_list(self) -> Tuple[Optional[FreelistNode],
Optional[FreelistNode]]:
if self._freelist_start_page == 0:
return None, None
second_to_last_node = None
last_node = self.get_node(self._freelist_start_page)
while last_node.next_page is not None:
second_to_last_node = last_node
last_node = self.get_node(second_to_last_node.next_page)
return second_to_last_node, last_node
def _insert_in_freelist(self, page: int):
"""Insert a page at the end of the freelist."""
_, last_node = self._traverse_free_list()
self.set_node(FreelistNode(self._tree_conf, page=page, next_page=None))
if last_node is None:
# Write in metadata that the freelist got a new starting point
self._freelist_start_page = page
self.set_metadata(None, None)
else:
last_node.next_page = page
self.set_node(last_node)
def _pop_from_freelist(self) -> Optional[int]:
"""Remove the last page from the freelist and return its page."""
second_to_last_node, last_node = self._traverse_free_list()
if last_node is None:
# Freelist is completely empty, nothing to pop
return None
if second_to_last_node is None:
# Write in metadata that the freelist is empty
self._freelist_start_page = 0
self.set_metadata(None, None)
else:
second_to_last_node.next_page = None
self.set_node(second_to_last_node)
return last_node.page
# Todo: make metadata as a normal Node
def get_metadata(self) -> tuple:
try:
data = self._read_page(0)
except ReachedEndOfFile:
raise ValueError('Metadata not set yet')
end_root_node_page = PAGE_REFERENCE_BYTES
root_node_page = int.from_bytes(
data[0:end_root_node_page], ENDIAN
)
end_page_size = end_root_node_page + OTHERS_BYTES
page_size = int.from_bytes(
data[end_root_node_page:end_page_size], ENDIAN
)
end_order = end_page_size + OTHERS_BYTES
order = int.from_bytes(
data[end_page_size:end_order], ENDIAN
)
end_key_size = end_order + OTHERS_BYTES
key_size = int.from_bytes(
data[end_order:end_key_size], ENDIAN
)
end_value_size = end_key_size + OTHERS_BYTES
value_size = int.from_bytes(
data[end_key_size:end_value_size], ENDIAN
)
end_freelist_start_page = end_value_size + PAGE_REFERENCE_BYTES
self._freelist_start_page = int.from_bytes(
data[end_value_size:end_freelist_start_page], ENDIAN
)
self._tree_conf = TreeConf(
page_size, order, key_size, value_size, self._tree_conf.serializer
)
self._root_node_page = root_node_page
return root_node_page, self._tree_conf
def set_metadata(self, root_node_page: Optional[int],
tree_conf: Optional[TreeConf]):
if root_node_page is None:
root_node_page = self._root_node_page
if tree_conf is None:
tree_conf = self._tree_conf
length = 2 * PAGE_REFERENCE_BYTES + 4 * OTHERS_BYTES
data = (
root_node_page.to_bytes(PAGE_REFERENCE_BYTES, ENDIAN) +
tree_conf.page_size.to_bytes(OTHERS_BYTES, ENDIAN) +
tree_conf.order.to_bytes(OTHERS_BYTES, ENDIAN) +
tree_conf.key_size.to_bytes(OTHERS_BYTES, ENDIAN) +
tree_conf.value_size.to_bytes(OTHERS_BYTES, ENDIAN) +
self._freelist_start_page.to_bytes(PAGE_REFERENCE_BYTES, ENDIAN) +
bytes(tree_conf.page_size - length)
)
self._write_page_in_tree(0, data, fsync=True)
self._tree_conf = tree_conf
self._root_node_page = root_node_page
def close(self):
self.perform_checkpoint()
self._fd.close()
if self._dir_fd is not None:
os.close(self._dir_fd)
def perform_checkpoint(self, reopen_wal=False):
logger.info('Performing checkpoint of %s', self._filename)
for page, page_data in self._wal.checkpoint():
self._write_page_in_tree(page, page_data, fsync=False)
fsync_file_and_dir(self._fd.fileno(), self._dir_fd)
if reopen_wal:
self._wal = WAL(self._filename, self._tree_conf.page_size)
def _read_page(self, page: int) -> bytes:
start = page * self._tree_conf.page_size
stop = start + self._tree_conf.page_size
assert stop - start == self._tree_conf.page_size
return read_from_file(self._fd, start, stop)
def _write_page_in_tree(self, page: int, data: Union[bytes, bytearray],
fsync: bool=True):
"""Write a page of data in the tree file itself.
To be used during checkpoints and other non-standard uses.
"""
assert len(data) == self._tree_conf.page_size
self._fd.seek(page * self._tree_conf.page_size)
write_to_file(self._fd, self._dir_fd, data, fsync=fsync)
def __repr__(self):
return '<FileMemory: {}>'.format(self._filename)
class FrameType(enum.Enum):
PAGE = 1
COMMIT = 2
ROLLBACK = 3
class WAL:
__slots__ = ['filename', '_fd', '_dir_fd', '_page_size',
'_committed_pages', '_not_committed_pages', 'needs_recovery']
FRAME_HEADER_LENGTH = (
FRAME_TYPE_BYTES + PAGE_REFERENCE_BYTES
)
def __init__(self, filename: str, page_size: int):
self.filename = filename + '-wal'
self._fd, self._dir_fd = open_file_in_dir(self.filename)
self._page_size = page_size
self._committed_pages = dict()
self._not_committed_pages = dict()
self._fd.seek(0, io.SEEK_END)
if self._fd.tell() == 0:
self._create_header()
self.needs_recovery = False
else:
logger.warning('Found an existing WAL file, '
'the B+Tree was not closed properly')
self.needs_recovery = True
self._load_wal()
def checkpoint(self):
"""Transfer the modified data back to the tree and close the WAL."""
if self._not_committed_pages:
logger.warning('Closing WAL with uncommitted data, discarding it')
fsync_file_and_dir(self._fd.fileno(), self._dir_fd)
for page, page_start in self._committed_pages.items():
page_data = read_from_file(
self._fd,
page_start,
page_start + self._page_size
)
yield page, page_data
self._fd.close()
os.unlink(self.filename)
if self._dir_fd is not None:
os.fsync(self._dir_fd)
os.close(self._dir_fd)
def _create_header(self):
data = self._page_size.to_bytes(OTHERS_BYTES, ENDIAN)
self._fd.seek(0)
write_to_file(self._fd, self._dir_fd, data, True)
def _load_wal(self):
self._fd.seek(0)
header_data = read_from_file(self._fd, 0, OTHERS_BYTES)
assert int.from_bytes(header_data, ENDIAN) == self._page_size
while True:
try:
self._load_next_frame()
except ReachedEndOfFile:
break
if self._not_committed_pages:
logger.warning('WAL has uncommitted data, discarding it')
self._not_committed_pages = dict()
def _load_next_frame(self):
start = self._fd.tell()
stop = start + self.FRAME_HEADER_LENGTH
data = read_from_file(self._fd, start, stop)
frame_type = int.from_bytes(data[0:FRAME_TYPE_BYTES], ENDIAN)
page = int.from_bytes(
data[FRAME_TYPE_BYTES:FRAME_TYPE_BYTES+PAGE_REFERENCE_BYTES],
ENDIAN
)
frame_type = FrameType(frame_type)
if frame_type is FrameType.PAGE:
self._fd.seek(stop + self._page_size)
self._index_frame(frame_type, page, stop)
def _index_frame(self, frame_type: FrameType, page: int, page_start: int):
if frame_type is FrameType.PAGE:
self._not_committed_pages[page] = page_start
elif frame_type is FrameType.COMMIT:
self._committed_pages.update(self._not_committed_pages)
self._not_committed_pages = dict()
elif frame_type is FrameType.ROLLBACK:
self._not_committed_pages = dict()
else:
assert False
def _add_frame(self, frame_type: FrameType, page: Optional[int]=None,
page_data: Optional[bytes]=None):
if frame_type is FrameType.PAGE and (not page or not page_data):
raise ValueError('PAGE frame without page data')
if page_data and len(page_data) != self._page_size:
raise ValueError('Page data is different from page size')
if not page:
page = 0
if frame_type is not FrameType.PAGE:
page_data = b''
data = (
frame_type.value.to_bytes(FRAME_TYPE_BYTES, ENDIAN) +
page.to_bytes(PAGE_REFERENCE_BYTES, ENDIAN) +
page_data
)
self._fd.seek(0, io.SEEK_END)
write_to_file(self._fd, self._dir_fd, data,
fsync=frame_type != FrameType.PAGE)
self._index_frame(frame_type, page, self._fd.tell() - self._page_size)
def get_page(self, page: int) -> Optional[bytes]:
page_start = None
for store in (self._not_committed_pages, self._committed_pages):
page_start = store.get(page)
if page_start:
break
if not page_start:
return None
return read_from_file(self._fd, page_start,
page_start + self._page_size)
def set_page(self, page: int, page_data: bytes):
self._add_frame(FrameType.PAGE, page, page_data)
def commit(self):
# Commit is a no-op when there is no uncommitted pages
if self._not_committed_pages:
self._add_frame(FrameType.COMMIT)
def rollback(self):
# Rollback is a no-op when there is no uncommitted pages
if self._not_committed_pages:
self._add_frame(FrameType.ROLLBACK)
def __repr__(self):
return '<WAL: {}>'.format(self.filename)
|
aw_nas/objective/container.py
|
Harald-R/aw_nas
| 195 |
144657
|
from aw_nas.objective.base import BaseObjective
class ContainerObjective(BaseObjective):
NAME = "container"
def __init__(self, search_space, sub_objectives,
losses_coef=None, rewards_coef=None,
schedule_cfg=None):
super().__init__(search_space, schedule_cfg=schedule_cfg)
self.objectives = [
BaseObjective.get_class_(obj["objective_type"])(
search_space, **obj["objective_cfg"]) for obj in sub_objectives
]
self.losses_coef = losses_coef
self.rewards_coef = rewards_coef
if self.losses_coef is None:
self.losses_coef = [1.] * len(self.objectives)
if self.rewards_coef is None:
self.rewards_coef = [1.] * len(self.objectives)
assert len(self.rewards_coef) == len(self.losses_coef) == len(self.objectives), \
("expect rewards_coef and losses_coef have the exactly"
"same length with objectives, got {}, {} and {} instead.").format(
len(rewards_coef), len(self.losses_coef), len(self.objectives))
@classmethod
def supported_data_types(cls):
return ["image"]
def aggregate_fn(self, perf_name, is_training=True):
for obj in self.objectives:
if perf_name in obj.perf_names():
return obj.aggregate_fn(perf_name, is_training)
else:
return super().aggregate_fn(perf_name, is_training)
def perf_names(self):
return sum([obj.perf_names() for obj in self.objectives], [])
def get_perfs(self, inputs, outputs, targets, cand_net):
perfs = []
for obj in self.objectives:
perfs.extend(obj.get_perfs(inputs, outputs, targets, cand_net))
assert len(perfs) == len(self.perf_names()), \
("expect performances have the exactly "
"same length with perf_names, got {} and {} instead.").format(
len(perfs), len(self.perf_names()))
return perfs
def get_loss(self, inputs, outputs, targets, cand_net,
add_controller_regularization=True, add_evaluator_regularization=True):
losses = [
obj.get_loss(
inputs, outputs, targets, cand_net,
add_controller_regularization, add_evaluator_regularization
) for obj in self.objectives
]
weighted_loss = [l * c for l, c in zip(losses, self.losses_coef)]
return sum(weighted_loss)
def get_reward(self, inputs, outputs, targets, cand_net):
rewards = [
obj.get_reward(
inputs, outputs, targets, cand_net
) for obj in self.objectives
]
weighted_rewards = [l * c for l, c in zip(rewards, self.rewards_coef)]
return sum(weighted_rewards)
|
control/gcs/return.py
|
CNRoboComp2020/XTDrone
| 457 |
144658
|
import rospy
import PyKDL
from geometry_msgs.msg import Twist, Point, PoseStamped, TwistStamped
from std_msgs.msg import String
import numpy
import math
import sys
import copy
from gazebo_msgs.srv import GetModelState
class ReturnHome:
def __init__(self,uav_id):
self.uav_type = 'typhoon_h480'
self.id = int(uav_id)
self.uav_num = 6
self.f = 30 # pin lv
self.count = 0
self.local_pose = PoseStamped()
self.following_local_pose = [PoseStamped() for i in range(self.uav_num)]
self.following_local_pose_sub = [None]*(self.uav_num)
self.uav_current_pose = Point()
self.uav_current_yaw = 0.0
self.uav_vel = Twist()
self.arrive_point = False
self.Kp = 0.5
self.Kpy = 1
self.Kpvel = 1
self.z = 12.0 # height
self.velxy_max = 4
self.velz_max = 3
self.angz_max = 3
self.bias = [[-10, 32.7],[100,33.5],[75,30],[60,-3],[-30,-40.5],[45,-15]]
self.target_position = Twist()
self.target_yaw = 0.0
self.last_yaw = 0.0
self.arrive_count = 0
self.safe_dis = 0.3
self.safe_height = 0.5
self.cmd = ''
self.last_ugv0_pose = Point()
self.current_ugv0_pose = Point()
self.last_ugv1_pose = Point()
self.current_ugv1_pose = Point()
self.situation_flag = 0
self.change_task_flag = False
#variables of rostopic
rospy.init_node('uav'+str(self.id))
self.local_pose_sub = rospy.Subscriber(self.uav_type + '_' + str(self.id) + "/mavros/local_position/pose",
PoseStamped, self.local_pose_callback)
self.vel_enu_pub = rospy.Publisher('/xtdrone/'+self.uav_type+'_'+str(self.id)+'/cmd_vel_flu', Twist, queue_size=10)
self.cmd_pub = rospy.Publisher('/xtdrone/'+self.uav_type+'_'+str(self.id)+'/cmd',String,queue_size=10)
self.gazeboModelstate = rospy.ServiceProxy('gazebo/get_model_state', GetModelState)
def local_pose_callback(self, msg):
self.local_pose = msg
self.uav_current_pose = self.local_pose.pose.position
self.uav_current_pose.x = self.uav_current_pose.x+self.bias[self.id][0]
self.uav_current_pose.y = self.uav_current_pose.y+self.bias[self.id][1]
self.uav_current_pose.z = self.uav_current_pose.z
# change Quaternion to TF:
x = self.local_pose.pose.orientation.x
y = self.local_pose.pose.orientation.y
z = self.local_pose.pose.orientation.z
w = self.local_pose.pose.orientation.w
rot = PyKDL.Rotation.Quaternion(x, y, z, w)
res = rot.GetRPY()[2]
while res > math.pi:
res -= 2.0*math.pi
while res < -math.pi:
res += 2.0*math.pi
if res < 0:
res = res + 2.0 * math.pi
self.uav_current_yaw = res # 0 to 2pi
def following_local_pose_callback(self, msg, id):
self.following_local_pose[id] = msg
self.following_local_pose[id].pose.position.x = self.following_local_pose[id].pose.position.x+self.bias[id][0]
self.following_local_pose[id].pose.position.y = self.following_local_pose[id].pose.position.y+self.bias[id][1]
self.following_local_pose[id].pose.position.z = self.following_local_pose[id].pose.position.z
def loop(self):
rate = rospy.Rate(self.f)
count_situ_one = 0
for i in range(self.uav_num):
if not i == self.id:
self.following_local_pose_sub[i] = rospy.Subscriber(self.uav_type + '_' + str(i) + "/mavros/local_position/pose", PoseStamped, self.following_local_pose_callback, i)
while not rospy.is_shutdown():
self.count += 1
self.velxy_max = 4.0
self.cmd = ''
# get position of ugvs:
try:
get_ugv0_state = self.gazeboModelstate('ugv_0', 'ground_plane')
self.last_ugv0_pose = self.current_ugv0_pose
self.current_ugv0_pose = get_ugv0_state.pose.position
get_ugv1_state = self.gazeboModelstate('ugv_1', 'ground_plane')
self.last_ugv1_pose = self.current_ugv1_pose
self.current_ugv1_pose = get_ugv1_state.pose.position
except rospy.ServiceException as e:
print("Gazebo model state service"+" call failed: %s") % e
# fly to the same altitude xian offboard hou arm
if self.count == 40 or self.count == 42 or self.count == 44:
self.cmd = 'OFFBOARD'
if self.count == 94 or self.count == 96 or self.count == 98:
self.cmd = 'ARM'
if self.situation_flag == 0: # ding gao
self.target_position.linear.z = self.z
self.target_position.linear.x = self.uav_current_pose.x
self.target_position.linear.y = self.uav_current_pose.y
self.uav_vel.angular.x = self.uav_vel.angular.x
self.uav_vel.angular.y = self.uav_vel.angular.y
self.uav_vel.angular.z = self.uav_vel.angular.z
if self.situation_flag == 1 and self.change_task_flag: # chu shi hua
self.change_task_flag = False
#if not self.avoid_start_flag:
self.init_point()
if self.situation_flag == 2 and self.change_task_flag: # chu shi hua
self.change_task_flag = False
#if not self.avoid_start_flag:
self.return_home()
print 'flag222222'
distance_tar_cur = self.VectNorm3(self.target_position.linear, self.uav_current_pose)
if distance_tar_cur < 0.5:
self.arrive_count += 1
if self.arrive_count > 5:
self.arrive_point = True
self.arrive_count = 0
else:
self.arrive_point = False
else:
self.arrive_count = 0
self.arrive_point = False
# task changes:
if (self.situation_flag == 0) and self.arrive_point:
self.change_task_flag = True
self.situation_flag = 1
self.arrive_point = False
elif (self.situation_flag == 1) and self.arrive_point:
self.situation_flag = 2
# self.start_yolo_pub.publish('gogogo')
self.arrive_point = False
self.change_task_flag = True
if self.situation_flag == 2:
self.velz_max = 1
if self.uav_current_pose.z < 2.2:
self.target_position.linear.x = self.uav_current_pose.x
self.target_position.linear.y = self.uav_current_pose.y
if self.uav_current_pose.z < 1.9:
self.cmd = 'DISARM'
self.get_control_vel()
# self.obstacle_avoid()
self.vel_enu_pub.publish(self.uav_vel)
self.cmd_pub.publish(self.cmd)
rate.sleep()
def get_control_vel(self): # P kong zhi, flu zuo biao xi
uav_dis_curtar = self.VectNorm2(self.target_position.linear, self.uav_current_pose) #distance
temp = self.VectDiff(self.target_position.linear, self.uav_current_pose) # vector
uav_vel_total = self.Kp * uav_dis_curtar # velocity
if uav_vel_total > self.velxy_max:
uav_vel_total = self.velxy_max
'''
if not uav_dis_curtar == 0.0:
self.uav_vel.linear.x = (temp.x/uav_dis_curtar) * uav_vel_total
self.uav_vel.linear.y = (temp.y/uav_dis_curtar) * uav_vel_total
else:
self.uav_vel.linear.x = 0.0
self.uav_vel.linear.y = 0.0
'''
self.target_yaw = self.pos2ang(self.target_position.linear.x, self.target_position.linear.y, self.uav_current_pose.x, self.uav_current_pose.y)
mid_yaw = self.target_yaw - self.uav_current_yaw
if mid_yaw > math.pi:
mid_yaw = mid_yaw - 2*math.pi
elif mid_yaw < -math.pi:
mid_yaw = 2*math.pi + mid_yaw
self.uav_vel.angular.z = self.Kpy * mid_yaw
if self.uav_vel.angular.z > self.angz_max:
self.uav_vel.angular.z = self.angz_max
elif self.uav_vel.angular.z < -self.angz_max:
self.uav_vel.angular.z = -self.angz_max
self.uav_vel.linear.x = uav_vel_total * math.cos(mid_yaw)
self.uav_vel.linear.y = uav_vel_total * math.sin(mid_yaw)
self.uav_vel.linear.z = self.Kp * (self.target_position.linear.z - self.uav_current_pose.z)
if self.uav_vel.linear.z > self.velz_max:
self.uav_vel.linear.z = self.velz_max
elif self.uav_vel.linear.z < - self.velz_max:
self.uav_vel.linear.z = - self.velz_max
def init_point(self):
if self.id == 0: # middle circle 3
self.target_position.linear.x = self.current_ugv0_pose.x # ugv0 -0.3
self.target_position.linear.y = self.current_ugv0_pose.y-0.2
elif self.id == 1: # middle circle 2
self.target_position.linear.x = self.current_ugv0_pose.x # ugv0 0.5
self.target_position.linear.y = self.current_ugv0_pose.y+0.6
elif self.id == 2: # outer loop 0
self.target_position.linear.x = self.current_ugv0_pose.x #ugv0 1.3
self.target_position.linear.y = self.current_ugv0_pose.y+1.3
elif self.id == 3: # outer loop 4
self.target_position.linear.x = self.current_ugv1_pose.x #ugv1 -0.3
self.target_position.linear.y = self.current_ugv1_pose.y-0.2
elif self.id == 4: # outer loop 1
self.target_position.linear.x = self.current_ugv1_pose.x
self.target_position.linear.y = self.current_ugv1_pose.y+0.6
elif self.id == 5: # outer loop 5
self.target_position.linear.x = self.current_ugv1_pose.x
self.target_position.linear.y = self.current_ugv1_pose.y+1.3
def return_home(self):
self.target_position.linear.z = 0.0
# ji jian bi zhang
def obstacle_avoid(self):
self.avo_id = []
for i in range(self.uav_num):
if not i == self.id:
dis_partner = math.sqrt(
(self.uav_current_pose.x - self.following_local_pose[i].pose.position.x) ** 2 + (self.uav_current_pose.y - self.following_local_pose[i].pose.position.y) ** 2)
if dis_partner < self.safe_dis:
if (self.uav_current_pose.z - self.following_local_pose[i].pose.position.z) < self.safe_height:
self.avo_id.append(i)
avoid_num = len(self.avo_id)
heigher_num = 0
if avoid_num > 0:
for j in range(avoid_num):
if self.following_local_pose[self.avo_id[j]].pose.position.z > self.uav_current_pose.z:
heigher_num = heigher_num + 1
if heigher_num == 0:
self.target_position.linear.z = self.target_position.linear.z + self.safe_height
else:
self.target_position.linear.z = self.target_position.linear.z - self.safe_height * heigher_num
else:
self.target_position.linear.z = self.target_position.linear.z
def pos2ang(self, xa, ya, xb, yb): #([xb,yb] to [xa, ya])
if not xa-xb == 0:
angle = math.atan2((ya - yb),(xa - xb))
if (ya-yb > 0) and (angle < 0):
angle = angle + math.pi
elif (ya-yb < 0) and (angle > 0):
angle = angle - math.pi
elif ya-yb == 0:
if xa-xb > 0:
angle = 0.0
else:
angle = math.pi
else:
if ya-yb > 0:
angle = math.pi / 2
elif ya-yb <0:
angle = -math.pi / 2
else:
angle = 0.0
if angle < 0:
angle = angle + 2 * math.pi # 0 to 2pi
return angle
def VectNorm3(self, Pt1, Pt2):
norm = math.sqrt(pow(Pt1.x - Pt2.x, 2) + pow(Pt1.y - Pt2.y, 2)+ pow(Pt1.z - Pt2.z, 2))
return norm
def VectNorm2(self, Pt1, Pt2):
norm = math.sqrt(pow(Pt1.x - Pt2.x, 2) + pow(Pt1.y - Pt2.y, 2))
return norm
def VectDiff(self, endPt, startPt):
temp = Point()
temp.x = endPt.x - startPt.x
temp.y = endPt.y - startPt.y
return temp
if __name__ == '__main__':
returnhome = ReturnHome(sys.argv[1])
returnhome.loop()
|
tests/sendpkt.py
|
mmjiang2019/ovs
| 2,919 |
144680
|
#!/usr/bin/env python3
# Copyright (c) 2018, 2020 VMware, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# This program can be used send L2-L7 protocol messages using the hex bytes
# of the packet, to test simple protocol scenarios. (e.g. generate simple
# nsh packets to test nsh match fields/actions)
#
# Currently, the script supports sending the packets starting from the
# Ethernet header. As a part of future enchancement, raw ip packet support
# can also be added, and that's why there is "-t"/"--type" option
#
import socket
import sys
from optparse import OptionParser
usage = "usage: %prog [OPTIONS] OUT-INTERFACE HEX-BYTES \n \
bytes in HEX-BYTES must be separated by space(s)"
parser = OptionParser(usage=usage)
parser.add_option("-t", "--type", type="string", dest="packet_type",
help="packet type ('eth' is the default PACKET_TYPE)",
default="eth")
(options, args) = parser.parse_args()
# validate the arguments
if len(args) < 2:
parser.print_help()
sys.exit(1)
# validate the "-t" or "--type" option
if options.packet_type != "eth":
parser.error('invalid argument to "-t"/"--type". Allowed value is "eth".')
# store the hex bytes with 0x appended at the beginning
# if not present in the user input and validate the hex bytes
hex_list = []
for a in args[1:]:
if a[:2] != "0x":
hex_byte = "0x" + a
else:
hex_byte = a
try:
temp = int(hex_byte, 0)
except:
parser.error("invalid hex byte " + a)
if temp > 0xff:
parser.error("hex byte " + a + " cannot be greater than 0xff!")
hex_list.append(temp)
if sys.version_info < (3, 0):
pkt = "".join(map(chr, hex_list))
else:
pkt = bytes(hex_list)
try:
sockfd = socket.socket(socket.AF_PACKET, socket.SOCK_RAW)
except socket.error as msg:
print('unable to create socket! error code: ' + str(msg[0]) + ' : '
+ msg[1])
sys.exit(2)
try:
sockfd.bind((args[0], 0))
except socket.error as msg:
print('unable to bind socket! error code: ' + str(msg[0]) + ' : '
+ msg[1])
sys.exit(2)
try:
sockfd.send(pkt)
except socket.error as msg:
print('unable to send packet! error code: ' + str(msg[0]) + ' : '
+ msg[1])
sys.exit(2)
print('send success!')
sys.exit(0)
|
tests/test_constant.py
|
civilian/django-business-logic
| 160 |
144687
|
# -*- coding: utf-8 -*-
#
from .common import *
class ConstantTest(TestCase):
def test_init(self):
integer_const = NumberConstant(value=33)
self.assertEqual(33, integer_const.value)
def test_str(self):
integer_const = NumberConstant(value=33)
self.assertEqual(str(33), str(integer_const))
def test_interpret(self):
integer_const = NumberConstant(value=33)
context = Context()
self.assertEqual(33, integer_const.interpret(context))
|
freeline/freeline_core/cursor.py
|
xyzmst/rxlist
| 6,094 |
144692
|
# -*- coding:utf8 -*-
from terminal import Terminal
class Cursor(object):
def __init__(self, term=None):
self.term = Terminal() if term is None else term
self._stream = self.term.stream
self._saved = False
def write(self, s):
self._stream.write(s)
def save(self):
self.write(self.term.save)
self._saved = True
def restore(self):
if self._saved:
self.write(self.term.restore)
def flush(self):
self._stream.flush()
def newline(self):
self.write(self.term.move_down)
self.write(self.term.clear_bol)
def clear_lines(self, num_lines=0):
for i in range(num_lines):
self.write(self.term.clear_eol)
self.write(self.term.move_down)
for i in range(num_lines):
self.write(self.term.move_up)
|
test/feature/steps/__init__.py
|
drakejund/contract
| 172 |
144707
|
#
# Copyright IBM Corp. All Rights Reserved.
#
# SPDX-License-Identifier: Apache-2.0
#
|
alipay/aop/api/domain/KoubeiCateringOrderInfoCancelModel.py
|
snowxmas/alipay-sdk-python-all
| 213 |
144741
|
<filename>alipay/aop/api/domain/KoubeiCateringOrderInfoCancelModel.py<gh_stars>100-1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.PosOrderKey import PosOrderKey
class KoubeiCateringOrderInfoCancelModel(object):
def __init__(self):
self._close_time = None
self._pos_order_key = None
@property
def close_time(self):
return self._close_time
@close_time.setter
def close_time(self, value):
self._close_time = value
@property
def pos_order_key(self):
return self._pos_order_key
@pos_order_key.setter
def pos_order_key(self, value):
if isinstance(value, PosOrderKey):
self._pos_order_key = value
else:
self._pos_order_key = PosOrderKey.from_alipay_dict(value)
def to_alipay_dict(self):
params = dict()
if self.close_time:
if hasattr(self.close_time, 'to_alipay_dict'):
params['close_time'] = self.close_time.to_alipay_dict()
else:
params['close_time'] = self.close_time
if self.pos_order_key:
if hasattr(self.pos_order_key, 'to_alipay_dict'):
params['pos_order_key'] = self.pos_order_key.to_alipay_dict()
else:
params['pos_order_key'] = self.pos_order_key
return params
@staticmethod
def from_alipay_dict(d):
if not d:
return None
o = KoubeiCateringOrderInfoCancelModel()
if 'close_time' in d:
o.close_time = d['close_time']
if 'pos_order_key' in d:
o.pos_order_key = d['pos_order_key']
return o
|
PyObjCTest/test_nsoperation.py
|
Khan/pyobjc-framework-Cocoa
| 132 |
144749
|
from Foundation import *
from PyObjCTools.TestSupport import *
try:
unicode
except NameError:
unicode = str
class TestNSOperation (TestCase):
def testConstants(self):
self.assertEqual(NSOperationQueuePriorityVeryLow, -8)
self.assertEqual(NSOperationQueuePriorityLow, -4)
self.assertEqual(NSOperationQueuePriorityNormal, 0)
self.assertEqual(NSOperationQueuePriorityHigh, 4)
self.assertEqual(NSOperationQueuePriorityVeryHigh, 8)
self.assertIsInstance(NSInvocationOperationVoidResultException, unicode)
self.assertIsInstance(NSInvocationOperationCancelledException, unicode)
self.assertEqual(NSOperationQueueDefaultMaxConcurrentOperationCount, -1)
def testMethods(self):
self.assertResultIsBOOL(NSOperation.isCancelled)
self.assertResultIsBOOL(NSOperation.isExecuting)
self.assertResultIsBOOL(NSOperation.isFinished)
self.assertResultIsBOOL(NSOperation.isConcurrent)
self.assertResultIsBOOL(NSOperation.isReady)
self.assertResultIsBOOL(NSOperationQueue.isSuspended)
self.assertArgIsBOOL(NSOperationQueue.setSuspended_, 0)
@min_os_level('10.6')
def testMethods10_6(self):
self.assertResultIsBlock(NSOperation.completionBlock, b'v')
self.assertArgIsBlock(NSOperation.setCompletionBlock_, 0, b'v')
self.assertArgIsBlock(NSBlockOperation.blockOperationWithBlock_, 0, b'v')
self.assertArgIsBlock(NSBlockOperation.addExecutionBlock_, 0, b'v')
self.assertArgIsBOOL(NSOperationQueue.addOperations_waitUntilFinished_, 1)
self.assertArgIsBlock(NSOperationQueue.addOperationWithBlock_, 0, b'v')
if __name__ == "__main__":
main()
|
train.py
|
sharsnik2/grid-cells
| 206 |
144802
|
<gh_stars>100-1000
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Supervised training for the Grid cell network."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import matplotlib
import numpy as np
import tensorflow as tf
import Tkinter # pylint: disable=unused-import
matplotlib.use('Agg')
import dataset_reader # pylint: disable=g-bad-import-order, g-import-not-at-top
import model # pylint: disable=g-bad-import-order
import scores # pylint: disable=g-bad-import-order
import utils # pylint: disable=g-bad-import-order
# Task config
tf.flags.DEFINE_string('task_dataset_info', 'square_room',
'Name of the room in which the experiment is performed.')
tf.flags.DEFINE_string('task_root',
None,
'Dataset path.')
tf.flags.DEFINE_float('task_env_size', 2.2,
'Environment size (meters).')
tf.flags.DEFINE_list('task_n_pc', [256],
'Number of target place cells.')
tf.flags.DEFINE_list('task_pc_scale', [0.01],
'Place cell standard deviation parameter (meters).')
tf.flags.DEFINE_list('task_n_hdc', [12],
'Number of target head direction cells.')
tf.flags.DEFINE_list('task_hdc_concentration', [20.],
'Head direction concentration parameter.')
tf.flags.DEFINE_integer('task_neurons_seed', 8341,
'Seeds.')
tf.flags.DEFINE_string('task_targets_type', 'softmax',
'Type of target, soft or hard.')
tf.flags.DEFINE_string('task_lstm_init_type', 'softmax',
'Type of LSTM initialisation, soft or hard.')
tf.flags.DEFINE_bool('task_velocity_inputs', True,
'Input velocity.')
tf.flags.DEFINE_list('task_velocity_noise', [0.0, 0.0, 0.0],
'Add noise to velocity.')
# Model config
tf.flags.DEFINE_integer('model_nh_lstm', 128, 'Number of hidden units in LSTM.')
tf.flags.DEFINE_integer('model_nh_bottleneck', 256,
'Number of hidden units in linear bottleneck.')
tf.flags.DEFINE_list('model_dropout_rates', [0.5],
'List of floats with dropout rates.')
tf.flags.DEFINE_float('model_weight_decay', 1e-5,
'Weight decay regularisation')
tf.flags.DEFINE_bool('model_bottleneck_has_bias', False,
'Whether to include a bias in linear bottleneck')
tf.flags.DEFINE_float('model_init_weight_disp', 0.0,
'Initial weight displacement.')
# Training config
tf.flags.DEFINE_integer('training_epochs', 1000, 'Number of training epochs.')
tf.flags.DEFINE_integer('training_steps_per_epoch', 1000,
'Number of optimization steps per epoch.')
tf.flags.DEFINE_integer('training_minibatch_size', 10,
'Size of the training minibatch.')
tf.flags.DEFINE_integer('training_evaluation_minibatch_size', 4000,
'Size of the minibatch during evaluation.')
tf.flags.DEFINE_string('training_clipping_function', 'utils.clip_all_gradients',
'Function for gradient clipping.')
tf.flags.DEFINE_float('training_clipping', 1e-5,
'The absolute value to clip by.')
tf.flags.DEFINE_string('training_optimizer_class', 'tf.train.RMSPropOptimizer',
'The optimizer used for training.')
tf.flags.DEFINE_string('training_optimizer_options',
'{"learning_rate": 1e-5, "momentum": 0.9}',
'Defines a dict with opts passed to the optimizer.')
# Store
tf.flags.DEFINE_string('saver_results_directory',
None,
'Path to directory for saving results.')
tf.flags.DEFINE_integer('saver_eval_time', 2,
'Frequency at which results are saved.')
# Require flags
tf.flags.mark_flag_as_required('task_root')
tf.flags.mark_flag_as_required('saver_results_directory')
FLAGS = tf.flags.FLAGS
def train():
"""Training loop."""
tf.reset_default_graph()
# Create the motion models for training and evaluation
data_reader = dataset_reader.DataReader(
FLAGS.task_dataset_info, root=FLAGS.task_root, num_threads=4)
train_traj = data_reader.read(batch_size=FLAGS.training_minibatch_size)
# Create the ensembles that provide targets during training
place_cell_ensembles = utils.get_place_cell_ensembles(
env_size=FLAGS.task_env_size,
neurons_seed=FLAGS.task_neurons_seed,
targets_type=FLAGS.task_targets_type,
lstm_init_type=FLAGS.task_lstm_init_type,
n_pc=FLAGS.task_n_pc,
pc_scale=FLAGS.task_pc_scale)
head_direction_ensembles = utils.get_head_direction_ensembles(
neurons_seed=FLAGS.task_neurons_seed,
targets_type=FLAGS.task_targets_type,
lstm_init_type=FLAGS.task_lstm_init_type,
n_hdc=FLAGS.task_n_hdc,
hdc_concentration=FLAGS.task_hdc_concentration)
target_ensembles = place_cell_ensembles + head_direction_ensembles
# Model creation
rnn_core = model.GridCellsRNNCell(
target_ensembles=target_ensembles,
nh_lstm=FLAGS.model_nh_lstm,
nh_bottleneck=FLAGS.model_nh_bottleneck,
dropoutrates_bottleneck=np.array(FLAGS.model_dropout_rates),
bottleneck_weight_decay=FLAGS.model_weight_decay,
bottleneck_has_bias=FLAGS.model_bottleneck_has_bias,
init_weight_disp=FLAGS.model_init_weight_disp)
rnn = model.GridCellsRNN(rnn_core, FLAGS.model_nh_lstm)
# Get a trajectory batch
input_tensors = []
init_pos, init_hd, ego_vel, target_pos, target_hd = train_traj
if FLAGS.task_velocity_inputs:
# Add the required amount of noise to the velocities
vel_noise = tf.distributions.Normal(0.0, 1.0).sample(
sample_shape=ego_vel.get_shape()) * FLAGS.task_velocity_noise
input_tensors = [ego_vel + vel_noise] + input_tensors
# Concatenate all inputs
inputs = tf.concat(input_tensors, axis=2)
# Replace euclidean positions and angles by encoding of place and hd ensembles
# Note that the initial_conds will be zeros if the ensembles were configured
# to provide that type of initialization
initial_conds = utils.encode_initial_conditions(
init_pos, init_hd, place_cell_ensembles, head_direction_ensembles)
# Encode targets as well
ensembles_targets = utils.encode_targets(
target_pos, target_hd, place_cell_ensembles, head_direction_ensembles)
# Estimate future encoding of place and hd ensembles inputing egocentric vels
outputs, _ = rnn(initial_conds, inputs, training=True)
ensembles_logits, bottleneck, lstm_output = outputs
# Training loss
pc_loss = tf.nn.softmax_cross_entropy_with_logits_v2(
labels=ensembles_targets[0], logits=ensembles_logits[0], name='pc_loss')
hd_loss = tf.nn.softmax_cross_entropy_with_logits_v2(
labels=ensembles_targets[1], logits=ensembles_logits[1], name='hd_loss')
total_loss = pc_loss + hd_loss
train_loss = tf.reduce_mean(total_loss, name='train_loss')
# Optimisation ops
optimizer_class = eval(FLAGS.training_optimizer_class) # pylint: disable=eval-used
optimizer = optimizer_class(**eval(FLAGS.training_optimizer_options)) # pylint: disable=eval-used
grad = optimizer.compute_gradients(train_loss)
clip_gradient = eval(FLAGS.training_clipping_function) # pylint: disable=eval-used
clipped_grad = [
clip_gradient(g, var, FLAGS.training_clipping) for g, var in grad
]
train_op = optimizer.apply_gradients(clipped_grad)
# Store the grid scores
grid_scores = dict()
grid_scores['btln_60'] = np.zeros((FLAGS.model_nh_bottleneck,))
grid_scores['btln_90'] = np.zeros((FLAGS.model_nh_bottleneck,))
grid_scores['btln_60_separation'] = np.zeros((FLAGS.model_nh_bottleneck,))
grid_scores['btln_90_separation'] = np.zeros((FLAGS.model_nh_bottleneck,))
grid_scores['lstm_60'] = np.zeros((FLAGS.model_nh_lstm,))
grid_scores['lstm_90'] = np.zeros((FLAGS.model_nh_lstm,))
# Create scorer objects
starts = [0.2] * 10
ends = np.linspace(0.4, 1.0, num=10)
masks_parameters = zip(starts, ends.tolist())
latest_epoch_scorer = scores.GridScorer(20, data_reader.get_coord_range(),
masks_parameters)
with tf.train.SingularMonitoredSession() as sess:
for epoch in range(FLAGS.training_epochs):
loss_acc = list()
for _ in range(FLAGS.training_steps_per_epoch):
res = sess.run({'train_op': train_op, 'total_loss': train_loss})
loss_acc.append(res['total_loss'])
tf.logging.info('Epoch %i, mean loss %.5f, std loss %.5f', epoch,
np.mean(loss_acc), np.std(loss_acc))
if epoch % FLAGS.saver_eval_time == 0:
res = dict()
for _ in xrange(FLAGS.training_evaluation_minibatch_size //
FLAGS.training_minibatch_size):
mb_res = sess.run({
'bottleneck': bottleneck,
'lstm': lstm_output,
'pos_xy': target_pos
})
res = utils.concat_dict(res, mb_res)
# Store at the end of validation
filename = 'rates_and_sac_latest_hd.pdf'
grid_scores['btln_60'], grid_scores['btln_90'], grid_scores[
'btln_60_separation'], grid_scores[
'btln_90_separation'] = utils.get_scores_and_plot(
latest_epoch_scorer, res['pos_xy'], res['bottleneck'],
FLAGS.saver_results_directory, filename)
def main(unused_argv):
tf.logging.set_verbosity(3) # Print INFO log messages.
train()
if __name__ == '__main__':
tf.app.run()
|
tests/test_parser.py
|
transfluxus/jsonpath-ng
| 339 |
144805
|
from __future__ import unicode_literals, print_function, absolute_import, division, generators, nested_scopes
import unittest
from jsonpath_ng.lexer import JsonPathLexer
from jsonpath_ng.parser import JsonPathParser
from jsonpath_ng.jsonpath import *
class TestParser(unittest.TestCase):
# TODO: This will be much more effective with a few regression tests and `arbitrary` parse . pretty testing
@classmethod
def setup_class(cls):
logging.basicConfig()
def check_parse_cases(self, test_cases):
parser = JsonPathParser(debug=True, lexer_class=lambda:JsonPathLexer(debug=False)) # Note that just manually passing token streams avoids this dep, but that sucks
for string, parsed in test_cases:
print(string, '=?=', parsed) # pytest captures this and we see it only on a failure, for debugging
assert parser.parse(string) == parsed
def test_atomic(self):
self.check_parse_cases([('foo', Fields('foo')),
('*', Fields('*')),
('baz,bizzle', Fields('baz','bizzle')),
('[1]', Index(1)),
('[1:]', Slice(start=1)),
('[:]', Slice()),
('[*]', Slice()),
('[:2]', Slice(end=2)),
('[1:2]', Slice(start=1, end=2)),
('[5:-2]', Slice(start=5, end=-2))
])
def test_nested(self):
self.check_parse_cases([('foo.baz', Child(Fields('foo'), Fields('baz'))),
('foo.baz,bizzle', Child(Fields('foo'), Fields('baz', 'bizzle'))),
('foo where baz', Where(Fields('foo'), Fields('baz'))),
('foo..baz', Descendants(Fields('foo'), Fields('baz'))),
('foo..baz.bing', Descendants(Fields('foo'), Child(Fields('baz'), Fields('bing'))))])
|
learn_to_infer/metrics.py
|
deepneuralmachine/google-research
| 23,901 |
144811
|
# coding=utf-8
# Copyright 2021 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Functions for computing performance metrics of various inference methods.
"""
import collections
import functools
import itertools
import jax
import jax.numpy as jnp
import numpy as onp
import sklearn
import sklearn.cluster
import sklearn.metrics
import sklearn.mixture
def accuracy(preds, labels, unused_num_modes):
return onp.mean(preds == labels)
@functools.partial(onp.vectorize, signature="(n)->(m)")
def to_pairwise(x):
pairwise = x[onp.newaxis, :] == x[:, onp.newaxis]
return pairwise[onp.tril_indices_from(pairwise, k=-1)]
def pairwise_accuracy(preds, labels, unused_num_modes):
preds = to_pairwise(preds)
labels = to_pairwise(labels)
return jnp.mean(preds == labels)
def permutation_invariant_accuracy(preds, labels, num_modes):
permutations = jnp.array(list(itertools.permutations(range(num_modes))))
permuted_labels = jax.lax.map(lambda p: p[labels], permutations)
acc = jnp.max(
jax.lax.map(lambda ls: jnp.mean(ls == preds), permuted_labels))
return acc
def pairwise_f1(preds, labels, unused_num_modes):
preds = to_pairwise(preds)
labels = to_pairwise(labels)
return binary_f1(preds, labels, unused_num_modes)
def pairwise_micro_f1(preds, labels, unused_num_modes):
preds = to_pairwise(preds)
labels = to_pairwise(labels)
return micro_f1(preds, labels, unused_num_modes)
def pairwise_macro_f1(preds, labels, unused_num_modes):
preds = to_pairwise(preds)
labels = to_pairwise(labels)
return macro_f1(preds, labels, unused_num_modes)
def binary_f1(preds, labels, unused_num_modes):
return sklearn.metrics.f1_score(labels, preds, average="binary")
def macro_f1(preds, labels, unused_num_modes):
return sklearn.metrics.f1_score(labels, preds, average="macro")
def micro_f1(preds, labels, unused_num_modes):
return sklearn.metrics.f1_score(labels, preds, average="micro")
def permutation_invariant_binary_f1(preds, labels, unused_num_modes):
f1_pos = binary_f1(preds, labels, unused_num_modes)
permuted_predictions = onp.array([1, 0])[preds]
f1_neg = binary_f1(permuted_predictions, labels, unused_num_modes)
return onp.maximum(onp.mean(f1_pos), onp.mean(f1_neg))
METRIC_FNS = {
"accuracy": accuracy,
"pairwise_accuracy": pairwise_accuracy,
"permutation_invariant_accuracy": permutation_invariant_accuracy,
"binary_f1": binary_f1,
"permutation_invariant_binary_f1": permutation_invariant_binary_f1,
"pairwise_f1": pairwise_f1,
"micro_f1": micro_f1,
"macro_f1": macro_f1,
"pairwise_micro_f1": pairwise_micro_f1,
"pairwise_macro_f1": pairwise_macro_f1
}
def em_fit_and_predict(xs, num_modes):
return sklearn.mixture.GaussianMixture(
n_components=num_modes,
covariance_type="full",
init_params="kmeans",
n_init=3).fit_predict(xs)
def spectral_rbf_fit_and_predict(xs, num_modes):
return sklearn.cluster.SpectralClustering(
n_clusters=num_modes,
n_init=3,
affinity="rbf").fit_predict(xs)
def agglomerative_fit_and_predict(xs, num_modes):
return sklearn.cluster.AgglomerativeClustering(
n_clusters=num_modes,
affinity="euclidean").fit_predict(xs)
METHODS = {"em": em_fit_and_predict,
"spectral_rbf": spectral_rbf_fit_and_predict,
"agglomerative": agglomerative_fit_and_predict}
def compute_baseline_metrics(xs, cs,
num_modes,
predict_fns=METHODS,
metrics=[
"pairwise_accuracy", "pairwise_f1",
"pairwise_micro_f1", "pairwise_macro_f1"
]):
batch_size = xs.shape[0]
metric_lists = collections.defaultdict(lambda: collections.defaultdict(list))
for i in range(batch_size):
for name, predict_fn in predict_fns.items():
predicted_cs = predict_fn(xs[i], num_modes)
for metric_name in metrics:
m = METRIC_FNS[metric_name](predicted_cs, cs[i], num_modes)
metric_lists[name][metric_name].append(m)
avg_metrics = collections.defaultdict(dict)
for method_name, metric_dict in metric_lists.items():
for metric_name, metric_list in metric_dict.items():
avg_metrics[method_name][metric_name] = onp.mean(metric_list)
return avg_metrics
def compute_metrics(cs, pred_cs, num_modes,
metrics=["pairwise_accuracy", "pairwise_f1",
"pairwise_micro_f1", "pairwise_macro_f1"]):
batch_size = cs.shape[0]
metric_lists = collections.defaultdict(list)
for i in range(batch_size):
for metric_name in metrics:
m = METRIC_FNS[metric_name](pred_cs[i], cs[i], num_modes)
metric_lists[metric_name].append(m)
avg_metrics = {}
for metric_name, metric_list in metric_lists.items():
avg_metrics[metric_name] = onp.mean(metric_list)
return avg_metrics
def compute_masked_metrics(cs, pred_cs, num_modes, num_points,
metrics=["pairwise_accuracy", "pairwise_f1",
"pairwise_micro_f1", "pairwise_macro_f1"]):
batch_size = cs.shape[0]
metric_lists = collections.defaultdict(list)
for i in range(batch_size):
for metric_name in metrics:
m = METRIC_FNS[metric_name](pred_cs[i, :num_points[i]],
cs[i, :num_points[i]], num_modes[i])
metric_lists[metric_name].append(m)
avg_metrics = {}
for metric_name, metric_list in metric_lists.items():
avg_metrics[metric_name] = onp.mean(metric_list)
return avg_metrics
def compute_masked_baseline_metrics(xs, cs, num_modes, num_points,
predict_fns=METHODS,
metrics=[
"pairwise_accuracy", "pairwise_f1",
"pairwise_micro_f1", "pairwise_macro_f1"
]):
batch_size = xs.shape[0]
metric_lists = collections.defaultdict(lambda: collections.defaultdict(list))
for i in range(batch_size):
for name, predict_fn in predict_fns.items():
predicted_cs = predict_fn(xs[i, :num_points[i]], num_modes[i])
for metric_name in metrics:
m = METRIC_FNS[metric_name](predicted_cs,
cs[i, :num_points[i]],
num_modes[i])
metric_lists[name][metric_name].append(m)
avg_metrics = collections.defaultdict(dict)
for method_name, metric_dict in metric_lists.items():
for metric_name, metric_list in metric_dict.items():
avg_metrics[method_name][metric_name] = onp.mean(metric_list)
return avg_metrics
|
selenium__examples/get_html_source.py
|
DazEB2/SimplePyScripts
| 117 |
144818
|
<reponame>DazEB2/SimplePyScripts
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
# pip install selenium
from selenium import webdriver
driver = webdriver.Firefox()
driver.get('https://www.youtube.com/')
print('Title: "{}"'.format(driver.title))
html = driver.page_source
print('Length:', len(html))
open('driver.page_source.html', 'w').write(html)
driver.quit()
|
torchbenchmark/models/fastNLP/fastNLP/doc_utils.py
|
Chillee/benchmark
| 2,693 |
144835
|
r"""undocumented
用于辅助生成 fastNLP 文档的代码
"""
__all__ = []
import inspect
import sys
def doc_process(m):
for name, obj in inspect.getmembers(m):
if inspect.isclass(obj) or inspect.isfunction(obj):
if obj.__module__ != m.__name__:
if obj.__doc__ is None:
# print(name, obj.__doc__)
pass
else:
module_name = obj.__module__
# 识别并标注类和函数在不同层次中的位置
while 1:
defined_m = sys.modules[module_name]
try:
if "undocumented" not in defined_m.__doc__ and name in defined_m.__all__:
obj.__doc__ = r"别名 :class:`" + m.__name__ + "." + name + "`" \
+ " :class:`" + module_name + "." + name + "`\n" + obj.__doc__
break
module_name = ".".join(module_name.split('.')[:-1])
if module_name == m.__name__:
# print(name, ": not found defined doc.")
break
except:
print("Warning: Module {} lacks `__doc__`".format(module_name))
break
# 识别并标注基类,只有基类也在 fastNLP 中定义才显示
if inspect.isclass(obj):
for base in obj.__bases__:
if base.__module__.startswith("fastNLP"):
parts = base.__module__.split(".") + []
module_name, i = "fastNLP", 1
for i in range(len(parts) - 1):
defined_m = sys.modules[module_name]
try:
if "undocumented" not in defined_m.__doc__ and name in defined_m.__all__:
obj.__doc__ = r"基类 :class:`" + defined_m.__name__ + "." + base.__name__ + "` \n\n" + obj.__doc__
break
module_name += "." + parts[i + 1]
except:
print("Warning: Module {} lacks `__doc__`".format(module_name))
break
|
slack/web/classes/attachments.py
|
timgates42/python-slack-sdk
| 2,486 |
144848
|
<filename>slack/web/classes/attachments.py
from slack_sdk.models.attachments import Attachment # noqa
from slack_sdk.models.attachments import AttachmentField # noqa
from slack_sdk.models.attachments import BlockAttachment # noqa
from slack_sdk.models.attachments import InteractiveAttachment # noqa
from slack_sdk.models.attachments import SeededColors # noqa
from slack import deprecation
deprecation.show_message(__name__, "slack_sdk.models.attachments")
|
Chapter08_Hardware-Interrupts/capSense/serialScope.py
|
anseljh/AVR-Programming
| 608 |
144853
|
<gh_stars>100-1000
import serial
def readValue(serialPort):
return(ord(serialPort.read(1)))
def plotValue(value):
""" Displays the value on a scaled scrolling bargraph"""
leadingSpaces = "-" * int(value*(SCREEN_WIDTH-3) / 255)
print(f"{leadingSpaces} {value:03}")
def cheapoScope(serialPort):
while(1):
newValue = readValue(serialPort)
plotValue(newValue)
if __name__ == "__main__":
## list all serial ports being used: python -m serial.tools.list_ports
PORT = '/dev/ttyUSB0' # update to whatever port is listed in serial.tools.list_ports
BAUDRATE = 9600
TIMEOUT = None
SCREEN_WIDTH = 80
## Take command-line arguments to override defaults above
import sys
if len(sys.argv) == 3:
port = sys.argv[1]
baudrate = int(sys.argv[2])
else: # nothing passed, use defaults
print ("Optional arguments port, baudrate set to defaults.")
port, baudrate = (PORT, BAUDRATE)
serialPort = serial.Serial(port, baudrate, timeout=TIMEOUT)
serialPort.flush()
cheapoScope(serialPort)
|
stanza/tests/test_pipeline_ner_processor.py
|
asears/stanza
| 3,633 |
144855
|
import pytest
import stanza
from stanza.utils.conll import CoNLL
from stanza.models.common.doc import Document
from stanza.tests import *
pytestmark = [pytest.mark.pipeline, pytest.mark.travis]
# data for testing
EN_DOCS = ["<NAME> was born in Hawaii.", "He was elected president in 2008.", "Obama attended Harvard."]
EXPECTED_ENTS = [[{
"text": "<NAME>",
"type": "PERSON",
"start_char": 0,
"end_char": 12
}, {
"text": "Hawaii",
"type": "GPE",
"start_char": 25,
"end_char": 31
}],
[{
"text": "2008",
"type": "DATE",
"start_char": 28,
"end_char": 32
}],
[{
"text": "Obama",
"type": "PERSON",
"start_char": 0,
"end_char": 5
}, {
"text": "Harvard",
"type": "ORG",
"start_char": 15,
"end_char": 22
}]]
@pytest.fixture(scope="module")
def pipeline():
"""
A reusable pipeline with the NER module
"""
return stanza.Pipeline(dir=TEST_MODELS_DIR, processors="tokenize,ner")
@pytest.fixture(scope="module")
def processed_doc(pipeline):
""" Document created by running full English pipeline on a few sentences """
return [pipeline(text) for text in EN_DOCS]
@pytest.fixture(scope="module")
def processed_bulk(pipeline):
""" Document created by running full English pipeline on a few sentences """
docs = [Document([], text=t) for t in EN_DOCS]
return pipeline(docs)
def check_entities_equal(doc, expected):
"""
Checks that the entities of a doc are equal to the given list of maps
"""
assert len(doc.ents) == len(expected)
for doc_entity, expected_entity in zip(doc.ents, expected):
for k in expected_entity:
assert getattr(doc_entity, k) == expected_entity[k]
def test_bulk_ents(processed_bulk):
assert len(processed_bulk) == len(EXPECTED_ENTS)
for doc, expected in zip(processed_bulk, EXPECTED_ENTS):
check_entities_equal(doc, expected)
def test_ents(processed_doc):
assert len(processed_doc) == len(EXPECTED_ENTS)
for doc, expected in zip(processed_doc, EXPECTED_ENTS):
check_entities_equal(doc, expected)
|
objectives.py
|
ShuaiW/kaggle-heart
| 182 |
144865
|
<filename>objectives.py
"""Library implementing different objective functions.
"""
import numpy as np
import lasagne
import theano
import theano.tensor as T
import theano_printer
import utils
class TargetVarDictObjective(object):
def __init__(self, input_layers, penalty=0):
try:
self.target_vars
except:
self.target_vars = dict()
self.penalty = penalty
def get_loss(self, average=True, *args, **kwargs):
"""Compute the loss in Theano.
Args:
average: Indicates whether the loss should already be averaged over the batch.
If not, call the compute_average method on the aggregated losses.
"""
raise NotImplementedError
def compute_average(self, losses, loss_name=""):
"""Averages the aggregated losses in Numpy."""
return losses.mean(axis=0)
def get_kaggle_loss(self, average=True, *args, **kwargs):
"""Computes the CRPS score in Theano."""
return theano.shared([-1])
def get_segmentation_loss(self, average=True, *args, **kwargs):
return theano.shared([-1])
class KaggleObjective(TargetVarDictObjective):
"""
This is the objective as defined by Kaggle: https://www.kaggle.com/c/second-annual-data-science-bowl/details/evaluation
"""
def __init__(self, input_layers, *args, **kwargs):
super(KaggleObjective, self).__init__(input_layers, *args, **kwargs)
self.input_systole = input_layers["systole"]
self.input_diastole = input_layers["diastole"]
self.target_vars["systole"] = T.fmatrix("systole_target")
self.target_vars["diastole"] = T.fmatrix("diastole_target")
def get_loss(self, average=True, other_losses={}, *args, **kwargs):
network_systole = lasagne.layers.helper.get_output(self.input_systole, *args, **kwargs)
network_diastole = lasagne.layers.helper.get_output(self.input_diastole, *args, **kwargs)
systole_target = self.target_vars["systole"]
diastole_target = self.target_vars["diastole"]
CRPS_systole = T.mean((network_systole - systole_target)**2, axis=(1,))
CRPS_diastole = T.mean((network_diastole - diastole_target)**2, axis=(1,))
loss = 0.5*CRPS_systole + 0.5*CRPS_diastole
if average:
loss = T.mean(loss, axis=(0,))
CRPS_systole = T.mean(CRPS_systole, axis=(0,))
CRPS_diastole = T.mean(CRPS_diastole, axis=(0,))
other_losses['CRPS_systole'] = CRPS_systole
other_losses['CRPS_diastole'] = CRPS_diastole
return loss + self.penalty
#def get_kaggle_loss(self, *args, **kwargs):
# return self.get_loss(*args, **kwargs)
class MeanKaggleObjective(TargetVarDictObjective):
"""
This is the objective as defined by Kaggle: https://www.kaggle.com/c/second-annual-data-science-bowl/details/evaluation
"""
def __init__(self, input_layers, *args, **kwargs):
super(MeanKaggleObjective, self).__init__(input_layers, *args, **kwargs)
self.input_average = input_layers["average"]
self.target_vars["average"] = T.fmatrix("average_target")
self.input_systole = input_layers["systole"]
self.input_diastole = input_layers["diastole"]
self.target_vars["systole"] = T.fmatrix("systole_target")
self.target_vars["diastole"] = T.fmatrix("diastole_target")
def get_loss(self, average=True, other_losses={}, *args, **kwargs):
network_average = lasagne.layers.helper.get_output(self.input_average, *args, **kwargs)
network_systole = lasagne.layers.helper.get_output(self.input_systole, *args, **kwargs)
network_diastole = lasagne.layers.helper.get_output(self.input_diastole, *args, **kwargs)
average_target = self.target_vars["average"]
systole_target = self.target_vars["systole"]
diastole_target = self.target_vars["diastole"]
CRPS_average = T.mean((network_average - average_target)**2, axis=(1,))
CRPS_systole = T.mean((network_systole - systole_target)**2, axis=(1,))
CRPS_diastole = T.mean((network_diastole - diastole_target)**2, axis=(1,))
loss = 0.2*CRPS_average + 0.4*CRPS_systole + 0.4*CRPS_diastole
if average:
loss = T.mean(loss, axis=(0,))
CRPS_average = T.mean(CRPS_average, axis=(0,))
CRPS_systole = T.mean(CRPS_systole, axis=(0,))
CRPS_diastole = T.mean(CRPS_diastole, axis=(0,))
other_losses['CRPS_average'] = CRPS_average
other_losses['CRPS_systole'] = CRPS_systole
other_losses['CRPS_diastole'] = CRPS_diastole
return loss + self.penalty
#def get_kaggle_loss(self, *args, **kwargs):
# return self.get_loss(*args, **kwargs)
class MSEObjective(TargetVarDictObjective):
def __init__(self, input_layers, *args, **kwargs):
super(MSEObjective, self).__init__(input_layers, *args, **kwargs)
self.input_systole = input_layers["systole:value"]
self.input_diastole = input_layers["diastole:value"]
self.target_vars["systole:value"] = T.fvector("systole_target_value")
self.target_vars["diastole:value"] = T.fvector("diastole_target_value")
def get_loss(self, average=True, *args, **kwargs):
network_systole = lasagne.layers.helper.get_output(self.input_systole, *args, **kwargs)[:,0]
network_diastole = lasagne.layers.helper.get_output(self.input_diastole, *args, **kwargs)[:,0]
systole_target = self.target_vars["systole:value"]
diastole_target = self.target_vars["diastole:value"]
loss = 0.5 * (network_systole - systole_target )**2 + 0.5 * (network_diastole - diastole_target)**2
if average:
loss = T.mean(loss, axis=(0,))
return loss + self.penalty
class RMSEObjective(TargetVarDictObjective):
def __init__(self, input_layers, *args, **kwargs):
super(RMSEObjective, self).__init__(input_layers, *args, **kwargs)
self.input_systole = input_layers["systole:value"]
self.input_diastole = input_layers["diastole:value"]
self.target_vars["systole:value"] = T.fvector("systole_target_value")
self.target_vars["diastole:value"] = T.fvector("diastole_target_value")
def get_loss(self, average=True, *args, **kwargs):
network_systole = lasagne.layers.helper.get_output(self.input_systole, *args, **kwargs)[:,0]
network_diastole = lasagne.layers.helper.get_output(self.input_diastole, *args, **kwargs)[:,0]
systole_target = self.target_vars["systole:value"]
diastole_target = self.target_vars["diastole:value"]
loss = 0.5 * (network_systole - systole_target) ** 2 + 0.5 * (network_diastole - diastole_target)**2
if average:
loss = T.sqrt(T.mean(loss, axis=(0,)))
return loss
def compute_average(self, aggregate):
return np.sqrt(np.mean(aggregate, axis=0))
def get_kaggle_loss(self, validation=False, average=True, *args, **kwargs):
if not validation: # only evaluate this one in the validation step
return theano.shared([-1])
network_systole = utils.theano_mu_sigma_erf(lasagne.layers.helper.get_output(self.input_systole, *args, **kwargs)[:,0],
lasagne.layers.helper.get_output(self.input_systole_sigma, *args, **kwargs)[:,0])
network_diastole = utils.theano_mu_sigma_erf(lasagne.layers.helper.get_output(self.input_diastole, *args, **kwargs)[:,0],
lasagne.layers.helper.get_output(self.input_diastole_sigma, *args, **kwargs)[:,0])
systole_target = self.target_vars["systole"]
diastole_target = self.target_vars["diastole"]
if not average:
CRPS = (T.mean((network_systole - systole_target)**2, axis = (1,)) +
T.mean((network_diastole - diastole_target)**2, axis = (1,)) )/2
return CRPS
else:
CRPS = (T.mean((network_systole - systole_target)**2, axis = (0,1)) +
T.mean((network_diastole - diastole_target)**2, axis = (0,1)) )/2
return CRPS
class KaggleValidationMSEObjective(MSEObjective):
"""
This is the objective as defined by Kaggle: https://www.kaggle.com/c/second-annual-data-science-bowl/details/evaluation
"""
def __init__(self, input_layers, *args, **kwargs):
super(KaggleValidationMSEObjective, self).__init__(input_layers, *args, **kwargs)
self.target_vars["systole"] = T.fmatrix("systole_target_kaggle")
self.target_vars["diastole"] = T.fmatrix("diastole_target_kaggle")
def get_kaggle_loss(self, validation=False, average=True, *args, **kwargs):
if not validation: # only evaluate this one in the validation step
return theano.shared([-1])
sigma = T.sqrt(self.get_loss() - self.penalty)
network_systole = utils.theano_mu_sigma_erf(lasagne.layers.helper.get_output(self.input_systole, *args, **kwargs)[:,0],
sigma)
network_diastole = utils.theano_mu_sigma_erf(lasagne.layers.helper.get_output(self.input_diastole, *args, **kwargs)[:,0],
sigma)
systole_target = self.target_vars["systole"]
diastole_target = self.target_vars["diastole"]
if not average:
CRPS = (T.mean((network_systole - systole_target)**2, axis = (1,)) +
T.mean((network_diastole - diastole_target)**2, axis = (1,)) )/2
return CRPS
else:
CRPS = (T.mean((network_systole - systole_target)**2, axis = (0,1)) +
T.mean((network_diastole - diastole_target)**2, axis = (0,1)) )/2
return CRPS
def _theano_pdf_to_cdf(pdfs):
return T.extra_ops.cumsum(pdfs, axis=1)
def _crps(cdfs1, cdfs2):
return T.mean((cdfs1 - cdfs2)**2, axis=(1,))
class LogLossObjective(TargetVarDictObjective):
def __init__(self, input_layers, *args, **kwargs):
super(LogLossObjective, self).__init__(input_layers, *args, **kwargs)
self.input_systole = input_layers["systole:onehot"]
self.input_diastole = input_layers["diastole:onehot"]
self.target_vars["systole:onehot"] = T.fmatrix("systole_target_onehot")
self.target_vars["diastole:onehot"] = T.fmatrix("diastole_target_onehot")
def get_loss(self, average=True, other_losses={}, *args, **kwargs):
network_systole = lasagne.layers.helper.get_output(self.input_systole, *args, **kwargs)
network_diastole = lasagne.layers.helper.get_output(self.input_diastole, *args, **kwargs)
systole_target = self.target_vars["systole:onehot"]
diastole_target = self.target_vars["diastole:onehot"]
ll_sys = log_loss(network_systole, systole_target)
ll_dia = log_loss(network_diastole, diastole_target)
ll = 0.5 * ll_sys + 0.5 * ll_dia
# CRPS scores
cdf = _theano_pdf_to_cdf
CRPS_systole = _crps(cdf(network_systole), cdf(systole_target))
CRPS_diastole = _crps(cdf(network_diastole), cdf(diastole_target))
if average:
ll = T.mean(ll, axis=(0,))
CRPS_systole = T.mean(CRPS_systole, axis=(0,))
CRPS_diastole = T.mean(CRPS_diastole, axis=(0,))
other_losses['CRPS_systole'] = CRPS_systole
other_losses['CRPS_diastole'] = CRPS_diastole
return ll + self.penalty
class KaggleValidationLogLossObjective(LogLossObjective):
"""
This is the objective as defined by Kaggle: https://www.kaggle.com/c/second-annual-data-science-bowl/details/evaluation
"""
def __init__(self, input_layers, *args, **kwargs):
super(KaggleValidationLogLossObjective, self).__init__(input_layers, *args, **kwargs)
self.target_vars["systole"] = T.fmatrix("systole_target_kaggle")
self.target_vars["diastole"] = T.fmatrix("diastole_target_kaggle")
def get_kaggle_loss(self, validation=False, average=True, *args, **kwargs):
if not validation:
return theano.shared([-1])
network_systole = T.clip(T.extra_ops.cumsum(lasagne.layers.helper.get_output(self.input_systole, *args, **kwargs), axis=1), 0.0, 1.0)
network_diastole = T.clip(T.extra_ops.cumsum(lasagne.layers.helper.get_output(self.input_diastole, *args, **kwargs), axis=1), 0.0, 1.0)
systole_target = self.target_vars["systole"]
diastole_target = self.target_vars["diastole"]
if not average:
CRPS = (T.mean((network_systole - systole_target)**2, axis = (1,)) +
T.mean((network_diastole - diastole_target)**2, axis = (1,)) )/2
return CRPS
else:
CRPS = (T.mean((network_systole - systole_target)**2, axis = (0,1)) +
T.mean((network_diastole - diastole_target)**2, axis = (0,1)) )/2
return CRPS
def log_loss(y, t, eps=1e-7):
"""
cross entropy loss, summed over classes, mean over batches
"""
y = T.clip(y, eps, 1 - eps)
loss = -T.mean(t * np.log(y) + (1-t) * np.log(1-y), axis=(1,))
return loss
class WeightedLogLossObjective(TargetVarDictObjective):
def __init__(self, input_layers, *args, **kwargs):
super(WeightedLogLossObjective, self).__init__(input_layers, *args, **kwargs)
self.input_systole = input_layers["systole:onehot"]
self.input_diastole = input_layers["diastole:onehot"]
self.target_vars["systole"] = T.fmatrix("systole_target")
self.target_vars["diastole"] = T.fmatrix("diastole_target")
self.target_vars["systole:onehot"] = T.fmatrix("systole_target_onehot")
self.target_vars["diastole:onehot"] = T.fmatrix("diastole_target_onehot")
self.target_vars["systole:class_weight"] = T.fmatrix("systole_target_weights")
self.target_vars["diastole:class_weight"] = T.fmatrix("diastole_target_weights")
def get_loss(self, *args, **kwargs):
network_systole = lasagne.layers.helper.get_output(self.input_systole, *args, **kwargs)
network_diastole = lasagne.layers.helper.get_output(self.input_diastole, *args, **kwargs)
systole_target = self.target_vars["systole:onehot"]
diastole_target = self.target_vars["diastole:onehot"]
systole_weights = self.target_vars["systole:class_weight"]
diastole_weights = self.target_vars["diastole:class_weight"]
if "average" in kwargs and not kwargs["average"]:
ll = 0.5 * weighted_log_loss(network_systole, systole_target, weights=systole_weights) + \
0.5 * weighted_log_loss(network_diastole, diastole_target, weights=diastole_weights)
return ll
ll = 0.5 * T.mean(weighted_log_loss(network_systole, systole_target, weights=systole_weights), axis = (0,)) + \
0.5 * T.mean(weighted_log_loss(network_diastole, diastole_target, weights=diastole_weights), axis = (0,))
return ll + self.penalty
def get_kaggle_loss(self, validation=False, average=True, *args, **kwargs):
if not validation:
return theano.shared([-1])
network_systole = T.clip(T.extra_ops.cumsum(lasagne.layers.helper.get_output(self.input_systole, *args, **kwargs), axis=1), 0.0, 1.0).astype('float32')
network_diastole = T.clip(T.extra_ops.cumsum(lasagne.layers.helper.get_output(self.input_diastole, *args, **kwargs), axis=1), 0.0, 1.0).astype('float32')
systole_target = self.target_vars["systole"].astype('float32')
diastole_target = self.target_vars["diastole"].astype('float32')
if not average:
CRPS = T.mean((network_systole - systole_target)**2 + (network_diastole - diastole_target)**2, axis = 1)/2
return CRPS
else:
CRPS = (T.mean((network_systole - systole_target)**2, axis = (0,1)) +
T.mean((network_diastole - diastole_target)**2, axis = (0,1)) )/2
theano_printer.print_me_this("CRPS", CRPS)
return CRPS
def weighted_log_loss(y, t, weights, eps=1e-7):
"""
cross entropy loss, summed over classes, mean over batches
"""
y = T.clip(y, eps, 1 - eps)
loss = -T.mean(weights * (t * np.log(y) + (1-t) * np.log(1-y)), axis=(1,))
return loss
class BinaryCrossentropyImageObjective(TargetVarDictObjective):
def __init__(self, input_layers, *args, **kwargs):
super(BinaryCrossentropyImageObjective, self).__init__(input_layers, *args, **kwargs)
self.input_layer = input_layers["segmentation"]
self.target_vars = dict()
self.target_vars["segmentation"] = T.ftensor3("segmentation_target")
def get_loss(self, *args, **kwargs):
network_output = lasagne.layers.helper.get_output(self.input_layer, *args, **kwargs)
segmentation_target = self.target_vars["segmentation"]
if "average" in kwargs and not kwargs["average"]:
loss = log_loss( network_output.flatten(ndim=2), segmentation_target.flatten(ndim=2) )
return loss
return T.mean(log_loss(network_output.flatten(ndim=2), segmentation_target.flatten(ndim=2))) + self.penalty
class MixedKaggleSegmentationObjective(KaggleObjective, BinaryCrossentropyImageObjective):
def __init__(self, input_layers, segmentation_weight=1.0, *args, **kwargs):
super(MixedKaggleSegmentationObjective, self).__init__(input_layers, *args, **kwargs)
self.segmentation_weight = segmentation_weight
def get_loss(self, *args, **kwargs):
return self.get_kaggle_loss(*args, **kwargs) + self.segmentation_weight * self.get_segmentation_loss(*args, **kwargs)
def get_kaggle_loss(self, *args, **kwargs):
return KaggleObjective.get_loss(self, *args, **kwargs)
def get_segmentation_loss(self, *args, **kwargs):
return BinaryCrossentropyImageObjective.get_loss(self, *args, **kwargs)
class UpscaledImageObjective(BinaryCrossentropyImageObjective):
def get_loss(self, *args, **kwargs):
network_output = lasagne.layers.helper.get_output(self.input_layer, *args, **kwargs)
segmentation_target = self.target_vars["segmentation"]
return log_loss(network_output.flatten(ndim=2), segmentation_target[:,fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b,4::8].flatten(ndim=2)) + self.penalty
class R2Objective(TargetVarDictObjective):
def __init__(self, input_layers, *args, **kwargs):
super(R2Objective, self).__init__(input_layers, *args, **kwargs)
self.input_systole = input_layers["systole"]
self.input_diastole = input_layers["diastole"]
self.target_vars["systole"] = T.fvector("systole_target")
self.target_vars["diastole"] = T.fvector("diastole_target")
def get_loss(self, *args, **kwargs):
network_systole = lasagne.layers.helper.get_output(self.input_systole, *args, **kwargs)
network_diastole = lasagne.layers.helper.get_output(self.input_diastole, *args, **kwargs)
systole_target = self.target_vars["systole"]
diastole_target = self.target_vars["diastole"]
return T.sum((network_diastole-diastole_target)**2) + T.sum((network_systole-systole_target)**2) + self.penalty
|
api/v2/serializers/fields/tag.py
|
simpsonw/atmosphere
| 197 |
144866
|
<reponame>simpsonw/atmosphere
from core.models import Tag
from rest_framework import serializers
from api.v2.serializers.summaries import TagSummarySerializer
class TagRelatedField(serializers.RelatedField):
def __init__(self, **kwargs):
kwargs['read_only'] = True
super(TagRelatedField, self).__init__(**kwargs)
def to_representation(self, value):
serializer = TagSummarySerializer(value, context=self.context)
return serializer.data
def to_internal_value(self, data):
tag = Tag.objects.get(id=data)
return tag
|
pyqt5_lesson_01.py
|
AnshulPorwal1/pythonprogramming
| 158 |
144868
|
#! /usr/bin/env python3
# -*- coding:utf-8 -*-
###############################################################
# kenwaldek MIT-license
# Title: PyQt5 lesson 1 Version: 1.0
# Date: 08-01-17 Language: python3
# Description: pyqt5 simple example of empty window
# pythonprogramming.net from PyQt4 to PyQt5
###############################################################
# do something
import sys
from PyQt5.QtWidgets import QApplication, QWidget
app = QApplication(sys.argv)
window = QWidget()
window.setGeometry(50, 50, 500, 300)
window.setWindowTitle('pyQt Tuts')
window.show()
sys.exit(app.exec_())
|
release/stubs.min/System/__init___parts/DateTime.py
|
htlcnn/ironpython-stubs
| 182 |
144874
|
<filename>release/stubs.min/System/__init___parts/DateTime.py<gh_stars>100-1000
class DateTime(object,IComparable,IFormattable,IConvertible,ISerializable,IComparable[DateTime],IEquatable[DateTime]):
"""
Represents an instant in time,typically expressed as a date and time of day.
DateTime(ticks: Int64)
DateTime(ticks: Int64,kind: DateTimeKind)
DateTime(year: int,month: int,day: int)
DateTime(year: int,month: int,day: int,calendar: Calendar)
DateTime(year: int,month: int,day: int,hour: int,minute: int,second: int)
DateTime(year: int,month: int,day: int,hour: int,minute: int,second: int,kind: DateTimeKind)
DateTime(year: int,month: int,day: int,hour: int,minute: int,second: int,calendar: Calendar)
DateTime(year: int,month: int,day: int,hour: int,minute: int,second: int,millisecond: int)
DateTime(year: int,month: int,day: int,hour: int,minute: int,second: int,millisecond: int,kind: DateTimeKind)
DateTime(year: int,month: int,day: int,hour: int,minute: int,second: int,millisecond: int,calendar: Calendar)
DateTime(year: int,month: int,day: int,hour: int,minute: int,second: int,millisecond: int,calendar: Calendar,kind: DateTimeKind)
"""
def Add(self,value):
"""
Add(self: DateTime,value: TimeSpan) -> DateTime
Returns a new System.DateTime that adds the value of the specified System.TimeSpan to the value
of this instance.
value: A positive or negative time interval.
Returns: An object whose value is the sum of the date and time represented by this instance and the time
interval represented by value.
"""
pass
def AddDays(self,value):
"""
AddDays(self: DateTime,value: float) -> DateTime
Returns a new System.DateTime that adds the specified number of days to the value of this
instance.
value: A number of whole and fractional days. The value parameter can be negative or positive.
Returns: An object whose value is the sum of the date and time represented by this instance and the
number of days represented by value.
"""
pass
def AddHours(self,value):
"""
AddHours(self: DateTime,value: float) -> DateTime
Returns a new System.DateTime that adds the specified number of hours to the value of this
instance.
value: A number of whole and fractional hours. The value parameter can be negative or positive.
Returns: An object whose value is the sum of the date and time represented by this instance and the
number of hours represented by value.
"""
pass
def AddMilliseconds(self,value):
"""
AddMilliseconds(self: DateTime,value: float) -> DateTime
Returns a new System.DateTime that adds the specified number of milliseconds to the value of
this instance.
value: A number of whole and fractional milliseconds. The value parameter can be negative or positive.
Note that this value is rounded to the nearest integer.
Returns: An object whose value is the sum of the date and time represented by this instance and the
number of milliseconds represented by value.
"""
pass
def AddMinutes(self,value):
"""
AddMinutes(self: DateTime,value: float) -> DateTime
Returns a new System.DateTime that adds the specified number of minutes to the value of this
instance.
value: A number of whole and fractional minutes. The value parameter can be negative or positive.
Returns: An object whose value is the sum of the date and time represented by this instance and the
number of minutes represented by value.
"""
pass
def AddMonths(self,months):
"""
AddMonths(self: DateTime,months: int) -> DateTime
Returns a new System.DateTime that adds the specified number of months to the value of this
instance.
months: A number of months. The months parameter can be negative or positive.
Returns: An object whose value is the sum of the date and time represented by this instance and months.
"""
pass
def AddSeconds(self,value):
"""
AddSeconds(self: DateTime,value: float) -> DateTime
Returns a new System.DateTime that adds the specified number of seconds to the value of this
instance.
value: A number of whole and fractional seconds. The value parameter can be negative or positive.
Returns: An object whose value is the sum of the date and time represented by this instance and the
number of seconds represented by value.
"""
pass
def AddTicks(self,value):
"""
AddTicks(self: DateTime,value: Int64) -> DateTime
Returns a new System.DateTime that adds the specified number of ticks to the value of this
instance.
value: A number of 100-nanosecond ticks. The value parameter can be positive or negative.
Returns: An object whose value is the sum of the date and time represented by this instance and the time
represented by value.
"""
pass
def AddYears(self,value):
"""
AddYears(self: DateTime,value: int) -> DateTime
Returns a new System.DateTime that adds the specified number of years to the value of this
instance.
value: A number of years. The value parameter can be negative or positive.
Returns: An object whose value is the sum of the date and time represented by this instance and the
number of years represented by value.
"""
pass
@staticmethod
def Compare(t1,t2):
"""
Compare(t1: DateTime,t2: DateTime) -> int
Compares two instances of System.DateTime and returns an integer that indicates whether the
first instance is earlier than,the same as,or later than the second instance.
t1: The first object to compare.
t2: The second object to compare.
Returns: A signed number indicating the relative values of t1 and t2.Value Type Condition Less than zero
t1 is earlier than t2. Zero t1 is the same as t2. Greater than zero t1 is later than t2.
"""
pass
def CompareTo(self,value):
"""
CompareTo(self: DateTime,value: DateTime) -> int
Compares the value of this instance to a specified System.DateTime value and returns an integer
that indicates whether this instance is earlier than,the same as,or later than the specified
System.DateTime value.
value: The object to compare to the current instance.
Returns: A signed number indicating the relative values of this instance and the value parameter.Value
Description Less than zero This instance is earlier than value. Zero This instance is the same
as value. Greater than zero This instance is later than value.
CompareTo(self: DateTime,value: object) -> int
Compares the value of this instance to a specified object that contains a specified
System.DateTime value,and returns an integer that indicates whether this instance is earlier
than,the same as,or later than the specified System.DateTime value.
value: A boxed object to compare,or null.
Returns: A signed number indicating the relative values of this instance and value.Value Description Less
than zero This instance is earlier than value. Zero This instance is the same as value. Greater
than zero This instance is later than value,or value is null.
"""
pass
@staticmethod
def DaysInMonth(year,month):
"""
DaysInMonth(year: int,month: int) -> int
Returns the number of days in the specified month and year.
year: The year.
month: The month (a number ranging from 1 to 12).
Returns: The number of days in month for the specified year.For example,if month equals 2 for February,
the return value is 28 or 29 depending upon whether year is a leap year.
"""
pass
def Equals(self,*__args):
"""
Equals(t1: DateTime,t2: DateTime) -> bool
Returns a value indicating whether two System.DateTime instances have the same date and time
value.
t1: The first object to compare.
t2: The second object to compare.
Returns: true if the two values are equal; otherwise,false.
Equals(self: DateTime,value: DateTime) -> bool
Returns a value indicating whether the value of this instance is equal to the value of the
specified System.DateTime instance.
value: The object to compare to this instance.
Returns: true if the value parameter equals the value of this instance; otherwise,false.
Equals(self: DateTime,value: object) -> bool
Returns a value indicating whether this instance is equal to a specified object.
value: The object to compare to this instance.
Returns: true if value is an instance of System.DateTime and equals the value of this instance;
otherwise,false.
"""
pass
@staticmethod
def FromBinary(dateData):
"""
FromBinary(dateData: Int64) -> DateTime
Deserializes a 64-bit binary value and recreates an original serialized System.DateTime object.
dateData: A 64-bit signed integer that encodes the System.DateTime.Kind property in a 2-bit field and the
System.DateTime.Ticks property in a 62-bit field.
Returns: An object that is equivalent to the System.DateTime object that was serialized by the
System.DateTime.ToBinary method.
"""
pass
@staticmethod
def FromFileTime(fileTime):
"""
FromFileTime(fileTime: Int64) -> DateTime
Converts the specified Windows file time to an equivalent local time.
fileTime: A Windows file time expressed in ticks.
Returns: An object that represents the local time equivalent of the date and time represented by the
fileTime parameter.
"""
pass
@staticmethod
def FromFileTimeUtc(fileTime):
"""
FromFileTimeUtc(fileTime: Int64) -> DateTime
Converts the specified Windows file time to an equivalent UTC time.
fileTime: A Windows file time expressed in ticks.
Returns: An object that represents the UTC time equivalent of the date and time represented by the
fileTime parameter.
"""
pass
@staticmethod
def FromOADate(d):
"""
FromOADate(d: float) -> DateTime
Returns a System.DateTime equivalent to the specified OLE Automation Date.
d: An OLE Automation Date value.
Returns: An object that represents the same date and time as d.
"""
pass
def GetDateTimeFormats(self,*__args):
"""
GetDateTimeFormats(self: DateTime,format: Char) -> Array[str]
Converts the value of this instance to all the string representations supported by the specified
standard date and time format specifier.
format: A standard date and time format string (see Remarks).
Returns: A string array where each element is the representation of the value of this instance formatted
with the format standard date and time format specifier.
GetDateTimeFormats(self: DateTime,format: Char,provider: IFormatProvider) -> Array[str]
Converts the value of this instance to all the string representations supported by the specified
standard date and time format specifier and culture-specific formatting information.
format: A date and time format string (see Remarks).
provider: An object that supplies culture-specific formatting information about this instance.
Returns: A string array where each element is the representation of the value of this instance formatted
with one of the standard date and time format specifiers.
GetDateTimeFormats(self: DateTime) -> Array[str]
Converts the value of this instance to all the string representations supported by the standard
date and time format specifiers.
Returns: A string array where each element is the representation of the value of this instance formatted
with one of the standard date and time format specifiers.
GetDateTimeFormats(self: DateTime,provider: IFormatProvider) -> Array[str]
Converts the value of this instance to all the string representations supported by the standard
date and time format specifiers and the specified culture-specific formatting information.
provider: An object that supplies culture-specific formatting information about this instance.
Returns: A string array where each element is the representation of the value of this instance formatted
with one of the standard date and time format specifiers.
"""
pass
def GetHashCode(self):
"""
GetHashCode(self: DateTime) -> int
Returns the hash code for this instance.
Returns: A 32-bit signed integer hash code.
"""
pass
def GetTypeCode(self):
"""
GetTypeCode(self: DateTime) -> TypeCode
Returns the System.TypeCode for value type System.DateTime.
Returns: The enumerated constant,System.TypeCode.DateTime.
"""
pass
def IsDaylightSavingTime(self):
"""
IsDaylightSavingTime(self: DateTime) -> bool
Indicates whether this instance of System.DateTime is within the daylight saving time range for
the current time zone.
Returns: true if System.DateTime.Kind is System.DateTimeKind.Local or System.DateTimeKind.Unspecified and
the value of this instance of System.DateTime is within the daylight saving time range for the
current time zone. false if System.DateTime.Kind is System.DateTimeKind.Utc.
"""
pass
@staticmethod
def IsLeapYear(year):
"""
IsLeapYear(year: int) -> bool
Returns an indication whether the specified year is a leap year.
year: A 4-digit year.
Returns: true if year is a leap year; otherwise,false.
"""
pass
@staticmethod
def Parse(s,provider=None,styles=None):
"""
Parse(s: str,provider: IFormatProvider,styles: DateTimeStyles) -> DateTime
Converts the specified string representation of a date and time to its System.DateTime
equivalent using the specified culture-specific format information and formatting style.
s: A string containing a date and time to convert.
provider: An object that supplies culture-specific formatting information about s.
styles: A bitwise combination of the enumeration values that indicates the style elements that can be
present in s for the parse operation to succeed and that defines how to interpret the parsed
date in relation to the current time zone or the current date. A typical value to specify is
System.Globalization.DateTimeStyles.None.
Returns: An object that is equivalent to the date and time contained in s,as specified by provider and
styles.
Parse(s: str,provider: IFormatProvider) -> DateTime
Converts the specified string representation of a date and time to its System.DateTime
equivalent using the specified culture-specific format information.
s: A string containing a date and time to convert.
provider: An object that supplies culture-specific format information about s.
Returns: An object that is equivalent to the date and time contained in s as specified by provider.
Parse(s: str) -> DateTime
Converts the specified string representation of a date and time to its System.DateTime
equivalent.
s: A string containing a date and time to convert.
Returns: An object that is equivalent to the date and time contained in s.
"""
pass
@staticmethod
def ParseExact(s,*__args):
"""
ParseExact(s: str,formats: Array[str],provider: IFormatProvider,style: DateTimeStyles) -> DateTime
Converts the specified string representation of a date and time to its System.DateTime
equivalent using the specified array of formats,culture-specific format information,and style.
The format of the string representation must match at least one of the specified formats exactly
or an exception is thrown.
s: A string containing one or more dates and times to convert.
formats: An array of allowable formats of s.
provider: An object that supplies culture-specific format information about s.
style: A bitwise combination of enumeration values that indicates the permitted format of s. A typical
value to specify is System.Globalization.DateTimeStyles.None.
Returns: An object that is equivalent to the date and time contained in s,as specified by formats,
provider,and style.
ParseExact(s: str,format: str,provider: IFormatProvider,style: DateTimeStyles) -> DateTime
Converts the specified string representation of a date and time to its System.DateTime
equivalent using the specified format,culture-specific format information,and style. The
format of the string representation must match the specified format exactly or an exception is
thrown.
s: A string containing a date and time to convert.
format: A format specifier that defines the required format of s.
provider: An object that supplies culture-specific formatting information about s.
style: A bitwise combination of the enumeration values that provides additional information about s,
about style elements that may be present in s,or about the conversion from s to a
System.DateTime value. A typical value to specify is System.Globalization.DateTimeStyles.None.
Returns: An object that is equivalent to the date and time contained in s,as specified by format,
provider,and style.
ParseExact(s: str,format: str,provider: IFormatProvider) -> DateTime
Converts the specified string representation of a date and time to its System.DateTime
equivalent using the specified format and culture-specific format information. The format of the
string representation must match the specified format exactly.
s: A string that contains a date and time to convert.
format: A format specifier that defines the required format of s.
provider: An object that supplies culture-specific format information about s.
Returns: An object that is equivalent to the date and time contained in s,as specified by format and
provider.
"""
pass
@staticmethod
def SpecifyKind(value,kind):
"""
SpecifyKind(value: DateTime,kind: DateTimeKind) -> DateTime
Creates a new System.DateTime object that has the same number of ticks as the specified
System.DateTime,but is designated as either local time,Coordinated Universal Time (UTC),or
neither,as indicated by the specified System.DateTimeKind value.
value: A date and time.
kind: One of the enumeration values that indicates whether the new object represents local time,UTC,
or neither.
Returns: A new object that has the same number of ticks as the object represented by the value parameter
and the System.DateTimeKind value specified by the kind parameter.
"""
pass
def Subtract(self,value):
"""
Subtract(self: DateTime,value: TimeSpan) -> DateTime
Subtracts the specified duration from this instance.
value: The time interval to subtract.
Returns: An object that is equal to the date and time represented by this instance minus the time
interval represented by value.
Subtract(self: DateTime,value: DateTime) -> TimeSpan
Subtracts the specified date and time from this instance.
value: The date and time value to subtract.
Returns: A time interval that is equal to the date and time represented by this instance minus the date
and time represented by value.
"""
pass
def ToBinary(self):
"""
ToBinary(self: DateTime) -> Int64
Serializes the current System.DateTime object to a 64-bit binary value that subsequently can be
used to recreate the System.DateTime object.
Returns: A 64-bit signed integer that encodes the System.DateTime.Kind and System.DateTime.Ticks
properties.
"""
pass
def ToFileTime(self):
"""
ToFileTime(self: DateTime) -> Int64
Converts the value of the current System.DateTime object to a Windows file time.
Returns: The value of the current System.DateTime object expressed as a Windows file time.
"""
pass
def ToFileTimeUtc(self):
"""
ToFileTimeUtc(self: DateTime) -> Int64
Converts the value of the current System.DateTime object to a Windows file time.
Returns: The value of the current System.DateTime object expressed as a Windows file time.
"""
pass
def ToLocalTime(self):
"""
ToLocalTime(self: DateTime) -> DateTime
Converts the value of the current System.DateTime object to local time.
Returns: An object whose System.DateTime.Kind property is System.DateTimeKind.Local,and whose value is
the local time equivalent to the value of the current System.DateTime object,or
System.DateTime.MaxValue if the converted value is too large to be represented by a
System.DateTime object,or System.DateTime.MinValue if the converted value is too small to be
represented as a System.DateTime object.
"""
pass
def ToLongDateString(self):
"""
ToLongDateString(self: DateTime) -> str
Converts the value of the current System.DateTime object to its equivalent long date string
representation.
Returns: A string that contains the long date string representation of the current System.DateTime object.
"""
pass
def ToLongTimeString(self):
"""
ToLongTimeString(self: DateTime) -> str
Converts the value of the current System.DateTime object to its equivalent long time string
representation.
Returns: A string that contains the long time string representation of the current System.DateTime object.
"""
pass
def ToOADate(self):
"""
ToOADate(self: DateTime) -> float
Converts the value of this instance to the equivalent OLE Automation date.
Returns: A double-precision floating-point number that contains an OLE Automation date equivalent to the
value of this instance.
"""
pass
def ToShortDateString(self):
"""
ToShortDateString(self: DateTime) -> str
Converts the value of the current System.DateTime object to its equivalent short date string
representation.
Returns: A string that contains the short date string representation of the current System.DateTime
object.
"""
pass
def ToShortTimeString(self):
"""
ToShortTimeString(self: DateTime) -> str
Converts the value of the current System.DateTime object to its equivalent short time string
representation.
Returns: A string that contains the short time string representation of the current System.DateTime
object.
"""
pass
def ToString(self,*__args):
"""
ToString(self: DateTime,provider: IFormatProvider) -> str
Converts the value of the current System.DateTime object to its equivalent string representation
using the specified culture-specific format information.
provider: An object that supplies culture-specific formatting information.
Returns: A string representation of value of the current System.DateTime object as specified by provider.
ToString(self: DateTime,format: str,provider: IFormatProvider) -> str
Converts the value of the current System.DateTime object to its equivalent string representation
using the specified format and culture-specific format information.
format: A standard or custom date and time format string.
provider: An object that supplies culture-specific formatting information.
Returns: A string representation of value of the current System.DateTime object as specified by format
and provider.
ToString(self: DateTime) -> str
Converts the value of the current System.DateTime object to its equivalent string representation.
Returns: A string representation of the value of the current System.DateTime object.
ToString(self: DateTime,format: str) -> str
Converts the value of the current System.DateTime object to its equivalent string representation
using the specified format.
format: A standard or custom date and time format string (see Remarks).
Returns: A string representation of value of the current System.DateTime object as specified by format.
"""
pass
def ToUniversalTime(self):
"""
ToUniversalTime(self: DateTime) -> DateTime
Converts the value of the current System.DateTime object to Coordinated Universal Time (UTC).
Returns: An object whose System.DateTime.Kind property is System.DateTimeKind.Utc,and whose value is the
UTC equivalent to the value of the current System.DateTime object,or System.DateTime.MaxValue
if the converted value is too large to be represented by a System.DateTime object,or
System.DateTime.MinValue if the converted value is too small to be represented by a
System.DateTime object.
"""
pass
@staticmethod
def TryParse(s,*__args):
"""
TryParse(s: str,provider: IFormatProvider,styles: DateTimeStyles) -> (bool,DateTime)
Converts the specified string representation of a date and time to its System.DateTime
equivalent using the specified culture-specific format information and formatting style,and
returns a value that indicates whether the conversion succeeded.
s: A string containing a date and time to convert.
provider: An object that supplies culture-specific formatting information about s.
styles: A bitwise combination of enumeration values that defines how to interpret the parsed date in
relation to the current time zone or the current date. A typical value to specify is
System.Globalization.DateTimeStyles.None.
Returns: true if the s parameter was converted successfully; otherwise,false.
TryParse(s: str) -> (bool,DateTime)
Converts the specified string representation of a date and time to its System.DateTime
equivalent and returns a value that indicates whether the conversion succeeded.
s: A string containing a date and time to convert.
Returns: true if the s parameter was converted successfully; otherwise,false.
"""
pass
@staticmethod
def TryParseExact(s,*__args):
"""
TryParseExact(s: str,formats: Array[str],provider: IFormatProvider,style: DateTimeStyles) -> (bool,DateTime)
Converts the specified string representation of a date and time to its System.DateTime
equivalent using the specified array of formats,culture-specific format information,and style.
The format of the string representation must match at least one of the specified formats
exactly. The method returns a value that indicates whether the conversion succeeded.
s: A string containing one or more dates and times to convert.
formats: An array of allowable formats of s.
provider: An object that supplies culture-specific format information about s.
style: A bitwise combination of enumeration values that indicates the permitted format of s. A typical
value to specify is System.Globalization.DateTimeStyles.None.
Returns: true if the s parameter was converted successfully; otherwise,false.
TryParseExact(s: str,format: str,provider: IFormatProvider,style: DateTimeStyles) -> (bool,DateTime)
Converts the specified string representation of a date and time to its System.DateTime
equivalent using the specified format,culture-specific format information,and style. The
format of the string representation must match the specified format exactly. The method returns
a value that indicates whether the conversion succeeded.
s: A string containing a date and time to convert.
format: The required format of s.
provider: An object that supplies culture-specific formatting information about s.
style: A bitwise combination of one or more enumeration values that indicate the permitted format of s.
Returns: true if s was converted successfully; otherwise,false.
"""
pass
def __add__(self,*args):
""" x.__add__(y) <==> x+y """
pass
def __cmp__(self,*args):
""" x.__cmp__(y) <==> cmp(x,y) """
pass
def __eq__(self,*args):
""" x.__eq__(y) <==> x==y """
pass
def __format__(self,*args):
""" __format__(formattable: IFormattable,format: str) -> str """
pass
def __ge__(self,*args):
pass
def __gt__(self,*args):
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
def __le__(self,*args):
pass
def __lt__(self,*args):
pass
@staticmethod
def __new__(self,*__args):
"""
__new__(cls: type,ticks: Int64)
__new__(cls: type,ticks: Int64,kind: DateTimeKind)
__new__(cls: type,year: int,month: int,day: int)
__new__(cls: type,year: int,month: int,day: int,calendar: Calendar)
__new__(cls: type,year: int,month: int,day: int,hour: int,minute: int,second: int)
__new__(cls: type,year: int,month: int,day: int,hour: int,minute: int,second: int,kind: DateTimeKind)
__new__(cls: type,year: int,month: int,day: int,hour: int,minute: int,second: int,calendar: Calendar)
__new__(cls: type,year: int,month: int,day: int,hour: int,minute: int,second: int,millisecond: int)
__new__(cls: type,year: int,month: int,day: int,hour: int,minute: int,second: int,millisecond: int,kind: DateTimeKind)
__new__(cls: type,year: int,month: int,day: int,hour: int,minute: int,second: int,millisecond: int,calendar: Calendar)
__new__(cls: type,year: int,month: int,day: int,hour: int,minute: int,second: int,millisecond: int,calendar: Calendar,kind: DateTimeKind)
__new__[DateTime]() -> DateTime
"""
pass
def __ne__(self,*args):
pass
def __reduce_ex__(self,*args):
pass
def __repr__(self,*args):
""" __repr__(self: object) -> str """
pass
def __rsub__(self,*args):
"""
__rsub__(d1: DateTime,d2: DateTime) -> TimeSpan
Subtracts a specified date and time from another specified date and time and returns a time
interval.
d1: The date and time value to subtract from (the minuend).
d2: The date and time value to subtract (the subtrahend).
Returns: The time interval between d1 and d2; that is,d1 minus d2.
"""
pass
def __str__(self,*args):
pass
def __sub__(self,*args):
""" x.__sub__(y) <==> x-yx.__sub__(y) <==> x-y """
pass
Date=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the date component of this instance.
Get: Date(self: DateTime) -> DateTime
"""
Day=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the day of the month represented by this instance.
Get: Day(self: DateTime) -> int
"""
DayOfWeek=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the day of the week represented by this instance.
Get: DayOfWeek(self: DateTime) -> DayOfWeek
"""
DayOfYear=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the day of the year represented by this instance.
Get: DayOfYear(self: DateTime) -> int
"""
Hour=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the hour component of the date represented by this instance.
Get: Hour(self: DateTime) -> int
"""
Kind=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets a value that indicates whether the time represented by this instance is based on local time,Coordinated Universal Time (UTC),or neither.
Get: Kind(self: DateTime) -> DateTimeKind
"""
Millisecond=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the milliseconds component of the date represented by this instance.
Get: Millisecond(self: DateTime) -> int
"""
Minute=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the minute component of the date represented by this instance.
Get: Minute(self: DateTime) -> int
"""
Month=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the month component of the date represented by this instance.
Get: Month(self: DateTime) -> int
"""
Second=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the seconds component of the date represented by this instance.
Get: Second(self: DateTime) -> int
"""
Ticks=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the number of ticks that represent the date and time of this instance.
Get: Ticks(self: DateTime) -> Int64
"""
TimeOfDay=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the time of day for this instance.
Get: TimeOfDay(self: DateTime) -> TimeSpan
"""
Year=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the year component of the date represented by this instance.
Get: Year(self: DateTime) -> int
"""
MaxValue=None
MinValue=None
Now=None
Today=None
UtcNow=None
|
apps/benchmark_ncs/benchmark_ncs.py
|
neuralbotnetworks/ncappzoo
| 968 |
144880
|
#! /usr/bin/env python3
# Copyright(c) 2017-2018 Intel Corporation.
# License: MIT See LICENSE file in root directory.
GREEN = '\033[1;32m'
RED = '\033[1;31m'
NOCOLOR = '\033[0m'
YELLOW = '\033[1;33m'
try:
from openvino.inference_engine import IENetwork, ExecutableNetwork, IECore
import openvino.inference_engine.ie_api
except:
print(RED + '\nPlease make sure your OpenVINO environment variables are set by sourcing the' + YELLOW + ' setupvars.sh ' + RED + 'script found in <your OpenVINO install location>/bin/ folder.\n' + NOCOLOR)
exit(1)
import cv2
import numpy
import time
import sys
import threading
import os
from sys import argv
import datetime
import queue
from queue import *
INFERENCE_DEV = "MYRIAD"
sep = os.path.sep
DEFAULT_IMAGE_DIR = "." + sep + "images"
DEFAULT_MODEL_XML = "." + sep + "googlenet-v1.xml"
DEFAULT_MODEL_BIN = "." + sep + "googlenet-v1.bin"
cv_window_name = "benchmark_ncs"
# how long to wait for queues
QUEUE_WAIT_SECONDS = 10
# set some global parameters to initial values that may get overriden with arguments to the application.
inference_device = INFERENCE_DEV
image_dir = DEFAULT_IMAGE_DIR
number_of_devices = 1
number_of_inferences = 1000
run_async = True
time_threads = True
time_main = False
threads_per_dev = 3 # for each device one executable network will be created and this many threads will be
simultaneous_infer_per_thread = 6 # Each thread will start this many async inferences at at time.
# it should be at least the number of NCEs on board. The Myriad X has 2
# seem to get slightly better results more. Myriad X does well with 4
report_interval = int(number_of_inferences / 10) #report out the current FPS every this many inferences
model_xml_fullpath = DEFAULT_MODEL_XML
model_bin_fullpath = DEFAULT_MODEL_BIN
net_config = {'HW_STAGES_OPTIMIZATION': 'YES', 'COMPUTE_LAYOUT':'VPU_NCHW', 'RESHAPE_OPTIMIZATION':'NO'}
INFER_RES_QUEUE_SIZE = 6
def handle_args():
"""Reads the commandline args and adjusts initial values of globals values to match
:return: False if there was an error with the args, or True if args processed ok.
"""
global number_of_devices, number_of_inferences, model_xml_fullpath, model_bin_fullpath, run_async, \
time_threads, time_main, num_ncs_devs, threads_per_dev, simultaneous_infer_per_thread, report_interval, \
image_dir, inference_device
have_model_xml = False
have_model_bin = False
for an_arg in argv:
lower_arg = str(an_arg).lower()
if (an_arg == argv[0]):
continue
elif (lower_arg == 'help'):
return False
elif (lower_arg.startswith('num_devices=') or lower_arg.startswith("nd=")):
try:
arg, val = str(an_arg).split('=', 1)
num_dev_str = val
number_of_devices = int(num_dev_str)
if (number_of_devices < 0):
print('Error - num_devices argument invalid. It must be > 0')
return False
print('setting num_devices: ' + str(number_of_devices))
except:
print('Error - num_devices argument invalid. It must be between 1 and number of devices in system')
return False;
elif (lower_arg.startswith('device=') or lower_arg.startswith("dev=")):
try:
arg, val = str(an_arg).split('=', 1)
dev = val
inference_device = str(dev)
print("inference device:", inference_device)
if (inference_device != "MYRIAD" and inference_device != "CPU" ):
print('Error - Device must be CPU or MYRIAD')
return False
print('setting device: ' + str(inference_device))
except:
print('Error - Device must be CPU or MYRIAD')
return False;
elif (lower_arg.startswith('report_interval=') or lower_arg.startswith("ri=")):
try:
arg, val = str(an_arg).split('=', 1)
val_str = val
report_interval = int(val_str)
if (report_interval < 0):
print('Error - report_interval must be greater than or equal to 0')
return False
print('setting report_interval: ' + str(report_interval))
except:
print('Error - report_interval argument invalid. It must be greater than or equal to zero')
return False;
elif (lower_arg.startswith('num_inferences=') or lower_arg.startswith('ni=')):
try:
arg, val = str(an_arg).split('=', 1)
num_infer_str = val
number_of_inferences = int(num_infer_str)
if (number_of_inferences < 0):
print('Error - num_inferences argument invalid. It must be > 0')
return False
print('setting num_inferences: ' + str(number_of_inferences))
except:
print('Error - num_inferences argument invalid. It must be between 1 and number of devices in system')
return False;
elif (lower_arg.startswith('num_threads_per_device=') or lower_arg.startswith('ntpd=')):
try:
arg, val = str(an_arg).split('=', 1)
val_str = val
threads_per_dev = int(val_str)
if (threads_per_dev < 0):
print('Error - threads_per_dev argument invalid. It must be > 0')
return False
print('setting num_threads_per_device: ' + str(threads_per_dev))
except:
print('Error - num_threads_per_device argument invalid, it must be a positive integer.')
return False;
elif (lower_arg.startswith('num_simultaneous_inferences_per_thread=') or lower_arg.startswith('nsipt=')):
try:
arg, val = str(an_arg).split('=', 1)
val_str = val
simultaneous_infer_per_thread = int(val_str)
if (simultaneous_infer_per_thread < 0):
print('Error - simultaneous_infer_per_thread argument invalid. It must be > 0')
return False
print('setting num_simultaneous_inferences_per_thread: ' + str(simultaneous_infer_per_thread))
except:
print('Error - num_simultaneous_inferences_per_thread argument invalid, it must be a positive integer.')
return False;
elif (lower_arg.startswith('model_xml=') or lower_arg.startswith('mx=')):
try:
arg, val = str(an_arg).split('=', 1)
model_xml_fullpath = val
if not (os.path.isfile(model_xml_fullpath)):
print("Error - Model XML file passed does not exist or isn't a file")
return False
print('setting model_xml: ' + str(model_xml_fullpath))
have_model_xml = True
except:
print('Error with model_xml argument. It must be a valid model file generated by the OpenVINO Model Optimizer')
return False;
elif (lower_arg.startswith('model_bin=') or lower_arg.startswith('mb=')):
try:
arg, val = str(an_arg).split('=', 1)
model_bin_fullpath = val
if not (os.path.isfile(model_bin_fullpath)):
print("Error - Model bin file passed does not exist or isn't a file")
return False
print('setting model_bin: ' + str(model_bin_fullpath))
have_model_bin = True
except:
print('Error with model_bin argument. It must be a valid model file generated by the OpenVINO Model Optimizer')
return False;
elif (lower_arg.startswith('run_async=') or lower_arg.startswith('ra=')) :
try:
arg, val = str(an_arg).split('=', 1)
run_async = (val.lower() == 'true')
print ('setting run_async: ' + str(run_async))
except:
print("Error with run_async argument. It must be 'True' or 'False' ")
return False;
elif (lower_arg.startswith('image_dir=') or lower_arg.startswith('id=')):
try:
arg, val = str(an_arg).split('=', 1)
image_dir = val
if not (os.path.isdir(image_dir)):
print("Error - Image directory passed does not exist or isn't a directory:")
print(" passed value: " + image_dir)
return False
print('setting image_dir: ' + str(image_dir))
except:
print('Error with model_xml argument. It must be a valid model file generated by the OpenVINO Model Optimizer')
return False;
elif (lower_arg.startswith('time_threads=') or lower_arg.startswith('tt=')) :
try:
arg, val = str(an_arg).split('=', 1)
time_threads = (val.lower() == 'true')
print ('setting time_threads: ' + str(time_threads))
except:
print("Error with time_threads argument. It must be 'True' or 'False' ")
return False;
elif (lower_arg.startswith('time_main=') or lower_arg.startswith('tm=')) :
try:
arg, val = str(an_arg).split('=', 1)
time_main = (val.lower() == 'true')
print ('setting time_main: ' + str(time_main))
except:
print("Error with time_main argument. It must be 'True' or 'False' ")
return False;
if (time_main == False and time_threads == False):
print("Error - Both time_threads and time_main args were set to false. One of these must be true. ")
return False
if ((have_model_bin and not have_model_xml) or (have_model_xml and not have_model_bin)):
print("Error - only one of model_bin and model_xml were specified. You must specify both or neither.")
return False
if (run_async == False) and (simultaneous_infer_per_thread != 1):
print("Warning - If run_async is False then num_simultaneous_inferences_per_thread must be 1.")
print("Setting num_simultaneous_inferences_per_thread to 1")
simultaneous_infer_per_thread = 1
return True
def print_arg_vals():
print("")
print("--------------------------------------------------------")
print("Current date and time: " + str(datetime.datetime.now()))
print("")
print("program arguments:")
print("------------------")
print('device: ' + inference_device)
print('num_devices: ' + str(number_of_devices))
print('num_inferences: ' + str(number_of_inferences))
print('num_threads_per_device: ' + str(threads_per_dev))
print('num_simultaneous_inferences_per_thread: ' + str(simultaneous_infer_per_thread))
print('report_interval: ' + str(report_interval))
print('model_xml: ' + str(model_xml_fullpath))
print('model_bin: ' + str(model_bin_fullpath))
print('image_dir: ' + str(image_dir))
print('run_async: ' + str(run_async))
print('time_threads: ' + str(time_threads))
print('time_main: ' + str(time_main))
print("--------------------------------------------------------")
def print_usage():
print('\nusage: ')
print('python3 benchmark_ncs [help][nd=<number of devices to use>] [ni=<number of inferences per device>]')
print(' [report_interval=<num inferences between reporting>] [ntpd=<number of threads to use per device>]')
print(' [nsipt=<simultaneous inference on each thread>] [mx=<path to model xml file> mb=<path to model bin file>]')
print('')
print('options:')
print(" num_devices or nd - The number of devices to use for inferencing ")
print(" The value must be between 1 and the total number of devices in the system.")
print(" Default is to use 1 device. ")
print(" num_inferences or ni - The number of inferences to run on each device. ")
print(" Default is to run 200 inferences. ")
print(" report_interval or ri - Report the current FPS every time this many inferences are complete. To surpress reporting set to 0")
print(" Default is to report FPS ever 400 inferences. ")
print(" num_threads_per_device or ntpd - The number of threads to create that will run inferences in parallel for each device. ")
print(" Default is to create 2 threads per device. ")
print(" num_simultaneous_inferences_per_thread or nsipt - The number of inferences that each thread will create asynchronously. ")
print(" This should be at least equal to the number of NCEs on board or more.")
print(" Default is 4 simultaneous inference per thread.")
print(" model_xml or mx - Full path to the model xml file generated by the model optimizer. ")
print(" Default is " + DEFAULT_MODEL_XML)
print(" model_bin or mb - Full path to the model bin file generated by the model optimizer. ")
print(" Default is " + DEFAULT_MODEL_BIN)
print(" image_dir or id - Path to directory with images to use. ")
print(" Default is " + DEFAULT_IMAGE_DIR)
print(" run_async or ra - Set to true to run asynchronous inferences using two threads per device")
print(" Default is True ")
print(" time_main or tm - Set to true to use the time and calculate FPS from the main loop")
print(" Default is False ")
print(" time_threads or tt - Set to true to use the time and calculate FPS from the time reported from inference threads")
print(" Default is True ")
def preprocess_image(n:int, c:int, h:int, w:int, image_filename:str) :
image = cv2.imread(image_filename)
image = cv2.resize(image, (w, h))
image = image.transpose((2, 0, 1)) # Change data layout from HWC to CHW
preprocessed_image = image.reshape((n, c, h, w))
return preprocessed_image
def main():
"""Main function for the program. Everything starts here.
:return: None
"""
if (handle_args() != True):
print_usage()
exit()
print_arg_vals()
num_ncs_devs = number_of_devices
# Calculate the number of number of inferences to be made per thread
total_number_of_threads = threads_per_dev * num_ncs_devs
inferences_per_thread = int(number_of_inferences / total_number_of_threads)
# This total will be the total number of inferences to be made
inferences_per_thread = int(inferences_per_thread / simultaneous_infer_per_thread) * simultaneous_infer_per_thread
# Total number of threads that need to be spawned
total_number_threads = num_ncs_devs * threads_per_dev
# Lists and queues to hold data
infer_result_queue = queue.Queue(INFER_RES_QUEUE_SIZE)
infer_time_list = [None] * (total_number_threads)
thread_list = [None] * (total_number_threads)
# Threading barrier to sync all thread processing
start_barrier = threading.Barrier(total_number_threads + 1)
end_barrier = threading.Barrier(total_number_threads + 1)
ie = IECore()
# Create the network object
net = IENetwork(model=model_xml_fullpath, weights=model_bin_fullpath)
# Get the input and output blob names and the network input information
input_blob = next(iter(net.inputs))
output_blob = next(iter(net.outputs))
n, c, h, w = net.inputs[input_blob].shape
# Get a list of all the .mp4 files in the image directory and put them in a list
image_filename_list = os.listdir(image_dir)
image_filename_list = [image_dir + sep + i for i in image_filename_list if (i.endswith('.jpg') or i.endswith(".png"))]
if (len(image_filename_list) < 1):
# no images to show
print('No image files found (.jpg or .png)')
return 1
print("Found " + str(len(image_filename_list)) + " images.")
# Preprocess all images in the list
preprocessed_image_list = [None]*len(image_filename_list)
preprocessed_image_index = 0
for one_image_filename in image_filename_list:
one_preprocessed_image = preprocess_image(n,c,h,w,one_image_filename)
preprocessed_image_list[preprocessed_image_index] = one_preprocessed_image
preprocessed_image_index += 1
# Number of images to be inferred per thread
images_per_thread = int(len(preprocessed_image_list) / total_number_threads)
exec_net_list = [None] * num_ncs_devs
# creates an executable network for each device
for dev_index in range(0, num_ncs_devs):
exec_net_list[dev_index] = ie.load_network(network = net, num_requests = threads_per_dev * simultaneous_infer_per_thread, device_name=inference_device)
# create threads (3) for each executable network (one executable network per device)
for dev_thread_index in range(0, threads_per_dev):
# divide up the images to be processed by each thread
# device thread index starts at 0. device indexes start at 0. 3 threads per device. (0, 1, 2)
total_thread_index = dev_thread_index + (threads_per_dev * dev_index)
# Find out which index in preprocessed_image_list to start from
first_image_index = int(total_thread_index * images_per_thread)
# Find out which index in preprocessed_image_list to stop at
last_image_index = int(first_image_index + images_per_thread - 1)
if (run_async):
dev_thread_req_id = dev_thread_index * simultaneous_infer_per_thread
thread_list[total_thread_index] = threading.Thread(target=infer_async_thread_proc,
args=[net, exec_net_list[dev_index], dev_thread_req_id,
preprocessed_image_list,
first_image_index, last_image_index,
inferences_per_thread,
infer_time_list, total_thread_index,
start_barrier, end_barrier, simultaneous_infer_per_thread,
infer_result_queue, input_blob, output_blob], daemon = True)
else:
print("run_async=false not yet supported")
exit(-1)
del net
# Start the threads
try:
for one_thread in thread_list:
one_thread.start()
except (KeyboardInterrupt, SystemExit):
cleanup_stop_thread()
sys.exit()
start_barrier.wait()
# Save the main starting time
main_start_time = time.time()
interval_start_time = time.time()
print("Inferences started...")
cur_fps = 0.0
result_counter = 0
accum_fps = 0.0
frames_since_last_report = 0
total_number_inferences = total_number_threads * inferences_per_thread
# Report intermediate results
while (result_counter < total_number_inferences):
# Get the number of completed inferences
infer_res = infer_result_queue.get(True, QUEUE_WAIT_SECONDS)
infer_res_index = infer_res[0]
infer_res_probability = infer_res[1]
result_counter += 1
frames_since_last_report += 1
if (report_interval > 0):
if ((frames_since_last_report > report_interval)):
cur_time = time.time()
accum_duration = cur_time - main_start_time
cur_duration = cur_time - interval_start_time
cur_fps = frames_since_last_report / cur_duration
accum_fps = result_counter / accum_duration
print(str(result_counter) + " inferences completed. Current fps: " + '{0:.1f}'.format(accum_fps))
frames_since_last_report = 0
interval_start_time = time.time()
infer_result_queue.task_done()
# wait for all the inference threads to reach end barrier
print("Main end barrier reached")
end_barrier.wait()
# Save main end time
main_end_time = time.time()
print("Inferences finished.")
# wait for all threads to finish
for one_thread in thread_list:
one_thread.join()
total_thread_fps = 0.0
total_thread_time = 0.0
# Calculate total time and fps
for thread_index in range(0, (num_ncs_devs*threads_per_dev)):
total_thread_time += infer_time_list[thread_index]
total_thread_fps += (inferences_per_thread / infer_time_list[thread_index])
devices_count = str(number_of_devices)
if (time_threads):
print("\n------------------- Thread timing -----------------------")
print("--- Device: " + str(inference_device))
print("--- Model: " + model_xml_fullpath)
print("--- Total FPS: " + '{0:.1f}'.format(total_thread_fps))
print("--- FPS per device: " + '{0:.1f}'.format(total_thread_fps / num_ncs_devs))
print("---------------------------------------------------------")
main_time = main_end_time - main_start_time
if (time_main):
main_fps = result_counter / main_time
print ("\n------------------ Main timing -------------------------")
print ("--- FPS: " + str(main_fps))
print ("--- FPS per device: " + str(main_fps/num_ncs_devs))
print ("--------------------------------------------------------")
# Clean up
for one_exec_net in exec_net_list:
del one_exec_net
# use this thread proc to try to implement:
# 1 plugin per app
# 1 executable Network per device
# multiple threads per executable network
# multiple requests per executable network per thread
def infer_async_thread_proc(net, exec_net: ExecutableNetwork, dev_thread_request_id: int,
image_list: list,
first_image_index:int, last_image_index:int,
num_total_inferences: int, result_list: list, result_index:int,
start_barrier: threading.Barrier, end_barrier: threading.Barrier,
simultaneous_infer_per_thread:int, infer_result_queue:queue.Queue, input_blob, output_blob):
# Sync with the main start barrier
start_barrier.wait()
# Start times for the fps counter
start_time = time.time()
end_time = start_time
handle_list = [None]*simultaneous_infer_per_thread
image_index = first_image_index
image_result_start_index = 0
inferences_per_req = int(num_total_inferences/simultaneous_infer_per_thread)
# For each thread, 6 async inference requests will be created
for outer_index in range(0, inferences_per_req):
# Start the simultaneous async inferences
for infer_id in range(0, simultaneous_infer_per_thread):
new_request_id = dev_thread_request_id + infer_id
handle_list[infer_id] = exec_net.start_async(request_id = new_request_id, inputs={input_blob: image_list[image_index]})
image_index += 1
if (image_index > last_image_index):
image_index = first_image_index
# Wait for the simultaneous async inferences to finish.
for wait_index in range(0, simultaneous_infer_per_thread):
infer_status = handle_list[wait_index].wait()
result = handle_list[wait_index].outputs[output_blob]
top_index = numpy.argsort(result, axis = 1)[0, -1:][::-1]
top_index = top_index[0]
prob = result[0][top_index]
infer_result_queue.put((top_index, prob))
handle_list[wait_index] = None
# Save the time spent on inferences within this inference thread and associated reader thread
end_time = time.time()
total_inference_time = end_time - start_time
result_list[result_index] = total_inference_time
print("Thread " + str(result_index) + " end barrier reached")
# Wait for all inference threads to finish
end_barrier.wait()
# main entry point for program. we'll call main() to do what needs to be done.
if __name__ == "__main__":
sys.exit(main())
|
aliyun-python-sdk-arms/aliyunsdkarms/request/v20190808/ApplyScenarioRequest.py
|
yndu13/aliyun-openapi-python-sdk
| 1,001 |
144893
|
<filename>aliyun-python-sdk-arms/aliyunsdkarms/request/v20190808/ApplyScenarioRequest.py<gh_stars>1000+
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from aliyunsdkcore.request import RpcRequest
from aliyunsdkarms.endpoint import endpoint_data
class ApplyScenarioRequest(RpcRequest):
def __init__(self):
RpcRequest.__init__(self, 'ARMS', '2019-08-08', 'ApplyScenario','arms')
self.set_method('POST')
if hasattr(self, "endpoint_map"):
setattr(self, "endpoint_map", endpoint_data.getEndpointMap())
if hasattr(self, "endpoint_regional"):
setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional())
def get_SnForce(self):
return self.get_query_params().get('SnForce')
def set_SnForce(self,SnForce):
self.add_query_param('SnForce',SnForce)
def get_Sign(self):
return self.get_query_params().get('Sign')
def set_Sign(self,Sign):
self.add_query_param('Sign',Sign)
def get_SnStat(self):
return self.get_query_params().get('SnStat')
def set_SnStat(self,SnStat):
self.add_query_param('SnStat',SnStat)
def get_Scenario(self):
return self.get_query_params().get('Scenario')
def set_Scenario(self,Scenario):
self.add_query_param('Scenario',Scenario)
def get_SnDump(self):
return self.get_query_params().get('SnDump')
def set_SnDump(self,SnDump):
self.add_query_param('SnDump',SnDump)
def get_AppId(self):
return self.get_query_params().get('AppId')
def set_AppId(self,AppId):
self.add_query_param('AppId',AppId)
def get_Name(self):
return self.get_query_params().get('Name')
def set_Name(self,Name):
self.add_query_param('Name',Name)
def get_SnTransfer(self):
return self.get_query_params().get('SnTransfer')
def set_SnTransfer(self,SnTransfer):
self.add_query_param('SnTransfer',SnTransfer)
def get_UpdateOption(self):
return self.get_query_params().get('UpdateOption')
def set_UpdateOption(self,UpdateOption):
self.add_query_param('UpdateOption',UpdateOption)
def get_Config(self):
return self.get_query_params().get('Config')
def set_Config(self,Config):
self.add_query_param('Config',Config)
|
sampler/commands.py
|
crestonbunch/tbcnn
| 124 |
144903
|
"""File for defining commands for the sampler."""
import argparse
import logging
import sampler.trees as trees
import sampler.nodes as nodes
def main():
parser = argparse.ArgumentParser(
description="Sample trees or nodes from a crawler file.",
)
subparsers = parser.add_subparsers(help='sub-command help')
tree_parser = subparsers.add_parser(
'trees', help='Sample trees from a data source.'
)
tree_parser.add_argument('--infile', type=str, help='Data file to sample from')
tree_parser.add_argument('--outfile', type=str, help='File to store samples in')
tree_parser.add_argument('--test', default=30, type=int, help='Percent to save as test data')
tree_parser.add_argument(
'--label-key', type=str, default='label',
help='Change which key to use for the label'
)
tree_parser.add_argument(
'--maxsize', type=int, default=10000,
help='Ignore trees with more than --maxsize nodes'
)
tree_parser.add_argument(
'--minsize', type=int, default=100,
help='Ignore trees with less than --minsize nodes'
)
tree_parser.set_defaults(func=trees.parse)
node_parser = subparsers.add_parser(
'nodes', help='Sample nodes from a data source.'
)
node_parser.add_argument('--infile', type=str, help='Data file to sample from')
node_parser.add_argument('--outfile', type=str, help='File to store samples in')
node_parser.add_argument(
'--per-node', type=int, default=-1,
help='Sample up to a maxmimum number for each node type'
)
node_parser.add_argument(
'--limit', type=int, default=-1,
help='Maximum number of samples to store.'
)
node_parser.set_defaults(func=nodes.parse)
args = parser.parse_args()
args.func(args)
|
src/ploomber/executors/__init__.py
|
MarcoJHB/ploomber
| 2,141 |
144938
|
<gh_stars>1000+
from ploomber.executors.serial import Serial
from ploomber.executors.parallel import Parallel
__all__ = ['Serial', 'Parallel']
|
tests/helpers/imports.py
|
neptune-ml/pytorch-lightning
| 15,666 |
144950
|
<reponame>neptune-ml/pytorch-lightning<gh_stars>1000+
import operator
from pytorch_lightning.utilities.imports import _compare_version, _TORCHTEXT_LEGACY
if _TORCHTEXT_LEGACY:
if _compare_version("torchtext", operator.ge, "0.9.0"):
from torchtext.legacy.data import Batch, Dataset, Example, Field, Iterator, LabelField
else:
from torchtext.data import Batch, Dataset, Example, Field, Iterator, LabelField
else:
Batch = type(None)
Dataset = type(None)
Example = type(None)
Field = type(None)
Iterator = type(None)
LabelField = type(None)
|
tests/conftest.py
|
chris48s/datapackage-py
| 183 |
144964
|
<reponame>chris48s/datapackage-py
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import mock
import pytest
import tempfile
from datapackage import DataPackage
# Fixtures
@pytest.yield_fixture()
def tmpfile():
with tempfile.NamedTemporaryFile() as file:
yield file
@pytest.yield_fixture()
def txt_tmpfile():
with tempfile.NamedTemporaryFile(suffix='.txt') as file:
yield file
@pytest.yield_fixture()
def csv_tmpfile():
with tempfile.NamedTemporaryFile(suffix='.csv') as file:
yield file
@pytest.yield_fixture()
def json_tmpfile():
with tempfile.NamedTemporaryFile(suffix='.json') as file:
yield file
|
tests/test_warnings.py
|
vshalts/fastaudio
| 152 |
144967
|
<filename>tests/test_warnings.py
import pytest
from fastaudio.augment.spectrogram import (
CropTime,
Delta,
MaskFreq,
MaskTime,
SGRoll,
TfmResize
)
from fastaudio.util import test_audio_tensor
def invoke_class(cls, **args):
audio = test_audio_tensor()
with pytest.warns(Warning):
cls(**args)(audio)
def test_show_warning_with_tfm_on_sig():
"""
When we invoke a transform intended for a spectrogram on
something that is most likely a signal, we show a warning.
Check Issue #17
"""
transforms = [CropTime, Delta, MaskFreq, MaskTime, SGRoll, TfmResize]
for t in transforms:
# Some of the transforms require init arguments
if t == CropTime:
invoke_class(t, duration=1)
elif t == TfmResize:
invoke_class(t, size=2)
else:
invoke_class(t)
|
test/submit_test.py
|
mike715/assignment
| 101 |
144969
|
import sys, os, pytest
sys.path.append('.')
import submit
output_worked = 'Your submission has been accepted and will be graded shortly.'
from io import StringIO
class TestCorrectMetadata:
def test_001(self):
meta_data = submit.load_metadata('test/_coursera')
assert len(meta_data.part_data) == 6
class TestBrokenMetadata:
# file not found
def test_001(self):
with pytest.raises(SystemExit):
submit.load_metadata('test/_missing')
# bad meta data format
def test_002(self):
with pytest.raises(SystemExit):
submit.load_metadata('test/_empty')
class TestLogin:
def setup_class(self):
self.parser = submit.build_parser()
def test_001(self):
sys.stdin = StringIO(u'username\ntoken\n')
login, token = submit.login_prompt('')
assert(login == 'username')
assert(token == 'token')
def test_002(self):
login, token = submit.login_prompt('test/_credentials')
assert(login == '<EMAIL>')
assert(token == '<KEY>')
# testing manual override when credentials file is incorrect
# def test_003(self, capfd):
# login, token = submit.login_prompt('test/_credentials')
# sys.stdin = StringIO(u'1\n%s\n%s\n' % (login, token))
# submit.main(self.parser.parse_args(['-o', './test/model/model.mzn', '-m', './test/_coursera', '-c', './test/_credentials3']))
# resout, reserr = capfd.readouterr()
# assert(output_worked in resout)
class TestPartsPrompt:
def setup_class(self):
self.metadata = submit.load_metadata('test/_coursera')
def test_001(self, capfd):
sys.stdin = StringIO(u'0.1\n1\n')
problems = submit.part_prompt(self.metadata.part_data)
assert(len(problems) == 1)
resout, reserr = capfd.readouterr()
assert('It is not an integer.' in resout)
def test_002(self, capfd):
sys.stdin = StringIO(u'100\n1\n')
problems = submit.part_prompt(self.metadata.part_data)
assert(len(problems) == 1)
resout, reserr = capfd.readouterr()
assert('It is out of the valid range' in resout)
def test_003(self, capfd):
sys.stdin = StringIO(u'-1\n1\n')
problems = submit.part_prompt(self.metadata.part_data)
assert(len(problems) == 1)
resout, reserr = capfd.readouterr()
assert('It is out of the valid range' in resout)
def test_004(self, capfd):
sys.stdin = StringIO(u'1,2\n')
problems = submit.part_prompt(self.metadata.part_data)
assert(len(problems) == 2)
def test_005(self, capfd):
sys.stdin = StringIO(u'0\n')
problems = submit.part_prompt(self.metadata.part_data)
assert(len(problems) == len(self.metadata.part_data))
class TestProblemSubmission:
def setup_class(self):
self.parser = submit.build_parser()
# # tests problem selection
# def test_001(self, capfd):
# sys.stdin = StringIO(u'1\n')
# submit.main(self.parser.parse_args(['-m', './test/_coursera', '-c', './test/_credentials']))
# output = 'Unable to locate assignment file'
# resout, reserr = capfd.readouterr()
# assert(output in resout)
# tests running a problem
def test_002(self, capfd):
sys.stdin = StringIO(u'1\n')
submit.main(self.parser.parse_args(['-m', './test/_coursera', '-c', './test/_credentials']))
resout, reserr = capfd.readouterr()
assert(output_worked in resout)
# tests running a problem in record mode
def test_003(self, capfd):
sys.stdin = StringIO(u'1\n')
submit.main(self.parser.parse_args(['-m', './test/_coursera', '-c', './test/_credentials', '-rs']))
output = 'writting submission file: _awPVV'
resout, reserr = capfd.readouterr()
assert(output in resout)
assert(not output_worked in resout)
os.remove('_awPVV/submission.sub')
os.rmdir('_awPVV')
# tests running a solver with a int return value
def test_004(self, capfd):
# sys.stdin = StringIO(u'2\n')
# submit.main(self.parser.parse_args(['-m', './test/_coursera', '-c', './test/_credentials']))
# resout, reserr = capfd.readouterr()
# assert(output_worked in resout)
sys.path.insert(0, 'test/solver')
submission = submit.output('./test/_empty', 'int_val_solver.py')
assert('0' in submission)
resout, reserr = capfd.readouterr()
assert('Warning' in resout)
# tests running a solver with a unicode return value
def test_005(self, capfd):
# sys.stdin = StringIO(u'3\n')
# submit.main(self.parser.parse_args(['-m', './test/_coursera', '-c', './test/_credentials']))
# resout, reserr = capfd.readouterr()
# assert(output_worked in resout)
sys.path.insert(0, 'test/solver')
submission = submit.output('./test/_empty', 'unicode_solver.py')
assert(u'\u03BB' in submission)
# class TestBrokenSubmission:
# def setup_method(self, _):
# self.parser = submit.build_parser()
# # should throw incorrect problem parts
# def test_001(self, capfd):
# sys.stdin = StringIO(u'1\n')
# submit.main(self.parser.parse_args(['-m', './test/_coursera3', '-c', './test/_credentials2', '-o', './test/model/model.mzn']))
# output_1 = 'Unexpected response code, please contact the course staff.'
# output_2 = 'Expected parts: '
# output_3 = 'but found: '
# resout, reserr = capfd.readouterr()
# print(resout)
# assert(output_1 in resout)
# assert(output_2 in resout)
# assert(output_3 in resout)
# # should throw incorrect login details
# def test_002(self, capfd):
# sys.stdin = StringIO(u'1\n')
# submit.main(self.parser.parse_args(['-m', './test/_coursera3', '-c', './test/_credentials', '-o', './test/model/model.mzn']))
# output = 'Please use a token for the assignment you are submitting.'
# resout, reserr = capfd.readouterr()
# print(resout)
# assert(output in resout)
|
benchmark/otb.py
|
meetdave06/THOR
| 163 |
144994
|
import cv2
import sys, os, glob, re
import json
from os.path import join, dirname, abspath, realpath, isdir
from os import makedirs
import numpy as np
from shutil import rmtree
from ipdb import set_trace
from .bench_utils.bbox_helper import rect_2_cxy_wh, cxy_wh_2_rect
def center_error(rects1, rects2):
"""Center error.
Args:
rects1 (numpy.ndarray): An N x 4 numpy array, each line represent a rectangle
(left, top, width, height).
rects2 (numpy.ndarray): An N x 4 numpy array, each line represent a rectangle
(left, top, width, height).
"""
centers1 = rects1[..., :2] + (rects1[..., 2:] - 1) / 2
centers2 = rects2[..., :2] + (rects2[..., 2:] - 1) / 2
errors = np.sqrt(np.sum(np.power(centers1 - centers2, 2), axis=-1))
return errors
def _intersection(rects1, rects2):
r"""Rectangle intersection.
Args:
rects1 (numpy.ndarray): An N x 4 numpy array, each line represent a rectangle
(left, top, width, height).
rects2 (numpy.ndarray): An N x 4 numpy array, each line represent a rectangle
(left, top, width, height).
"""
assert rects1.shape == rects2.shape
x1 = np.maximum(rects1[..., 0], rects2[..., 0])
y1 = np.maximum(rects1[..., 1], rects2[..., 1])
x2 = np.minimum(rects1[..., 0] + rects1[..., 2],
rects2[..., 0] + rects2[..., 2])
y2 = np.minimum(rects1[..., 1] + rects1[..., 3],
rects2[..., 1] + rects2[..., 3])
w = np.maximum(x2 - x1, 0)
h = np.maximum(y2 - y1, 0)
return np.stack([x1, y1, w, h]).T
def rect_iou(rects1, rects2, bound=None):
r"""Intersection over union.
Args:
rects1 (numpy.ndarray): An N x 4 numpy array, each line represent a rectangle
(left, top, width, height).
rects2 (numpy.ndarray): An N x 4 numpy array, each line represent a rectangle
(left, top, width, height).
bound (numpy.ndarray): A 4 dimensional array, denotes the bound
(min_left, min_top, max_width, max_height) for ``rects1`` and ``rects2``.
"""
assert rects1.shape == rects2.shape
if bound is not None:
# bounded rects1
rects1[:, 0] = np.clip(rects1[:, 0], 0, bound[0])
rects1[:, 1] = np.clip(rects1[:, 1], 0, bound[1])
rects1[:, 2] = np.clip(rects1[:, 2], 0, bound[0] - rects1[:, 0])
rects1[:, 3] = np.clip(rects1[:, 3], 0, bound[1] - rects1[:, 1])
# bounded rects2
rects2[:, 0] = np.clip(rects2[:, 0], 0, bound[0])
rects2[:, 1] = np.clip(rects2[:, 1], 0, bound[1])
rects2[:, 2] = np.clip(rects2[:, 2], 0, bound[0] - rects2[:, 0])
rects2[:, 3] = np.clip(rects2[:, 3], 0, bound[1] - rects2[:, 1])
rects_inter = _intersection(rects1, rects2)
areas_inter = np.prod(rects_inter[..., 2:], axis=-1)
areas1 = np.prod(rects1[..., 2:], axis=-1)
areas2 = np.prod(rects2[..., 2:], axis=-1)
areas_union = areas1 + areas2 - areas_inter
eps = np.finfo(float).eps
ious = areas_inter / (areas_union + eps)
ious = np.clip(ious, 0.0, 1.0)
return ious
def overlap_ratio(rect1, rect2):
'''
Compute overlap ratio between two rects
- rect: 1d array of [x,y,w,h] or
2d array of N x [x,y,w,h]
'''
if rect1.ndim==1:
rect1 = rect1[None,:]
if rect2.ndim==1:
rect2 = rect2[None,:]
left = np.maximum(rect1[:,0], rect2[:,0])
right = np.minimum(rect1[:,0]+rect1[:,2], rect2[:,0]+rect2[:,2])
top = np.maximum(rect1[:,1], rect2[:,1])
bottom = np.minimum(rect1[:,1]+rect1[:,3], rect2[:,1]+rect2[:,3])
intersect = np.maximum(0,right - left) * np.maximum(0,bottom - top)
union = rect1[:,2]*rect1[:,3] + rect2[:,2]*rect2[:,3] - intersect
iou = np.clip(intersect / union, 0, 1)
return iou
def calc_curves(ious, center_errors, nbins_iou, nbins_ce):
ious = np.asarray(ious, float)[:, np.newaxis]
center_errors = np.asarray(center_errors, float)[:, np.newaxis]
thr_iou = np.linspace(0, 1, nbins_iou)[np.newaxis, :]
thr_ce = np.arange(0, nbins_ce)[np.newaxis, :]
bin_iou = np.greater(ious, thr_iou)
bin_ce = np.less_equal(center_errors, thr_ce)
succ_curve = np.mean(bin_iou, axis=0)
prec_curve = np.mean(bin_ce, axis=0)
return succ_curve, prec_curve
def compute_success_overlap(gt_bb, result_bb):
thresholds_overlap = np.arange(0, 1.05, 0.05)
n_frame = len(gt_bb)
success = np.zeros(len(thresholds_overlap))
iou = overlap_ratio(gt_bb, result_bb)
for i in range(len(thresholds_overlap)):
success[i] = sum(iou > thresholds_overlap[i]) / float(n_frame)
return success
def compute_success_error(gt_center, result_center):
thresholds_error = np.arange(0, 51, 1)
n_frame = len(gt_center)
success = np.zeros(len(thresholds_error))
dist = np.sqrt(np.sum(np.power(gt_center - result_center, 2), axis=1))
for i in range(len(thresholds_error)):
success[i] = sum(dist <= thresholds_error[i]) / float(n_frame)
return success
def get_result_bb(arch, seq):
result_path = join(arch, seq + '.txt')
temp = np.loadtxt(result_path, delimiter=',').astype(np.float)
return np.array(temp)
def convert_bb_to_center(bboxes):
return np.array([(bboxes[:, 0] + (bboxes[:, 2] - 1) / 2),
(bboxes[:, 1] + (bboxes[:, 3] - 1) / 2)]).T
def test_otb(v_id, tracker, video, args):
toc, regions = 0, []
image_files, gt = video['image_files'], video['gt']
for f, image_file in enumerate(image_files):
im = cv2.imread(image_file)
tic = cv2.getTickCount()
if f == 0:
init_pos, init_sz = rect_2_cxy_wh(gt[f])
state = tracker.setup(im, init_pos, init_sz)
location = gt[f]
regions.append(gt[f])
elif f > 0:
state = tracker.track(im, state)
location = cxy_wh_2_rect(state['target_pos'], state['target_sz'])
regions.append(location)
toc += cv2.getTickCount() - tic
if args.viz and f > 0: # visualization
if f == 0: cv2.destroyAllWindows()
if len(gt[f]) == 8:
cv2.polylines(im, [np.array(gt[f], np.int).reshape((-1, 1, 2))],
True, (0, 255, 0), 3)
else:
cv2.rectangle(im, (gt[f, 0], gt[f, 1]), (gt[f, 0] + gt[f, 2], gt[f, 1] + gt[f, 3]),
(0, 255, 0), 3)
if len(location) == 8:
cv2.polylines(im, [location.reshape((-1, 1, 2))], True, (0, 255, 255), 3)
else:
location = [int(l) for l in location] #
cv2.rectangle(im, (location[0], location[1]),
(location[0] + location[2], location[1] + location[3]),
(0, 255, 255), 3)
cv2.putText(im, "score: {:.4f}".format(state['score']), (40, 40),
cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 255), 2)
cv2.imshow(video['name'], im)
cv2.moveWindow(video['name'], 200, 50)
cv2.waitKey(1)
cv2.destroyAllWindows()
toc /= cv2.getTickFrequency()
# save result
video_path = join('benchmark/results/', args.dataset, args.save_path)
if not isdir(video_path): makedirs(video_path)
result_path = join(video_path, '{:s}.txt'.format(video['name']))
with open(result_path, "w") as fin:
for x in regions:
fin.write(','.join([str(i) for i in x])+'\n')
print('({:d}) Video: {:12s} Time: {:02.1f}s Speed: {:3.1f}fps'.format(
v_id, video['name'], toc, f / toc))
return f / toc
def eval_otb(save_path, delete_after):
base_path = join(realpath(dirname(__file__)), '../data', 'OTB2015')
json_path = base_path + '.json'
annos = json.load(open(json_path, 'r'))
seqs = list(annos.keys())
video_path = join('benchmark/results/OTB2015/', save_path)
trackers = glob.glob(join(video_path))
_, _, files = next(os.walk(trackers[0]))
num_files = len(files)
thresholds_overlap = np.arange(0, 1.05, 0.05)
success_overlap = np.zeros((num_files, len(trackers), len(thresholds_overlap)))
thresholds_error = np.arange(0, 51, 1)
success_error = np.zeros((num_files, len(trackers), len(thresholds_error)))
for i, f in enumerate(files):
seq = f.replace('.txt', '')
gt_rect = np.array(annos[seq]['gt_rect']).astype(np.float)
gt_center = convert_bb_to_center(gt_rect)
for j in range(len(trackers)):
tracker = trackers[j]
bb = get_result_bb(tracker, seq)
center = convert_bb_to_center(bb)
success_overlap[i][j] = compute_success_overlap(gt_rect, bb)
success_error[i][j] = compute_success_error(gt_center, center)
max_auc = 0.0
max_prec = 0.0
for i in range(len(trackers)):
auc = success_overlap[:, i, :].mean()
if auc > max_auc:
max_auc = auc
prec = success_error[:, i, :].mean()
if prec > max_prec:
max_prec = prec
if delete_after:
rmtree(trackers[0])
return {'auc': max_auc, 'precision': prec}
|
bcs-ui/backend/components/ssm.py
|
schneesu/bk-bcs
| 599 |
145028
|
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2021 TH<NAME>, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
"""
from django.conf import settings
from backend.components import utils
from backend.utils import cache
from backend.utils.decorators import parse_response_data
HEADERS = {"X-BK-APP-CODE": settings.APP_ID, "X-BK-APP-SECRET": settings.APP_TOKEN}
@parse_response_data(default_data={})
def get_access_token(params):
url = f"{settings.BK_SSM_HOST}/api/v1/auth/access-tokens"
return utils.http_post(url, json=params, headers=HEADERS)
@cache.region.cache_on_arguments(expiration_time=240)
def get_bk_login_access_token(bk_token):
"""获取access_token"""
return get_access_token({"grant_type": "authorization_code", "id_provider": "bk_login", "bk_token": bk_token})
def get_client_access_token():
"""获取非用户态access_token"""
return get_access_token({"grant_type": "client_credentials", "id_provider": "client"})
@parse_response_data(default_data={})
def get_authorization_by_access_token(access_token):
url = f"{settings.BK_SSM_HOST}/api/v1/auth/access-tokens/verify"
return utils.http_post(url, json={"access_token": access_token}, headers=HEADERS)
|
experiments/launcher_exp1_collect.py
|
MenshovSergey/DetectChess
| 144 |
145041
|
<reponame>MenshovSergey/DetectChess<gh_stars>100-1000
import os
from os2d.utils.logger import extract_value_from_os2d_binary_log, mAP_percent_to_points
if __name__ == "__main__":
config_path = os.path.dirname(os.path.abspath(__file__))
config_job_name = "exp1"
log_path = os.path.abspath(os.path.join(config_path, "..", "output/exp1"))
def get_result(job_name,
sub_index,
backbone_arch,
init_model_nickname,
rand_seed,
):
job_name = f"{config_job_name}.{sub_index}.{job_name}_seed{rand_seed}"
log_folder = job_name + "_" + backbone_arch + "_init_" + init_model_nickname
log_folder = os.path.join(log_path, log_folder)
data_file = os.path.join(log_folder, "train_log.pkl")
return mAP_percent_to_points(extract_value_from_os2d_binary_log(data_file, "[email protected]_grozi-val-new-cl", reduce="max"))
results = []
random_seed = 0
results.append(get_result(\
"lossCL", 0, "ResNet50", "imageNetCaffe2", random_seed,
))
results.append(get_result(\
"lossRLL", 1, "ResNet50", "imageNetCaffe2", random_seed
))
results.append(get_result(\
"lossRLL_remap", 2, "ResNet50", "imageNetCaffe2", random_seed
))
results.append(get_result(\
"lossRLL_remap_mine", 3, "ResNet50", "imageNetCaffe2", random_seed
))
results.append(get_result(\
"lossRLL_remap_invFullAffine", 4, "ResNet50", "imageNetCaffe2", random_seed
))
results.append(get_result(\
"lossRLL_remap_mine_fullAffine", 5, "ResNet50", "imageNetCaffe2", random_seed
))
results.append(get_result(\
"lossRLL_remap_invFullAffine_initTranform", 6, "ResNet50", "imageNetCaffe2", random_seed,
))
results.append(get_result(\
"lossRLL_remap_invFullAffine_initTranform_zeroLocLoss", 7, "ResNet50", "imageNetCaffe2", random_seed
))
results.append(get_result(\
"lossRLL_remap_invFullAffine_initTranform_zeroLocLoss_mine", 8, "ResNet50", "imageNetCaffe2", random_seed
))
results.append(get_result(\
"lossCL_invFullAffine_initTranform_zeroLocLoss", 9, "ResNet50", "imageNetCaffe2", random_seed
))
results.append(get_result(\
"lossCL_remap_invFullAffine_initTranform_zeroLocLoss", 10, "ResNet50", "imageNetCaffe2", random_seed
))
results.append(get_result(\
"lossRLL_invFullAffine_initTranform_zeroLocLoss", 11, "ResNet50", "imageNetCaffe2", random_seed
))
for r in results:
print(r)
|
parserator/main.py
|
timgates42/parserator
| 785 |
145066
|
<filename>parserator/main.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import absolute_import
from builtins import open
import argparse
import os
import shutil
import fileinput
import sys
import glob
import textwrap
from lxml import etree
import chardet
from . import manual_labeling
from . import training
from . import parser_template
from . import data_prep_utils
def dispatch():
parser = argparse.ArgumentParser(description="")
parser_subparsers = parser.add_subparsers()
# Arguments for label command
sub_label = parser_subparsers.add_parser('label')
sub_label.add_argument(dest='infile',
help='input csv filepath for the label task',
type=file_type)
sub_label.add_argument(dest='outfile',
help='output xml filepath for the label task',
action=XML)
sub_label.add_argument(dest='module',
help='parser module name',
type=python_module)
sub_label.set_defaults(func=label)
# Arguments for train command
sub_train = parser_subparsers.add_parser('train')
sub_train.add_argument(dest='traindata',
help='comma separated xml filepaths, or "path/to/traindata/*.xml"',
type=training_data)
sub_train.add_argument(dest='module',
help='parser module name',
type=python_module)
sub_train.add_argument('--modelfile',
dest='model_path',
help='location of model file',
action=ModelFile,
required=False)
sub_train.set_defaults(func=train)
# Arguments for init command
sub_init = parser_subparsers.add_parser('init')
sub_init.add_argument(dest='modulename',
help='module name for a new parser')
sub_init.set_defaults(func=init)
if len(sys.argv[1:]) == 0:
parser.print_help()
parser.exit()
args = parser.parse_args()
args.func(args)
def label(args) :
manual_labeling.label(args.module, args.infile, args.outfile, args.xml)
def train(args) :
training_data = args.traindata
module = args.module
model_path = args.model_path
if model_path is None:
model_path = module.__name__ + '/' +module.MODEL_FILE
if hasattr(module, 'MODEL_FILES'):
msg = """
NOTE: this parser allows for multiple model files
You can specify a model with the --modelfile argument
Models available:"""
print(textwrap.dedent(msg))
for m in module.MODEL_FILES:
print(" - %s" % m)
print("Since no model was specified, we will train the default model")
training.train(module, training_data, model_path)
def init(args) :
name = args.modulename
data = "raw"
training = "training"
tests = 'tests'
dirs_to_mk = [name, data, training, tests]
print('\nInitializing directories for %s' %name, sys.stderr)
for directory in dirs_to_mk:
if not os.path.exists(directory):
os.mkdir(directory)
print('* %s' %directory, sys.stderr)
print('\nGenerating __init__.py', sys.stderr)
init_path = name + '/__init__.py'
if os.path.exists(init_path):
print(' warning: %s already exists' %init_path, sys.stderr)
else:
with open(init_path, "w") as f:
f.write(parser_template.init_template())
print('* %s' %init_path)
print('\nGenerating setup.py')
if os.path.exists('setup.py'):
print(' warning: setup.py already exists', sys.stderr)
else:
with open('setup.py', 'w') as f:
f.write(parser_template.setup_template(name))
print('* setup.py', sys.stderr)
print('\nGenerating test file', sys.stderr)
token_test_path = tests+'/test_tokenizing.py'
if os.path.exists(token_test_path):
print(' warning: %s already exists' % token_test_path, sys.stderr)
else:
with open(token_test_path, 'w') as f:
f.write(parser_template.test_tokenize_template(name))
print('* %s' %token_test_path, sys.stderr)
class XML(argparse.Action):
def __call__(self, parser, namespace, string, option_string):
try:
with open(string, 'r') as f:
tree = etree.parse(f)
xml = tree.getroot()
except (OSError, IOError):
xml = None
except etree.XMLSyntaxError as e:
if 'Document is empty' not in str(e):
raise argparse.ArgumentError(self,
"%s does not seem to be a valid xml file"
% string)
xml = None
setattr(namespace, self.dest, string)
setattr(namespace, 'xml', xml)
def file_type(arg):
try:
f = open(arg, 'rb')
except OSError as e:
message = _("can't open '%s': %s")
raise ArgumentTypeError(message % (arg, e))
else:
detector = chardet.universaldetector.UniversalDetector()
for line in f.readlines():
detector.feed(line)
if detector.done:
break
f.close()
detector.close()
f = open(arg, 'r', encoding=detector.result['encoding'])
return f
def training_data(arg):
all_files = []
for path in arg.split(','):
all_files.extend(glob.glob(path))
xml_files = [f for f in all_files
if (f.lower().endswith('.xml')
and os.path.isfile(f))]
if not xml_files:
raise argparse.ArgumentTypeError('Please specify one or more xml training files (comma separated) [--trainfile FILE]')
training_data = set()
for xml_file in xml_files:
with open(xml_file, 'r') as f:
try:
tree = etree.parse(f)
except etree.XMLSyntaxError:
raise argparse.ArgumentTypeError('%s is not a valid xml file' % (f.name,))
file_xml = tree.getroot()
training_data.update(data_prep_utils.TrainingData(file_xml))
if not training_data:
raise argparse.ArgumentTypeError("No training data found. Perhaps double check "
"your training data filepaths?")
msg = """
training model on {num} training examples from {file_list} file(s)"""
print(textwrap.dedent(msg.format(num=len(training_data),
file_list=xml_files)))
return training_data
class ModelFile(argparse.Action):
def __call__(self, parser, namespace, model_file, option_string):
module = namespace.module
if hasattr(module, 'MODEL_FILES'):
try:
model_path = module.__name__ + '/' +module.MODEL_FILES[model_file]
except KeyError:
msg = """
Invalid --modelfile argument
Models available: %s"""
raise argparse.ArgumentTypeError(text.dedent(msg) % module.MODEL_FILES)
else:
raise argparse.ArgumentError(self, 'This parser does not allow for multiple models')
setattr(namespace, self.dest, model_path)
def python_module(arg):
module = __import__(arg)
return module
|
dev/Gems/CloudGemDynamicContent/AWS/resource-manager-code/update.py
|
brianherrera/lumberyard
| 1,738 |
145070
|
<filename>dev/Gems/CloudGemDynamicContent/AWS/resource-manager-code/update.py
#
# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
# its licensors.
#
# For complete copyright and license terms please see the LICENSE at the root of this
# distribution (the "License"). All use of this software is governed by the License,
# or, if provided, by the license below or the license accompanying this file. Do not
# remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#
# $Revision: #1 $
import content_manifest
import dynamic_content_migrator
import dynamic_content_settings
def before_this_resource_group_updated(hook, deployment_name, **kwargs):
dynamic_content_migrator.export_current_table_entries(hook.context, deployment_name)
def after_this_resource_group_updated(hook, deployment_name, **kwargs):
dynamic_content_migrator.import_table_entries_from_backup(hook.context, deployment_name)
if not content_manifest.validate_writable(hook.context, None):
# Not raising here - we want to continue and let the user upload after
return
# Pass None to upload whatever is set in the startup/bootstrap manifest and immediately stage it as PUBLIC
staging_args = {}
staging_args['StagingStatus'] = 'PUBLIC'
auto_upload_name = None
resource_group = hook.context.resource_groups.get(dynamic_content_settings.get_default_resource_group())
if resource_group:
auto_upload_name = resource_group.get_editor_setting('DynamicContentDefaultManifest')
content_manifest.upload_manifest_content(hook.context, auto_upload_name, deployment_name, staging_args)
def gather_writable_check_list(hook, check_list, **kwargs):
this_path = content_manifest.determine_manifest_path(hook.context, None)
check_list.append(this_path)
|
tests/test_timing.py
|
ruohoruotsi/amen
| 324 |
145088
|
<reponame>ruohoruotsi/amen
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import librosa
from amen.audio import Audio
from amen.utils import example_audio_file
from amen.utils import example_mono_audio_file
from amen.timing import TimeSlice
t = 5
d = 10
dummy_audio = None
time_slice = TimeSlice(t, d, dummy_audio)
def test_time():
assert time_slice.time == pd.to_timedelta(t, 's')
def test_duration():
assert time_slice.duration == pd.to_timedelta(d, 's')
def test_units():
time_slice = TimeSlice(t, d, dummy_audio, unit='ms')
assert time_slice.time == pd.to_timedelta(t, 'ms')
EXAMPLE_FILE = example_audio_file()
stereo_audio = Audio(EXAMPLE_FILE)
time_slice = TimeSlice(t, d, stereo_audio)
EXAMPLE_MONO_FILE = example_mono_audio_file()
mono_audio = Audio(EXAMPLE_FILE)
def test_get_offsets():
left, right = time_slice._get_offsets(3, 4, stereo_audio.num_channels)
assert left == (-1, 3)
def test_offset_samples_mono():
res = mono_audio.timings['beats'][0]._offset_samples(
1, 2, (-1, 1), (-1, 1), mono_audio.num_channels
)
assert res.shape == (2, 3)
def test_offset_samples_stereo():
res = stereo_audio.timings['beats'][0]._offset_samples(
1, 2, (-1, 1), (-1, 1), stereo_audio.num_channels
)
assert res.shape == (2, 3)
def test_get_samples_shape_both_stereo_and_mono():
def get_samples(audio):
beat = audio.timings['beats'][0]
start = beat.time.delta * 1e-9
duration = beat.duration.delta * 1e-9
starting_sample, ending_sample = librosa.time_to_samples(
[start, start + duration], beat.audio.sample_rate
)
samples, left_offset, right_offset = beat.get_samples()
left_offsets, right_offsets = beat._get_offsets(
starting_sample, ending_sample, beat.audio.num_channels
)
duration = beat.duration.delta * 1e-9
starting_sample, ending_sample = librosa.time_to_samples(
[0, duration], audio.sample_rate
)
initial_length = ending_sample - starting_sample
left_offset_length = initial_length - left_offsets[0] + left_offsets[1]
right_offset_length = initial_length - right_offsets[0] + right_offsets[1]
return samples, left_offset_length, right_offset_length
mono_samples, mono_left_offset_length, mono_right_offset_length = get_samples(
mono_audio
)
assert len(mono_samples[0]) == mono_left_offset_length
assert len(mono_samples[1]) == mono_right_offset_length
stereo_samples, stereo_left_offset_length, stereo_right_offset_length = get_samples(
stereo_audio
)
assert len(stereo_samples[0]) == stereo_left_offset_length
assert len(stereo_samples[1]) == stereo_right_offset_length
def test_get_samples_audio():
def get_samples_audio(audio):
beat = audio.timings['beats'][0]
samples, left_offset, right_offset = beat.get_samples()
start = beat.time.delta * 1e-9
duration = beat.duration.delta * 1e-9
starting_sample, ending_sample = librosa.time_to_samples(
[start, start + duration], beat.audio.sample_rate
)
left_offsets, right_offsets = beat._get_offsets(
starting_sample, ending_sample, beat.audio.num_channels
)
start_sample = left_offsets[0] * -1
end_sample = len(samples[0]) - left_offsets[1]
reset_samples = samples[0][start_sample:end_sample]
original_samples = audio.raw_samples[0, starting_sample:ending_sample]
return reset_samples, original_samples
mono_reset_samples, mono_original_samples = get_samples_audio(mono_audio)
assert np.array_equiv(mono_reset_samples, mono_original_samples)
stereo_reset_samples, stereo_original_samples = get_samples_audio(stereo_audio)
assert np.array_equiv(stereo_reset_samples, stereo_original_samples)
|
jasmin/protocols/http/endpoints/send.py
|
paradiseng/jasmin
| 750 |
145091
|
<reponame>paradiseng/jasmin
from datetime import datetime, timedelta
import re
import json
import pickle
from twisted.internet import reactor, defer
from twisted.web.resource import Resource
from twisted.web.server import NOT_DONE_YET
from smpp.pdu.constants import priority_flag_value_map
from smpp.pdu.smpp_time import parse
from smpp.pdu.pdu_types import RegisteredDeliveryReceipt, RegisteredDelivery
from jasmin.routing.Routables import RoutableSubmitSm
from jasmin.protocols.smpp.configs import SMPPClientConfig
from jasmin.protocols.smpp.operations import SMPPOperationFactory
from jasmin.protocols.http.errors import UrlArgsValidationError
from jasmin.protocols.http.validation import UrlArgsValidator, HttpAPICredentialValidator
from jasmin.protocols.http.errors import (HttpApiError, AuthenticationError, ServerError, RouteNotFoundError, ConnectorNotFoundError,
ChargingError, ThroughputExceededError, InterceptorNotSetError,
InterceptorNotConnectedError, InterceptorRunError)
from jasmin.protocols.http.endpoints import hex2bin, authenticate_user
def update_submit_sm_pdu(routable, config, config_update_params=None):
"""Will set pdu parameters from smppclient configuration.
Parameters that were locked through the routable.lockPduParam() method will not be updated.
config parameter can be the connector config object or just a simple dict"""
if config_update_params is None:
# Set default config params to get from the config object
config_update_params = [
'protocol_id',
'replace_if_present_flag',
'dest_addr_ton',
'source_addr_npi',
'dest_addr_npi',
'service_type',
'source_addr_ton',
'sm_default_msg_id',
]
for param in config_update_params:
_pdu = routable.pdu
# Force setting param in main pdu
if not routable.pduParamIsLocked(param):
if isinstance(config, SMPPClientConfig) and hasattr(config, param):
_pdu.params[param] = getattr(config, param)
elif isinstance(config, dict) and param in config:
_pdu.params[param] = config[param]
# Force setting param in sub-pdus (multipart use case)
while hasattr(_pdu, 'nextPdu'):
_pdu = _pdu.nextPdu
if not routable.pduParamIsLocked(param):
if isinstance(config, SMPPClientConfig) and hasattr(config, param):
_pdu.params[param] = getattr(config, param)
elif isinstance(config, dict) and param in config:
_pdu.params[param] = config[param]
return routable
class Send(Resource):
isleaf = True
def __init__(self, HTTPApiConfig, RouterPB, SMPPClientManagerPB, stats, log, interceptorpb_client):
Resource.__init__(self)
self.SMPPClientManagerPB = SMPPClientManagerPB
self.RouterPB = RouterPB
self.stats = stats
self.log = log
self.interceptorpb_client = interceptorpb_client
self.config = HTTPApiConfig
# opFactory is initiated with a dummy SMPPClientConfig used for building SubmitSm only
self.opFactory = SMPPOperationFactory(long_content_max_parts=HTTPApiConfig.long_content_max_parts,
long_content_split=HTTPApiConfig.long_content_split)
@defer.inlineCallbacks
def route_routable(self, updated_request):
try:
# Do we have a hex-content ?
if b'hex-content' not in updated_request.args:
# Convert utf8 to GSM 03.38
if updated_request.args[b'coding'][0] == b'0':
if isinstance(updated_request.args[b'content'][0], bytes):
short_message = updated_request.args[b'content'][0].decode().encode('gsm0338', 'replace')
else:
short_message = updated_request.args[b'content'][0].encode('gsm0338', 'replace')
updated_request.args[b'content'][0] = short_message
else:
# Otherwise forward it as is
short_message = updated_request.args[b'content'][0]
else:
# Otherwise convert hex to bin
short_message = hex2bin(updated_request.args[b'hex-content'][0])
# Authentication
user = authenticate_user(
updated_request.args[b'username'][0],
updated_request.args[b'password'][0],
self.RouterPB,
self.stats,
self.log
)
# Update CnxStatus
user.getCnxStatus().httpapi['connects_count'] += 1
user.getCnxStatus().httpapi['submit_sm_request_count'] += 1
user.getCnxStatus().httpapi['last_activity_at'] = datetime.now()
# Build SubmitSmPDU
SubmitSmPDU = self.opFactory.SubmitSM(
source_addr=None if b'from' not in updated_request.args else updated_request.args[b'from'][0],
destination_addr=updated_request.args[b'to'][0],
short_message=short_message,
data_coding=int(updated_request.args[b'coding'][0]),
custom_tlvs=updated_request.args[b'custom_tlvs'][0])
self.log.debug("Built base SubmitSmPDU: %s", SubmitSmPDU)
# Make Credential validation
v = HttpAPICredentialValidator('Send', user, updated_request, submit_sm=SubmitSmPDU)
v.validate()
# Update SubmitSmPDU by default values from user MtMessagingCredential
SubmitSmPDU = v.updatePDUWithUserDefaults(SubmitSmPDU)
# Prepare for interception then routing
routedConnector = None # init
routable = RoutableSubmitSm(SubmitSmPDU, user)
self.log.debug("Built Routable %s for SubmitSmPDU: %s", routable, SubmitSmPDU)
# Should we tag the routable ?
tags = []
if b'tags' in updated_request.args:
tags = updated_request.args[b'tags'][0].split(b',')
for tag in tags:
if isinstance(tag, bytes):
routable.addTag(tag.decode())
else:
routable.addTag(tag)
self.log.debug('Tagged routable %s: +%s', routable, tag)
# Intercept
interceptor = self.RouterPB.getMTInterceptionTable().getInterceptorFor(routable)
if interceptor is not None:
self.log.debug("RouterPB selected %s interceptor for this SubmitSmPDU", interceptor)
if self.interceptorpb_client is None:
self.stats.inc('interceptor_error_count')
self.log.error("InterceptorPB not set !")
raise InterceptorNotSetError('InterceptorPB not set !')
if not self.interceptorpb_client.isConnected:
self.stats.inc('interceptor_error_count')
self.log.error("InterceptorPB not connected !")
raise InterceptorNotConnectedError('InterceptorPB not connected !')
script = interceptor.getScript()
self.log.debug("Interceptor script loaded: %s", script)
# Run !
r = yield self.interceptorpb_client.run_script(script, routable)
if isinstance(r, dict) and r['http_status'] != 200:
self.stats.inc('interceptor_error_count')
self.log.error('Interceptor script returned %s http_status error.', r['http_status'])
raise InterceptorRunError(
code=r['http_status'],
message='Interception specific error code %s' % r['http_status']
)
elif isinstance(r, (str, bytes)):
self.stats.inc('interceptor_count')
routable = pickle.loads(r)
else:
self.stats.inc('interceptor_error_count')
self.log.error('Failed running interception script, got the following return: %s', r)
raise InterceptorRunError(message='Failed running interception script, check log for details')
# Get the route
route = self.RouterPB.getMTRoutingTable().getRouteFor(routable)
if route is None:
self.stats.inc('route_error_count')
self.log.error("No route matched from user %s for SubmitSmPDU: %s", user, routable.pdu)
raise RouteNotFoundError("No route found")
# Get connector from selected route
self.log.debug("RouterPB selected %s route for this SubmitSmPDU", route)
routedConnector = route.getConnector()
# Is it a failover route ? then check for a bound connector, otherwise don't route
# The failover route requires at least one connector to be up, no message enqueuing will
# occur otherwise.
if repr(route) == 'FailoverMTRoute':
self.log.debug('Selected route is a failover, will ensure connector is bound:')
while True:
c = self.SMPPClientManagerPB.perspective_connector_details(routedConnector.cid)
if c:
self.log.debug('Connector [%s] is: %s', routedConnector.cid, c['session_state'])
else:
self.log.debug('Connector [%s] is not found', routedConnector.cid)
if c and c['session_state'][:6] == 'BOUND_':
# Choose this connector
break
else:
# Check next connector, None if no more connectors are available
routedConnector = route.getConnector()
if routedConnector is None:
break
if routedConnector is None:
self.stats.inc('route_error_count')
self.log.error("Failover route has no bound connector to handle SubmitSmPDU: %s", routable.pdu)
raise ConnectorNotFoundError("Failover route has no bound connectors")
# Re-update SubmitSmPDU with parameters from the route's connector
connector_config = self.SMPPClientManagerPB.perspective_connector_config(routedConnector.cid)
if connector_config:
connector_config = pickle.loads(connector_config)
routable = update_submit_sm_pdu(routable=routable, config=connector_config)
# Set a placeholder for any parameter update to be applied on the pdu(s)
param_updates = {}
# Set priority
priority = 0
if b'priority' in updated_request.args:
priority = int(updated_request.args[b'priority'][0])
param_updates['priority_flag'] = priority_flag_value_map[priority]
self.log.debug("SubmitSmPDU priority is set to %s", priority)
# Set schedule_delivery_time
if b'sdt' in updated_request.args:
param_updates['schedule_delivery_time'] = parse(updated_request.args[b'sdt'][0])
self.log.debug(
"SubmitSmPDU schedule_delivery_time is set to %s (%s)",
routable.pdu.params['schedule_delivery_time'],
updated_request.args[b'sdt'][0])
# Set validity_period
if b'validity-period' in updated_request.args:
delta = timedelta(minutes=int(updated_request.args[b'validity-period'][0]))
param_updates['validity_period'] = datetime.today() + delta
self.log.debug(
"SubmitSmPDU validity_period is set to %s (+%s minutes)",
routable.pdu.params['validity_period'],
updated_request.args[b'validity-period'][0])
# Got any updates to apply on pdu(s) ?
if len(param_updates) > 0:
routable = update_submit_sm_pdu(routable=routable, config=param_updates,
config_update_params=list(param_updates))
# Set DLR bit mask on the last pdu
_last_pdu = routable.pdu
while True:
if hasattr(_last_pdu, 'nextPdu'):
_last_pdu = _last_pdu.nextPdu
else:
break
# DLR setting is clearly described in #107
_last_pdu.params['registered_delivery'] = RegisteredDelivery(
RegisteredDeliveryReceipt.NO_SMSC_DELIVERY_RECEIPT_REQUESTED)
if updated_request.args[b'dlr'][0] == b'yes':
_last_pdu.params['registered_delivery'] = RegisteredDelivery(
RegisteredDeliveryReceipt.SMSC_DELIVERY_RECEIPT_REQUESTED)
self.log.debug(
"SubmitSmPDU registered_delivery is set to %s",
str(_last_pdu.params['registered_delivery']))
dlr_level = int(updated_request.args[b'dlr-level'][0])
if b'dlr-url' in updated_request.args:
dlr_url = updated_request.args[b'dlr-url'][0]
else:
dlr_url = None
if updated_request.args[b'dlr-level'][0] == b'1':
dlr_level_text = 'SMS-C'
elif updated_request.args[b'dlr-level'][0] == b'2':
dlr_level_text = 'Terminal'
else:
dlr_level_text = 'All'
dlr_method = updated_request.args[b'dlr-method'][0]
else:
dlr_url = None
dlr_level = 0
dlr_level_text = 'No'
dlr_method = None
# QoS throttling
if (user.mt_credential.getQuota('http_throughput') and user.mt_credential.getQuota('http_throughput') >= 0) and user.getCnxStatus().httpapi[
'qos_last_submit_sm_at'] != 0:
qos_throughput_second = 1 / float(user.mt_credential.getQuota('http_throughput'))
qos_throughput_ysecond_td = timedelta(microseconds=qos_throughput_second * 1000000)
qos_delay = datetime.now() - user.getCnxStatus().httpapi['qos_last_submit_sm_at']
if qos_delay < qos_throughput_ysecond_td:
self.stats.inc('throughput_error_count')
self.log.error(
"QoS: submit_sm_event is faster (%s) than fixed throughput (%s), user:%s, rejecting message.",
qos_delay,
qos_throughput_ysecond_td,
user)
raise ThroughputExceededError("User throughput exceeded")
user.getCnxStatus().httpapi['qos_last_submit_sm_at'] = datetime.now()
# Get number of PDUs to be sent (for billing purpose)
_pdu = routable.pdu
submit_sm_count = 1
while hasattr(_pdu, 'nextPdu'):
_pdu = _pdu.nextPdu
submit_sm_count += 1
# Pre-sending submit_sm: Billing processing
bill = route.getBillFor(user)
self.log.debug("SubmitSmBill [bid:%s] [ttlamounts:%s] generated for this SubmitSmPDU (x%s)",
bill.bid, bill.getTotalAmounts(), submit_sm_count)
charging_requirements = []
u_balance = user.mt_credential.getQuota('balance')
u_subsm_count = user.mt_credential.getQuota('submit_sm_count')
if u_balance is not None and bill.getTotalAmounts() > 0:
# Ensure user have enough balance to pay submit_sm and submit_sm_resp
charging_requirements.append({
'condition': bill.getTotalAmounts() * submit_sm_count <= u_balance,
'error_message': 'Not enough balance (%s) for charging: %s' % (
u_balance, bill.getTotalAmounts())})
if u_subsm_count is not None:
# Ensure user have enough submit_sm_count to to cover
# the bill action (decrement_submit_sm_count)
charging_requirements.append({
'condition': bill.getAction('decrement_submit_sm_count') * submit_sm_count <= u_subsm_count,
'error_message': 'Not enough submit_sm_count (%s) for charging: %s' % (
u_subsm_count, bill.getAction('decrement_submit_sm_count'))})
if self.RouterPB.chargeUserForSubmitSms(user, bill, submit_sm_count, charging_requirements) is None:
self.stats.inc('charging_error_count')
self.log.error('Charging user %s failed, [bid:%s] [ttlamounts:%s] SubmitSmPDU (x%s)',
user, bill.bid, bill.getTotalAmounts(), submit_sm_count)
raise ChargingError('Cannot charge submit_sm, check RouterPB log file for details')
########################################################
# Send SubmitSmPDU through smpp client manager PB server
self.log.debug("Connector '%s' is set to be a route for this SubmitSmPDU", routedConnector.cid)
c = self.SMPPClientManagerPB.perspective_submit_sm(
uid=user.uid,
cid=routedConnector.cid,
SubmitSmPDU=routable.pdu,
submit_sm_bill=bill,
priority=priority,
pickled=False,
dlr_url=dlr_url,
dlr_level=dlr_level,
dlr_method=dlr_method,
dlr_connector=routedConnector.cid)
# Build final response
if not c.result:
self.stats.inc('server_error_count')
self.log.error('Failed to send SubmitSmPDU to [cid:%s]', routedConnector.cid)
raise ServerError('Cannot send submit_sm, check SMPPClientManagerPB log file for details')
else:
self.stats.inc('success_count')
self.stats.set('last_success_at', datetime.now())
self.log.debug('SubmitSmPDU sent to [cid:%s], result = %s', routedConnector.cid, c.result)
response = {'return': c.result, 'status': 200}
except HttpApiError as e:
self.log.error("Error: %s", e)
response = {'return': e.message, 'status': e.code}
except Exception as e:
self.log.error("Error: %s", e)
response = {'return': "Unknown error: %s" % e, 'status': 500}
raise
finally:
self.log.debug("Returning %s to %s.", response, updated_request.getClientIP())
updated_request.setResponseCode(response['status'])
# Default return
_return = 'Error "%s"' % response['return']
# Success return
if response['status'] == 200 and routedConnector is not None:
# Do not log text for privacy reasons
# Added in #691
if self.config.log_privacy:
logged_content = '** %s byte content **' % len(short_message)
else:
if isinstance(short_message, str):
short_message = short_message.encode()
logged_content = '%r' % re.sub(rb'[^\x20-\x7E]+', b'.', short_message)
self.log.info(
'SMS-MT [uid:%s] [cid:%s] [msgid:%s] [prio:%s] [dlr:%s] [from:%s] [to:%s] [content:%s]',
user.uid,
routedConnector.cid,
response['return'],
priority,
dlr_level_text,
routable.pdu.params['source_addr'],
updated_request.args[b'to'][0],
logged_content)
_return = 'Success "%s"' % response['return']
updated_request.write(_return.encode())
updated_request.finish()
def render_POST(self, request):
"""
/send request processing
Note: This method MUST behave exactly like jasmin.protocols.smpp.factory.SMPPServerFactory.submit_sm_event
"""
self.log.debug("Rendering /send response with args: %s from %s", request.args, request.getClientIP())
request.responseHeaders.addRawHeader(b"content-type", b"text/plain")
response = {'return': None, 'status': 200}
self.stats.inc('request_count')
self.stats.set('last_request_at', datetime.now())
# updated_request will be filled with default values where request will never get modified
# updated_request is used for sending the SMS, request is just kept as an original request object
updated_request = request
try:
# Validation (must have almost the same params as /rate service)
fields = {b'to': {'optional': False, 'pattern': re.compile(rb'^\+{0,1}\d+$')},
b'from': {'optional': True},
b'coding': {'optional': True, 'pattern': re.compile(rb'^(0|1|2|3|4|5|6|7|8|9|10|13|14){1}$')},
b'username': {'optional': False, 'pattern': re.compile(rb'^.{1,16}$')},
b'password': {'optional': False, 'pattern': re.compile(rb'^.{1,16}$')},
# Priority validation pattern can be validated/filtered further more
# through HttpAPICredentialValidator
b'priority': {'optional': True, 'pattern': re.compile(rb'^[0-3]$')},
b'sdt': {'optional': True,
'pattern': re.compile(rb'^\d{2}\d{2}\d{2}\d{2}\d{2}\d{2}\d{1}\d{2}(\+|-|R)$')},
# Validity period validation pattern can be validated/filtered further more
# through HttpAPICredentialValidator
b'validity-period': {'optional': True, 'pattern': re.compile(rb'^\d+$')},
b'dlr': {'optional': False, 'pattern': re.compile(rb'^(yes|no)$')},
b'dlr-url': {'optional': True, 'pattern': re.compile(rb'^(http|https)\://.*$')},
# DLR Level validation pattern can be validated/filtered further more
# through HttpAPICredentialValidator
b'dlr-level' : {'optional': True, 'pattern': re.compile(rb'^[1-3]$')},
b'dlr-method' : {'optional': True, 'pattern': re.compile(rb'^(get|post)$', re.IGNORECASE)},
b'tags' : {'optional': True, 'pattern': re.compile(rb'^([-a-zA-Z0-9,])*$')},
b'content' : {'optional': True},
b'hex-content' : {'optional': True},
b'custom_tlvs' : {'optional': True}}
if updated_request.getHeader(b'content-type') == b'application/json':
json_body = updated_request.content.read()
json_data = json.loads(json_body)
for key, value in json_data.items():
# Make the values look like they came from form encoding all surrounded by [ ]
if isinstance(value, str):
value = value.encode()
if isinstance(key, str):
key = key.encode()
updated_request.args[key] = [value]
# If no custom TLVs present, defaujlt to an [] which will be passed down to SubmitSM
if b'custom_tlvs' not in updated_request.args:
updated_request.args[b'custom_tlvs'] = [[]]
# Default coding is 0 when not provided
if b'coding' not in updated_request.args:
updated_request.args[b'coding'] = [b'0']
# Set default for undefined updated_request.arguments
if b'dlr-url' in updated_request.args or b'dlr-level' in updated_request.args:
updated_request.args[b'dlr'] = [b'yes']
if b'dlr' not in updated_request.args:
# Setting DLR updated_request to 'no'
updated_request.args[b'dlr'] = [b'no']
# Set default values
if updated_request.args[b'dlr'][0] == b'yes':
if b'dlr-level' not in updated_request.args:
# If DLR is requested and no dlr-level were provided, assume minimum level (1)
updated_request.args[b'dlr-level'] = [1]
if b'dlr-method' not in updated_request.args:
# If DLR is requested and no dlr-method were provided, assume default (POST)
updated_request.args[b'dlr-method'] = [b'POST']
# DLR method must be uppercase
if b'dlr-method' in updated_request.args:
updated_request.args[b'dlr-method'][0] = updated_request.args[b'dlr-method'][0].upper()
# Make validation
v = UrlArgsValidator(updated_request, fields)
v.validate()
# Check if have content --OR-- hex-content
# @TODO: make this inside UrlArgsValidator !
if b'content' not in request.args and b'hex-content' not in request.args:
raise UrlArgsValidationError("content or hex-content not present.")
elif b'content' in request.args and b'hex-content' in request.args:
raise UrlArgsValidationError("content and hex-content cannot be used both in same request.")
# Continue routing in a separate thread
reactor.callFromThread(self.route_routable, updated_request=updated_request)
except HttpApiError as e:
self.log.error("Error: %s", e)
response = {'return': e.message, 'status': e.code}
self.log.debug("Returning %s to %s.", response, updated_request.getClientIP())
updated_request.setResponseCode(response['status'])
return b'Error "%s"' % (response['return'] if isinstance(response['return'], bytes) else response['return'].encode())
except Exception as e:
self.log.error("Error: %s", e)
response = {'return': "Unknown error: %s" % e, 'status': 500}
self.log.debug("Returning %s to %s.", response, updated_request.getClientIP())
updated_request.setResponseCode(response['status'])
return b'Error "%s"' % response['return'].encode()
else:
return NOT_DONE_YET
def render_GET(self, request):
"""Allow GET /send for backward compatibility"""
return self.render_POST(request)
|
tests/test_util.py
|
ThePrez/gunicorn
| 6,851 |
145115
|
<filename>tests/test_util.py<gh_stars>1000+
# -*- coding: utf-8 -
#
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
import os
import pytest
from gunicorn import util
from gunicorn.errors import AppImportError
from urllib.parse import SplitResult
@pytest.mark.parametrize('test_input, expected', [
('unix://var/run/test.sock', 'var/run/test.sock'),
('unix:/var/run/test.sock', '/var/run/test.sock'),
('tcp://localhost', ('localhost', 8000)),
('tcp://localhost:5000', ('localhost', 5000)),
('', ('0.0.0.0', 8000)),
('[::1]:8000', ('::1', 8000)),
('[::1]:5000', ('::1', 5000)),
('[::1]', ('::1', 8000)),
('localhost:8000', ('localhost', 8000)),
('127.0.0.1:8000', ('127.0.0.1', 8000)),
('localhost', ('localhost', 8000)),
('fd://33', 33),
])
def test_parse_address(test_input, expected):
assert util.parse_address(test_input) == expected
def test_parse_address_invalid():
with pytest.raises(RuntimeError) as exc_info:
util.parse_address('127.0.0.1:test')
assert "'test' is not a valid port number." in str(exc_info.value)
def test_parse_fd_invalid():
with pytest.raises(RuntimeError) as exc_info:
util.parse_address('fd://asd')
assert "'asd' is not a valid file descriptor." in str(exc_info.value)
def test_http_date():
assert util.http_date(1508607753.740316) == 'Sat, 21 Oct 2017 17:42:33 GMT'
@pytest.mark.parametrize('test_input, expected', [
('fc00:db20:35b:7399::5', True),
('fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b:fdf8:f53e:61e4::18:7777:1313', False),
('fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b', True),
('1200:0000:AB00:1234:O000:2552:7777:1313', False),
])
def test_is_ipv6(test_input, expected):
assert util.is_ipv6(test_input) == expected
def test_warn(capsys):
util.warn('test warn')
_, err = capsys.readouterr()
assert '!!! WARNING: test warn' in err
@pytest.mark.parametrize(
"value",
[
"support",
"support:app",
"support:create_app()",
"support:create_app('Gunicorn', 3)",
"support:create_app(count=3)",
],
)
def test_import_app_good(value):
assert util.import_app(value)
@pytest.mark.parametrize(
("value", "exc_type", "msg"),
[
("a:app", ImportError, "No module"),
("support:create_app(", AppImportError, "Failed to parse"),
("support:create.app()", AppImportError, "Function reference"),
("support:create_app(Gunicorn)", AppImportError, "literal values"),
("support:create.app", AppImportError, "attribute name"),
("support:wrong_app", AppImportError, "find attribute"),
("support:error_factory(1)", AppImportError, "error_factory() takes"),
("support:error_factory()", TypeError, "inner"),
("support:none_app", AppImportError, "find application object"),
("support:HOST", AppImportError, "callable"),
],
)
def test_import_app_bad(value, exc_type, msg):
with pytest.raises(exc_type) as exc_info:
util.import_app(value)
assert msg in str(exc_info.value)
def test_import_app_py_ext(monkeypatch):
monkeypatch.chdir(os.path.dirname(__file__))
with pytest.raises(ImportError) as exc_info:
util.import_app("support.py")
assert "did you mean" in str(exc_info.value)
def test_to_bytestring():
assert util.to_bytestring('test_str', 'ascii') == b'test_str'
assert util.to_bytestring('test_str®') == b'test_str\xc2\xae'
assert util.to_bytestring(b'byte_test_str') == b'byte_test_str'
with pytest.raises(TypeError) as exc_info:
util.to_bytestring(100)
msg = '100 is not a string'
assert msg in str(exc_info.value)
@pytest.mark.parametrize('test_input, expected', [
('https://example.org/a/b?c=1#d',
SplitResult(scheme='https', netloc='example.org', path='/a/b', query='c=1', fragment='d')),
('a/b?c=1#d',
SplitResult(scheme='', netloc='', path='a/b', query='c=1', fragment='d')),
('/a/b?c=1#d',
SplitResult(scheme='', netloc='', path='/a/b', query='c=1', fragment='d')),
('//a/b?c=1#d',
SplitResult(scheme='', netloc='', path='//a/b', query='c=1', fragment='d')),
('///a/b?c=1#d',
SplitResult(scheme='', netloc='', path='///a/b', query='c=1', fragment='d')),
])
def test_split_request_uri(test_input, expected):
assert util.split_request_uri(test_input) == expected
|
datalad/core/distributed/tests/test_push.py
|
DisasterMo/datalad
| 298 |
145117
|
# -*- coding: utf-8 -*-
# ex: set sts=4 ts=4 sw=4 noet:
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the datalad package for the
# copyright and license terms.
#
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
"""Test push
"""
import os
import logging
from datalad.distribution.dataset import Dataset
from datalad.support.exceptions import (
IncompleteResultsError,
InsufficientArgumentsError,
)
from datalad.tests.utils import (
assert_false,
assert_in,
assert_in_results,
assert_not_in,
assert_not_in_results,
assert_raises,
assert_repo_status,
assert_result_count,
assert_status,
DEFAULT_BRANCH,
DEFAULT_REMOTE,
eq_,
known_failure_githubci_osx,
known_failure_githubci_win,
neq_,
ok_,
ok_file_has_content,
serve_path_via_http,
skip_if_adjusted_branch,
skip_if_on_windows,
skip_ssh,
slow,
swallow_logs,
with_tempfile,
with_tree,
SkipTest,
)
from datalad.utils import (
Path,
chpwd,
path_startswith,
swallow_outputs,
)
from datalad.support.gitrepo import GitRepo
from datalad.support.annexrepo import AnnexRepo
from datalad.core.distributed.clone import Clone
from datalad.core.distributed.push import Push
from datalad.support.network import get_local_file_url
DEFAULT_REFSPEC = "refs/heads/{0}:refs/heads/{0}".format(DEFAULT_BRANCH)
@with_tempfile(mkdir=True)
@with_tempfile(mkdir=True)
def test_invalid_call(origin, tdir):
ds = Dataset(origin).create()
# no target
assert_status('impossible', ds.push(on_failure='ignore'))
# no dataset
with chpwd(tdir):
assert_raises(InsufficientArgumentsError, Push.__call__)
# dataset, but outside path
assert_raises(IncompleteResultsError, ds.push, path=tdir)
# given a path constraint that doesn't match anything, will cause
# nothing to be done
assert_status('notneeded', ds.push(path=ds.pathobj / 'nothere'))
# unavailable subdataset
dummy_sub = ds.create('sub')
dummy_sub.uninstall()
assert_in('sub', ds.subdatasets(fulfilled=False, result_xfm='relpaths'))
# now an explicit call to publish the unavailable subdataset
assert_raises(ValueError, ds.push, 'sub')
target = mk_push_target(ds, 'target', tdir, annex=True)
# revision that doesn't exist
assert_raises(
ValueError,
ds.push, to='target', since='09320957509720437523')
# If a publish() user accidentally passes since='', which push() spells as
# since='^', the call is aborted.
assert_raises(
ValueError,
ds.push, to='target', since='')
def mk_push_target(ds, name, path, annex=True, bare=True):
# life could be simple, but nothing is simple on windows
#src.create_sibling(dst_path, name='target')
if annex:
if bare:
target = GitRepo(path=path, bare=True, create=True)
# cannot use call_annex()
target.call_git(['annex', 'init'])
else:
target = AnnexRepo(path, init=True, create=True)
if not target.is_managed_branch():
# for managed branches we need more fireworks->below
target.config.set(
'receive.denyCurrentBranch', 'updateInstead',
where='local')
else:
target = GitRepo(path=path, bare=bare, create=True)
ds.siblings('add', name=name, url=path, result_renderer=None)
if annex and not bare and target.is_managed_branch():
# maximum complication
# the target repo already has a commit that is unrelated
# to the source repo, because it has built a reference
# commit for the managed branch.
# the only sane approach is to let git-annex establish a shared
# history
if AnnexRepo.git_annex_version > "8.20210631":
ds.repo.call_annex(['sync', '--allow-unrelated-histories'])
else:
ds.repo.call_annex(['sync'])
ds.repo.call_annex(['sync', '--cleanup'])
return target
@with_tempfile(mkdir=True)
@with_tempfile(mkdir=True)
def check_push(annex, src_path, dst_path):
# prepare src
src = Dataset(src_path).create(annex=annex)
src_repo = src.repo
# push should not add branches to the local dataset
orig_branches = src_repo.get_branches()
assert_not_in('synced/' + DEFAULT_BRANCH, orig_branches)
res = src.push(on_failure='ignore')
assert_result_count(res, 1)
assert_in_results(
res, status='impossible',
message='No push target given, and none could be auto-detected, '
'please specify via --to')
eq_(orig_branches, src_repo.get_branches())
# target sibling
target = mk_push_target(src, 'target', dst_path, annex=annex)
eq_(orig_branches, src_repo.get_branches())
res = src.push(to="target")
eq_(orig_branches, src_repo.get_branches())
assert_result_count(res, 2 if annex else 1)
assert_in_results(
res,
action='publish', status='ok', target='target',
refspec=DEFAULT_REFSPEC,
operations=['new-branch'])
assert_repo_status(src_repo, annex=annex)
eq_(list(target.get_branch_commits_(DEFAULT_BRANCH)),
list(src_repo.get_branch_commits_(DEFAULT_BRANCH)))
# configure a default merge/upstream target
src.config.set('branch.{}.remote'.format(DEFAULT_BRANCH),
'target', where='local')
src.config.set('branch.{}.merge'.format(DEFAULT_BRANCH),
DEFAULT_BRANCH, where='local')
# don't fail when doing it again, no explicit target specification
# needed anymore
res = src.push()
eq_(orig_branches, src_repo.get_branches())
# and nothing is pushed
assert_status('notneeded', res)
assert_repo_status(src_repo, annex=annex)
eq_(list(target.get_branch_commits_(DEFAULT_BRANCH)),
list(src_repo.get_branch_commits_(DEFAULT_BRANCH)))
# some modification:
(src.pathobj / 'test_mod_file').write_text("Some additional stuff.")
src.save(to_git=True, message="Modified.")
(src.pathobj / 'test_mod_annex_file').write_text("Heavy stuff.")
src.save(to_git=not annex, message="Modified again.")
assert_repo_status(src_repo, annex=annex)
# we could say since='HEAD~2' to make things fast, or we are lazy
# and say since='^' to indicate the state of the tracking remote
# which is the same, because we made to commits since the last push.
res = src.push(to='target', since="^", jobs=2)
assert_in_results(
res,
action='publish', status='ok', target='target',
refspec=DEFAULT_REFSPEC,
# we get to see what happened
operations=['fast-forward'])
if annex:
# we got to see the copy result for the annexed files
assert_in_results(
res,
action='copy',
status='ok',
path=str(src.pathobj / 'test_mod_annex_file'))
# we published, so we can drop and reobtain
ok_(src_repo.file_has_content('test_mod_annex_file'))
src_repo.drop('test_mod_annex_file')
ok_(not src_repo.file_has_content('test_mod_annex_file'))
src_repo.get('test_mod_annex_file')
ok_(src_repo.file_has_content('test_mod_annex_file'))
ok_file_has_content(
src_repo.pathobj / 'test_mod_annex_file',
'Heavy stuff.')
eq_(list(target.get_branch_commits_(DEFAULT_BRANCH)),
list(src_repo.get_branch_commits_(DEFAULT_BRANCH)))
if not (annex and src_repo.is_managed_branch()):
# the following doesn't make sense in managed branches, because
# a commit that could be amended is no longer the last commit
# of a branch after a sync has happened (which did happen
# during the last push above
# amend and change commit msg in order to test for force push:
src_repo.commit("amended", options=['--amend'])
# push should be rejected (non-fast-forward):
res = src.push(to='target', since='HEAD~2', on_failure='ignore')
# fails before even touching the annex branch
assert_in_results(
res,
action='publish', status='error', target='target',
refspec=DEFAULT_REFSPEC,
operations=['rejected', 'error'])
# push with force=True works:
res = src.push(to='target', since='HEAD~2', force='gitpush')
assert_in_results(
res,
action='publish', status='ok', target='target',
refspec=DEFAULT_REFSPEC,
operations=['forced-update'])
eq_(list(target.get_branch_commits_(DEFAULT_BRANCH)),
list(src_repo.get_branch_commits_(DEFAULT_BRANCH)))
# we do not have more branches than we had in the beginning
# in particular no 'synced/<default branch>'
eq_(orig_branches, src_repo.get_branches())
def test_push():
yield check_push, False
yield check_push, True
def check_datasets_order(res, order='bottom-up'):
"""Check that all type=dataset records not violating the expected order
it is somewhat weak test, i.e. records could be produced so we
do not detect that order is violated, e.g. a/b c/d would satisfy
either although they might be neither depth nor breadth wise. But
this test would allow to catch obvious violations like a, a/b, a
"""
prev = None
for r in res:
if r.get('type') != 'dataset':
continue
if prev and r['path'] != prev:
if order == 'bottom-up':
assert_false(path_startswith(r['path'], prev))
elif order == 'top-down':
assert_false(path_startswith(prev, r['path']))
else:
raise ValueError(order)
prev = r['path']
@slow # 33sec on Yarik's laptop
@with_tempfile
@with_tempfile(mkdir=True)
@with_tempfile(mkdir=True)
@with_tempfile(mkdir=True, suffix='sub')
@with_tempfile(mkdir=True, suffix='subnoannex')
@with_tempfile(mkdir=True, suffix='subsub')
def test_push_recursive(
origin_path, src_path, dst_top, dst_sub, dst_subnoannex, dst_subsub):
# dataset with two submodules and one subsubmodule
origin = Dataset(origin_path).create()
origin_subm1 = origin.create('sub m')
origin_subm1.create('subsub m')
origin.create('subm noannex', annex=False)
origin.save()
assert_repo_status(origin.path)
# prepare src as a fresh clone with all subdatasets checkout out recursively
# running on a clone should make the test scenario more different than
# test_push(), even for the pieces that should be identical
top = Clone.__call__(source=origin.path, path=src_path)
subs = top.get('.', recursive=True, get_data=False, result_xfm='datasets')
# order for '.' should not be relied upon, so sort by path
sub, subsub, subnoannex = sorted(subs, key=lambda ds: ds.path)
target_top = mk_push_target(top, 'target', dst_top, annex=True)
# subdatasets have no remote yet, so recursive publishing should fail:
res = top.push(to="target", recursive=True, on_failure='ignore')
check_datasets_order(res)
assert_in_results(
res, path=top.path, type='dataset',
refspec=DEFAULT_REFSPEC,
operations=['new-branch'], action='publish', status='ok',
target='target')
for d in (sub, subsub, subnoannex):
assert_in_results(
res, status='error', type='dataset', path=d.path,
message=("Unknown target sibling '%s'.",
'target'))
# now fix that and set up targets for the submodules
target_sub = mk_push_target(sub, 'target', dst_sub, annex=True)
target_subnoannex = mk_push_target(
subnoannex, 'target', dst_subnoannex, annex=False)
target_subsub = mk_push_target(subsub, 'target', dst_subsub, annex=True)
# and same push call as above
res = top.push(to="target", recursive=True)
check_datasets_order(res)
# topds skipped
assert_in_results(
res, path=top.path, type='dataset',
action='publish', status='notneeded', target='target')
# the rest pushed
for d in (sub, subsub, subnoannex):
assert_in_results(
res, status='ok', type='dataset', path=d.path,
refspec=DEFAULT_REFSPEC)
# all corresponding branches match across all datasets
for s, d in zip((top, sub, subnoannex, subsub),
(target_top, target_sub, target_subnoannex,
target_subsub)):
eq_(list(s.repo.get_branch_commits_(DEFAULT_BRANCH)),
list(d.get_branch_commits_(DEFAULT_BRANCH)))
if s != subnoannex:
eq_(list(s.repo.get_branch_commits_("git-annex")),
list(d.get_branch_commits_("git-annex")))
# rerun should not result in further pushes of the default branch
res = top.push(to="target", recursive=True)
check_datasets_order(res)
assert_not_in_results(
res, status='ok', refspec=DEFAULT_REFSPEC)
assert_in_results(
res, status='notneeded', refspec=DEFAULT_REFSPEC)
# now annex a file in subsub
test_copy_file = subsub.pathobj / 'test_mod_annex_file'
test_copy_file.write_text("Heavy stuff.")
# save all the way up
assert_status(
('ok', 'notneeded'),
top.save(message='subsub got something', recursive=True))
assert_repo_status(top.path)
# publish straight up, should be smart by default
res = top.push(to="target", recursive=True)
check_datasets_order(res)
# we see 3 out of 4 datasets pushed (sub noannex was left unchanged)
for d in (top, sub, subsub):
assert_in_results(
res, status='ok', type='dataset', path=d.path,
refspec=DEFAULT_REFSPEC)
# file content copied too
assert_in_results(
res,
action='copy',
status='ok',
path=str(test_copy_file))
# verify it is accessible, drop and bring back
assert_status('ok', top.drop(str(test_copy_file)))
ok_(not subsub.repo.file_has_content('test_mod_annex_file'))
top.get(test_copy_file)
ok_file_has_content(test_copy_file, 'Heavy stuff.')
# make two modification
(sub.pathobj / 'test_mod_annex_file').write_text('annex')
(subnoannex.pathobj / 'test_mod_file').write_text('git')
# save separately
top.save(sub.pathobj, message='annexadd', recursive=True)
top.save(subnoannex.pathobj, message='gitadd', recursive=True)
# now only publish the latter one
res = top.push(to="target", since=DEFAULT_BRANCH + '~1', recursive=True)
# nothing copied, no reports on the other modification
assert_not_in_results(res, action='copy')
assert_not_in_results(res, path=sub.path)
for d in (top, subnoannex):
assert_in_results(
res, status='ok', type='dataset', path=d.path,
refspec=DEFAULT_REFSPEC)
# an unconditional push should now pick up the remaining changes
res = top.push(to="target", recursive=True)
assert_in_results(
res,
action='copy',
status='ok',
path=str(sub.pathobj / 'test_mod_annex_file'))
assert_in_results(
res, status='ok', type='dataset', path=sub.path,
refspec=DEFAULT_REFSPEC)
for d in (top, subnoannex, subsub):
assert_in_results(
res, status='notneeded', type='dataset', path=d.path,
refspec=DEFAULT_REFSPEC)
# if noannex target gets some annex, we still should not fail to push
target_subnoannex.call_git(['annex', 'init'])
# just to ensure that we do need something to push
(subnoannex.pathobj / "newfile").write_text("content")
subnoannex.save()
res = subnoannex.push(to="target")
assert_in_results(res, status='ok', type='dataset')
@slow # 12sec on Yarik's laptop
@with_tempfile(mkdir=True)
@with_tempfile(mkdir=True)
@with_tempfile(mkdir=True)
@with_tempfile(mkdir=True)
def test_push_subds_no_recursion(src_path, dst_top, dst_sub, dst_subsub):
# dataset with one submodule and one subsubmodule
top = Dataset(src_path).create()
sub = top.create('sub m')
test_file = sub.pathobj / 'subdir' / 'test_file'
test_file.parent.mkdir()
test_file.write_text('some')
subsub = sub.create(sub.pathobj / 'subdir' / 'subsub m')
top.save(recursive=True)
assert_repo_status(top.path)
target_top = mk_push_target(top, 'target', dst_top, annex=True)
target_sub = mk_push_target(sub, 'target', dst_sub, annex=True)
target_subsub = mk_push_target(subsub, 'target', dst_subsub, annex=True)
# now publish, but NO recursion, instead give the parent dir of
# both a subdataset and a file in the middle subdataset
res = top.push(
to='target',
# give relative to top dataset to elevate the difficulty a little
path=str(test_file.relative_to(top.pathobj).parent))
assert_status('ok', res)
assert_in_results(res, action='publish', type='dataset', path=top.path)
assert_in_results(res, action='publish', type='dataset', path=sub.path)
assert_in_results(res, action='copy', type='file', path=str(test_file))
# the lowest-level subdataset isn't touched
assert_not_in_results(
res, action='publish', type='dataset', path=subsub.path)
@with_tempfile(mkdir=True)
@with_tempfile(mkdir=True)
def test_force_checkdatapresent(srcpath, dstpath):
src = Dataset(srcpath).create()
target = mk_push_target(src, 'target', dstpath, annex=True, bare=True)
(src.pathobj / 'test_mod_annex_file').write_text("Heavy stuff.")
src.save(to_git=False, message="New annex file")
assert_repo_status(src.path, annex=True)
whereis_prior = src.repo.whereis(files=['test_mod_annex_file'])[0]
res = src.push(to='target', data='nothing')
# nothing reported to be copied
assert_not_in_results(res, action='copy')
# we got the git-push nevertheless
eq_(src.repo.get_hexsha(DEFAULT_BRANCH), target.get_hexsha(DEFAULT_BRANCH))
# nothing moved
eq_(whereis_prior, src.repo.whereis(files=['test_mod_annex_file'])[0])
# now a push without forced no-transfer
# we do not give since, so the non-transfered file is picked up
# and transferred
res = src.push(to='target', force=None)
# no branch change, done before
assert_in_results(res, action='publish', status='notneeded',
refspec=DEFAULT_REFSPEC)
# but availability update
assert_in_results(res, action='publish', status='ok',
refspec='refs/heads/git-annex:refs/heads/git-annex')
assert_in_results(res, status='ok',
path=str(src.pathobj / 'test_mod_annex_file'),
action='copy')
# whereis info reflects the change
ok_(len(whereis_prior) < len(
src.repo.whereis(files=['test_mod_annex_file'])[0]))
# do it yet again will do nothing, because all is up-to-date
assert_status('notneeded', src.push(to='target', force=None))
# an explicit reference point doesn't change that
assert_status('notneeded',
src.push(to='target', force=None, since='HEAD~1'))
# now force data transfer
res = src.push(to='target', force='checkdatapresent')
# no branch change, done before
assert_in_results(res, action='publish', status='notneeded',
refspec=DEFAULT_REFSPEC)
# no availability update
assert_in_results(res, action='publish', status='notneeded',
refspec='refs/heads/git-annex:refs/heads/git-annex')
# but data transfer
assert_in_results(res, status='ok',
path=str(src.pathobj / 'test_mod_annex_file'),
action='copy')
# force data transfer, but data isn't available
src.repo.drop('test_mod_annex_file')
res = src.push(to='target', path='.', force='checkdatapresent', on_failure='ignore')
assert_in_results(res, status='impossible',
path=str(src.pathobj / 'test_mod_annex_file'),
action='copy',
message='Slated for transport, but no content present')
@skip_if_on_windows # https://github.com/datalad/datalad/issues/4278
@with_tempfile(mkdir=True)
@with_tree(tree={'ria-layout-version': '1\n'})
def test_ria_push(srcpath, dstpath):
# complex test involving a git remote, a special remote, and a
# publication dependency
src = Dataset(srcpath).create()
testfile = src.pathobj / 'test_mod_annex_file'
testfile.write_text("Heavy stuff.")
src.save()
assert_status(
'ok',
src.create_sibling_ria(
"ria+{}".format(get_local_file_url(dstpath, compatibility='git')),
"datastore", new_store_ok=True))
res = src.push(to='datastore')
assert_in_results(
res, action='publish', target='datastore', status='ok',
refspec=DEFAULT_REFSPEC)
assert_in_results(
res, action='publish', target='datastore', status='ok',
refspec='refs/heads/git-annex:refs/heads/git-annex')
assert_in_results(
res, action='copy', target='datastore-storage', status='ok',
path=str(testfile))
@with_tempfile(mkdir=True)
@with_tempfile(mkdir=True)
def test_gh1426(origin_path, target_path):
# set up a pair of repos, one the published copy of the other
origin = Dataset(origin_path).create()
target = mk_push_target(
origin, 'target', target_path, annex=True, bare=False)
origin.push(to='target')
assert_repo_status(origin.path)
assert_repo_status(target.path)
eq_(origin.repo.get_hexsha(DEFAULT_BRANCH),
target.get_hexsha(DEFAULT_BRANCH))
# gist of #1426 is that a newly added subdataset does not cause the
# superdataset to get published
origin.create('sub')
assert_repo_status(origin.path)
neq_(origin.repo.get_hexsha(DEFAULT_BRANCH),
target.get_hexsha(DEFAULT_BRANCH))
# now push
res = origin.push(to='target')
assert_result_count(
res, 1, status='ok', type='dataset', path=origin.path,
action='publish', target='target', operations=['fast-forward'])
eq_(origin.repo.get_hexsha(DEFAULT_BRANCH),
target.get_hexsha(DEFAULT_BRANCH))
@skip_if_adjusted_branch # gh-4075
@skip_if_on_windows # create_sibling incompatible with win servers
@skip_ssh
@with_tree(tree={'1': '123'})
@with_tempfile(mkdir=True)
@serve_path_via_http
def test_publish_target_url(src, desttop, desturl):
# https://github.com/datalad/datalad/issues/1762
ds = Dataset(src).create(force=True)
ds.save('1')
ds.create_sibling('ssh://datalad-test:%s/subdir' % desttop,
name='target',
target_url=desturl + 'subdir/.git')
results = ds.push(to='target')
assert results
ok_file_has_content(Path(desttop, 'subdir', '1'), '123')
@with_tempfile(mkdir=True)
@with_tempfile()
@with_tempfile()
def test_gh1763(src, target1, target2):
# this test is very similar to test_publish_depends, but more
# comprehensible, and directly tests issue 1763
src = Dataset(src).create(force=True)
target1 = mk_push_target(src, 'target1', target1, bare=False)
target2 = mk_push_target(src, 'target2', target2, bare=False)
src.siblings('configure', name='target2', publish_depends='target1',
result_renderer=None)
# a file to annex
(src.pathobj / 'probe1').write_text('probe1')
src.save('probe1', to_git=False)
# make sure the probe is annexed, not straight in Git
assert_in('probe1', src.repo.get_annexed_files(with_content_only=True))
# publish to target2, must handle dependency
src.push(to='target2')
for target in (target1, target2):
# with a managed branch we are pushing into the corresponding branch
# and do not see a change in the worktree
if not target.is_managed_branch():
# direct test for what is in the checkout
assert_in(
'probe1',
target.get_annexed_files(with_content_only=True))
# ensure git-annex knows this target has the file
assert_in(target.config.get('annex.uuid'), src.repo.whereis(['probe1'])[0])
@with_tempfile()
@with_tempfile()
def test_gh1811(srcpath, clonepath):
orig = Dataset(srcpath).create()
(orig.pathobj / 'some').write_text('some')
orig.save()
clone = Clone.__call__(source=orig.path, path=clonepath)
(clone.pathobj / 'somemore').write_text('somemore')
clone.save()
clone.repo.call_git(['checkout', 'HEAD~1'])
res = clone.push(to=DEFAULT_REMOTE, on_failure='ignore')
assert_result_count(res, 1)
assert_result_count(
res, 1,
path=clone.path, type='dataset', action='publish',
status='impossible',
message='There is no active branch, cannot determine remote '
'branch',
)
# FIXME: on crippled FS post-update hook enabling via create-sibling doesn't
# work ATM
@skip_if_adjusted_branch
@with_tempfile()
@with_tempfile()
def test_push_wanted(srcpath, dstpath):
src = Dataset(srcpath).create()
(src.pathobj / 'data.0').write_text('0')
(src.pathobj / 'secure.1').write_text('1')
(src.pathobj / 'secure.2').write_text('2')
src.save()
# Dropping a file to mimic a case of simply not having it locally (thus not
# to be "pushed")
src.drop('secure.2', check=False)
# Annotate sensitive content, actual value "verysecure" does not matter in
# this example
src.repo.set_metadata(
add={'distribution-restrictions': 'verysecure'},
files=['secure.1', 'secure.2'])
src.create_sibling(
dstpath,
annex_wanted="not metadata=distribution-restrictions=*",
name='target',
)
# check that wanted is obeyed, since set in sibling configuration
res = src.push(to='target')
assert_in_results(
res, action='copy', path=str(src.pathobj / 'data.0'), status='ok')
for p in ('secure.1', 'secure.2'):
assert_not_in_results(res, path=str(src.pathobj / p))
assert_status('notneeded', src.push(to='target'))
# check the target to really make sure
dst = Dataset(dstpath)
# normal file, yes
eq_((dst.pathobj / 'data.0').read_text(), '0')
# secure file, no
if dst.repo.is_managed_branch():
neq_((dst.pathobj / 'secure.1').read_text(), '1')
else:
assert_raises(FileNotFoundError, (dst.pathobj / 'secure.1').read_text)
# reset wanted config, which must enable push of secure file
src.repo.set_preferred_content('wanted', '', remote='target')
res = src.push(to='target')
assert_in_results(res, path=str(src.pathobj / 'secure.1'))
eq_((dst.pathobj / 'secure.1').read_text(), '1')
# FIXME: on crippled FS post-update hook enabling via create-sibling doesn't
# work ATM
@skip_if_adjusted_branch
@slow # 10sec on Yarik's laptop
@with_tempfile(mkdir=True)
def test_auto_data_transfer(path):
path = Path(path)
ds_a = Dataset(path / "a").create()
(ds_a.pathobj / "foo.dat").write_text("foo")
ds_a.save()
# Should be the default, but just in case.
ds_a.repo.config.set("annex.numcopies", "1", where="local")
ds_a.create_sibling(str(path / "b"), name="b")
# With numcopies=1, no data is copied with data="auto".
res = ds_a.push(to="b", data="auto", since=None)
assert_not_in_results(res, action="copy")
# Even when a file is explicitly given.
res = ds_a.push(to="b", path="foo.dat", data="auto", since=None)
assert_not_in_results(res, action="copy")
# numcopies=2 changes that.
ds_a.repo.config.set("annex.numcopies", "2", where="local")
res = ds_a.push(to="b", data="auto", since=None)
assert_in_results(
res, action="copy", target="b", status="ok",
path=str(ds_a.pathobj / "foo.dat"))
# --since= limits the files considered by --auto.
(ds_a.pathobj / "bar.dat").write_text("bar")
ds_a.save()
(ds_a.pathobj / "baz.dat").write_text("baz")
ds_a.save()
res = ds_a.push(to="b", data="auto", since="HEAD~1")
assert_not_in_results(
res,
action="copy", path=str(ds_a.pathobj / "bar.dat"))
assert_in_results(
res,
action="copy", target="b", status="ok",
path=str(ds_a.pathobj / "baz.dat"))
# --auto also considers preferred content.
ds_a.repo.config.unset("annex.numcopies", where="local")
ds_a.repo.set_preferred_content("wanted", "nothing", remote="b")
res = ds_a.push(to="b", data="auto", since=None)
assert_not_in_results(
res,
action="copy", path=str(ds_a.pathobj / "bar.dat"))
ds_a.repo.set_preferred_content("wanted", "anything", remote="b")
res = ds_a.push(to="b", data="auto", since=None)
assert_in_results(
res,
action="copy", target="b", status="ok",
path=str(ds_a.pathobj / "bar.dat"))
# FIXME: on crippled FS post-update hook enabling via create-sibling doesn't
# work ATM
@skip_if_adjusted_branch
@slow # 16sec on Yarik's laptop
@with_tempfile(mkdir=True)
def test_auto_if_wanted_data_transfer_path_restriction(path):
path = Path(path)
ds_a = Dataset(path / "a").create()
ds_a_sub0 = ds_a.create("sub0")
ds_a_sub1 = ds_a.create("sub1")
for ds in [ds_a, ds_a_sub0, ds_a_sub1]:
(ds.pathobj / "sec.dat").write_text("sec")
(ds.pathobj / "reg.dat").write_text("reg")
ds_a.save(recursive=True)
ds_a.create_sibling(str(path / "b"), name="b",
annex_wanted="not metadata=distribution-restrictions=*",
recursive=True)
for ds in [ds_a, ds_a_sub0, ds_a_sub1]:
ds.repo.set_metadata(add={"distribution-restrictions": "doesntmatter"},
files=["sec.dat"])
# wanted-triggered --auto can be restricted to subdataset...
res = ds_a.push(to="b", path="sub0", data="auto-if-wanted",
recursive=True)
assert_not_in_results(
res,
action="copy", target="b", status="ok",
path=str(ds_a.pathobj / "reg.dat"))
assert_in_results(
res,
action="copy", target="b", status="ok",
path=str(ds_a_sub0.pathobj / "reg.dat"))
assert_not_in_results(
res,
action="copy", target="b", status="ok",
path=str(ds_a_sub0.pathobj / "sec.dat"))
assert_not_in_results(
res,
action="copy", target="b", status="ok",
path=str(ds_a_sub1.pathobj / "reg.dat"))
# ... and to a wanted file.
res = ds_a.push(to="b", path="reg.dat", data="auto-if-wanted",
recursive=True)
assert_in_results(
res,
action="copy", target="b", status="ok",
path=str(ds_a.pathobj / "reg.dat"))
assert_not_in_results(
res,
action="copy", target="b", status="ok",
path=str(ds_a_sub1.pathobj / "reg.dat"))
# But asking to transfer a file does not do it if the remote has a
# wanted setting and doesn't want it.
res = ds_a.push(to="b", path="sec.dat", data="auto-if-wanted",
recursive=True)
assert_not_in_results(
res,
action="copy", target="b", status="ok",
path=str(ds_a.pathobj / "sec.dat"))
res = ds_a.push(to="b", path="sec.dat", data="anything", recursive=True)
assert_in_results(
res,
action="copy", target="b", status="ok",
path=str(ds_a.pathobj / "sec.dat"))
@with_tempfile(mkdir=True)
def test_push_git_annex_branch_when_no_data(path):
path = Path(path)
ds = Dataset(path / "a").create()
target = mk_push_target(ds, "target", str(path / "target"),
annex=False, bare=True)
(ds.pathobj / "f0").write_text("0")
ds.save()
ds.push(to="target", data="nothing")
assert_in("git-annex",
{d["refname:strip=2"]
for d in target.for_each_ref_(fields="refname:strip=2")})
@known_failure_githubci_osx
@with_tree(tree={"ds": {"f0": "0", "f1": "0", "f2": "0",
"f3": "1",
"f4": "2", "f5": "2"}})
def test_push_git_annex_branch_many_paths_same_data(path):
path = Path(path)
ds = Dataset(path / "ds").create(force=True)
ds.save()
mk_push_target(ds, "target", str(path / "target"),
annex=True, bare=False)
nbytes = sum(ds.repo.get_content_annexinfo(paths=[f])[f]["bytesize"]
for f in [ds.repo.pathobj / "f0",
ds.repo.pathobj / "f3",
ds.repo.pathobj / "f4"])
with swallow_logs(new_level=logging.DEBUG) as cml:
res = ds.push(to="target")
assert_in("{} bytes of annex data".format(nbytes), cml.out)
# 3 files point to content already covered by another file.
assert_result_count(res, 3,
action="copy", type="file", status="notneeded")
@known_failure_githubci_osx
@with_tree(tree={"ds": {"f0": "0"}})
def test_push_matching(path):
path = Path(path)
ds = Dataset(path / "ds").create(force=True)
ds.config.set('push.default', 'matching', where='local')
ds.save()
remote_ds = mk_push_target(ds, 'local', str(path / 'dssibling'),
annex=True, bare=False)
# that fact that the next one even runs makes sure that we are in a better
# place than https://github.com/datalad/datalad/issues/4888
ds.push(to='local')
# and we pushed the commit in the current branch
eq_(remote_ds.get_hexsha(DEFAULT_BRANCH),
ds.repo.get_hexsha(DEFAULT_BRANCH))
@known_failure_githubci_win # https://github.com/datalad/datalad/issues/5271
@with_tempfile(mkdir=True)
@with_tempfile(mkdir=True)
@with_tempfile(mkdir=True)
def test_nested_pushclone_cycle_allplatforms(origpath, storepath, clonepath):
if 'DATALAD_SEED' in os.environ:
# we are using create-sibling-ria via the cmdline in here
# this will create random UUIDs for datasets
# however, given a fixed seed each call to this command will start
# with the same RNG seed, hence yield the same UUID on the same
# machine -- leading to a collision
raise SkipTest(
'Test incompatible with fixed random number generator seed')
# the aim here is this high-level test a std create-push-clone cycle for a
# dataset with a subdataset, with the goal to ensure that correct branches
# and commits are tracked, regardless of platform behavior and condition
# of individual clones. Nothing fancy, just that the defaults behave in
# sensible ways
from datalad.cmd import WitlessRunner as Runner
run = Runner().run
# create original nested dataset
with chpwd(origpath):
run(['datalad', 'create', 'super'])
run(['datalad', 'create', '-d', 'super', str(Path('super', 'sub'))])
# verify essential linkage properties
orig_super = Dataset(Path(origpath, 'super'))
orig_sub = Dataset(orig_super.pathobj / 'sub')
(orig_super.pathobj / 'file1.txt').write_text('some1')
(orig_sub.pathobj / 'file2.txt').write_text('some1')
with chpwd(orig_super.path):
run(['datalad', 'save', '--recursive'])
# TODO not yet reported clean with adjusted branches
#assert_repo_status(orig_super.path)
# the "true" branch that sub is on, and the gitsha of the HEAD commit of it
orig_sub_corr_branch = \
orig_sub.repo.get_corresponding_branch() or orig_sub.repo.get_active_branch()
orig_sub_corr_commit = orig_sub.repo.get_hexsha(orig_sub_corr_branch)
# make sure the super trackes this commit
assert_in_results(
orig_super.subdatasets(),
path=orig_sub.path,
gitshasum=orig_sub_corr_commit,
# TODO it should also track the branch name
# Attempted: https://github.com/datalad/datalad/pull/3817
# But reverted: https://github.com/datalad/datalad/pull/4375
)
# publish to a store, to get into a platform-agnostic state
# (i.e. no impact of an annex-init of any kind)
store_url = 'ria+' + get_local_file_url(storepath)
with chpwd(orig_super.path):
run(['datalad', 'create-sibling-ria', '--recursive',
'-s', 'store', store_url, '--new-store-ok'])
run(['datalad', 'push', '--recursive', '--to', 'store'])
# we are using the 'store' sibling's URL, which should be a plain path
store_super = AnnexRepo(orig_super.siblings(name='store')[0]['url'], init=False)
store_sub = AnnexRepo(orig_sub.siblings(name='store')[0]['url'], init=False)
# both datasets in the store only carry the real branches, and nothing
# adjusted
for r in (store_super, store_sub):
eq_(set(r.get_branches()), set([orig_sub_corr_branch, 'git-annex']))
# and reobtain from a store
cloneurl = 'ria+' + get_local_file_url(str(storepath), compatibility='git')
with chpwd(clonepath):
run(['datalad', 'clone', cloneurl + '#' + orig_super.id, 'super'])
run(['datalad', '-C', 'super', 'get', '--recursive', '.'])
# verify that nothing has changed as a result of a push/clone cycle
clone_super = Dataset(Path(clonepath, 'super'))
clone_sub = Dataset(clone_super.pathobj / 'sub')
assert_in_results(
clone_super.subdatasets(),
path=clone_sub.path,
gitshasum=orig_sub_corr_commit,
)
for ds1, ds2, f in ((orig_super, clone_super, 'file1.txt'),
(orig_sub, clone_sub, 'file2.txt')):
eq_((ds1.pathobj / f).read_text(), (ds2.pathobj / f).read_text())
# get status info that does not recursive into subdatasets, i.e. not
# looking for uncommitted changes
# we should see no modification reported
assert_not_in_results(
clone_super.status(eval_subdataset_state='commit'),
state='modified')
# and now the same for a more expensive full status
assert_not_in_results(
clone_super.status(recursive=True),
state='modified')
@with_tempfile
def test_push_custom_summary(path):
path = Path(path)
ds = Dataset(path / "ds").create()
sib = mk_push_target(ds, "sib", str(path / "sib"), bare=False, annex=False)
(sib.pathobj / "f1").write_text("f1")
sib.save()
(ds.pathobj / "f2").write_text("f2")
ds.save()
# These options are true by default and our tests usually run with a
# temporary home, but set them to be sure.
ds.config.set("advice.pushUpdateRejected", "true", where="local")
ds.config.set("advice.pushFetchFirst", "true", where="local")
with swallow_outputs() as cmo:
ds.push(to="sib", result_renderer="default", on_failure="ignore")
assert_in("Hints:", cmo.out)
assert_in("action summary:", cmo.out)
|
perma_web/perma/migrations/0023_apikey.py
|
rachelaus/perma
| 317 |
145118
|
<reponame>rachelaus/perma<filename>perma_web/perma/migrations/0023_apikey.py
# -*- coding: utf-8 -*-
# Generated by Django 1.9.13 on 2017-05-04 20:55
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
def copy_keys(apps, schema_editor):
if not schema_editor.connection.alias == 'default':
return
cursor = schema_editor.connection.cursor()
try:
# this did not work, as there's a column order mismatch between the two tables
# cursor.execute("INSERT INTO perma_apikey SELECT * FROM tastypie_apikey")
# instead, we ran this:
cursor.execute("INSERT INTO perma_apikey (`id`, `key`, `created`, `user_id`) SELECT `id`, `key`, `created`, `user_id` FROM tastypie_apikey")
# and then faked the migration:
# ./manage.py migrate --fake perma 0023_apikey
except django.db.utils.ProgrammingError:
pass # old tastypie api_key table doesn't exist for this deployment
class Migration(migrations.Migration):
dependencies = [
('perma', '0022_auto_20170320_2050'),
]
operations = [
migrations.CreateModel(
name='ApiKey',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('key', models.CharField(blank=True, db_index=True, default=b'', max_length=128)),
('created', models.DateTimeField(default=django.utils.timezone.now)),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='api_key', to=settings.AUTH_USER_MODEL)),
],
),
migrations.RunPython(copy_keys),
]
|
glslc/test/option_dash_M.py
|
janesma/shaderc
| 2,151 |
145141
|
# Copyright 2015 The Shaderc Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import expect
import os.path
from environment import File, Directory
from glslc_test_framework import inside_glslc_testsuite
from placeholder import FileShader
from glslc_test_framework import GlslCTest
MINIMAL_SHADER = '#version 140\nvoid main() {}'
EMPTY_SHADER_IN_CURDIR = Directory('.', [File('shader.vert', MINIMAL_SHADER)])
EMPTY_SHADER_IN_SUBDIR = Directory('subdir',
[File('shader.vert', MINIMAL_SHADER)])
def process_test_specified_dependency_info_rules(test_specified_rules):
"""A helper function to process the expected dependency info rules
specified in tests before checking the actual dependency rule output.
This is required because the filename and path of temporary files created
through FileShader is unknown at the time the expected dependency info rules
are declared.
Note this function process the given rule list in-place.
"""
for rule in test_specified_rules:
# If the 'target' value is not a hard-coded file name but a
# FileShader, we need its full path, append extension to it and
# strip the directory component from it to get the complete target
# name.
if isinstance(rule['target'], FileShader):
rule['target'] = rule['target'].filename
if 'target_extension' in rule:
if rule['target_extension'] is not None:
rule['target'] = rule['target'] + rule['target_extension']
rule.pop('target_extension')
rule['target'] = os.path.basename(rule['target'])
# The dependency set may have FileShader too, we need to replace
# them with their absolute paths.
dependent_file_name_set = set()
for dependent_file in rule['dependency']:
if isinstance(dependent_file, FileShader):
dependent_file_name_set.add(dependent_file.filename)
else:
dependent_file_name_set.add(dependent_file)
rule['dependency'] = dependent_file_name_set
def parse_text_rules(text_lines):
""" A helper function to read text lines and construct and returns a list of
dependency rules which can be used for comparison.
The list is built with the text order. Each rule is described in the
following way:
{'target': <target name>, 'dependency': <set of dependent filenames>}
"""
rules = []
for line in text_lines:
if line.strip() == "":
continue
rule = {'target': line.split(': ')[0].strip(),
'dependency': set(line.split(': ')[-1].strip().split(' '))}
rules.append(rule)
return rules
class DependencyInfoStdoutMatch(GlslCTest):
"""Mixin class for tests that can expect dependency info in Stdout.
To mix in this class, the subclass needs to provide
dependency_rules_expected as a list of dictionaries, each dictionary
describes one expected make rule for a target file. A expected rule should
be specified in the following way:
rule = {'target': <target name>,
'target_extension': <.spv, .spvasm or None>,
'dependency': <dependent file names>}
The 'target_extension' field is optional, its value will be appended to
'target' to get complete target name.
And the list 'dependency_rules_expected' is a list of such rules and the
order of the rules does matter.
"""
def check_stdout_dependency_info(self, status):
if not status.stdout:
return False, 'Expect dependency rules on stdout'
rules = parse_text_rules(status.stdout.split('\n'))
process_test_specified_dependency_info_rules(
self.dependency_rules_expected)
if self.dependency_rules_expected != rules:
return False, ('Incorrect dependency info:\n{ac_rules}\n'
'Expected:\n{ex_rules}\n'
'Stdout output:\n{ac_stdout}\n'.format(
ac_rules=rules,
ex_rules=self.dependency_rules_expected,
ac_stdout=status.stdout))
return True, ''
@inside_glslc_testsuite('OptionsCapM')
class TestDashCapMSingleInputRelativePathNoInclude(DependencyInfoStdoutMatch):
"""Tests -M with single input file which doesn't contain #include and is
represented in relative path.
e.g. glslc -M shader.vert
=> shader.vert.spv: shader.vert
"""
environment = EMPTY_SHADER_IN_CURDIR
glslc_args = ['-M', 'shader.vert']
dependency_rules_expected = [{'target': "shader.vert.spv",
'dependency': {"shader.vert"}}]
@inside_glslc_testsuite('OptionsCapM')
class TestDashCapMSingleInputAbsolutePathNoInclude(DependencyInfoStdoutMatch):
"""Tests -M with single input file which doesn't contain #include and is
represented in absolute path.
e.g. glslc -M /usr/local/shader.vert
=> shader.vert.spv: /usr/local/shader.vert
"""
shader = FileShader(MINIMAL_SHADER, '.vert')
glslc_args = ['-M', shader]
dependency_rules_expected = [{'target': shader,
'target_extension': '.spv',
'dependency': {shader}}]
@inside_glslc_testsuite('OptionsCapM')
class TestDashCapMSingleInputRelativePathWithInclude(
DependencyInfoStdoutMatch):
"""Tests -M with single input file which does contain #include and is
represented in relative path.
e.g. glslc -M a.vert
=> a.vert.spv: a.vert b.vert
"""
environment = Directory('.', [
File('a.vert', '#version 140\n#include "b.vert"\nvoid main(){}\n'),
File('b.vert', 'void foo(){}\n'),
])
glslc_args = ['-M', 'a.vert']
dependency_rules_expected = [{'target': 'a.vert.spv',
'dependency': {'a.vert', 'b.vert'}}]
@inside_glslc_testsuite('OptionsCapM')
class TestDashCapMSingleInputRelativePathWithIncludeSubdir(
DependencyInfoStdoutMatch):
"""Tests -M with single input file which does #include another file in a
subdirectory of current directory and is represented in relative path.
e.g. glslc -M a.vert
=> a.vert.spv: a.vert include/b.vert
"""
environment = Directory('.', [
File('a.vert', ('#version 140\n#include "include/b.vert"'
'\nvoid main(){}\n')),
Directory('include', [File('b.vert', 'void foo(){}\n')]),
])
glslc_args = ['-M', 'a.vert']
dependency_rules_expected = [{'target': 'a.vert.spv',
'dependency': {'a.vert', 'include/b.vert'}}]
@inside_glslc_testsuite('OptionsCapM')
class TestDashCapMSingleInputRelativePathWithDashI(DependencyInfoStdoutMatch):
"""Tests -M with single input file works with -I option. The #include
directive does not specify 'include/' for the file to be include.
e.g. glslc -M a.vert -I include
=> a.vert.spv: a.vert include/b.vert
"""
environment = Directory('.', [
File('a.vert', ('#version 140\n#include "b.vert"'
'\nvoid main(){}\n')),
Directory('include', [File('b.vert', 'void foo(){}\n')]),
])
glslc_args = ['-M', 'a.vert', '-I', 'include']
dependency_rules_expected = [{'target': 'a.vert.spv',
'dependency': {'a.vert', 'include/b.vert'}}]
@inside_glslc_testsuite('OptionsCapM')
class TestDashCapMSingleInputRelativePathWithNestedInclude(
DependencyInfoStdoutMatch):
"""Tests -M with single input file under nested #include case. The input file
is represented in relative path.
e.g. glslc -M a.vert
=> a.vert.spv: a.vert b.vert c.vert
"""
environment = Directory('.', [
File('a.vert', '#version 140\n#include "b.vert"\nvoid main(){}\n'),
File('b.vert', 'void foo(){}\n#include "c.vert"\n'),
File('c.vert', 'void bar(){}\n'),
])
glslc_args = ['-M', 'a.vert']
dependency_rules_expected = [{'target': 'a.vert.spv',
'dependency':
{'a.vert', 'b.vert', 'c.vert'}}]
@inside_glslc_testsuite('OptionsCapM')
class TestDashCapMMultipleInputRelativePathNoInclude(
DependencyInfoStdoutMatch):
"""Tests -M with multiple input file which don't contain #include and are
represented in relative paths.
e.g. glslc -M a.vert b.vert
=> a.vert.spv: a.vert
b.vert.spv: b.vert
"""
environment = Directory('.', [
File('a.vert', MINIMAL_SHADER),
File('b.vert', MINIMAL_SHADER),
])
glslc_args = ['-M', 'a.vert', 'b.vert']
dependency_rules_expected = [{'target': 'a.vert.spv',
'dependency': {'a.vert'}},
{'target': 'b.vert.spv',
'dependency': {'b.vert'}}, ]
@inside_glslc_testsuite('OptionsCapM')
class TestDashCapMMultipleInputAbsolutePathNoInclude(
DependencyInfoStdoutMatch):
"""Tests -M with single input file which doesn't contain #include and is
represented in absolute path.
e.g. glslc -M /usr/local/a.vert /usr/local/b.vert
=> a.vert.spv: /usr/local/a.vert
b.vert.spv: /usr/local/b.vert
"""
shader_a = FileShader(MINIMAL_SHADER, '.vert')
shader_b = FileShader(MINIMAL_SHADER, '.vert')
glslc_args = ['-M', shader_a, shader_b]
dependency_rules_expected = [{'target': shader_a,
'target_extension': '.spv',
'dependency': {shader_a}},
{'target': shader_b,
'target_extension': '.spv',
'dependency': {shader_b}}, ]
@inside_glslc_testsuite('OptionsCapM')
class TestDashCapMDashCapMT(DependencyInfoStdoutMatch):
"""Tests -MT works with -M. User can specify the target object name in the
generated dependency info.
e.g. glslc -M shader.vert -MT target
=> target: shader.vert
"""
environment = EMPTY_SHADER_IN_CURDIR
glslc_args = ['-M', 'shader.vert', '-MT', 'target']
dependency_rules_expected = [{'target': 'target',
'dependency': {'shader.vert'}}]
@inside_glslc_testsuite('OptionsCapM')
class TestDashCapMInputAbsolutePathWithInclude(DependencyInfoStdoutMatch):
"""Tests -M have included files represented in absolute paths when the input
file is represented in absolute path.
E.g. Assume a.vert has '#include "b.vert"'
glslc -M /usr/local/a.vert
=> a.vert.spv: /usr/local/a.vert /usr/local/b.vert
"""
environment = Directory('.', [File('b.vert', 'void foo(){}\n')])
shader_main = FileShader(
'#version 140\n#include "b.vert"\nvoid main(){}\n', '.vert')
glslc_args = ['-M', shader_main]
dependency_rules_expected = [{
'target': shader_main,
'target_extension': '.spv',
'dependency': {shader_main}
# The dependency here is not complete. we can not get the absolute path
# of b.vert here. It will be added in check_stdout_dependency_info()
}]
def check_stdout_dependency_info(self, status):
# Add the absolute path of b.vert to the dependency set
self.dependency_rules_expected[0]['dependency'].add(os.path.dirname(
self.shader_main.filename) + '/b.vert')
return DependencyInfoStdoutMatch.check_stdout_dependency_info(self,
status)
@inside_glslc_testsuite('OptionsCapM')
class TestDashCapMSingleInputAbsolutePathWithIncludeSubdir(
DependencyInfoStdoutMatch):
"""Tests -M with single input file which does #include another file in a
subdirectory of current directory and is represented in absolute path.
e.g. glslc -M /usr/local/a.vert
=> a.vert.spv: /usr/local/a.vert /usr/local/include/b.vert
"""
environment = Directory('.', [
Directory('include', [File('b.vert', 'void foo(){}\n')]),
])
shader_main = FileShader('#version 140\n#include "include/b.vert"',
'.vert')
glslc_args = ['-M', shader_main]
dependency_rules_expected = [{
'target': shader_main,
'target_extension': '.spv',
'dependency': {shader_main}
# The dependency here is not complete. we can not get the absolute
# path of include/b.vert here. It will be added in
# check_stdout_dependency_info()
}]
def check_stdout_dependency_info(self, status):
# Add the absolute path of include/b.vert to the dependency set
self.dependency_rules_expected[0]['dependency'].add(os.path.dirname(
self.shader_main.filename) + '/include/b.vert')
return DependencyInfoStdoutMatch.check_stdout_dependency_info(self,
status)
@inside_glslc_testsuite('OptionsCapM')
class TestDashCapMOverridesOtherModes(DependencyInfoStdoutMatch):
"""Tests -M overrides other compiler mode options, includeing -E, -c and -S.
"""
environment = Directory('.', [
File('a.vert', MINIMAL_SHADER),
File('b.vert', MINIMAL_SHADER),
])
glslc_args = ['-M', '-E', '-c', '-S', 'a.vert', 'b.vert']
dependency_rules_expected = [{'target': 'a.vert.spv',
'dependency': {'a.vert'}},
{'target': 'b.vert.spv',
'dependency': {'b.vert'}}]
@inside_glslc_testsuite('OptionsCapM')
class TestDashCapMMEquivalentToCapM(DependencyInfoStdoutMatch):
"""Tests that -MM behaves as -M.
e.g. glslc -MM shader.vert
=> shader.vert.spv: shader.vert
"""
environment = EMPTY_SHADER_IN_CURDIR
glslc_args = ['-MM', 'shader.vert']
dependency_rules_expected = [{'target': 'shader.vert.spv',
'dependency': {'shader.vert'}}]
@inside_glslc_testsuite('OptionsCapM')
class TestDashCapMImpliesDashCapE(DependencyInfoStdoutMatch,
expect.NoOutputOnStderr):
"""Tests that -M implies -E, a .glsl file without an explict stage should
not generate an error.
e.g. glslc -M shader.glsl
=> shader.spv: shader.glsl
<no error message should be generated>
"""
environment = Directory('.', [File('shader.glsl', MINIMAL_SHADER)])
glslc_args = ['-M', 'shader.glsl']
dependency_rules_expected = [{'target': 'shader.spv',
'dependency': {'shader.glsl'}}]
@inside_glslc_testsuite('OptionsCapM')
class TestDashCapMImpliesDashW(DependencyInfoStdoutMatch,
expect.NoOutputOnStderr):
"""Tests that -M implies -w, a deprecated attribute should not generate
warning message.
e.g. glslc -M shader.vert
=> shader.vert.spv: shader.vert
<no warning message should be generated>
"""
environment = Directory('.', [File(
'shader.vert', '#version 140\nattribute float x;\nvoid main() {}')])
glslc_args = ['-M', 'shader.vert']
dependency_rules_expected = [{'target': 'shader.vert.spv',
'dependency': {'shader.vert'}}]
@inside_glslc_testsuite('OptionsCapM')
class TestDashCapMMImpliesDashCapE(DependencyInfoStdoutMatch,
expect.NoOutputOnStderr):
"""Tests that -M implies -E, a .glsl file without an explict stage should
not generate an error.
e.g. glslc -MM shader.glsl
=> shader.spv: shader.glsl
<no error message should be generated>
"""
environment = Directory('.', [File('shader.glsl', MINIMAL_SHADER)])
glslc_args = ['-MM', 'shader.glsl']
dependency_rules_expected = [{'target': 'shader.spv',
'dependency': {'shader.glsl'}}]
@inside_glslc_testsuite('OptionsCapM')
class TestDashCapMMImpliesDashW(DependencyInfoStdoutMatch,
expect.NoOutputOnStderr):
"""Tests that -MM implies -w, a deprecated attribute should not generate
warning message.
e.g. glslc -MM shader.vert
=> shader.vert.spv: shader.vert
<no warning message should be generated>
"""
environment = Directory('.', [File(
'shader.vert', '#version 140\nattribute float x;\nvoid main() {}')])
glslc_args = ['-MM', 'shader.vert']
dependency_rules_expected = [{'target': 'shader.vert.spv',
'dependency': {'shader.vert'}}]
@inside_glslc_testsuite('OptionsCapM')
class TestDashCapMD(expect.ValidFileContents, expect.ValidNamedObjectFile):
"""Tests that -MD generates dependency info file and compilation output.
e.g. glslc -MD shader.vert
=> <a.spv: valid SPIR-V object file>
=> <shader.vert.spv.d: dependency info>
"""
environment = EMPTY_SHADER_IN_CURDIR
glslc_args = ['-MD', 'shader.vert']
expected_object_filenames = ('a.spv', )
target_filename = 'shader.vert.spv.d'
expected_file_contents = ['shader.vert.spv: shader.vert\n']
class DependencyInfoFileMatch(GlslCTest):
"""Mixin class for tests that can expect dependency info files.
To mix in this class, subclasses need to provide dependency_info_filenames
and dependency_info_files_expected_contents which are two lists.
list dependency_info_filenames contains the dependency info file names and
list dependency_info_files_expected_contents contains the expected matching
dependency rules.
The item order of the two lists should match, which means:
dependency_info_files_expected_contents[i] should describe the
dependency rules saved in dependency_info_filenames[i]
The content of each dependency info file is described in same 'list of dict'
structure explained in class DependencyInfoStdoutMatch's doc string.
"""
def check_dependency_info_files(self, status):
dep_info_files = \
[os.path.join(status.directory,
f) for f in self.dependency_info_filenames]
for i, df in enumerate(dep_info_files):
if not os.path.isfile(df):
return False, 'Cannot find file: ' + df
try:
with open(df, 'r') as dff:
content = dff.read()
rules = parse_text_rules(content.split('\n'))
process_test_specified_dependency_info_rules(
self.dependency_info_files_expected_contents[i])
if self.dependency_info_files_expected_contents[
i] != rules:
return False, (
'Incorrect dependency info:\n{ac_rules}\n'
'Expected:\n{ex_rules}\n'
'Incorrect file output:\n{ac_out}\n'
'Incorrect dependency info file:\n{ac_file}\n'.format(
ac_rules=rules,
ex_rules=self.dependency_rules_expected,
ac_stdout=content,
ac_file=df))
except IOError:
return False, ('Could not open dependency info file ' + df +
' for reading')
return True, ''
@inside_glslc_testsuite('OptionsCapM')
class TestDashCapMWorksWithDashO(DependencyInfoFileMatch):
"""Tests -M works with -o option. When user specifies an output file name
with -o, the dependency info should be dumped to the user specified output
file.
"""
environment = EMPTY_SHADER_IN_CURDIR
glslc_args = ['-M', 'shader.vert', '-o', 'dep_info']
dependency_info_filenames = ('dep_info', )
dependency_info_files_expected_contents = []
dependency_info_files_expected_contents.append(
[{'target': 'shader.vert.spv',
'dependency': {'shader.vert'}}])
@inside_glslc_testsuite('OptionsCapM')
class TestDashCapMDMultipleFile(expect.ValidNamedObjectFile,
DependencyInfoFileMatch):
"""Tests that -MD generates dependency info file for multiple files.
e.g. glslc -MD a.vert b.vert -c
=> <a.vert.spv: valid SPIR-V object file>
=> <a.vert.spv.d: dependency info: "a.vert.spv: a.vert">
=> <b.vert.spv: valid SPIR-V object file>
=> <b.vert.spv.d: dependency info: "b.vert.spv: b.vert">
"""
environment = Directory('.', [File('a.vert', MINIMAL_SHADER),
File('b.vert', MINIMAL_SHADER)])
glslc_args = ['-MD', 'a.vert', 'b.vert', '-c']
expected_object_filenames = ('a.vert.spv', 'b.vert.spv', )
dependency_info_filenames = ['a.vert.spv.d', 'b.vert.spv.d']
dependency_info_files_expected_contents = []
dependency_info_files_expected_contents.append([{'target': 'a.vert.spv',
'dependency': {'a.vert'}}
])
dependency_info_files_expected_contents.append([{'target': 'b.vert.spv',
'dependency': {'b.vert'}}
])
@inside_glslc_testsuite('OptionsCapM')
class TestDashCapMDMultipleFilePreprocessingOnlyMode(expect.StdoutMatch,
DependencyInfoFileMatch):
"""Tests that -MD generates dependency info file for multiple files in
preprocessing only mode.
e.g. glslc -MD a.vert b.vert -E
=> stdout: preprocess result of a.vert and b.vert
=> <a.vert.spv.d: dependency info: "a.vert.spv: a.vert">
=> <b.vert.spv.d: dependency info: "b.vert.spv: b.vert">
"""
environment = Directory('.', [File('a.vert', MINIMAL_SHADER),
File('b.vert', MINIMAL_SHADER)])
glslc_args = ['-MD', 'a.vert', 'b.vert', '-E']
dependency_info_filenames = ['a.vert.spv.d', 'b.vert.spv.d']
dependency_info_files_expected_contents = []
dependency_info_files_expected_contents.append([{'target': 'a.vert.spv',
'dependency': {'a.vert'}}
])
dependency_info_files_expected_contents.append([{'target': 'b.vert.spv',
'dependency': {'b.vert'}}
])
expected_stdout = ("#version 140\nvoid main(){ }\n"
"#version 140\nvoid main(){ }\n")
@inside_glslc_testsuite('OptionsCapM')
class TestDashCapMDMultipleFileDisassemblyMode(expect.ValidNamedAssemblyFile,
DependencyInfoFileMatch):
"""Tests that -MD generates dependency info file for multiple files in
disassembly mode.
e.g. glslc -MD a.vert b.vert -S
=> <a.vert.spvasm: valid SPIR-V assembly file>
=> <a.vert.spvasm.d: dependency info: "a.vert.spvasm: a.vert">
=> <b.vert.spvasm: valid SPIR-V assembly file>
=> <b.vert.spvasm.d: dependency info: "b.vert.spvasm: b.vert">
"""
environment = Directory('.', [File('a.vert', MINIMAL_SHADER),
File('b.vert', MINIMAL_SHADER)])
glslc_args = ['-MD', 'a.vert', 'b.vert', '-S']
expected_assembly_filenames = ('a.vert.spvasm', 'b.vert.spvasm', )
dependency_info_filenames = ['a.vert.spvasm.d', 'b.vert.spvasm.d']
dependency_info_files_expected_contents = []
dependency_info_files_expected_contents.append([{'target': 'a.vert.spvasm',
'dependency': {'a.vert'}}
])
dependency_info_files_expected_contents.append([{'target': 'b.vert.spvasm',
'dependency': {'b.vert'}}
])
@inside_glslc_testsuite('OptionsCapM')
class TestDashCapMT(expect.ValidFileContents, expect.ValidNamedObjectFile):
"""Tests that -MT generates dependency info file with specified target label.
e.g. glslc -MD shader.vert -MT target_label
=> <a.spv: valid SPIR-V object file>
=> <shader.vert.spv.d: dependency info: "target_label: shader.vert">
"""
environment = EMPTY_SHADER_IN_CURDIR
glslc_args = ['-MD', 'shader.vert', '-MT', 'target_label']
expected_object_filenames = ('a.spv', )
target_filename = 'shader.vert.spv.d'
expected_file_contents = ['target_label: shader.vert\n']
@inside_glslc_testsuite('OptionsCapM')
class TestDashCapMF(expect.ValidFileContents, expect.ValidNamedObjectFile):
"""Tests that -MF dumps dependency info into specified file.
e.g. glslc -MD shader.vert -MF dep_file
=> <a.spv: valid SPIR-V object file>
=> <dep_file: dependency info: "shader.vert.spv: shader.vert">
"""
environment = EMPTY_SHADER_IN_CURDIR
glslc_args = ['-MD', 'shader.vert', '-MF', 'dep_file']
expected_object_filenames = ('a.spv', )
target_filename = 'dep_file'
expected_file_contents = ['shader.vert.spv: shader.vert\n']
@inside_glslc_testsuite('OptionsCapM')
class TestDashCapMDSpecifyOutputFileName(expect.ValidFileContents,
expect.ValidNamedObjectFile):
"""Tests that -MD has the default dependency info file name and target
label correct when -o <output_file_name> appears in the command line.
The default dependency info file name and target label should be deduced
from the linking-disabled compilation output.
e.g. glslc -MD subdir/shader.vert -c -o output
=> <./output: valid SPIR-V object file>
=> <./output.d: dependency info: "output: shader.vert">
"""
environment = EMPTY_SHADER_IN_SUBDIR
glslc_args = ['-MD', 'subdir/shader.vert', '-c', '-o', 'output']
expected_object_filenames = ('output', )
target_filename = 'output.d'
expected_file_contents = ['output: subdir/shader.vert\n']
@inside_glslc_testsuite('OptionsCapM')
class TestDashCapMDWithDashMFDashMTDashO(expect.ValidFileContents,
expect.ValidNamedObjectFile):
"""Tests that -MD, -MF, -MT and -o gernates dependency info file and
compilation output file correctly
e.g. glslc -MD subdir/shader.vert -c -o subdir/out -MF dep_info -MT label
=> <subdir/out: valid SPIR-V object file>
=> <dep_info: dependency info: "label: shader.vert">
"""
environment = EMPTY_SHADER_IN_SUBDIR
glslc_args = ['-MD', 'subdir/shader.vert', '-c', '-o', 'subdir/out', '-MF',
'dep_info', '-MT', 'label']
expected_object_filenames = ('subdir/out', )
target_filename = 'dep_info'
expected_file_contents = ['label: subdir/shader.vert\n']
@inside_glslc_testsuite('OptionsCapM')
class TestDashCapMDWithDashMFDashMTDashODisassemblyMode(
expect.ValidFileContents, expect.ValidNamedAssemblyFile):
"""Tests that -MD, -MF, -MT and -o gernates dependency info file and
compilation output file correctly in disassembly mode
e.g. glslc -MD subdir/shader.vert -s -o subdir/out -MF dep_info -MT label
=> <subdir/out: valid SPIR-V object file>
=> <dep_info: dependency info: "label: shader.vert">
"""
environment = EMPTY_SHADER_IN_SUBDIR
glslc_args = ['-MD', 'subdir/shader.vert', '-S', '-o', 'subdir/out', '-MF',
'dep_info', '-MT', 'label']
expected_assembly_filenames = ('subdir/out', )
target_filename = 'dep_info'
expected_file_contents = ['label: subdir/shader.vert\n']
@inside_glslc_testsuite('OptionsCapM')
class TestErrorSetBothDashCapMAndDashCapMD(expect.StderrMatch):
"""Tests that when both -M (or -MM) and -MD are specified, glslc should exit
with an error message complaining the case and neither dependency info
output nor compilation output. This test has -MD before -M flag.
"""
environment = EMPTY_SHADER_IN_CURDIR
glslc_args = ['-MD', '-M', 'shader.vert']
expected_stderr = ['glslc: error: both -M (or -MM) and -MD are specified. '
'Only one should be used at one time.\n']
@inside_glslc_testsuite('OptionsCapM')
class TestErrorSetBothDashCapMDAndDashCapM(expect.StderrMatch):
"""Tests that when both -M (or -MM) and -MD are specified, glslc should exit
with an error message complaining the case and neither dependency info
output nor compilation output. This test has -M before -MD flag.
"""
environment = EMPTY_SHADER_IN_CURDIR
glslc_args = ['-M', '-MD', 'shader.vert']
expected_stderr = ['glslc: error: both -M (or -MM) and -MD are specified. '
'Only one should be used at one time.\n']
@inside_glslc_testsuite('OptionsCapM')
class TestErrorDashCapMFWithMultipleInputFiles(expect.StderrMatch):
"""Tests that when -MF option is specified, only one input file should be
provided."""
environment = Directory('.', [File('a.vert', MINIMAL_SHADER),
File('b.vert', MINIMAL_SHADER)])
glslc_args = ['-MD', 'a.vert', 'b.vert', '-c', '-MF', 'dep_info']
expected_stderr = ['glslc: error: '
'to specify dependency info file name or dependency '
'info target, only one input file is allowed.\n']
@inside_glslc_testsuite('OptionsCapM')
class TestErrorDashCapMTWithMultipleInputFiles(expect.StderrMatch):
"""Tests that when -MT option is specified, only one input file should be
provided."""
environment = Directory('.', [File('a.vert', MINIMAL_SHADER),
File('b.vert', MINIMAL_SHADER)])
glslc_args = ['-M', 'a.vert', 'b.vert', '-c', '-MT', 'target']
expected_stderr = ['glslc: error: '
'to specify dependency info file name or dependency '
'info target, only one input file is allowed.\n']
@inside_glslc_testsuite('OptionsCapM')
class TestErrorDashCapMFMissingDashMAndDashMD(expect.StderrMatch):
"""Tests that when only -MF is specified while -M and -MD are not specified,
glslc should emit an error complaining that the user must specifiy either
-M (-MM) or -MD to generate dependency info.
"""
environment = EMPTY_SHADER_IN_CURDIR
glslc_args = ['-MF', 'dep_info', 'shader.vert', '-c']
expected_stderr = ['glslc: error: '
'to generate dependencies you must specify either -M '
'(-MM) or -MD\n']
@inside_glslc_testsuite('OptionsCapM')
class TestErrorDashCapMTMissingDashMAndMDWith(expect.StderrMatch):
"""Tests that when only -MF and -MT is specified while -M and -MD are not
specified, glslc should emit an error complaining that the user must
specifiy either -M (-MM) or -MD to generate dependency info.
"""
environment = EMPTY_SHADER_IN_CURDIR
glslc_args = ['-MF', 'dep_info', '-MT', 'target', 'shader.vert', '-c']
expected_stderr = ['glslc: error: '
'to generate dependencies you must specify either -M '
'(-MM) or -MD\n']
@inside_glslc_testsuite('OptionsCapM')
class TestErrorMissingDependencyInfoFileName(expect.StderrMatch):
"""Tests that dependency file name is missing when -MF is specified."""
environment = EMPTY_SHADER_IN_CURDIR
glslc_args = ['target', 'shader.vert', '-c', '-MF']
expected_stderr = ['glslc: error: '
'missing dependency info filename after \'-MF\'\n']
@inside_glslc_testsuite('OptionsCapM')
class TestErrorMissingDependencyTargetName(expect.StderrMatch):
"""Tests that dependency target name is missing when -MT is specified."""
environment = EMPTY_SHADER_IN_CURDIR
glslc_args = ['target', 'shader.vert', '-c', '-MT']
expected_stderr = ['glslc: error: '
'missing dependency info target after \'-MT\'\n']
|
next_steps/operations/ml_ops/personalize-step-functions/lambdas/list-solutions/list-solutions.py
|
kamoljan/amazon-personalize-samples
| 442 |
145158
|
<reponame>kamoljan/amazon-personalize-samples<filename>next_steps/operations/ml_ops/personalize-step-functions/lambdas/list-solutions/list-solutions.py
from os import environ
from loader import Loader
import actions
import json
LOADER = Loader()
def lambda_handler(event, context):
try:
response = LOADER.personalize_cli.list_solutions(
datasetGroupArn=event['datasetGroupArn'],
maxResults=100
)
return json.loads(json.dumps(response['solutions'], default=str))
except Exception as e:
LOADER.logger.error(f'Error listing solutions {e}')
raise e
|
src/oci/identity/models/create_idp_group_mapping_details.py
|
Manny27nyc/oci-python-sdk
| 249 |
145167
|
<filename>src/oci/identity/models/create_idp_group_mapping_details.py
# coding: utf-8
# Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401
from oci.decorators import init_model_state_from_kwargs
@init_model_state_from_kwargs
class CreateIdpGroupMappingDetails(object):
"""
CreateIdpGroupMappingDetails model.
"""
def __init__(self, **kwargs):
"""
Initializes a new CreateIdpGroupMappingDetails object with values from keyword arguments.
The following keyword arguments are supported (corresponding to the getters/setters of this class):
:param idp_group_name:
The value to assign to the idp_group_name property of this CreateIdpGroupMappingDetails.
:type idp_group_name: str
:param group_id:
The value to assign to the group_id property of this CreateIdpGroupMappingDetails.
:type group_id: str
"""
self.swagger_types = {
'idp_group_name': 'str',
'group_id': 'str'
}
self.attribute_map = {
'idp_group_name': 'idpGroupName',
'group_id': 'groupId'
}
self._idp_group_name = None
self._group_id = None
@property
def idp_group_name(self):
"""
**[Required]** Gets the idp_group_name of this CreateIdpGroupMappingDetails.
The name of the IdP group you want to map.
:return: The idp_group_name of this CreateIdpGroupMappingDetails.
:rtype: str
"""
return self._idp_group_name
@idp_group_name.setter
def idp_group_name(self, idp_group_name):
"""
Sets the idp_group_name of this CreateIdpGroupMappingDetails.
The name of the IdP group you want to map.
:param idp_group_name: The idp_group_name of this CreateIdpGroupMappingDetails.
:type: str
"""
self._idp_group_name = idp_group_name
@property
def group_id(self):
"""
**[Required]** Gets the group_id of this CreateIdpGroupMappingDetails.
The OCID of the IAM Service :class:`Group`
you want to map to the IdP group.
:return: The group_id of this CreateIdpGroupMappingDetails.
:rtype: str
"""
return self._group_id
@group_id.setter
def group_id(self, group_id):
"""
Sets the group_id of this CreateIdpGroupMappingDetails.
The OCID of the IAM Service :class:`Group`
you want to map to the IdP group.
:param group_id: The group_id of this CreateIdpGroupMappingDetails.
:type: str
"""
self._group_id = group_id
def __repr__(self):
return formatted_flat_dict(self)
def __eq__(self, other):
if other is None:
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not self == other
|
src/you_get/__main__.py
|
adger-me/you-get
| 46,956 |
145169
|
#!/usr/bin/env python
import getopt
import os
import platform
import sys
from .version import script_name, __version__
from .util import git, log
_options = [
'help',
'version',
'gui',
'force',
'playlists',
]
_short_options = 'hVgfl'
_help = """Usage: {} [OPTION]... [URL]...
TODO
""".format(script_name)
# TBD
def main_dev(**kwargs):
"""Main entry point.
you-get-dev
"""
# Get (branch, commit) if running from a git repo.
head = git.get_head(kwargs['repo_path'])
# Get options and arguments.
try:
opts, args = getopt.getopt(sys.argv[1:], _short_options, _options)
except getopt.GetoptError as e:
log.wtf("""
[Fatal] {}.
Try '{} --help' for more options.""".format(e, script_name))
if not opts and not args:
# Display help.
print(_help)
# Enter GUI mode.
#from .gui import gui_main
#gui_main()
else:
conf = {}
for opt, arg in opts:
if opt in ('-h', '--help'):
# Display help.
print(_help)
elif opt in ('-V', '--version'):
# Display version.
log.println("you-get:", log.BOLD)
log.println(" version: {}".format(__version__))
if head is not None:
log.println(" branch: {}\n commit: {}".format(*head))
else:
log.println(" branch: {}\n commit: {}".format("(stable)", "(tag v{})".format(__version__)))
log.println(" platform: {}".format(platform.platform()))
log.println(" python: {}".format(sys.version.split('\n')[0]))
elif opt in ('-g', '--gui'):
# Run using GUI.
conf['gui'] = True
elif opt in ('-f', '--force'):
# Force download.
conf['force'] = True
elif opt in ('-l', '--playlist', '--playlists'):
# Download playlist whenever possible.
conf['playlist'] = True
if args:
if 'gui' in conf and conf['gui']:
# Enter GUI mode.
from .gui import gui_main
gui_main(*args, **conf)
else:
# Enter console mode.
from .console import console_main
console_main(*args, **conf)
def main(**kwargs):
"""Main entry point.
you-get (legacy)
"""
from .common import main
main(**kwargs)
if __name__ == '__main__':
main()
|
data/video_utils.py
|
dexuiz/merlot
| 148 |
145171
|
import sys
import numpy as np
import skvideo.io
import concurrent.futures
import time
def _detect_black_bars_from_video(frames, blackbar_threshold=16, max_perc_to_trim=.2):
"""
:param frames: [num_frames, height, width, 3]
:param blackbar_threshold: Pixels must be this intense for us to not trim
:param max_perc_to_prim: Will trim 20% by default of the image at most in each dimension
:return:
"""
# Detect black bars####################
has_content = frames.max(axis=(0, -1)) >= blackbar_threshold
h, w = has_content.shape
y_frames = np.where(has_content.any(1))[0]
if y_frames.size == 0:
print("Oh no, there are no valid yframes")
y_frames = [h // 2]
y1 = min(y_frames[0], int(h * max_perc_to_trim))
y2 = max(y_frames[-1] + 1, int(h * (1 - max_perc_to_trim)))
x_frames = np.where(has_content.any(0))[0]
if x_frames.size == 0:
print("Oh no, there are no valid xframes")
x_frames = [w // 2]
x1 = min(x_frames[0], int(w * max_perc_to_trim))
x2 = max(x_frames[-1] + 1, int(w * (1 - max_perc_to_trim)))
return y1, y2, x1, x2
def extract_all_frames_from_video(video_file, blackbar_threshold=32, max_perc_to_trim=0.2,
every_nth_frame=1, verbosity=0):
"""
Same as exact_frames_from_video but no times meaning we grab every single frame
:param video_file:
:param r:
:param blackbar_threshold:
:param max_perc_to_trim:
:return:
"""
reader = skvideo.io.FFmpegReader(video_file, outputdict={'-r': '1', '-q:v': '2', '-pix_fmt': 'rgb24'},
verbosity=verbosity)
# frames = [x for x in iter(reader.nextFrame())]
frames = []
for i, frame in enumerate(reader.nextFrame()):
if (i % every_nth_frame) == 0:
frames.append(frame)
frames = np.stack(frames)
y1, y2, x1, x2 = _detect_black_bars_from_video(frames, blackbar_threshold=blackbar_threshold,
max_perc_to_trim=max_perc_to_trim)
frames = frames[:, y1:y2, x1:x2]
return frames
def extract_single_frame_from_video(video_file, t, verbosity=0):
"""
Reads the video, seeks to the given second option
:param video_file: input video file
:param t: where 2 seek to
:param use_rgb: True if use RGB, else BGR
:return: the frame at that timestep.
"""
timecode = '{:.3f}'.format(t)
input_dict ={ '-ss': timecode, '-threads': '1',}
reader = skvideo.io.FFmpegReader(video_file,
inputdict=input_dict,
outputdict={'-r': '1', '-q:v': '2', '-pix_fmt': 'rgb24', '-frames:v': '1'},
verbosity=verbosity,
)
try:
frame = next(iter(reader.nextFrame()))
except StopIteration:
frame = None
return frame
def extract_frames_from_video(video_file, times, info, use_multithreading=False, use_rgb=True,
blackbar_threshold=32, max_perc_to_trim=.20, verbose=False):
"""
Extracts multiple things from the video and even handles black bars
:param video_file: what we are loading
:param times: timestamps to use
:param use_multithreading: Whether to use multithreading
:param use_rgb whether to use RGB (default) or BGR
:param blackbar_threshold: Pixels must be this intense for us to not trim
:param max_perc_to_prim: Will trim 20% by default of the image at most in each dimension
:return:
"""
def _extract(i):
return i, extract_single_frame_from_video(video_file, times[i], verbosity=10 if verbose else 0)
time1 = time.time()
if not use_multithreading:
frames = [_extract(i)[1] for i in range(len(times))]
else:
frames = [None for t in times]
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:
submitted_threads = (executor.submit(_extract, i) for i in range(len(times)))
for future in concurrent.futures.as_completed(submitted_threads):
try:
i, img = future.result()
frames[i] = img
except Exception as exc:
print("Oh no {}".format(str(exc)), flush=True)
if verbose:
print("Extracting frames from video, multithreading={} took {:.3f}".format(use_multithreading,
time.time() - time1), flush=True)
if any([x is None for x in frames]):
print(f"Fail on {video_file}", flush=True)
return None
frames = np.stack(frames)
y1, y2, x1, x2 = _detect_black_bars_from_video(frames, blackbar_threshold=blackbar_threshold,
max_perc_to_trim=max_perc_to_trim)
frames = frames[:, y1:y2, x1:x2]
#############
return frames
|
attic/strings-bytes/encodings_demo.py
|
matteoshen/example-code
| 5,651 |
145215
|
import unicodedata
encodings = 'ascii latin1 cp1252 cp437 gb2312 utf-8 utf-16le'.split()
widths = {encoding:1 for encoding in encodings[:-3]}
widths.update(zip(encodings[-3:], (2, 4, 4)))
chars = sorted([
'A', # \u0041 : LATIN CAPITAL LETTER A
'¿', # \u00bf : INVERTED QUESTION MARK
'Ã', # \u00c3 : LATIN CAPITAL LETTER A WITH TILDE
'á', # \u00e1 : LATIN SMALL LETTER A WITH ACUTE
'Ω', # \u03a9 : GREEK CAPITAL LETTER OMEGA
'µ',
'Ц',
'€', # \u20ac : EURO SIGN
'“',
'┌',
'气',
'氣', # \u6c23 : CJK UNIFIED IDEOGRAPH-6C23
'𝄞', # \u1d11e : MUSICAL SYMBOL G CLEF
])
callout1_code = 0x278a # ➊ DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT ONE
missing_mark = '*'
def list_chars():
for char in chars:
print('%r, # \\u%04x : %s' % (char, ord(char), unicodedata.name(char)))
def show_encodings():
print(end='\t\t')
for encoding in encodings:
print(encoding.ljust(widths[encoding] * 2), end='\t')
print()
for lineno, char in enumerate(chars):
codepoint = 'U+{:04X}'.format(ord(char))
print(char, codepoint, sep='\t', end='\t')
for encoding in encodings:
try:
bytes = char.encode(encoding)
dump = ' '.join('%02X' % byte for byte in bytes)
except UnicodeEncodeError:
dump = missing_mark
dump = dump.ljust(widths[encoding] * 2)
print(dump, end='\t')
# print(chr(callout1_code + lineno))
print(unicodedata.name(char))
# print()
#list_chars()
show_encodings()
|
tests/test_client.py
|
ZackPashkin/toloka-kit
| 153 |
145265
|
from decimal import Decimal
import pickle
import pytest
import simplejson
from toloka.client import TolokaClient
import toloka.client as client
from .testutils.util_functions import check_headers
@pytest.fixture
def random_url():
return 'https://testing.toloka.yandex.ru'
def test_client_create_exceptions(random_url):
with pytest.raises(ValueError):
TolokaClient('fake-token', '<PASSWORD>', url=random_url)
with pytest.raises(ValueError):
TolokaClient('fake-token')
def test_client_pickleable(random_url):
toloka_client = TolokaClient('fake-token', '<PASSWORD>')
dumped = pickle.dumps(toloka_client) # Check that it's possible.
loaded = pickle.loads(dumped)
assert loaded
def test_different_urls(requests_mock, random_url):
result = {
'id': '566ec2b0ff0deeaae5f9d500',
'balance': Decimal('120.3'),
'public_name': {
'EN': '<NAME>',
'RU': '<NAME>',
},
'company': {
'id': '1',
'superintendent_id': 'superintendent-1id',
},
}
def get_requester(request, context):
expected_headers = {
'X-Caller-Context': 'client',
'X-Top-Level-Method': 'get_requester',
'X-Low-Level-Method': 'get_requester',
}
check_headers(request, expected_headers)
return simplejson.dumps(result)
requests_mock.get(f'{random_url}/api/v1/requester', text=get_requester)
toloka_client = TolokaClient('fake-token', url=random_url)
requester = toloka_client.get_requester()
assert result == client.unstructure(requester)
toloka_client = TolokaClient('fake-token', url=f'{random_url}/')
requester = toloka_client.get_requester()
assert result == client.unstructure(requester)
|
atlas/foundations_contrib/src/test/test_bucket_pipeline_archive.py
|
DeepLearnI/atlas
| 296 |
145303
|
from foundations_spec import *
class TestBucketPipelineArchive(Spec):
@let
def bucket_klass(self):
klass = ConditionalReturn()
klass.return_when(self.bucket, *self.constructor_args, **self.constructor_kwargs)
return klass
bucket = let_mock()
@let
def constructor_args(self):
return self.faker.words()
@let
def constructor_kwargs(self):
return self.faker.pydict()
@let
def object_name(self):
return self.faker.name()
@let
def random_data(self):
return self.faker.uuid4()
@let
def random_prefix(self):
return self.faker.uuid4()
@let
def file_listing_with_prefix(self):
return [f'{self.random_prefix}/{file}' for file in self.faker.words()]
@let
def blob_exists(self):
return self.faker.boolean()
@let
def archive(self):
from foundations_contrib.bucket_pipeline_archive import BucketPipelineArchive
return BucketPipelineArchive(self.bucket_klass, *self.constructor_args, **self.constructor_kwargs)
def test_append_binary_uploads_string_to_bucket(self):
self.archive.append_binary(self.object_name, self.random_data, self.random_prefix)
self.bucket.upload_from_string.assert_called_with(f'{self.random_prefix}/{self.object_name}', self.random_data)
def test_list_files_returns_list_of_files(self):
self.bucket.list_files = ConditionalReturn()
self.bucket.list_files.return_when(self.file_listing_with_prefix, f'{self.random_prefix}/*')
result = self.archive.list_files('*', self.random_prefix)
self.assertEqual(self.file_listing_with_prefix, result)
def test_exists_forwards_to_underlying_bucket(self):
self.bucket.exists = ConditionalReturn()
self.bucket.exists.return_when(self.blob_exists, f'{self.object_name}')
self.assertEqual(self.blob_exists, self.archive.exists(self.object_name))
def test_exists_forwards_to_underlying_bucket_with_prefix(self):
self.bucket.exists = ConditionalReturn()
self.bucket.exists.return_when(self.blob_exists, f'{self.random_prefix}/{self.object_name}')
self.assertEqual(self.blob_exists, self.archive.exists(self.object_name, prefix=self.random_prefix))
|
src/genie/libs/parser/iosxe/show_mab.py
|
jacobgarder/genieparser
| 204 |
145316
|
''' show_mab.py
IOSXE parsers for the following show commands:
* show mab all details
'''
# Python
import re
# Metaparser
from genie.metaparser import MetaParser
from genie.metaparser.util.schemaengine import Any, Optional, Or
# ====================================================
# Schema for show mab all details
# ====================================================
class ShowMabAllDetailsSchema(MetaParser):
schema = {
'interfaces': {
Any(): {
'mac_auth_bypass': str,
'client_mac':{
Any(): {
Optional('session_id'): str,
Optional('mab_sm_state'): str,
Optional('authen_status'): str,
},
},
},
}
}
# ====================================================
# Parser for show mab all details
# ====================================================
class ShowMabAllDetails(ShowMabAllDetailsSchema):
"""
Parser for show mab all details
"""
cli_command = 'show mab all details'
def cli(self, output = None):
cmd = 'show mab all details'
# MAB details for GigabitEthernet2/0/2
p1 = re.compile(r'(^MAB\s+details\s+for)\s*(.*)')
# Mac-Auth-Bypass = Enabled
p2 = re.compile(r'(^Mac-Auth-Bypass)\s*=\s*(?P<mac_auth_bypass>.*)')
# MAB Client List
p3 = re.compile(r'(^MAB\s+Client\s+List)\s*')
# My Client MAC = 0000.0001.0003
# My Session ID = 000000000000000C82FA130E
# My Authen Status = SUCCESS
p4 = re.compile(r'(^My)\s+(\w+\s+\w+)\s*=\s*(.*)')
# My MAB SM state = TERMINATE
p5 = re.compile(r'(^My\s*MAB\s*SM\s*state)\s*=\s*(?P<mab_sm_state>.*)')
ret_dict = {}
interface_dict = {}
mac_dict = {}
client_dict = {}
if output is None:
out = self.device.execute(self.cli_command)
else:
out = output
for line in out.splitlines():
line = line.strip()
# MAB details for GigabitEthernet2/0/2
res = p1.match(line)
if res:
interface_dict = ret_dict.setdefault('interfaces', {}).setdefault(res.group(2), {})
continue
# Mac-Auth-Bypass = Enabled
res = p2.match(line)
if res:
interface_dict.update(res.groupdict())
continue
# MAB Client List
res = p3.match(line)
if res:
mac_dict = interface_dict.setdefault('client_mac', {})
# My Client MAC = 0000.0001.0003
# My Session ID = 000000000000000C82FA130E
# My Authen Status = SUCCESS
res = p4.match(line)
if res:
key_string = (re.sub(r'\s+', '_', res.group(2))).lower()
if key_string == 'client_mac':
client_dict = mac_dict.setdefault(res.group(3), {})
else:
client_dict.update({key_string: res.group(3)})
# My MAB SM state = TERMINATE
res = p5.match(line)
if res:
client_dict.update(res.groupdict())
return ret_dict
|
logomaker/src/Glyph.py
|
ruxi/logomaker
| 125 |
145320
|
<filename>logomaker/src/Glyph.py
# explicitly set a matplotlib backend if called from python to avoid the
# 'Python is not installed as a framework... error'
import sys
if sys.version_info[0] == 2:
import matplotlib
matplotlib.use('TkAgg')
from matplotlib.textpath import TextPath
from matplotlib.patches import PathPatch
from matplotlib.transforms import Affine2D, Bbox
from matplotlib.font_manager import FontManager, FontProperties
from matplotlib.colors import to_rgb
import matplotlib.pyplot as plt
from matplotlib.axes import Axes
from logomaker.src.error_handling import check, handle_errors
from logomaker.src.colors import get_rgb
import numpy as np
# Create global font manager instance. This takes a second or two
font_manager = FontManager()
# Create global list of valid font weights
VALID_FONT_WEIGHT_STRINGS = [
'ultralight', 'light', 'normal', 'regular', 'book',
'medium', 'roman', 'semibold', 'demibold', 'demi',
'bold', 'heavy', 'extra bold', 'black']
def list_font_names():
"""
Returns a list of valid font_name options for use in Glyph or
Logo constructors.
parameters
----------
None.
returns
-------
fontnames: (list)
List of valid font_name names. This will vary from system to system.
"""
fontnames_dict = dict([(f.name, f.fname) for f in font_manager.ttflist])
fontnames = list(fontnames_dict.keys())
fontnames.append('sans') # This always exists
fontnames.sort()
return fontnames
class Glyph:
"""
A Glyph represents a character, drawn on a specified axes at a specified
position, rendered using specified styling such as color and font_name.
attributes
----------
p: (number)
x-coordinate value on which to center the Glyph.
c: (str)
The character represented by the Glyph.
floor: (number)
y-coordinate value where the bottom of the Glyph extends to.
Must be < ceiling.
ceiling: (number)
y-coordinate value where the top of the Glyph extends to.
Must be > floor.
ax: (matplotlib Axes object)
The axes object on which to draw the Glyph.
width: (number > 0)
x-coordinate span of the Glyph.
vpad: (number in [0,1])
Amount of whitespace to leave within the Glyph bounding box above
and below the actual Glyph. Specifically, in a glyph with
height h = ceiling-floor, a margin of size h*vpad/2 will be left blank
both above and below the rendered character.
font_name: (str)
The name of the font to use when rendering the Glyph. This is
the value passed as the 'family' parameter when calling the
matplotlib.font_manager.FontProperties constructor.
font_weight: (str or number)
The font weight to use when rendering the Glyph. Specifically, this is
the value passed as the 'weight' parameter in the
matplotlib.font_manager.FontProperties constructor.
From matplotlib documentation: "weight: A numeric
value in the range 0-1000 or one of 'ultralight', 'light',
'normal', 'regular', 'book', 'medium', 'roman', 'semibold',
'demibold', 'demi', 'bold', 'heavy', 'extra bold', 'black'."
color: (matplotlib color)
Color to use for Glyph face.
edgecolor: (matplotlib color)
Color to use for Glyph edge.
edgewidth: (number >= 0)
Width of Glyph edge.
dont_stretch_more_than: (str)
This parameter limits the amount that a character will be
horizontally stretched when rendering the Glyph. Specifying a
wide character such as 'W' corresponds to less potential stretching,
while specifying a narrow character such as '.' corresponds to more
stretching.
flip: (bool)
If True, the Glyph will be rendered upside down.
mirror: (bool)
If True, a mirror image of the Glyph will be rendered.
zorder: (number)
Placement of Glyph within the z-stack of ax.
alpha: (number in [0,1])
Opacity of the rendered Glyph.
figsize: ([float, float]):
The default figure size for the rendered glyph; only used if ax is
not supplied by the user.
"""
@handle_errors
def __init__(self,
p,
c,
floor,
ceiling,
ax=None,
width=0.95,
vpad=0.00,
font_name='sans',
font_weight='bold',
color='gray',
edgecolor='black',
edgewidth=0.0,
dont_stretch_more_than='E',
flip=False,
mirror=False,
zorder=None,
alpha=1,
figsize=(1, 1)):
# Set attributes
self.p = p
self.c = c
self.floor = floor
self.ceiling = ceiling
self.ax = ax
self.width = width
self.vpad = vpad
self.flip = flip
self.mirror = mirror
self.zorder = zorder
self.dont_stretch_more_than = dont_stretch_more_than
self.alpha = alpha
self.color = color
self.edgecolor = edgecolor
self.edgewidth = edgewidth
self.font_name = font_name
self.font_weight = font_weight
self.figsize = figsize
# Check inputs
self._input_checks()
# If ax is not set, set to current axes object
if self.ax is None:
fig, ax = plt.subplots(1, 1, figsize=self.figsize)
self.ax = ax
# Make patch
self._make_patch()
def set_attributes(self, **kwargs):
"""
Safe way to set the attributes of a Glyph object
parameters
----------
**kwargs:
Attributes and their values.
"""
# remove drawn patch
if (self.patch is not None) and (self.patch.axes is not None):
self.patch.remove()
# set each attribute passed by user
for key, value in kwargs.items():
# if key corresponds to a color, convert to rgb
if key in ('color', 'edgecolor'):
value = to_rgb(value)
# save variable name
self.__dict__[key] = value
# remake patch
self._make_patch()
def draw(self):
"""
Draws Glyph given current parameters.
parameters
----------
None.
returns
-------
None.
"""
# Draw character
if self.patch is not None:
self.ax.add_patch(self.patch)
def _make_patch(self):
"""
Returns an appropriately scaled patch object corresponding to
the Glyph.
"""
# Set height
height = self.ceiling - self.floor
# If height is zero, set patch to None and return None
if height == 0.0:
self.patch = None
return None
# Set bounding box for character,
# leaving requested amount of padding above and below the character
char_xmin = self.p - self.width / 2.0
char_ymin = self.floor + self.vpad * height / 2.0
char_width = self.width
char_height = height - self.vpad * height
bbox = Bbox.from_bounds(char_xmin,
char_ymin,
char_width,
char_height)
# Set font properties of Glyph
font_properties = FontProperties(family=self.font_name,
weight=self.font_weight)
# Create a path for Glyph that does not yet have the correct
# position or scaling
tmp_path = TextPath((0, 0), self.c, size=1,
prop=font_properties)
# Create create a corresponding path for a glyph representing
# the max stretched character
msc_path = TextPath((0, 0), self.dont_stretch_more_than, size=1,
prop=font_properties)
# If need to flip char, do it within tmp_path
if self.flip:
transformation = Affine2D().scale(sx=1, sy=-1)
tmp_path = transformation.transform_path(tmp_path)
# If need to mirror char, do it within tmp_path
if self.mirror:
transformation = Affine2D().scale(sx=-1, sy=1)
tmp_path = transformation.transform_path(tmp_path)
# Get bounding box for temporary character and max_stretched_character
tmp_bbox = tmp_path.get_extents()
msc_bbox = msc_path.get_extents()
# Compute horizontal stretch factor needed for tmp_path
hstretch_tmp = bbox.width / tmp_bbox.width
# Compute horizontal stretch factor needed for msc_path
hstretch_msc = bbox.width / msc_bbox.width
# Choose the MINIMUM of these two horizontal stretch factors.
# This prevents very narrow characters, such as 'I', from being
# stretched too much.
hstretch = min(hstretch_tmp, hstretch_msc)
# Compute the new character width, accounting for the
# limit placed on the stretching factor
char_width = hstretch * tmp_bbox.width
# Compute how much to horizontally shift the character path
char_shift = (bbox.width - char_width) / 2.0
# Compute vertical stetch factor needed for tmp_path
vstretch = bbox.height / tmp_bbox.height
# THESE ARE THE ESSENTIAL TRANSFORMATIONS
# 1. First, translate char path so that lower left corner is at origin
# 2. Then scale char path to desired width and height
# 3. Finally, translate char path to desired position
# char_path is the resulting path used for the Glyph
transformation = Affine2D() \
.translate(tx=-tmp_bbox.xmin, ty=-tmp_bbox.ymin) \
.scale(sx=hstretch, sy=vstretch) \
.translate(tx=bbox.xmin + char_shift, ty=bbox.ymin)
char_path = transformation.transform_path(tmp_path)
# Convert char_path to a patch, which can now be drawn on demand
self.patch = PathPatch(char_path,
facecolor=self.color,
zorder=self.zorder,
alpha=self.alpha,
edgecolor=self.edgecolor,
linewidth=self.edgewidth)
# add patch to axes
self.ax.add_patch(self.patch)
def _input_checks(self):
"""
check input parameters in the Logo constructor for correctness
"""
from numbers import Number
# validate p
check(isinstance(int(self.p), (float, int)),
'type(p) = %s must be a number' % type(self.p))
# check c is of type str
check(isinstance(self.c, str),
'type(c) = %s; must be of type str ' %
type(self.c))
# validate floor
check(isinstance(self.floor, (float, int)),
'type(floor) = %s must be a number' % type(self.floor))
self.floor = float(self.floor)
# validate ceiling
check(isinstance(self.ceiling, (float, int)),
'type(ceiling) = %s must be a number' % type(self.ceiling))
self.ceiling = float(self.ceiling)
# check floor <= ceiling
check(self.floor <= self.ceiling,
'must have floor <= ceiling. Currently, '
'floor=%f, ceiling=%f' % (self.floor, self.ceiling))
# check ax
check((self.ax is None) or isinstance(self.ax, Axes),
'ax must be either a matplotlib Axes object or None.')
# validate width
check(isinstance(self.width, (float, int)),
'type(width) = %s; must be of type float or int ' %
type(self.width))
check(self.width > 0, "width = %d must be > 0 " %
self.width)
# validate vpad
check(isinstance(self.vpad, (float, int)),
'type(vpad) = %s; must be of type float or int ' %
type(self.vpad))
check(0 <=self.vpad <1, "vpad = %d must be >= 0 and < 1 " %
self.vpad)
# validate font_name
check(isinstance(self.font_name, str),
'type(font_name) = %s must be of type str' % type(self.font_name))
# check font_weight
check(isinstance(self.font_weight, (str, int)),
'type(font_weight) = %s should either be a string or an int' %
(type(self.font_weight)))
if isinstance(self.font_weight, str):
check(self.font_weight in VALID_FONT_WEIGHT_STRINGS,
'font_weight must be one of %s' % VALID_FONT_WEIGHT_STRINGS)
elif isinstance(self.font_weight, int):
check(0 <= self.font_weight <= 1000,
'font_weight must be in range [0,1000]')
# check color safely
self.color = get_rgb(self.color)
# validate edgecolor safely
self.edgecolor = get_rgb(self.edgecolor)
# Check that edgewidth is a number
check(isinstance(self.edgewidth, (float, int)),
'type(edgewidth) = %s must be a number' % type(self.edgewidth))
self.edgewidth = float(self.edgewidth)
# Check that edgewidth is nonnegative
check(self.edgewidth >= 0,
' edgewidth must be >= 0; is %f' % self.edgewidth)
# check dont_stretch_more_than is of type str
check(isinstance(self.dont_stretch_more_than, str),
'type(dont_stretch_more_than) = %s; must be of type str ' %
type(self.dont_stretch_more_than))
# check that dont_stretch_more_than is a single character
check(len(self.dont_stretch_more_than)==1,
'dont_stretch_more_than must have length 1; '
'currently len(dont_stretch_more_than)=%d' %
len(self.dont_stretch_more_than))
# check that flip is a boolean
check(isinstance(self.flip, (bool, np.bool_)),
'type(flip) = %s; must be of type bool ' % type(self.flip))
self.flip = bool(self.flip)
# check that mirror is a boolean
check(isinstance(self.mirror, (bool, np.bool_)),
'type(mirror) = %s; must be of type bool ' % type(self.mirror))
self.mirror = bool(self.mirror)
# validate zorder
if self.zorder is not None :
check(isinstance(self.zorder, (float, int)),
'type(zorder) = %s; must be of type float or int ' %
type(self.zorder))
# Check alpha is a number
check(isinstance(self.alpha, (float, int)),
'type(alpha) = %s must be a float or int' %
type(self.alpha))
self.alpha = float(self.alpha)
# Check 0 <= alpha <= 1.0
check(0 <= self.alpha <= 1.0,
'alpha must be between 0.0 and 1.0 (inclusive)')
# validate that figsize is array=like
check(isinstance(self.figsize, (tuple, list, np.ndarray)),
'type(figsize) = %s; figsize must be array-like.' %
type(self.figsize))
self.figsize = tuple(self.figsize) # Just to pin down variable type.
# validate length of figsize
check(len(self.figsize) == 2, 'figsize must have length two.')
# validate that each element of figsize is a number
check(all([isinstance(n, (int, float)) and n > 0
for n in self.figsize]),
'all elements of figsize array must be numbers > 0.')
|
src/oci/database_management/models/database_storage_aggregate_metrics.py
|
Manny27nyc/oci-python-sdk
| 249 |
145322
|
<reponame>Manny27nyc/oci-python-sdk
# coding: utf-8
# Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401
from oci.decorators import init_model_state_from_kwargs
@init_model_state_from_kwargs
class DatabaseStorageAggregateMetrics(object):
"""
The database storage metric values.
"""
def __init__(self, **kwargs):
"""
Initializes a new DatabaseStorageAggregateMetrics object with values from keyword arguments.
The following keyword arguments are supported (corresponding to the getters/setters of this class):
:param storage_allocated:
The value to assign to the storage_allocated property of this DatabaseStorageAggregateMetrics.
:type storage_allocated: oci.database_management.models.MetricDataPoint
:param storage_used:
The value to assign to the storage_used property of this DatabaseStorageAggregateMetrics.
:type storage_used: oci.database_management.models.MetricDataPoint
:param storage_used_by_table_space:
The value to assign to the storage_used_by_table_space property of this DatabaseStorageAggregateMetrics.
:type storage_used_by_table_space: list[oci.database_management.models.MetricDataPoint]
"""
self.swagger_types = {
'storage_allocated': 'MetricDataPoint',
'storage_used': 'MetricDataPoint',
'storage_used_by_table_space': 'list[MetricDataPoint]'
}
self.attribute_map = {
'storage_allocated': 'storageAllocated',
'storage_used': 'storageUsed',
'storage_used_by_table_space': 'storageUsedByTableSpace'
}
self._storage_allocated = None
self._storage_used = None
self._storage_used_by_table_space = None
@property
def storage_allocated(self):
"""
Gets the storage_allocated of this DatabaseStorageAggregateMetrics.
:return: The storage_allocated of this DatabaseStorageAggregateMetrics.
:rtype: oci.database_management.models.MetricDataPoint
"""
return self._storage_allocated
@storage_allocated.setter
def storage_allocated(self, storage_allocated):
"""
Sets the storage_allocated of this DatabaseStorageAggregateMetrics.
:param storage_allocated: The storage_allocated of this DatabaseStorageAggregateMetrics.
:type: oci.database_management.models.MetricDataPoint
"""
self._storage_allocated = storage_allocated
@property
def storage_used(self):
"""
Gets the storage_used of this DatabaseStorageAggregateMetrics.
:return: The storage_used of this DatabaseStorageAggregateMetrics.
:rtype: oci.database_management.models.MetricDataPoint
"""
return self._storage_used
@storage_used.setter
def storage_used(self, storage_used):
"""
Sets the storage_used of this DatabaseStorageAggregateMetrics.
:param storage_used: The storage_used of this DatabaseStorageAggregateMetrics.
:type: oci.database_management.models.MetricDataPoint
"""
self._storage_used = storage_used
@property
def storage_used_by_table_space(self):
"""
Gets the storage_used_by_table_space of this DatabaseStorageAggregateMetrics.
A list of the storage metrics grouped by TableSpace for a specific database.
:return: The storage_used_by_table_space of this DatabaseStorageAggregateMetrics.
:rtype: list[oci.database_management.models.MetricDataPoint]
"""
return self._storage_used_by_table_space
@storage_used_by_table_space.setter
def storage_used_by_table_space(self, storage_used_by_table_space):
"""
Sets the storage_used_by_table_space of this DatabaseStorageAggregateMetrics.
A list of the storage metrics grouped by TableSpace for a specific database.
:param storage_used_by_table_space: The storage_used_by_table_space of this DatabaseStorageAggregateMetrics.
:type: list[oci.database_management.models.MetricDataPoint]
"""
self._storage_used_by_table_space = storage_used_by_table_space
def __repr__(self):
return formatted_flat_dict(self)
def __eq__(self, other):
if other is None:
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not self == other
|
scripts/sptk/do_ssl.py
|
unanan/setk
| 280 |
145325
|
#!/usr/bin/env python
# wujian@2019
import argparse
import numpy as np
from libs.ssl import ml_ssl, srp_ssl, music_ssl
from libs.data_handler import SpectrogramReader, NumpyReader
from libs.utils import get_logger, EPSILON
from libs.opts import StftParser, str2tuple
logger = get_logger(__name__)
def add_wta(masks_list, eps=1e-4):
"""
Produce winner-take-all masks
"""
masks = np.stack(masks_list, axis=-1)
max_mask = np.max(masks, -1)
wta_masks = []
for spk_mask in masks_list:
m = np.where(spk_mask == max_mask, spk_mask, eps)
wta_masks.append(m)
return wta_masks
def run(args):
stft_kwargs = {
"frame_len": args.frame_len,
"frame_hop": args.frame_hop,
"round_power_of_two": args.round_power_of_two,
"window": args.window,
"center": args.center,
"transpose": True
}
steer_vector = np.load(args.steer_vector)
logger.info(f"Shape of the steer vector: {steer_vector.shape}")
num_doa, _, _ = steer_vector.shape
min_doa, max_doa = str2tuple(args.doa_range)
if args.output == "radian":
angles = np.linspace(min_doa * np.pi / 180, max_doa * np.pi / 180,
num_doa + 1)
else:
angles = np.linspace(min_doa, max_doa, num_doa + 1)
spectrogram_reader = SpectrogramReader(args.wav_scp, **stft_kwargs)
mask_reader = None
if args.mask_scp:
mask_reader = [NumpyReader(scp) for scp in args.mask_scp.split(",")]
online = (args.chunk_len > 0 and args.look_back > 0)
if online:
logger.info("Set up in online mode: chunk_len " +
f"= {args.chunk_len}, look_back = {args.look_back}")
if args.backend == "srp":
split_index = lambda sstr: [
tuple(map(int, p.split(","))) for p in sstr.split(";")
]
srp_pair = split_index(args.srp_pair)
srp_pair = ([t[0] for t in srp_pair], [t[1] for t in srp_pair])
logger.info(f"Choose srp-based algorithm, srp pair is {srp_pair}")
else:
srp_pair = None
with open(args.doa_scp, "w") as doa_out:
for key, stft in spectrogram_reader:
# stft: M x T x F
_, _, F = stft.shape
if mask_reader:
# T x F => F x T
mask = [r[key] for r in mask_reader] if mask_reader else None
if args.mask_eps >= 0 and len(mask_reader) > 1:
mask = add_wta(mask, eps=args.mask_eps)
mask = mask[0]
# F x T => T x F
if mask.shape[-1] != F:
mask = mask.transpose()
else:
mask = None
if not online:
if srp_pair:
idx = srp_ssl(stft,
steer_vector,
srp_pair=srp_pair,
mask=mask)
elif args.backend == "ml":
idx = ml_ssl(stft,
steer_vector,
mask=mask,
compression=-1,
eps=EPSILON)
else:
idx = music_ssl(stft, steer_vector, mask=mask)
doa = idx if args.output == "index" else angles[idx]
logger.info(f"Processing utterance {key}: {doa:.4f}")
doa_out.write(f"{key}\t{doa:.4f}\n")
else:
logger.info(f"Processing utterance {key}...")
_, T, _ = stft.shape
online_doa = []
for t in range(0, T, args.chunk_len):
s = max(t - args.look_back, 0)
if mask is not None:
chunk_mask = mask[..., s:t + args.chunk_len]
else:
chunk_mask = None
stft_chunk = stft[:, s:t + args.chunk_len, :]
if srp_pair:
idx = srp_ssl(stft_chunk,
steer_vector,
srp_pair=srp_pair,
mask=chunk_mask)
elif args.backend == "ml":
idx = ml_ssl(stft_chunk,
steer_vector,
mask=chunk_mask,
compression=-1,
eps=EPSILON)
else:
idx = music_ssl(stft_chunk,
steer_vector,
mask=chunk_mask)
doa = idx if args.output == "index" else angles[idx]
online_doa.append(doa)
doa_str = " ".join([f"{d:.4f}" for d in online_doa])
doa_out.write(f"{key}\t{doa_str}\n")
logger.info(f"Processing {len(spectrogram_reader)} utterance done")
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Command to ML/SRP based sound souce localization (SSL)."
"Also see scripts/sptk/compute_steer_vector.py",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
parents=[StftParser.parser])
parser.add_argument("wav_scp",
type=str,
help="Multi-channel wave rspecifier")
parser.add_argument("steer_vector",
type=str,
help="Pre-computed steer vector in each "
"directions (in shape A x M x F, A: number "
"of DoAs, M: microphone number, F: FFT bins)")
parser.add_argument("doa_scp",
type=str,
help="Wspecifier for estimated DoA")
parser.add_argument("--backend",
type=str,
default="ml",
choices=["ml", "srp", "music"],
help="Which algorithm to choose for SSL")
parser.add_argument("--srp-pair",
type=str,
default="",
help="Microphone index pair to compute srp response")
parser.add_argument("--doa-range",
type=str,
default="0,360",
help="DoA range")
parser.add_argument("--mask-scp",
type=str,
default="",
help="Rspecifier for TF-masks in numpy format")
parser.add_argument("--output",
type=str,
default="degree",
choices=["radian", "degree", "index"],
help="Output type of the DoA")
parser.add_argument("--mask-eps",
type=float,
default=-1,
help="Value of eps used in masking winner-take-all")
parser.add_argument("--chunk-len",
type=int,
default=-1,
help="Number frames per chunk "
"(for online setups)")
parser.add_argument("--look-back",
type=int,
default=125,
help="Number of frames to look back "
"(for online setups)")
args = parser.parse_args()
run(args)
|
holocron/utils/data/collate.py
|
MateoLostanlen/Holocron
| 181 |
145348
|
<reponame>MateoLostanlen/Holocron
# Copyright (C) 2019-2021, <NAME>.
# This program is licensed under the Apache License version 2.
# See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details.
import numpy as np
import torch
from torch import Tensor
from torch.utils.data._utils.collate import default_collate
from typing import Tuple, List
__all__ = ['mixup_collate']
def mixup_collate(data: List[Tuple[Tensor, int]], alpha: float = 0.1) -> Tuple[Tensor, Tensor, Tensor, float]:
"""Implements a batch collate function with MixUp strategy from
`"mixup: Beyond Empirical Risk Minimization" <https://arxiv.org/pdf/1710.09412.pdf>`_
Args:
data: list of elements
alpha: mixup factor
Returns:
interpolated input
original target
resorted target
interpolation factor
Example::
>>> import torch
>>> from holocron import utils
>>> loader = torch.utils.data.DataLoader(dataset, batch_size, collate_fn=utils.data.mixup_collate)
"""
inputs, targets = default_collate(data)
# Sample lambda
if alpha > 0:
lam = np.random.beta(alpha, alpha)
else:
lam = 1
# Mix batch indices
batch_size = inputs.size()[0]
index = torch.randperm(batch_size)
# Create the new input and targets
inputs = lam * inputs + (1 - lam) * inputs[index, :]
targets_a, targets_b = targets, targets[index]
return inputs, targets_a, targets_b, lam
|
plugins/hanlp_demo/hanlp_demo/zh/demo_ner_dict.py
|
huminghe/HanLP
| 27,208 |
145352
|
<gh_stars>1000+
# -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2021-04-29 11:06
import hanlp
HanLP = hanlp.load(hanlp.pretrained.mtl.CLOSE_TOK_POS_NER_SRL_DEP_SDP_CON_ELECTRA_BASE_ZH)
HanLP['ner/msra'].dict_whitelist = {'午饭后': 'TIME'}
doc = HanLP('2021年测试高血压是138,时间是午饭后2点45,低血压是44', tasks='ner/msra')
doc.pretty_print()
print(doc['ner/msra'])
# See https://hanlp.hankcs.com/docs/api/hanlp/components/mtl/tasks/ner/tag_ner.html
|
i3pystatus/updates/dnf.py
|
fkusei/i3pystatus
| 413 |
145357
|
from i3pystatus.updates import Backend
import sys
# Remove first dir from sys.path to avoid shadowing dnf module from
# site-packages dir when this module executed directly on the CLI.
__module_dir = sys.path.pop(0)
try:
import dnf
HAS_DNF_BINDINGS = True
except ImportError:
HAS_DNF_BINDINGS = False
finally:
# Replace the directory we popped earlier
sys.path.insert(0, __module_dir)
class Dnf(Backend):
"""
Gets updates for RPM-based distributions using the `DNF API`_
The notification body consists of the package name and version for each
available update.
.. _`DNF API`: http://dnf.readthedocs.io/en/latest/api.html
.. note::
Users running i3pystatus from a virtualenv may see the updates display
as ``?`` due to an inability to import the ``dnf`` module. To ensure
that i3pystatus can access the DNF Python bindings, the virtualenv
should be created with ``--system-site-packages``.
If using `pyenv-virtualenv`_, the virtualenv must additionally be
created to use the system Python binary:
.. code-block:: bash
$ pyenv virtualenv --system-site-packages --python=/usr/bin/python3 pyenv_name
To invoke i3pystatus with this virtualenv, your ``bar`` section in
``~/.config/i3/config`` would look like this:
.. code-block:: bash
bar {
position top
status_command PYENV_VERSION=pyenv_name python /path/to/i3pystatus/script.py
}
.. _`pyenv-virtualenv`: https://github.com/yyuu/pyenv-virtualenv
"""
@property
def updates(self):
if HAS_DNF_BINDINGS:
try:
with dnf.Base() as base:
base.read_all_repos()
base.fill_sack()
upgrades = base.sack.query().upgrades().run()
notif_body = ''.join([
'%s: %s-%s\n' % (pkg.name, pkg.version, pkg.release)
for pkg in upgrades
])
return len(upgrades), notif_body
except Exception as exc:
self.logger.error('DNF update check failed', exc_info=True)
return '?', exc.__str__()
else:
return '?', 'Failed to import DNF Python bindings'
Backend = Dnf
if __name__ == "__main__":
"""
Call this module directly; Print the update count and notification body.
"""
print("Updates: {}\n\n{}".format(*Backend().updates))
|
dev/mlsqltestssupport/aliyun/upload_release.py
|
zhuimengrenweijian/mlsql
| 1,123 |
145369
|
<filename>dev/mlsqltestssupport/aliyun/upload_release.py
# -*- coding: utf-8 -*-
import os
import mlsqltestssupport.aliyun.config as config
if not os.environ['MLSQL_RELEASE_TAR']:
raise ValueError('MLSQL_RELEASE_TAR should be configured')
fileName = os.environ['MLSQL_RELEASE_TAR']
bucket = config.ossClient()
bucket.put_object_from_file(fileName.split("/")[-1], fileName)
print("success uploaded")
|
VisualBERT/mmf/datasets/builders/coco2017/masked_dataset.py
|
Fostereee/Transformer-MM-Explainability
| 322 |
145375
|
<filename>VisualBERT/mmf/datasets/builders/coco2017/masked_dataset.py
# Copyright (c) Facebook, Inc. and its affiliates.
from VisualBERT.mmf.common.typings import MMFDatasetConfigType
from VisualBERT.mmf.datasets.builders.localized_narratives.masked_dataset import (
MaskedLocalizedNarrativesDatasetMixin,
)
from VisualBERT.mmf.datasets.mmf_dataset import MMFDataset
class MaskedCoco2017Dataset(MaskedLocalizedNarrativesDatasetMixin, MMFDataset):
def __init__(
self,
config: MMFDatasetConfigType,
dataset_type: str,
index: int,
*args,
**kwargs,
):
super().__init__(
"masked_coco2017", config, dataset_type, index, *args, **kwargs
)
|
python/spinn/data/__init__.py
|
pramitmallick/spinn
| 103 |
145384
|
<gh_stars>100-1000
T_SHIFT = 0
T_REDUCE = 1
T_SKIP = 2
|
bhagavad_gita_api/cronjobs/celery.py
|
ayushsoni1010/bhagavad-gita-api
| 133 |
145397
|
import requests
from celery import Celery
from celery.schedules import crontab
from bhagavad_gita_api.config import settings
app = Celery(
"cronjobs",
broker=settings.CELERY_BROKER,
backend=settings.CELERY_BACKEND,
)
app.conf.timezone = "Asia/Calcutta"
@app.task
def set_verse():
url = "{}/v2/set-daily-verse/".format(settings.CRONJOB_BASE_URL)
data = {
"accept": "application/json",
"X-API-KEY": settings.TESTER_API_KEY,
}
r = requests.post(url=url, data=data, headers=data)
print(r)
app.conf.beat_schedule = {
"setup-verse-everyday": {
"task": "bhagavad_gita_api.cronjobs.celery.set_verse",
"schedule": crontab(hour=0, minute=0),
},
}
if __name__ == "__main__":
app.start()
|
Contributions/randomPassword.py
|
OluSure/Hacktoberfest2021-1
| 215 |
145411
|
#!/usr/bin/env python3
#RamSalado | BeeHackers
import random
# This library it´s necesary
k="abcdefghijklmnopqrstuvwxyz123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ#@!][}{?¿%&"
# Characters that the password will include
len = 12
# Password length
p="".join(random.sample(k,len))
print(p)
|
tensorflow/tools/tilecreator_t.py
|
fabian57fabian/tempoGAN
| 158 |
145412
|
#******************************************************************************
#
# tempoGAN: A Temporally Coherent, Volumetric GAN for Super-resolution Fluid Flow
# Copyright 2018 <NAME>, <NAME>, <NAME>, <NAME>
#
# This program is free software, distributed under the terms of the
# Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
#
#******************************************************************************
import os, math
import shutil, sys
from random import seed, random, randrange
import uniio
import numpy as np
import scipy.misc
import scipy.ndimage
import imageio
# check whether matplotlib is available to generate vector/quiver plots
import imp
try:
imp.find_module('matplotlib')
import matplotlib.pyplot
found_matplotlib = True
except ImportError:
found_matplotlib = False
#import matplotlib.pyplot as plt
# global channel keys, have to be one char
C_KEY_DEFAULT = 'd'
C_KEY_VELOCITY = 'v'
C_KEY_VORTICITY = 'x'
C_KEY_POSITION = 'p'
DATA_KEY_LOW = 0
DATA_KEY_HIGH= 1
#keys for augmentation operations
AOPS_KEY_ROTATE = 'rot'
AOPS_KEY_SCALE = 'scale'
AOPS_KEY_ROT90 = 'rot90'
AOPS_KEY_FLIP = 'flip'
seed( 42 )
# default channel layouts
C_LAYOUT = {
'dens':C_KEY_DEFAULT,
'dens_vel':'d,vx,vy,vz'
}
class TileCreator(object):
def __init__(self, tileSizeLow, simSizeLow=64, upres=2, dim=2, dim_t=1, overlapping=0, densityMinimum=0.02, premadeTiles=False, partTrain=0.8, partTest=0.2, partVal=0, channelLayout_low=C_LAYOUT['dens_vel'], channelLayout_high=C_LAYOUT['dens'], highIsLabel=False, loadPN=False, padding=0):
'''
tileSizeLow, simSizeLow: int, [int,int] if 2D, [int,int,int]
channelLayout: 'key,key,...'
the keys are NOT case sensitive and leading and trailing whitespace characters are REMOVED.
key:
default: d
velocity: v[label](x|y|z)
label can be arbitrary or empty,
key must be unique and x,y must exist while z is optional in 2D, x,y,z must exist in 3D.
if x does not exist y,z will be ignored (treaded as 'd').
rest is not yet supported
premadeTiles: cut regular tiles when loading data, can't use data augmentation
part(Train|Test|Val): relative size of the different data sets
highIsLabel: high data is not augmented
loadHigh:
simPath: path to the uni simulation files
loadPath: packed simulations are stored here
'''
# DATA DIMENSION
self.dim_t = dim_t # same for hi_res or low_res
if dim!=2 and dim!=3:
self.TCError('Data dimension must be 2 or 3.')
self.dim = dim
# TILE SIZE
if np.isscalar(tileSizeLow):
self.tileSizeLow = [tileSizeLow, tileSizeLow, tileSizeLow]
elif len(tileSizeLow)==2 and self.dim==2:
self.tileSizeLow = [1]+tileSizeLow
elif len(tileSizeLow)==3:
self.tileSizeLow = tileSizeLow
else:
self.TCError('Tile size mismatch.')
self.tileSizeLow = np.asarray(self.tileSizeLow)
#SIM SIZE
if np.isscalar(simSizeLow):
self.simSizeLow = [simSizeLow, simSizeLow, simSizeLow]
elif len(simSizeLow)==2 and self.dim==2:
self.simSizeLow = [1]+simSizeLow
elif len(simSizeLow)==3:
self.simSizeLow = simSizeLow
else:
self.TCError('Simulation size mismatch.')
self.simSizeLow = np.asarray(self.simSizeLow)
if upres < 1:
self.TCError('Upres must be at least 1.')
self.upres = upres
if not highIsLabel:
self.tileSizeHigh = self.tileSizeLow*upres
self.simSizeHigh = self.simSizeLow*upres
else:
self.tileSizeHigh = np.asarray([1])
self.simSizeHigh = np.asarray([1])
if self.dim==2:
self.tileSizeLow[0]=1
self.tileSizeHigh[0]=1
self.simSizeLow[0]=1
self.simSizeHigh[0]=1
if np.less(self.simSizeLow, self.tileSizeLow).any():
self.TCError('Tile size {} can not be larger than sim size {}, {}.'.format(self.tileSizeLow,self.simSizeLow))
if densityMinimum<0.:
self.TCError('densityMinimum can not be negative.')
self.densityMinimum = densityMinimum
self.premadeTiles = premadeTiles
self.useDataAug = False
#CHANNELS
self.c_lists = {}
self.c_low, self.c_lists[DATA_KEY_LOW] = self.parseChannels(channelLayout_low)
self.c_high, self.c_lists[DATA_KEY_HIGH] = self.parseChannels(channelLayout_high)
# print info
print('\n')
print('Dimension: {}, time dimension: {}'.format(self.dim,self.dim_t))
print('Low-res data:')
print(' channel layout: {}'.format(self.c_low))
print(' default channels: {}'.format(self.c_lists[DATA_KEY_LOW][C_KEY_DEFAULT]))
if len(self.c_lists[DATA_KEY_LOW][C_KEY_VELOCITY])>0:
print(' velocity channels: {}'.format(self.c_lists[DATA_KEY_LOW][C_KEY_VELOCITY]))
if len(self.c_lists[DATA_KEY_LOW][C_KEY_VORTICITY])>0:
print(' vorticity channels: {}'.format(self.c_lists[DATA_KEY_LOW][C_KEY_VORTICITY]))
print('High-res data:')
if highIsLabel:
print(' is Label')
print(' channel layout: {}'.format(self.c_high))
print(' default channels: {}'.format(self.c_lists[DATA_KEY_HIGH][C_KEY_DEFAULT]))
if len(self.c_lists[DATA_KEY_HIGH][C_KEY_VELOCITY])>0:
print(' velocity channels: {}'.format(self.c_lists[DATA_KEY_HIGH][C_KEY_VELOCITY]))
if len(self.c_lists[DATA_KEY_HIGH][C_KEY_VORTICITY])>0:
print(' vorticity channels: {}'.format(self.c_lists[DATA_KEY_HIGH][C_KEY_VORTICITY]))
#self.channels=len(self.c)
self.data_flags = {
DATA_KEY_LOW:{
'isLabel':False,
'channels':len(self.c_low),
C_KEY_VELOCITY:len(self.c_lists[DATA_KEY_LOW][C_KEY_VELOCITY])>0,
C_KEY_VORTICITY:len(self.c_lists[DATA_KEY_LOW][C_KEY_VORTICITY])>0,
C_KEY_POSITION:False
},
DATA_KEY_HIGH:{
'isLabel':highIsLabel,
'channels':len(self.c_high),
C_KEY_VELOCITY:len(self.c_lists[DATA_KEY_HIGH][C_KEY_VELOCITY])>0,
C_KEY_VORTICITY:len(self.c_lists[DATA_KEY_HIGH][C_KEY_VORTICITY])>0,
C_KEY_POSITION:False
}
}
if loadPN:
self.TCError('prev and next tiles not supported.')
self.hasPN = loadPN
self.padding=padding
#if self.hasPN:
#[z,y,x, velocities an/or position if enabled (density,vel,vel,vel, pos, pos [,pos])]
#DATA SHAPES
self.tile_shape_low = np.append(self.tileSizeLow, [self.data_flags[DATA_KEY_LOW]['channels']])
self.frame_shape_low = np.append(self.simSizeLow, [self.data_flags[DATA_KEY_LOW]['channels']])
if not self.data_flags[DATA_KEY_HIGH]['isLabel']:
self.tile_shape_high = np.append(self.tileSizeHigh, [self.data_flags[DATA_KEY_HIGH]['channels']])
self.frame_shape_high = np.append(self.simSizeHigh, [self.data_flags[DATA_KEY_HIGH]['channels']])
else:
self.tile_shape_high = self.tileSizeHigh[:]
self.frame_shape_high = self.simSizeHigh[:]
self.densityThreshold = (self.densityMinimum * self.tile_shape_low[0] * self.tile_shape_low[1] * self.tile_shape_low[2])
self.data = {
DATA_KEY_LOW:[],
DATA_KEY_HIGH:[]
}
all=partTrain+partTest+partVal
self.part_train=partTrain/all
self.part_test=partTest/all
self.part_validation=partVal/all
def initDataAugmentation(self, rot=2, minScale=0.85, maxScale=1.15 ,flip=True):
'''
set up data augmentation
rot: 1: 90 degree rotations; 2: full rotation; else: nop rotation
Scale: if both 1 disable scaling
'''
self.useDataAug = True
"""
specify the special augmentation operation needed for some channel types here
will only be applyed if the specified channel type is in the data
** Tempo Datum may have multiple channels as coherent frames, [batch, z, y, x, t*channels]
** They are reshaped first before these aops, [batch, z, y, x, t, channels], and then reshape back
** Because of this extra time dimention, all aops can only do isolate calculations, for e.g., value scaling,
** Any calculation relay on neighborhood will be wrong, for e.g., spacial scaling (zoom).
"""
self.aops = {
DATA_KEY_LOW:{
AOPS_KEY_ROTATE:{
C_KEY_VELOCITY:self.rotateVelocities,
C_KEY_VORTICITY:self.rotateVelocities
},
AOPS_KEY_SCALE:{
C_KEY_VELOCITY:self.scaleVelocities,
C_KEY_VORTICITY:self.scaleVelocities
},
AOPS_KEY_ROT90:{
C_KEY_VELOCITY:self.rotate90Velocities,
C_KEY_VORTICITY:self.rotate90Velocities
},
AOPS_KEY_FLIP:{
C_KEY_VELOCITY:self.flipVelocities,
C_KEY_VORTICITY:self.flipVelocities
}
},
DATA_KEY_HIGH:{
AOPS_KEY_ROTATE:{
C_KEY_VELOCITY:self.rotateVelocities,
C_KEY_VORTICITY:self.rotateVelocities
},
AOPS_KEY_SCALE:{
C_KEY_VELOCITY:self.scaleVelocities,
C_KEY_VORTICITY:self.scaleVelocities
},
AOPS_KEY_ROT90:{
C_KEY_VELOCITY:self.rotate90Velocities,
C_KEY_VORTICITY:self.rotate90Velocities
},
AOPS_KEY_FLIP:{
C_KEY_VELOCITY:self.flipVelocities,
C_KEY_VORTICITY:self.flipVelocities
}
}
}
msg = 'data augmentation: '
if rot==2:
self.do_rotation = True
self.do_rot90 = False
msg += 'rotation, '
elif rot==1:
self.do_rotation = False
self.do_rot90 = True
msg += 'rot90, '
z=(2,1)
nz=(1,2)
x=(1,0)
y=(0,2)
nx=(0,1)
ny=(2,0)
# thanks to http://www.euclideanspace.com/maths/discrete/groups/categorise/finite/cube/
self.cube_rot = {2: [[],[z],[z,z],[nz]], 3: [[],[x],[y],[x,x],[x,y],[y,x],[y,y],[nx],[x,x,y],[x,y,x],[x,y,y],[y,x,x],[y,y,x],[ny],[nx,y],[x,x,y,x],[x,x,y,y],[x,y,x,x],[x,ny],[y,nx],[ny,x],[nx,y,x],[x,y,nx],[x,ny,x]]}
else:
self.do_rotation = False
self.do_rot90 = False
self.scaleFactor = [minScale, maxScale]
if (self.scaleFactor[0]==1 and self.scaleFactor[1]==1):
self.do_scaling = False
else:
self.do_scaling = True
msg += 'scaling, '
self.do_flip = flip
if self.do_flip:
msg += 'flip'
msg += '.'
print(msg)
self.interpolation_order = 1
self.fill_mode = 'constant'
def addData(self, low, high):
'''
add data, tiles if premadeTiles, frames otherwise.
low, high: list of or single 3D data np arrays
'''
# check data shape
low = np.asarray(low)
high = np.asarray(high)
if not self.data_flags[DATA_KEY_HIGH]['isLabel']:
if len(low.shape)!=len(high.shape): #high-low mismatch
self.TCError('Data shape mismatch. Dimensions: {} low vs {} high. Dimensions must match or use highIsLabel.'.format(len(low.shape),len(high.shape)) )
if not (len(low.shape)==4 or len(low.shape)==5): #not single frame or sequence of frames
self.TCError('Input must be single 3D data or sequence of 3D data. Format: ([batch,] z, y, x, channels). For 2D use z=1.')
if (low.shape[-1]!=(self.dim_t * self.data_flags[DATA_KEY_LOW]['channels'])):
self.TCError('Dim_t ({}) * Channels ({}, {}) configured for LOW-res data don\'t match channels ({}) of input data.'.format(self.dim_t, self.data_flags[DATA_KEY_LOW]['channels'], self.c_low, low.shape[-1]) )
if not self.data_flags[DATA_KEY_HIGH]['isLabel']:
if (high.shape[-1]!=(self.dim_t * self.data_flags[DATA_KEY_HIGH]['channels'])):
self.TCError('Dim_t ({}) * Channels ({}, {}) configured for HIGH-res data don\'t match channels ({}) of input data.'.format(self.dim_t, self.data_flags[DATA_KEY_HIGH]['channels'], self.c_high, high.shape[-1]) )
low_shape = low.shape
high_shape = high.shape
if len(low.shape)==5: #sequence
if low.shape[0]!=high.shape[0]: #check amount
self.TCError('Unequal amount of low ({}) and high ({}) data.'.format(low.shape[1], high.shape[1]))
# get single data shape
low_shape = low_shape[1:]
if not self.data_flags[DATA_KEY_HIGH]['isLabel']:
high_shape = high_shape[1:]
else: high_shape = [1]
else: #single
low = [low]
high = [high]
if self.premadeTiles:
if not (self.dim_t == 1):
self.TCError('Currently, Dim_t = {} > 1 is not supported by premade tiles'.format(self.dim_t))
if not np.array_equal(low_shape, self.tile_shape_low) or not np.array_equal(high_shape,self.tile_shape_high):
self.TCError('Tile shape mismatch: is - specified\n\tlow: {} - {}\n\thigh {} - {}'.format(low_shape, self.tile_shape_low, high_shape,self.tile_shape_high))
else:
single_frame_low_shape = list(low_shape)
single_frame_high_shape = list(high_shape)
single_frame_low_shape[-1] = low_shape[-1] // self.dim_t
if not self.data_flags[DATA_KEY_HIGH]['isLabel']:
single_frame_high_shape[-1] = high_shape[-1] // self.dim_t
if not np.array_equal(single_frame_low_shape, self.frame_shape_low) or not np.array_equal(single_frame_high_shape,self.frame_shape_high):
self.TCError('Frame shape mismatch: is - specified\n\tlow: {} - {}\n\thigh: {} - {}, given dim_t as {}'.format(single_frame_low_shape, self.frame_shape_low, single_frame_high_shape,self.frame_shape_high, self.dim_t))
self.data[DATA_KEY_LOW].extend(low)
self.data[DATA_KEY_HIGH].extend(high)
print('\n')
print('Added {} datasets. Total: {}'.format(low.shape[0], len(self.data[DATA_KEY_LOW])))
self.splitSets()
def splitSets(self):
'''
calculate the set borders for training, testing and validation set
'''
length = len(self.data[DATA_KEY_LOW])
end_train = int( length * self.part_train )
end_test = end_train + int( length * self.part_test )
#just store the borders of the different sets to avoid data duplication
self.setBorders = [end_train, end_test, length]
print('Training set: {}'.format(self.setBorders[0]))
print('Testing set: {}'.format(self.setBorders[1]-self.setBorders[0]))
print('Validation set: {}'.format(self.setBorders[2]-self.setBorders[1]))
def clearData(self):
'''
clears the data buffer
'''
self.data = {
DATA_KEY_LOW:[],
DATA_KEY_HIGH:[]
}
def createTiles(self, data, tileShape, strides=-1):
'''
create tiles from a single frame. fixed, regular pattern
strides: <=0 or tileShape is normal, otherwise create overlapping tiles
'''
dataShape = data.shape #2D sim: [1,res,res,channels]
pad = [self.padding,self.padding,self.padding,0]
if np.isscalar(strides):
if strides <= 0:
strides = tileShape
else:
strides = [strides,strides,strides]
if dataShape[0]<=1:
pad[0] = 0
strides[0] = 1
channels = dataShape[3]
noTiles = [ (dataShape[0]-tileShape[0])//strides[0]+1, (dataShape[1]-tileShape[1])//strides[1]+1, (dataShape[2]-tileShape[2])//strides[2]+1 ]
tiles = []
for tileZ in range(0, noTiles[0]):
for tileY in range(0, noTiles[1]):
for tileX in range(0, noTiles[2]):
idx_from=[tileZ*strides[0], tileY*strides[1], tileX*strides[2]]
idx_to=[idx_from[0]+tileShape[0], idx_from[1]+tileShape[1], idx_from[2]+tileShape[2]]
currTile=data[ idx_from[0]:idx_to[0], idx_from[1]:idx_to[1], idx_from[2]:idx_to[2], :]
if self.padding > 0:
currTile = np.pad(currTile, pad, 'edge')
tiles.append(currTile)
return np.array(tiles)
def cutTile(self, data, tileShape, offset=[0,0,0]):
'''
cut a tile of with shape and offset
'''
offset = np.asarray(offset)
tileShape = np.asarray(tileShape)
tileShape[-1] = data.shape[-1]
if np.less(data.shape[:3], tileShape[:3]+offset[:3]).any():
self.TCError('Can\'t cut tile with shape {} and offset{} from data with shape {}.'.format(tileShape, offset, data.shape))
tile = data[offset[0]:offset[0]+tileShape[0], offset[1]:offset[1]+tileShape[1], offset[2]:offset[2]+tileShape[2], :]
if not np.array_equal(tile.shape,tileShape):
self.TCError('Wrong tile shape after cutting. is: {}. goal: {}.'.format(tile.shape,tileShape))
return tile
#####################################################################################
# batch creation
#####################################################################################
def selectRandomTiles(self, selectionSize, isTraining=True, augment=False, tile_t = 1):
'''
main method to create baches
Return:
shape: [selectionSize, z, y, x, channels * tile_t]
if 2D z = 1
channels: density, [vel x, vel y, vel z], [pos x, pox y, pos z]
'''
if isTraining:
if self.setBorders[0]<1:
self.TCError('no training data.')
else:
if (self.setBorders[1] - self.setBorders[0])<1:
self.TCError('no test data.')
if(tile_t > self.dim_t):
self.TCError('not enough coherent frames. Requested {}, available {}'.format(tile_t, self.dim_t))
batch_low = []
batch_high = []
for i in range(selectionSize):
if augment and self.useDataAug: #data augmentation
low, high = self.generateTile(isTraining, tile_t)
else: #cut random tile without augmentation
low, high = self.getRandomDatum(isTraining, tile_t)
if not self.premadeTiles:
low, high = self.getRandomTile(low, high)
batch_low.append(low)
batch_high.append(high)
return np.asarray(batch_low), np.asarray(batch_high)
def generateTile(self, isTraining=True, tile_t = 1):
'''
generates a random low-high pair of tiles (data augmentation)
'''
# get a frame, is a copy to avoid transormations affecting the raw dataset
data = {}
data[DATA_KEY_LOW], data[DATA_KEY_HIGH] = self.getRandomDatum(isTraining, tile_t)
if not self.premadeTiles:
#cut a tile for faster transformation
if self.do_scaling or self.do_rotation:
factor = 1
if self.do_rotation: # or self.do_scaling:
factor*=1.5 # scaling: to avoid size errors caused by rounding
if self.do_scaling:
scaleFactor = np.random.uniform(self.scaleFactor[0], self.scaleFactor[1])
factor/= scaleFactor
tileShapeLow = np.ceil(self.tile_shape_low*factor)
if self.dim==2:
tileShapeLow[0] = 1
data[DATA_KEY_LOW], data[DATA_KEY_HIGH] = self.getRandomTile(data[DATA_KEY_LOW], data[DATA_KEY_HIGH], tileShapeLow.astype(int))
#random scaling, changes resolution
if self.do_scaling:
data = self.scale(data, scaleFactor)
bounds = np.zeros(4)
#rotate
if self.do_rotation:
bounds = np.array(data[DATA_KEY_LOW].shape)*0.16 #bounds applied on all sides, 1.5*(1-2*0.16)~1
data = self.rotate(data)
#get a tile
data[DATA_KEY_LOW], data[DATA_KEY_HIGH] = self.getRandomTile(data[DATA_KEY_LOW], data[DATA_KEY_HIGH], bounds=bounds) #includes "shifting"
if self.do_rot90:
rot = np.random.choice(self.cube_rot[self.dim])
for axis in rot:
data = self.rotate90(data, axis)
#flip once
if self.do_flip:
axis = np.random.choice(4)
if axis < 3: # axis < self.dim
data = self.flip(data, [axis])
# check tile size
target_shape_low = np.copy(self.tile_shape_low)
target_shape_high = np.copy(self.tile_shape_high)
target_shape_low[-1] *= tile_t
target_shape_high[-1] *= tile_t
if not np.array_equal(data[DATA_KEY_LOW].shape,target_shape_low) or (not np.array_equal(data[DATA_KEY_HIGH].shape,target_shape_high) and not self.data_flags[DATA_KEY_HIGH]['isLabel']):
self.TCError('Wrong tile shape after data augmentation. is: {},{}. goal: {},{}.'.format(data[DATA_KEY_LOW].shape, data[DATA_KEY_HIGH].shape, target_shape_low, target_shape_high))
return data[DATA_KEY_LOW], data[DATA_KEY_HIGH]
def getRandomDatum(self, isTraining=True, tile_t = 1):
'''returns a copy of a random frame'''
if isTraining:
randNo = randrange(0, self.setBorders[0])
else:
randNo = randrange(self.setBorders[0], self.setBorders[1])
randFrame = 0
if tile_t<self.dim_t:
randFrame = randrange(0, self.dim_t - tile_t)
else:
tile_t = self.dim_t
return self.getDatum(randNo*self.dim_t+randFrame, tile_t)
def getDatum(self, index, tile_t = 1):
'''returns a copy of the indicated frame or tile'''
begin_ch = 0
if(self.dim_t > 1):
begin_ch = (index % self.dim_t) * self.tile_shape_low[-1]
end_ch = begin_ch + tile_t * self.tile_shape_low[-1]
begin_ch_y = 0
if(self.dim_t > 1):
begin_ch_y = (index % self.dim_t) * self.tile_shape_high[-1]
end_c_h_y = begin_ch_y + tile_t * self.tile_shape_high[-1]
if not self.data_flags[DATA_KEY_HIGH]['isLabel']:
return np.copy(self.data[DATA_KEY_LOW][index//self.dim_t][:,:,:,begin_ch:end_ch]), np.copy(self.data[DATA_KEY_HIGH][index//self.dim_t][:,:,:,begin_ch_y:end_c_h_y])
else:
return np.copy(self.data[DATA_KEY_LOW][index//self.dim_t][:,:,:,begin_ch:end_ch]), np.copy(self.data[DATA_KEY_HIGH][index//self.dim_t])
def getRandomTile(self, low, high, tileShapeLow=None, bounds=[0,0,0,0]): #bounds to avoid mirrored parts
'''
cut a random tile (low and high) from a given frame, considers densityMinimum
bounds: ignore edges of frames, used to discard mirrored parts after rotation
'''
if tileShapeLow is None:
tileShapeLow = np.copy(self.tile_shape_low) # use copy is very important!!!
tileShapeHigh = tileShapeLow*self.upres
frameShapeLow = np.asarray(low.shape)
if len(low.shape)!=4 or len(tileShapeLow)!=4:
self.TCError('Data shape mismatch.')
if len(high.shape)!=4 and not self.data_flags[DATA_KEY_HIGH]['isLabel']:
self.TCError('Data shape mismatch.')
start = np.ceil(bounds)
end = frameShapeLow - tileShapeLow + np.ones(4) - start
offset_up = np.array([self.upres, self.upres, self.upres])
if self.dim==2:
start[0] = 0
end[0] = 1
offset_up[0] = 1
tileShapeHigh[0] = 1
# check if possible to cut tile
if np.amin((end-start)[:3]) < 0:
self.TCError('Can\'t cut tile {} from frame {} with bounds {}.'.format(tileShapeLow, frameShapeLow, start))
# cut tile
hasMinDensity = False
i = 1
while (not hasMinDensity) and i<20:
offset = np.asarray([randrange(start[0], end[0]), randrange(start[1], end[1]), randrange(start[2], end[2])])
lowTile = self.cutTile(low, tileShapeLow, offset)
offset *= offset_up
if not self.data_flags[DATA_KEY_HIGH]['isLabel']:
highTile = self.cutTile(high, tileShapeHigh, offset)
else:
highTile = high
hasMinDensity = self.hasMinDensity(lowTile)
i+=1
return lowTile, highTile
#####################################################################################
# AUGMENTATION
#####################################################################################
def special_aug(self, data, ops_key, param):
"""
wrapper to call the augmentation operations specified in self.aops in initAugmentation
"""
for data_key in data:
if self.data_flags[data_key]['isLabel']: continue
orig_shape = data[data_key].shape
tile_t = orig_shape[-1] // self.data_flags[data_key]['channels']
data_array = data[data_key]
if(tile_t > 1): data_array = data[data_key].reshape( (-1, tile_t, self.data_flags[data_key]['channels']) )
for c_key, op in self.aops[data_key][ops_key].items():
if self.data_flags[data_key][c_key]:
data_array = op(data_array, self.c_lists[data_key][c_key], param)
if (tile_t > 1): data[data_key] = data_array.reshape(orig_shape)
return data
def rotate(self, data):
'''
random uniform rotation of low and high data of a given frame
'''
#check if single frame
#2D:
if self.dim==2:
theta = np.pi * np.random.uniform(0, 2)
rotation_matrix = np.array([[1, 0, 0, 0 ],
[0, np.cos(theta), -np.sin(theta), 0],
[0, np.sin(theta), np.cos(theta) , 0],
[0, 0, 0, 1] ])
#3D:
elif self.dim==3:
# random uniform rotation in 3D
quat = np.random.normal(size=4)
quat/= np.linalg.norm(quat)
q = np.outer(quat, quat)*2
rotation_matrix = np.array([[1-q[2, 2]-q[3, 3], q[1, 2]-q[3, 0], q[1, 3]+q[2, 0], 0],
[ q[1, 2]+q[3, 0], 1-q[1, 1]-q[3, 3], q[2, 3]-q[1, 0], 0],
[ q[1, 3]-q[2, 0], q[2, 3]+q[1, 0], 1-q[1, 1]-q[2, 2], 0],
[ 0, 0, 0, 1]])
data = self.special_aug(data, AOPS_KEY_ROTATE, rotation_matrix)
for data_key in data:
if not self.data_flags[data_key]['isLabel']:
data[data_key] = self.applyTransform(data[data_key], rotation_matrix.T)
return data
def rotate_simple(self, low, high, angle):
'''
use a different method for rotation. about 30-40% faster than with rotation matrix, but only one axis.
'''
if len(low.shape)!=4 or len(high.shape)!=4:
self.TCError('Data shape mismatch.')
#test rot around z (axis order z,y,x,c)
low = scipy.ndimage.rotate(low, angle, [1,2] , reshape=False, order=self.interpolation_order, mode=self.fill_mode, cval=1.0)
high = scipy.ndimage.rotate(high, angle, [1,2] , reshape=False, order=self.interpolation_order, mode=self.fill_mode, cval=1.0)
return low, high
def rotateVelocities(self, datum, c_list, rotationMatrix):
'''
rotate vel vectors (channel 1-3)
'''
rotation3 = rotationMatrix[:3, :3]
rotation2 = rotationMatrix[1:3, 1:3]
channels = np.split(datum, datum.shape[-1], -1)
for v in c_list:
if len(v) == 3: # currently always ends here!! even for 2D, #z,y,x to match rotation matrix
vel = np.stack([channels[v[2]].flatten(),channels[v[1]].flatten(),channels[v[0]].flatten()])
vel = rotation3.dot(vel)
channels[v[2]] = np.reshape(vel[0], channels[v[2]].shape)
channels[v[1]] = np.reshape(vel[1], channels[v[1]].shape)
channels[v[0]] = np.reshape(vel[2], channels[v[0]].shape)
if len(v) == 2:
vel = np.concatenate([channels[v[1]],channels[v[0]]], -1) #y,x to match rotation matrix
shape = vel.shape
vel = np.reshape(vel, (-1, 2))
vel = np.reshape(rotation2.dot(vel.T).T, shape)
vel = np.split(vel, 2, -1)
channels[v[1]] = vel[0]
channels[v[0]] = vel[1]
return np.concatenate(channels, -1)
def rotate90(self, data, axes):
'''
rotate the frame by 90 degrees from the first axis counterclockwise to the second
axes: 2 int, from axis to axis; see np.rot90
0,1,2 -> z,y,x
'''
if len(axes)!=2:
self.TCError('need 2 axes for rotate90.')
for data_key in data:
if not self.data_flags[data_key]['isLabel']:
data[data_key] = np.rot90(data[data_key], axes=axes)
data = self.special_aug(data, AOPS_KEY_ROT90, axes)
return data
def rotate90Velocities(self, datum, c_list, axes):
if len(axes)!=2:
self.TCError('need 2 axes for rotate90.')
channels = np.split(datum, datum.shape[-1], -1)
for v in c_list: #axes z,y,x -> vel x,y,z: 0,1,2 -> 2,1,0
channels[v[-axes[0]+2]], channels[v[-axes[1]+2]] = -channels[v[-axes[1]+2]], channels[v[-axes[0]+2]]
return np.concatenate(channels, -1)
def flip(self, data, axes, isFrame=True): #axes=list, flip multiple at once
'''
flip low and high data (single frame/tile) along the specified axes
low, high: data format: (z,x,y,c)
axes: list of axis indices 0,1,2-> z,y,x
'''
# axis: 0,1,2 -> z,y,x
if not isFrame:
axes = np.asarray(axes) + np.ones(axes.shape)
#flip tiles/frames
for axis in axes:
for data_key in data:
if not self.data_flags[data_key]['isLabel']:
data[data_key] = np.flip(data[data_key], axis)
data = self.special_aug(data, AOPS_KEY_FLIP, axes)
return data
def flipVelocities(self, datum, c_list, axes):
'''
flip velocity vectors along the specified axes
low: data with velocity to flip (4 channels: d,vx,vy,vz)
axes: list of axis indices 0,1,2-> z,y,x
'''
# !axis order: data z,y,x
channels = np.split(datum, datum.shape[-1], -1)
for v in c_list: # x,y,[z], 2,1,0
if 2 in axes: # flip vel x
channels[v[0]] *= (-1)
if 1 in axes:
channels[v[1]] *= (-1)
if 0 in axes and len(v)==3:
channels[v[2]] *= (-1)
return np.concatenate(channels, -1)
def scale(self, data, factor):
'''
changes frame resolution to "round((factor) * (original resolution))"
'''
# only same factor in every dim for now. how would it affect vel scaling?
# check for 2D
scale = [factor, factor, factor, 1] #single frame
if self.dim==2:
scale[0] = 1
# to ensure high/low ration stays the same
scale = np.round(np.array(data[DATA_KEY_LOW].shape) * scale )/np.array(data[DATA_KEY_LOW].shape)
if len(data[DATA_KEY_LOW].shape)==5: #frame sequence
scale = np.append([1],scale)
#apply transform
#low = self.applyTransform(low, zoom_matrix)
#high = self.applyTransform(high, zoom_matrix)
#changes the size of the frame. should work well with getRandomTile(), no bounds needed
for data_key in data:
if not self.data_flags[data_key]['isLabel']:
data[data_key] = scipy.ndimage.zoom( data[data_key], scale, order=self.interpolation_order, mode=self.fill_mode, cval=0.0)
#necessary?
data = self.special_aug(data, AOPS_KEY_SCALE, factor)
return data
def scaleVelocities(self, datum, c_list, factor):
#scale vel? vel*=factor
channels = np.split(datum, datum.shape[-1], -1)
for v in c_list: # x,y,[z]; 2,1,0
channels[v[0]] *= factor
channels[v[1]] *= factor
if len(v)==3:
channels[v[2]] *= factor
return np.concatenate(channels, -1)
def applyTransform(self, data, transform_matrix, data_dim=3):
# change axis order from z,y,x to x,y,z? (invert axis order +channel)
if len(data.shape)!=4:
self.TCError('Data shape mismatch.')
#set transform to center; from fluiddatagenerator.py
offset = np.array(data.shape) / 2 - np.array([0.5, 0.5, 0.5, 0])
offset_matrix = np.array([[1, 0, 0, offset[0]], [0, 1, 0, offset[1]], [0, 0, 1, offset[2]], [0, 0, 0, 1]])
reset_matrix = np.array([[1, 0, 0,-offset[0]], [0, 1, 0,-offset[1]], [0, 0, 1,-offset[2]], [0, 0, 0, 1]])
transform_matrix = np.dot(np.dot(offset_matrix, transform_matrix), reset_matrix)
data = np.rollaxis(data, 3, 0) #channel to front
channel_data = [scipy.ndimage.interpolation.affine_transform(
channel,
transform_matrix[:data_dim,:data_dim],
transform_matrix[:data_dim, data_dim],
order=self.interpolation_order,
mode=self.fill_mode,
cval=0.) for channel in data]
data = np.stack(channel_data, axis=-1) # stack axis=-1 ?\
return data
#####################################################################################
# HELPER METHODS
#####################################################################################
def concatTiles(self, tiles, frameShape ,tileBorder=[0,0,0,0]):
'''
build a frame by concatenation of the given tiles.
tiles: numpy array of same shaped tiles [batch,z,y,x,c]
frameShape: the shape of the frame in tiles [z,y,x]
tileBorder: cut off borders of the tiles. [z,y,x,c]
'''
if len(tiles.shape)!=5 or len(frameShape)!=3 or len(tileBorder)!=4:
self.TCError('Data shape mismatch.')
tiles_in_frame = frameShape[0]*frameShape[1]*frameShape[2]
if tiles_in_frame != len(tiles):
self.TCError('given tiles do not match required tiles.')
# cut borders
tileBorder = np.asarray(tileBorder)
if np.less(np.zeros(4),tileBorder).any():
tileShape = tiles.shape[1:] - 2*tileBorder
tiles_cut = []
for tile in tiles:
tiles_cut.append(self.cutTile(tile, tileShape, tileBorder))
tiles = tiles_cut
#combine tiles to image
frame = []
for z in range(frameShape[0]):
frame_slices = []
for y in range(frameShape[1]):
offset=z*frameShape[1]*frameShape[2] + y*frameShape[2]
frame_slices.append(np.concatenate(tiles[offset:offset+frameShape[2]],axis=2)) #combine x
frame.append(np.concatenate(frame_slices, axis=1)) #combine y
frame = np.concatenate(frame, axis=0) #combine z
return frame
def hasMinDensity(self, tile):
return self.getTileDensity(tile) >= (self.densityMinimum * tile.shape[0] * tile.shape[1] * tile.shape[2])
def getTileDensity(self, tile):
if self.data_flags[DATA_KEY_LOW]['channels'] > 1:
tile = np.split(tile, [1], axis=-1)[0]
return tile.sum( dtype=np.float64 )
def getFrameTiles(self, index):
''' returns the frame as tiles'''
low, high = self.getDatum(index)
return self.createTiles(low, self.tile_shape_low), self.createTiles(high, self.tile_shape_high)
#####################################################################################
# CHANNEL PARSING
#####################################################################################
def parseChannels(self, channelString):
''' arbitrary channel structure from string, expand if necessary. USE GLOBAL KEYS ^
'd': default/ density; data that needs no special operations during augmentation
'v[label](x|y|z)': vector/velocity; is transformed according to the augmentation
'''
#need this for low and high, +high only labels
c = channelString.lower().split(',')
for i in range(len(c)):
c[i] = c[i].strip()
c_types = {
C_KEY_DEFAULT:[], #list of indices of default channels. e.g. for normal sim data [0]
C_KEY_VELOCITY:[], #list of ordered (x,y,z; chnage to z,y,x to match data?) triples of velocity sets. e.g. for normal sim data [[1,2,3]]
C_KEY_VORTICITY:[]
}
self.parse = {
C_KEY_DEFAULT:self.parseCDefault,
C_KEY_VELOCITY:self.parseCVelocity,
C_KEY_VORTICITY:self.parseCVorticity
}
for i in range(len(c)):
if len(c[i])==0: # check empty key
self.TCError('empty channel key.'.format(i))
try:
self.parse[c[i][0]](c, i, c_types)
except KeyError:
self.TCError('channel {}: unknown channel key \"{}\".'.format(i, c[i]))
# TODO check unused channels here
return c, c_types
def parseCDefault(self, c, i, c_types):
# check length
if c[i]=='d':
c_types[C_KEY_DEFAULT].append(i)
else:
self.TCError('channel {}: unknown channel key \"{}\".'.format(i, c[i]))
def parseCVector(self, c, i, c_types, c_key, c_name='vector'):
# c_key[label](x|y|z)
if c[i][-1] == 'x' or c[i][-1] == 'y' or c[i][-1] == 'z':
label = c[i][1:-1] #can be empty
#get matching keys
v_x = c_key+label+'x'
v_y = c_key+label+'y'
v_z = c_key+label+'z'
#check for duplicates
if c.count(v_x)>1:
self.TCError('Duplicate {} ({}) x-channel with label \"{}\": {}. Vector keys must be unique.'.format(c_name, c_key, label, v_x))
if c.count(v_y)>1:
self.TCError('Duplicate {} ({}) y-channel with label \"{}\": {}. Vector keys must be unique.'.format(c_name, c_key, label, v_y))
if c.count(v_z)>1:
self.TCError('Duplicate {} ({}) z-channel with label \"{}\": {}. Vector keys must be unique.'.format(c_name, c_key, label, v_z))
#check missing
if c.count(v_x)==0:
self.TCError('Missing {} ({}) x-channel with label \"{}\": {}'.format(c_name, c_key, label, v_x))
if c.count(v_y)==0:
self.TCError('Missing {} ({}) y-channel with label \"{}\": {}'.format(c_name, c_key, label, v_y))
if self.dim==3 and c.count(v_z)==0:
self.TCError('Missing {} ({}) z-channel with label \"{}\": {}'.format(c_name, c_key, label, v_z))
if c[i][-1] == 'x':
if(c.count(v_z)==0 and self.dim==2):
c_types[C_KEY_VELOCITY].append([c.index(v_x),c.index(v_y)])
else:
c_types[C_KEY_VELOCITY].append([c.index(v_x),c.index(v_y),c.index(v_z)])
# check wrong suffix
else:
self.TCError('Channel {}, \"{}\": unknown {} ({}) channel suffix \"{}\". Valid suffixes are \"x\", \"y\", \"z\".'.format(i, c[i], c_name, c_key, c[i][-1]))
def parseCVelocity(self, c, i, c_types):
# C_KEY_VELOCITY[label](x|y|z)
self.parseCVector(c, i, c_types, C_KEY_VELOCITY, 'velociy')
def parseCVorticity(self, c, i, c_types):
# C_KEY_VELOCITY[label](x|y|z)
self.parseCVector(c, i, c_types, C_KEY_VELOCITY, 'vorticity')
#####################################################################################
# ERROR HANDLING
#####################################################################################
def TCError(self, msg):
raise TilecreatorError(msg)
class TilecreatorError(Exception):
''' Tilecreator errors '''
#####################################################################################
# IMAGE OUTPUT
#####################################################################################
# save summary images of all channels in a batch generated by the tile creator
# projects 3D data onto different axes, data has to be B-ZYX-C format
batchCounterGlob=0
def savePngsBatch(low,high, TC, path, batchCounter=-1, save_vels=False, dscale=1., vscale=1.):
global batchCounterGlob
if(low.shape[1]==1):
dim=2
else:
dim=3
# figure out good tile size, and project all axes for 3D
batch = low.shape[0]
tileX = 4 if batch>=4 else batch
if batch%tileX != 0: tileX = batch
# file names
if batchCounter < 0:
batchCounter = batchCounterGlob
batchCounterGlob += 1
path = path+"batch{:04d}_".format(batchCounter)
# show scalar channels, in tiled images
aNames = ["xy_","xz_","yz_"]
for axis in range(1 if dim==2 else 3):
suff = aNames[axis]
if dim == 3:
highD = np.average(high, axis=axis+1) * dscale
lowD = np.average(low, axis=axis+1) * dscale
if dim == 2:
highD = high*brightness ; lowD = low * dscale
lowD.shape = (batch, tll, tll, cl)
highD.shape = (batch, tlh, tlh, ch)
# note - outputs all channels as images, also vel channels...
clout = np.arange(low.shape[4])
savePngsGrayscale(lowD, path+'low_'+suff, tiles_in_image=[batch//tileX,tileX], channels=clout )
chout = np.arange(high.shape[4])
savePngsGrayscale(tiles=highD, path=path+'high_'+suff, imageCounter=0, tiles_in_image=[batch//tileX,tileX], channels=chout )
# plot velocities , for individual samples
if save_vels:
for i in range(low.shape[0]):
saveVelChannels(low[i], TC.c_lists[DATA_KEY_LOW][C_KEY_VELOCITY], path=path+'low_vel_i{:02d}_'.format(i), name="", scale=vscale )
for i in range(high.shape[0]):
saveVelChannels(high[i], TC.c_lists[DATA_KEY_HIGH][C_KEY_VELOCITY], path=path+'high_vel_i{:02d}_'.format(i), name="", scale=vscale )
# simpler function to output multiple tiles into grayscale pngs
def savePngsGrayscale(tiles, path, imageCounter=0, tiles_in_image=[1,1], channels=[0], save_gif=False, plot_vel_x_y=False, save_rgb=None, rgb_interval=[-1,1]):
'''
tiles_in_image: (y,x)
tiles: shape: (tile,y,x,c)
'''
tilesInImage = tiles_in_image[0]*tiles_in_image[1]
if len(tiles)%tilesInImage!=0:
print('ERROR: number of tiles does not match tiles per image')
return
tiles = np.asarray(tiles)
noImages = len(tiles)//tilesInImage
if save_gif:
gif=[]
for image in range(noImages):
img = []
#combine tiles to image
for y in range(tiles_in_image[0]):
offset=image*tilesInImage + y*tiles_in_image[1]
img.append(np.concatenate(tiles[offset:offset+tiles_in_image[1]],axis=1)) #combine x
img = np.concatenate(img, axis=0) #combine y
# move channels to first dim.
img_c = np.rollaxis(img, -1, 0)
if len(img_c)>1 and (plot_vel_x_y or save_rgb!=None):
if plot_vel_x_y: saveVel(img, path, imageCounter+image)
if save_rgb!=None: saveRGBChannels(img,path, save_rgb,value_interval=rgb_interval, imageCounter=imageCounter+image)
if len(channels) == 1:
scipy.misc.toimage(img_c[channels[0]], cmin=0.0, cmax=1.0).save(path + 'img_{:04d}.png'.format(imageCounter*noImages+image))
else:
for i in channels:
scipy.misc.toimage(img_c[i], cmin=0.0, cmax=1.0).save(path + 'img_{:04d}_c{:04d}.png'.format(imageCounter*noImages+image, i))
# store velocity as quiver plot
def saveVel(tile, path, imageCounter=0, name='vel-x-y'):
# origin is in upper left corner, transform acordingly
y, x = np.mgrid[-tile.shape[0]:0, 0:tile.shape[1]]
vx = None; vy = None
if tile.shape[-1]==4:
d, vx, vy, vz = np.split(tile, 4, -1)
elif tile.shape[-1]==2:
vx, vy = np.split(tile, 2, -1)
else:
print('ERROR: unknown nr of channels for vel input '+format(tile.shape))
vx = vx[::-1, ...]
vy = vy[::-1, ...]
if found_matplotlib:
matplotlib.pyplot.quiver(x,y,vx.flatten(),vy.flatten(), units = 'xy', scale = 1)
matplotlib.pyplot.axis('equal')
matplotlib.pyplot.savefig(path + '{}_{:04d}.png'.format(name,imageCounter))
matplotlib.pyplot.clf()
# save velocity channels from the tilecreator with multiple axis projections (uses saveVel)
def saveVelChannels(data, c_idx, path, average=False, scale=1.0, normalize=True, name=''):
channels = np.split(data, data.shape[-1], -1)
vpath = path
vcnt = 0
for v in c_idx:
if(len(c_idx)>1):
vpath = path + "vc{}".format(vcnt)
vcnt += 1
# compute scale factor
vscale = scale
if normalize:
vavg = np.concatenate( [ channels[v[0]],channels[v[1]] ], -1)
if(len(v))>2: vavg = np.concatenate( [ vavg, channels[v[2]] ],-1)
vscale *= (1./(np.max( vavg )+1e-10)) # normalize
vavg = np.concatenate( [ channels[v[0]],channels[v[1]] ] , -1)
vavg = np.average(vavg, axis=0)
vavg *= vscale
saveVel(vavg, path=vpath, name='_xy' )
if(len(v))>2: # also output xz,yz
vavg = np.concatenate( [ channels[v[0]],channels[v[2]] ] , -1)
vavg = np.average(vavg, axis=1)
vavg *= vscale
saveVel(vavg, path=vpath, name='_xz' )
vavg = np.concatenate( [ channels[v[1]],channels[v[2]] ] , -1)
vavg = np.average(vavg, axis=2)
vavg *= vscale
saveVel(vavg, path=vpath, name='_yz' )
def saveRGBChannels(data, path, channel_list, imageCounter=0, value_interval=[-1,1]):
"""
data: shape[y,x,c]
channels: list of triples of channel ids saved as RGB image
"""
cmin = value_interval[0]
cmax = value_interval[1]
num_channels = data.shape[-1]
channels = np.split(data, num_channels, -1)
for i in channel_list:
if len(i)==2:
img = np.concatenate([channels[i[0]], channels[i[1]], np.ones_like(channels[i[0]])*cmin], -1)
else:
img = np.concatenate([channels[i[0]], channels[i[1]], channels[i[2]]], -1)
scipy.misc.toimage(img, cmin=-1.0, cmax=1.0).save(path + 'img_rgb_{:04d}.png'.format(imageCounter))
def save3DasUni(tiles, path, motherUniPath, imageCounter=0, tiles_in_image=[1,1]):
'''
tiles_in_image: (y,x)
tiles: shape: (image,y,x,c)
'''
tilesInImage = tiles_in_image[0]*tiles_in_image[1]
if len(tiles)%tilesInImage!=0:
print('ERROR: number of tiles does not match tiles per image')
return
tiles = np.asarray(tiles)
noImages = len(tiles)//tilesInImage
tiles = np.reshape(tiles,(len(tiles), tiles.shape[1], tiles.shape[2], tiles.shape[-1]))
#only save the average
img_all = []
for image in range(noImages):
img = []
#combine tiles to image
for y in range(tiles_in_image[0]):
offset=( image) * tilesInImage + (y)*tiles_in_image[1]
img.append(np.concatenate(tiles[offset:offset+tiles_in_image[1]],axis=2)) #combine y
img = np.array(img)
img = np.concatenate(img, axis=1) #combine x
img = np.array(img)
# move channels to first dim.
img_c = np.rollaxis(img, 0, 0)
img_all.append(img_c)
img_all = np.array(img_all)
img_all = np.concatenate(img_all, axis=0)
img_all = np.array(img_all)
TDarrayToUni(img_all, path + 'source_{:04d}.uni'.format(imageCounter), motherUniPath, img_all.shape[0], img_all.shape[1], img_all.shape[2])
def TDarrayToUni(input, savePath, motherUniPath, imageHeight, imageWidth, imageDepth, is_vel=False):
head, _ = uniio.readUni(motherUniPath)
head['dimX'] = imageWidth
head['dimY'] = imageHeight
head['dimZ'] = imageDepth
if not is_vel:
fixedArray = np.zeros((imageHeight, imageWidth, imageDepth), dtype='f')
for x in range(0, imageHeight):
for y in range(0, imageWidth):
for z in range(0, imageDepth):
fixedArray[x][y][z] = input[imageDepth - 1 - z][y][(imageHeight - 1) - x]
else:
fixedArray = np.zeros((imageHeight, imageWidth, imageDepth, 3), dtype='f')
for x in range(0, imageHeight):
for y in range(0, imageWidth):
for z in range(0, imageDepth):
fixedArray[x][y][z] = input[imageDepth - 1 - z][y][(imageHeight - 1) - x]
uniio.writeUni(savePath, head, fixedArray)
# ******************************************************************************
# faster functions, batch operations
#
# grid interpolation method, order: only linear tested
# for velocity, macgridbatch.shape should be [b,z,y,x,3] (in 2D, should be [b,1,ny,nx,3])
# for density , macgridsource.shape should be [z,y,x,1] (in 2D, should be [1,ny,nx,1])
def gridInterpolBatch(macgridbatch, targetshape, order=1):
assert (targetshape[-1] == macgridbatch.shape[-1]) # no interpolation between channels
assert (len(targetshape) == 5 and len(macgridbatch.shape) == 5)
dim = 3
if (macgridbatch.shape[1] == 1 and targetshape[1] == 1): dim = 2
x_ = np.linspace(0.5, targetshape[3] - 0.5, targetshape[3])
y_ = np.linspace(0.5, targetshape[2] - 0.5, targetshape[2])
z_ = np.linspace(0.5, targetshape[1] - 0.5, targetshape[1])
c_ = np.linspace(0, targetshape[4] - 1, targetshape[4]) # no interpolation between channels
b_ = np.linspace(0, targetshape[0] - 1, targetshape[0]) # no interpolation between batches
b, z, y, x, c = np.meshgrid(b_, z_, y_, x_, c_, indexing='ij')
# scale
fx = float(macgridbatch.shape[3]) / targetshape[3]
fy = float(macgridbatch.shape[2]) / targetshape[2]
fz = float(macgridbatch.shape[1]) / targetshape[1]
mactargetbatch = scipy.ndimage.map_coordinates(macgridbatch, [b, z * fz, y * fy, x * fx, c], order=order, mode='reflect')
return mactargetbatch;
# macgrid_batch shape b, z, y, x, 3
# return a matrix in size [b,z,y,x,3] ( 2D: [b,y,x,2]), last channel in z-y-x order!(y-x order for 2D)
def getMACGridCenteredBatch(macgrid_batch, is3D):
_bn, _zn, _yn, _xn, _cn = macgrid_batch.shape
valid_idx = list(range(1, _xn))
valid_idx.append(_xn - 1)
add_x = macgrid_batch.take(valid_idx, axis=3)[:, :, :, :, 0] # shape, [b,z,y,x]
valid_idx = list(range(1, _yn))
valid_idx.append(_yn - 1)
add_y = macgrid_batch.take(valid_idx, axis=2)[:, :, :, :, 1] # shape, [b,z,y,x]
add_y = add_y.reshape([_bn, _zn, _yn, _xn, 1])
add_x = add_x.reshape([_bn, _zn, _yn, _xn, 1])
if (is3D):
valid_idx = list(range(1, _zn))
valid_idx.append(_zn - 1)
add_z = macgrid_batch.take(valid_idx, axis=1)[:, :, :, :, 2] # shape, [b,z,y,x]
add_z = add_z.reshape([_bn, _zn, _yn, _xn, 1])
resultgrid = 0.5 * (macgrid_batch[:, :, :, :, ::-1] + np.concatenate((add_z, add_y, add_x), axis=-1))
return resultgrid.reshape([_bn, _zn, _yn, _xn, 3])
resultgrid = 0.5 * (macgrid_batch[:, :, :, :, -2::-1] + np.concatenate((add_y, add_x), axis=4))
return resultgrid.reshape([_bn, _yn, _xn, 2])
# macgrid_batch shape b, z, y, x, 3 ( b,1,y,x,3 for 2D )
# return the re-sampling positions as a matrix, in size of [b,z,y,x,3] ( 2D: [b,y,x,2])
def getSemiLagrPosBatch(macgrid_batch, dt, cube_len_output=-1): # check interpolation later
assert (len(macgrid_batch.shape) == 5)
_bn, _zn, _yn, _xn, _cn = macgrid_batch.shape
assert (_cn == 3)
is3D = (_zn > 1)
if (cube_len_output == -1): cube_len_output = _xn
factor = float(_xn) / cube_len_output
x_ = np.linspace(0.5, int(_xn / factor + 0.5) - 0.5, int(_xn / factor + 0.5))
y_ = np.linspace(0.5, int(_yn / factor + 0.5) - 0.5, int(_yn / factor + 0.5))
interp_shape = [_bn, int(_zn / factor + 0.5), int(_yn / factor + 0.5), int(_xn / factor + 0.5), 3]
if (not is3D): interp_shape[1] = 1
if (is3D):
z_ = np.linspace(0.5, int(_zn / factor + 0.5) - 0.5, int(_zn / factor + 0.5))
z, y, x = np.meshgrid(z_, y_, x_, indexing='ij')
posArray = np.stack((z, y, x), axis=-1) # shape, z,y,x,3
tarshape = [1, int(_zn / factor + 0.5), int(_yn / factor + 0.5), int(_xn / factor + 0.5), 3]
else:
y, x = np.meshgrid(y_, x_, indexing='ij')
posArray = np.stack((y, x), axis=-1) # shape, y,x,2
tarshape = [1, int(_yn / factor + 0.5), int(_xn / factor + 0.5), 2]
posArray = posArray.reshape(tarshape)
if (cube_len_output == _xn):
return (posArray - getMACGridCenteredBatch(macgrid_batch, is3D) * dt)
# interpolate first
inter_mac_batch = gridInterpolBatch(macgrid_batch, interp_shape, 1)
inter_mac_batch = getMACGridCenteredBatch(inter_mac_batch, is3D) / factor
return (posArray - (inter_mac_batch) * dt)
# error! muss not shuffle for fluid data loader!
def selectRandomTempoTiles(self, selectionSize, isTraining=True, augment=False, n_t=3, dt=0.5, adv_flag = 1.0):
'''
main method to create coherent baches
Return:
shape: [n_t * selectionSize//n_t, z, y, x, channels]
if 2D z = 1
channels: density, [vel x, vel y, vel z], [pos x, pox y, pos z]
'''
batch_sz = int( max( 1, selectionSize // n_t) )
batch_low, batch_high = self.selectRandomTiles(batch_sz, isTraining, augment, tile_t = n_t)
real_batch_sz = batch_sz * n_t
ori_input_shape = batch_low.reshape((batch_sz, self.tileSizeLow[0], self.tileSizeLow[1], self.tileSizeLow[2], n_t, -1))
ori_input_shape = np.transpose(ori_input_shape, (0,4,1,2,3,5))
ori_input_shape = ori_input_shape.reshape((real_batch_sz, self.tileSizeLow[0], self.tileSizeLow[1], self.tileSizeLow[2], -1))
vel_pos_high_inter = None
if adv_flag:
# TODO check velocity channels and 3D
macgrid_input = ori_input_shape[:, :, :, :, self.c_lists[DATA_KEY_LOW][C_KEY_VELOCITY][0]]
macgrid_input = macgrid_input.reshape( (real_batch_sz, self.tileSizeLow[0], self.tileSizeLow[1], self.tileSizeLow[2], 3))
dtArray = np.array([i * dt for i in range(n_t // 2, -n_t // 2, -1)] * batch_sz, dtype=np.float32)
if (self.dim == 2):
dtArray = dtArray.reshape((-1, 1, 1, 1))
else:
dtArray = dtArray.reshape((-1, 1, 1, 1, 1))
vel_pos_high_inter = getSemiLagrPosBatch(macgrid_input, dtArray, self.tileSizeHigh[1]).reshape((real_batch_sz, -1))
# return reshape_input, selectedOutputs, vel_pos_high_inter
batch_high = batch_high.reshape((batch_sz, self.tileSizeHigh[0], self.tileSizeHigh[1], self.tileSizeHigh[2], n_t, -1))
batch_high = np.transpose(batch_high, (0,4,1,2,3,5))
return ori_input_shape.reshape((real_batch_sz, -1)), batch_high.reshape((real_batch_sz, -1)), vel_pos_high_inter
TileCreator.selectRandomTempoTiles = selectRandomTempoTiles
def pngs_to_gif(path, start_idx=0, end_idx=199, step=1, fps=20, mask="img_%04d.png"):
print("creating gif from {} to {} with {} fps".format(mask % start_idx, mask % end_idx, fps))
with imageio.get_writer(path + 'step%d.gif'%step, mode='I', fps=fps) as writer:
for i in range(start_idx - 1, end_idx, step):
image = imageio.imread(path+(mask % (i+1)))
writer.append_data(image)
|
cpgf/samples/irrlicht/26.occlusionquery.py
|
mousepawmedia/libdeps
| 187 |
145418
|
<gh_stars>100-1000
cpgf._import(None, "builtin.core");
KeyIsDown = [];
def makeMyEventReceiver(receiver) :
for i in range(irr.KEY_KEY_CODES_COUNT) :
KeyIsDown.append(False);
def OnEvent(me, event) :
if event.EventType == irr.EET_KEY_INPUT_EVENT :
KeyIsDown[event.KeyInput.Key + 1] = event.KeyInput.PressedDown;
return False;
receiver.OnEvent = OnEvent;
def IsKeyDown(keyCode) :
return KeyIsDown[keyCode + 1];
def start() :
driverType = irr.driverChoiceConsole();
if driverType == irr.EDT_COUNT :
return 1;
MyEventReceiver = cpgf.cloneClass(irr.IEventReceiverWrapper);
makeMyEventReceiver(MyEventReceiver);
receiver = MyEventReceiver();
device = irr.createDevice(driverType, irr.dimension2d_u32(640, 480), 16, False, False, False, receiver);
if device == None :
return 1;
driver = device.getVideoDriver();
smgr = device.getSceneManager();
smgr.getGUIEnvironment().addStaticText("Press Space to hide occluder.", irr.rect_s32(10,10, 200,50));
node = smgr.addSphereSceneNode(10, 64);
if node :
node.setPosition(irr.vector3df(0,0,60));
node.setMaterialTexture(0, driver.getTexture("../../media/wall.bmp"));
node.setMaterialFlag(irr.EMF_LIGHTING, False);
plane = smgr.addMeshSceneNode(smgr.addHillPlaneMesh("plane", irr.dimension2df(10,10), irr.dimension2du(2,2)), None, -1, irr.vector3df(0,0,20), irr.vector3df(270,0,0));
if plane :
plane.setMaterialTexture(0, driver.getTexture("../../media/t351sml.jpg"));
plane.setMaterialFlag(irr.EMF_LIGHTING, False);
plane.setMaterialFlag(irr.EMF_BACK_FACE_CULLING, True);
driver.addOcclusionQuery(node, cpgf.cast(node, irr.IMeshSceneNode).getMesh());
smgr.addCameraSceneNode();
lastFPS = -1;
timeNow = device.getTimer().getTime();
nodeVisible=True;
while device.run() :
plane.setVisible(not IsKeyDown(irr.KEY_SPACE));
driver.beginScene(True, True, irr.SColor(255,113,113,133));
node.setVisible(nodeVisible);
smgr.drawAll();
smgr.getGUIEnvironment().drawAll();
if device.getTimer().getTime()-timeNow>100 :
driver.runAllOcclusionQueries(False);
driver.updateAllOcclusionQueries();
nodeVisible=driver.getOcclusionQueryResult(node)>0;
timeNow=device.getTimer().getTime();
driver.endScene();
fps = driver.getFPS();
if lastFPS != fps :
tmp = "cpgf Irrlicht Python binding OcclusionQuery Example [";
tmp = tmp + driver.getName();
tmp = tmp + "] fps: ";
tmp = tmp + str(fps);
device.setWindowCaption(tmp);
lastFPS = fps;
device.drop();
return 0;
start();
|
tests/codegen/fcode/scripts/tuples.py
|
dina-fouad/pyccel
| 206 |
145431
|
# pylint: disable=missing-function-docstring, missing-module-docstring/
ai = (1,4,5)
ai[0] = 2
bi = ai[0]
ci = 2 * ai[0]
di = 2 * ai[0] + 3 * ai[1]
ei = 2 * ai[0] + bi * ai[1]
fi = ai
gi = (0,)*2
gi[:] = ai[1:]
ad = (1.,4.,5.)
ad[0] = 2.
bd = ad[0]
cd = 2. * ad[0]
dd = 2. * ad[0] + 3. * ad[1]
ed = 2. * ad[0] + bd * ad[1]
fd = ad
gd = (0.,)*2
gd[:] = ad[1:]
|
exchange_calendars/exchange_calendar_aixk.py
|
rajeshyogeshwar/exchange_calendars
| 128 |
145438
|
<reponame>rajeshyogeshwar/exchange_calendars
from datetime import time
from itertools import chain
import pandas as pd
from pandas.tseries.holiday import (
Holiday,
next_monday,
nearest_workday,
next_workday,
)
from pytz import timezone
from .common_holidays import new_years_day, eid_al_adha_first_day
from .exchange_calendar import (
HolidayCalendar,
ExchangeCalendar,
)
NewYearsDay = new_years_day()
NewYearHoliday = Holiday(
"New Year Holiday",
month=1,
day=2,
)
OrthodoxChristmasDay = Holiday(
"Orthodox Christmas Day",
month=1,
day=7,
)
InternationalWomensDay = Holiday(
"International Women's Day",
month=3,
day=8,
observance=nearest_workday,
)
NauryzHoliday1 = Holiday(
"Nauryz Holiday",
month=3,
day=21,
observance=next_monday,
)
NauryzHoliday2 = Holiday(
"Nauryz Holiday",
month=3,
day=21,
observance=lambda dt: next_workday(next_monday(dt)),
)
NauryzHoliday3 = Holiday(
"Nauryz Holiday",
month=3,
day=21,
observance=lambda dt: next_workday(next_workday(next_monday(dt))),
)
KazakhstanPeopleSolidarityDay = Holiday(
"Kazakhstan People Solidarity Day",
month=5,
day=1,
observance=next_monday,
)
DefendersDay = Holiday(
"Defender's Day",
month=5,
day=7,
observance=next_monday,
start_date=pd.Timestamp("2013-01-01"),
)
VictoryDayHoliday = Holiday(
"Victory Day Holiday",
month=5,
day=9,
observance=nearest_workday,
)
CapitalCityDay = Holiday(
"Capital City Day",
month=7,
day=6,
observance=next_monday,
)
ConstitutionDay = Holiday(
"Constitution Day",
month=8,
day=30,
observance=next_monday,
)
FirstPresidentDay = Holiday(
"First President Day",
month=12,
day=1,
observance=next_monday,
start_date=pd.Timestamp("2013-01-01"),
)
IndependenceDay = Holiday(
"Independence Day",
month=12,
day=16,
observance=next_monday,
)
IndependenceDayHoliday = Holiday(
"Independence Day",
month=12,
day=17,
observance=next_monday,
)
class AIXKExchangeCalendar(ExchangeCalendar):
"""
Exchange calendar for the Astana International Exchange (XIST).
Available here: https://www.aix.kz/trading/trading-calendar/
Regularly-Observed Holidays:
- New Year's Day
- New Year Holiday
- Orthodox Christmas Day
- International Women's Day
- Nauryz Holiday
- Nauryz Holiday
- Nauryz Holiday
- Kazakhstan People Solidarity Day
- Defender’s Day
- Victory Day Holiday
- Capital City Day
- Capital City Day
- Kurban Ait Holiday (Eid-al-Adha)
- Constitution Day
- First President Day
- Independence Day
- Independence Day Holiday
Early Closes:
- None
"""
name = "AIXK"
tz = timezone("Asia/Almaty")
open_times = ((None, time(11)),)
close_times = ((None, time(17, 00)),)
@property
def bound_start(self) -> pd.Timestamp:
return pd.Timestamp("2017-01-01", tz="UTC")
def _bound_start_error_msg(self, start: pd.Timestamp) -> str:
msg = super()._bound_start_error_msg(start)
return msg + f" (The exchange {self.name} was founded in 2017.)"
@property
def regular_holidays(self):
return HolidayCalendar(
[
NewYearsDay,
NewYearHoliday,
OrthodoxChristmasDay,
InternationalWomensDay,
NauryzHoliday1,
NauryzHoliday2,
NauryzHoliday3,
KazakhstanPeopleSolidarityDay,
DefendersDay,
VictoryDayHoliday,
CapitalCityDay,
ConstitutionDay,
FirstPresidentDay,
IndependenceDay,
IndependenceDayHoliday,
]
)
@property
def adhoc_holidays(self):
# It is common in Kazakhstan to have holidays also on days
# between regular holiday and weekend
misc_holidays = [
# Bridge Day between Women's day - Weekend
pd.Timestamp("2018-03-09"),
# Bridge Day between Weekend - Kazakhstan People Solidarity Day
pd.Timestamp("2018-04-30"),
# Bridge Day between Defender's Day - Victory Day
pd.Timestamp("2018-05-08"),
# Bridge Day between Constitution Day - Weekend
pd.Timestamp("2018-08-31"),
# Bridge Day between New Year's Eve - New Year's day
pd.Timestamp("2018-12-31"),
# Bridge Day between Victory Day - Weekend
pd.Timestamp("2019-05-10"),
# Bridge Day between New Year's day - Weekend
pd.Timestamp("2020-01-03"),
# Bridge Day between Independence day - Weekend
pd.Timestamp("2020-12-18"),
# Bridge Day between Weekend - Capital City day
pd.Timestamp("2021-06-05"),
# Bridge Day between Weekend - Women's day
pd.Timestamp("2022-03-07"),
]
return list(chain(misc_holidays, eid_al_adha_first_day))
|
checkov/common/bridgecrew/integration_features/integration_feature_registry.py
|
jamesholland-uk/checkov
| 4,013 |
145451
|
<gh_stars>1000+
class IntegrationFeatureRegistry:
def __init__(self):
self.features = []
def register(self, integration_feature):
self.features.append(integration_feature)
self.features.sort(key=lambda f: f.order)
def run_pre_scan(self):
for integration in self.features:
if integration.is_valid():
integration.pre_scan()
def run_pre_runner(self):
for integration in self.features:
if integration.is_valid():
integration.pre_runner()
def run_post_runner(self, scan_reports):
for integration in self.features:
if integration.is_valid():
integration.post_runner(scan_reports)
integration_feature_registry = IntegrationFeatureRegistry()
|
mfa/Common.py
|
soxhub/django-mfa2
| 135 |
145465
|
from django.conf import settings
from django.core.mail import EmailMessage
try:
from django.urls import reverse
except:
from django.core.urlresolver import reverse
def send(to,subject,body):
from_email_address = settings.EMAIL_HOST_USER
if '@' not in from_email_address:
from_email_address = settings.DEFAULT_FROM_EMAIL
From = "%s <%s>" % (settings.EMAIL_FROM, from_email_address)
email = EmailMessage(subject,body,From,to)
email.content_subtype = "html"
return email.send(False)
def get_redirect_url():
return {"redirect_html": reverse(getattr(settings, 'MFA_REDIRECT_AFTER_REGISTRATION', 'mfa_home')),
"reg_success_msg":getattr(settings,"MFA_SUCCESS_REGISTRATION_MSG")}
|
src/arch/x86/isa/insts/general_purpose/data_transfer/xchg.py
|
qianlong4526888/haha
| 135 |
145486
|
<filename>src/arch/x86/isa/insts/general_purpose/data_transfer/xchg.py<gh_stars>100-1000
# Copyright (c) 2007 The Hewlett-Packard Development Company
# All rights reserved.
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implementation of the functionality of the software
# licensed hereunder. You may use the software subject to the license
# terms below provided that you ensure that this notice is replicated
# unmodified and in its entirety in all distributions of the software,
# modified or unmodified, in source code or in binary form.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met: redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer;
# redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution;
# neither the name of the copyright holders nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Authors: <NAME>
microcode = '''
# All the memory versions need to use LOCK, regardless of if it was set
def macroop XCHG_R_R
{
# Use the xor trick instead of moves to reduce register pressure.
# This probably doesn't make much of a difference, but it's easy.
xor reg, reg, regm
xor regm, regm, reg
xor reg, reg, regm
};
def macroop XCHG_R_M
{
mfence
ldstl t1, seg, sib, disp
stul reg, seg, sib, disp
mfence
mov reg, reg, t1
};
def macroop XCHG_R_P
{
rdip t7
mfence
ldstl t1, seg, riprel, disp
stul reg, seg, riprel, disp
mfence
mov reg, reg, t1
};
def macroop XCHG_M_R
{
mfence
ldstl t1, seg, sib, disp
stul reg, seg, sib, disp
mfence
mov reg, reg, t1
};
def macroop XCHG_P_R
{
rdip t7
mfence
ldstl t1, seg, riprel, disp
stul reg, seg, riprel, disp
mfence
mov reg, reg, t1
};
def macroop XCHG_LOCKED_M_R
{
mfence
ldstl t1, seg, sib, disp
stul reg, seg, sib, disp
mfence
mov reg, reg, t1
};
def macroop XCHG_LOCKED_P_R
{
rdip t7
mfence
ldstl t1, seg, riprel, disp
stul reg, seg, riprel, disp
mfence
mov reg, reg, t1
};
'''
|
2013/Practice Round/Moist/Moist solution.py
|
prashantsingh2408/Google-Kick-Start
| 237 |
145494
|
T = int(input())
for x in range(1, T + 1):
N = int(input())
names = [input() for index in range(N)]
y = 0
previous = names[0]
for name in names[1:]:
if name < previous:
y += 1
else:
previous = name
print(f"Case #{x}: {y}", flush = True)
|
aws_lambda_powertools/utilities/parameters/exceptions.py
|
Sordie/aws-lambda-powertools-python
| 1,208 |
145517
|
<gh_stars>1000+
"""
Parameter retrieval exceptions
"""
class GetParameterError(Exception):
"""When a provider raises an exception on parameter retrieval"""
class TransformParameterError(Exception):
"""When a provider fails to transform a parameter value"""
|
salt/matchers/grain_pcre_match.py
|
babs/salt
| 9,425 |
145536
|
<gh_stars>1000+
"""
This is the default grains PCRE matcher.
"""
import logging
import salt.utils.data
from salt.defaults import DEFAULT_TARGET_DELIM
log = logging.getLogger(__name__)
def match(tgt, delimiter=DEFAULT_TARGET_DELIM, opts=None, minion_id=None):
"""
Matches a grain based on regex
"""
if not opts:
opts = __opts__
log.debug("grains pcre target: %s", tgt)
if delimiter not in tgt:
log.error(
"Got insufficient arguments for grains pcre match statement from master"
)
return False
return salt.utils.data.subdict_match(
opts["grains"], tgt, delimiter=delimiter, regex_match=True
)
|
oauth/services/gitlab.py
|
giuseppe/quay
| 2,027 |
145562
|
<reponame>giuseppe/quay<filename>oauth/services/gitlab.py
from oauth.base import OAuthService, OAuthEndpoint
from util import slash_join
class GitLabOAuthService(OAuthService):
def __init__(self, config, key_name):
super(GitLabOAuthService, self).__init__(config, key_name)
def service_id(self):
return "gitlab"
def service_name(self):
return "GitLab"
def _endpoint(self):
return self.config.get("GITLAB_ENDPOINT", "https://gitlab.com")
def user_endpoint(self):
raise NotImplementedError
def api_endpoint(self):
return self._endpoint()
def get_public_url(self, suffix):
return slash_join(self._endpoint(), suffix)
def authorize_endpoint(self):
return OAuthEndpoint(slash_join(self._endpoint(), "/oauth/authorize"))
def token_endpoint(self):
return OAuthEndpoint(slash_join(self._endpoint(), "/oauth/token"))
def validate_client_id_and_secret(self, http_client, url_scheme_and_hostname):
# We validate the client ID and secret by hitting the OAuth token exchange endpoint with
# the real client ID and secret, but a fake auth code to exchange. Gitlab's implementation will
# return `invalid_client` as the `error` if the client ID or secret is invalid; otherwise, it
# will return another error.
url = self.token_endpoint().to_url()
redirect_uri = self.get_redirect_uri(url_scheme_and_hostname, redirect_suffix="trigger")
data = {
"code": "fakecode",
"client_id": self.client_id(),
"client_secret": self.client_secret(),
"grant_type": "authorization_code",
"redirect_uri": redirect_uri,
}
# We validate by checking the error code we receive from this call.
result = http_client.post(url, data=data, timeout=5)
value = result.json()
if not value:
return False
return value.get("error", "") != "invalid_client"
def get_public_config(self):
return {
"CLIENT_ID": self.client_id(),
"AUTHORIZE_ENDPOINT": self.authorize_endpoint().to_url(),
"GITLAB_ENDPOINT": self._endpoint(),
}
|
pypyr/steps/cmd.py
|
mofm/pypyr
| 261 |
145594
|
"""pypyr step that executes a cmd as a sub-process.
You cannot use things like exit, return, shell pipes, filename wildcards,
environment,variable expansion, and expansion of ~ to a user’s home
directory.
"""
import logging
from pypyr.steps.dsl.cmd import CmdStep
# logger means the log level will be set correctly
logger = logging.getLogger(__name__)
def run_step(context):
"""Run command, program or executable.
Context is a dictionary or dictionary-like.
Context must contain the following keys:
cmd: <<cmd string>> (command + args to execute.)
OR, as a dict
cmd:
run: str. mandatory. <<cmd string>> command + args to execute.
save: bool. defaults False. save output to cmdOut.
Will execute the command string in the shell as a sub-process.
Escape curly braces: if you want a literal curly brace, double it like
{{ or }}.
If save is True, will save the output to context as follows:
cmdOut:
returncode: 0
stdout: 'stdout str here. None if empty.'
stderr: 'stderr str here. None if empty.'
cmdOut.returncode is the exit status of the called process. Typically 0
means OK. A negative value -N indicates that the child was terminated by
signal N (POSIX only).
context['cmd'] will interpolate anything in curly braces for values
found in context. So if your context looks like this:
key1: value1
key2: value2
cmd: mything --arg1 {key1}
The cmd passed to the shell will be "mything --arg value1"
"""
logger.debug("started")
CmdStep(name=__name__, context=context).run_step(is_shell=False)
logger.debug("done")
|
week6/dags/03-python_operator_with_context.py
|
socar-carrot/kyle-school
| 189 |
145600
|
<gh_stars>100-1000
from airflow import DAG
from airflow.operators.python_operator import PythonOperator
from datetime import datetime, timedelta
default_args = {
'owner': 'kyle',
'depends_on_past': False,
'start_date': datetime(2020, 2, 10),
'email': ['<EMAIL>'],
'email_on_failure': False,
'email_on_retry': True,
'retries': 1,
'retry_delay': timedelta(minutes=1),
}
dag = DAG('python_dag_with_context',
default_args=default_args,
schedule_interval='30 0 * * *')
def print_current_date_provide_context(*args, **kwargs):
"""
provide_context=True로 지정하면 kwargs 다양한 값들이 저장됨
{'dag': <DAG: python_dag_with_jinja>,
'ds': '2020-02-10',
'next_ds': '2020-02-11',
'next_ds_nodash': '20200211',
'prev_ds': '2020-02-09',
'prev_ds_nodash': '20200209',
'ds_nodash': '20200210',
'ts': '2020-02-10T00:30:00+00:00',
'ts_nodash': '20200210T003000',
'ts_nodash_with_tz': '20200210T003000+0000',
'yesterday_ds': '2020-02-09',
'yesterday_ds_nodash': '20200209',
'tomorrow_ds': '2020-02-11',
'tomorrow_ds_nodash': '20200211',
'end_date': '2020-02-10',
'execution_date': <Pendulum [2020-02-10T00:30:00+00:00]> ...}
"""
print(f"kwargs :{kwargs}")
execution_date = kwargs['ds']
execution_date = datetime.strptime(execution_date, "%Y-%m-%d").date()
date_kor = ["월", "화", "수", "목", "금", "토", "일"]
datetime_weeknum = execution_date.weekday()
print(f"{execution_date}는 {date_kor[datetime_weeknum]}요일입니다")
python_task_context = PythonOperator(
task_id='print_current_date_with_context_variable',
python_callable=print_current_date_provide_context,
provide_context=True,
dag=dag,
)
python_task_context
|
ioflo/aio/uxd/uxding.py
|
BradyHammond/ioflo
| 128 |
145606
|
"""
uxd async io (nonblocking) module
"""
from __future__ import absolute_import, division, print_function
import sys
import os
import socket
import errno
from binascii import hexlify
# Import ioflo libs
from ...aid.sixing import *
from ...aid.consoling import getConsole
console = getConsole()
class SocketUxdNb(object):
"""
Class to manage non blocking io on UXD (unix domain) socket.
Use instance method .close() to close socket
"""
def __init__(self, ha=None, umask=None, bufsize = 1024, wlog=None):
"""
Initialization method for instance.
ha = uxd file name
umask = umask for uxd file
bufsize = buffer size
"""
self.ha = ha # uxd host address string name
self.umask = umask
self.bs = bufsize
self.wlog = wlog
self.ss = None # server's socket needs to be opened
self.opened = False
def actualBufSizes(self):
"""
Returns duple of the the actual socket send and receive buffer size
(send, receive)
"""
if not self.ss:
return (0, 0)
return (self.ss.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF),
self.ss.getsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF))
def open(self):
"""
Opens socket in non blocking mode.
if socket not closed properly, binding socket gets error
socket.error: (48, 'Address already in use')
"""
#create socket ss = server socket
self.ss = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
# make socket address reusable.
# the SO_REUSEADDR flag tells the kernel to reuse a local socket in
# TIME_WAIT state, without waiting for its natural timeout to expire.
self.ss.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if self.ss.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF) < self.bs:
self.ss.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, self.bs)
if self.ss.getsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF) < self.bs:
self.ss.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, self.bs)
self.ss.setblocking(0) #non blocking socket
oldumask = None
if self.umask is not None: # change umask for the uxd file
oldumask = os.umask(self.umask) # set new and return old
#bind to Host Address Port
try:
self.ss.bind(self.ha)
except socket.error as ex:
if not ex.errno == errno.ENOENT: # No such file or directory
console.terse("socket.error = {0}\n".format(ex))
return False
try:
os.makedirs(os.path.dirname(self.ha))
except OSError as ex:
console.terse("OSError = {0}\n".format(ex))
return False
try:
self.ss.bind(self.ha)
except socket.error as ex:
console.terse("socket.error = {0}\n".format(ex))
return False
if oldumask is not None: # restore old umask
os.umask(oldumask)
self.ha = self.ss.getsockname() #get resolved ha after bind
self.opened = True
return True
def reopen(self):
"""
Idempotently open socket by closing first if need be
"""
self.close()
return self.open()
def close(self):
"""
Closes socket.
"""
if self.ss:
self.ss.close() #close socket
self.ss = None
self.opened = False
try:
os.unlink(self.ha)
except OSError:
if os.path.exists(self.ha):
raise
def receive(self):
"""
Perform non blocking receive on socket.
Returns tuple of form (data, sa)
If no data then returns ('',None)
"""
try:
#sa = source address tuple (sourcehost, sourceport)
data, sa = self.ss.recvfrom(self.bs)
except socket.error as ex:
# ex.args[0] is always ex.errno for better compat
if ex.args[0] in (errno.EAGAIN, errno.EWOULDBLOCK):
return (b'', None) #receive has nothing empty string for data
else:
emsg = "socket.error = {0}: receiving at {1}\n".format(ex, self.ha)
console.profuse(emsg)
raise #re raise exception ex1
if console._verbosity >= console.Wordage.profuse: # faster to check
try:
load = data.decode("UTF-8")
except UnicodeDecodeError as ex:
load = "0x{0}".format(hexlify(data).decode("ASCII"))
cmsg = ("Server at {0}, received from {1}:\n------------\n"
"{2}\n\n".format(self.ha, sa, load))
console.profuse(cmsg)
if self.wlog:
self.wlog.writeRx(sa, data)
return (data, sa)
def send(self, data, da):
"""Perform non blocking send on socket.
data is string in python2 and bytes in python3
da is destination address tuple (destHost, destPort)
"""
try:
result = self.ss.sendto(data, da) #result is number of bytes sent
except socket.error as ex:
emsg = "socket.error = {0}: sending from {1} to {2}\n".format(ex, self.ha, da)
console.profuse(emsg)
result = 0
raise
if console._verbosity >= console.Wordage.profuse:
try:
load = data[:result].decode("UTF-8")
except UnicodeDecodeError as ex:
load = "0x{0}".format(hexlify(data[:result]).decode("ASCII"))
cmsg = ("Server at {0}, sent {1} bytes to {2}:\n------------\n"
"{3}\n\n".format(self.ha, result, da, load))
console.profuse(cmsg)
if self.wlog:
self.wlog.writeTx(da, data)
return result
PeerUxd = SocketUxdNb # alias
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.